branch_name stringclasses 149 values | text stringlengths 23 89.3M | directory_id stringlengths 40 40 | languages listlengths 1 19 | num_files int64 1 11.8k | repo_language stringclasses 38 values | repo_name stringlengths 6 114 | revision_id stringlengths 40 40 | snapshot_id stringlengths 40 40 |
|---|---|---|---|---|---|---|---|---|
refs/heads/master | <file_sep>from flask import Flask
# Initialize the app
app = Flask(__name__, instance_relative_config=True)
# Load the views
from app import views
# Load the config file
app.config.from_object('config')
# Instantiate the database
import sqlite3
database = 'email.db'
# In this implementation, Message-ID is unique, and therefore primary key and not null.
create_email_table = """ CREATE TABLE IF NOT EXISTS email (
to_address text,
from_address text,
date text,
subject text,
message_id text PRIMARY KEY UNIQUE NOT NULL
); """
try:
conn = sqlite3.connect(database)
c = conn.cursor()
c.execute(create_email_table)
except Error as e:
print(e)
finally:
conn.close()
<file_sep># email_parsing_app
Parses emails submitted via web form and displays contents in table
Instructions:
1. Clone repository
2. cd into repository
3. run "docker-compose build"
4. run "docker-compose up"
5. If on Linux, go to "localhost:5000" in web browser. If on Windows, use "docker-machine ip". Then go to "<result-ip>:5000" in web browser.
<file_sep>Here is future work I would do if this was a production project:
Database in separate volume so you don't lose all data when docker goes down
Login/security
Testing
More javascript for error handling on client side
Better display for email table
More robust regex<file_sep># Enable Flask's debugging features. Should be False in production
DEBUG = True
UPLOAD_FOLDER = '/tmp'<file_sep>from flask import render_template, request, redirect, url_for
from werkzeug import secure_filename
from app import app
import os
import re
import sqlite3
import tarfile
# Regex for each email field
TO_REGEX = r"(?:^To:.*?)([a-zA-Z0-9\.\-_\+]+@[a-zA-Z0-9\.\-_\+]+)>?"
FROM_REGEX = r"(?:^From:.*?)([a-zA-Z0-9\.\-_\+]+@[a-zA-Z0-9\.\-_\+]+)>?"
DATE_REGEX = r"(?:^Date:[ ]*)(.*)"
SUBJECT_REGEX = r"(?:^Subject:[ ]*)(.*)"
MESSAGE_ID_REGEX = r"(?:^Message-ID:[ ]*)(.*)"
# Name of database
DB = 'email.db'
# Sqlite string to insert email into database
insert_email = '''INSERT INTO email(to_address,from_address,date,subject,message_id)
VALUES(?,?,?,?,?)'''
@app.route('/')
def index():
return render_template("index.html")
@app.route('/form')
def email_form():
return render_template("upload_email.html")
# Unzips the archive, parses the .msg files for relevant fields, and saves them to the database.
@app.route('/form/submit', methods=['GET', 'POST'])
def submit_email_form():
if request.method == 'POST':
error_string = ""
# Get and save file from email form
file = request.files['file']
filename = secure_filename(file.filename)
file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
# Ensure tar file is actually a compressed archive, doesn't just have the extension
try:
tarfile_obj = tarfile.open(os.path.join(app.config['UPLOAD_FOLDER'], filename))
except tarfile.TarError:
error_string = 'Failed to open tarfile, possibly corrupted'
app.logger.info(error_string)
# Return error page since this is a major failure
return render_template("error.html", data=error_string)
for member in tarfile_obj.getmembers():
# Ensure all emails are of the .msg format
if member.name.endswith('.msg'):
text = tarfile_obj.extractfile(member)
email_to = email_parser(text, TO_REGEX)
email_from = email_parser(text, FROM_REGEX)
email_date = email_parser(text, DATE_REGEX)
email_subject = email_parser(text, SUBJECT_REGEX)
email_message_id = email_parser(text, MESSAGE_ID_REGEX)
store_email(email_to, email_from, email_date, email_subject, email_message_id, member.name)
else:
error_string = "File in archive %s not of type .msg" % member.name
app.logger.info(error_string)
return redirect(url_for('email_table'))
# Displays all the emails currently in the database
@app.route('/email')
def email_table():
data = get_email()
return render_template("view_email.html", data=data)
# Gets all emails from database
def get_email():
conn = create_connection()
cur = conn.cursor()
cur.execute("SELECT * FROM email")
all_email = cur.fetchall()
return all_email
# Inserts emails into the database
def store_email(email_to, email_from, email_date, email_subject, email_message_id, file_name):
conn = create_connection()
cur = conn.cursor()
try:
cur.execute(insert_email, (email_to, email_from, email_date, email_subject, email_message_id))
except sqlite3.IntegrityError:
# Since message id is primary key, we want it to be unique
if email_message_id:
app.logger.info("Entry already exists with the Message-ID:%s" % email_message_id)
# Since message id is primary key, we want it to exist
else:
app.logger.info("File %s does not contain Message-ID field" % file_name)
return
conn.commit()
def create_connection():
conn = sqlite3.connect(DB)
return conn
# Searches each line of email text for the regex provided
def email_parser(content, regex):
match = None
for line in content.readlines():
match = re.search(regex, line)
if match:
match = match.group(1)
break;
content.seek(0)
return match
| 27a3ae390d71d930f5a27bb7b3a8146b6b4ba586 | [
"Markdown",
"Python",
"Text"
] | 5 | Python | brmqk3/email_parsing_app | d60018571918a5c44139a6a518b2faa401332ea3 | 135793af9261bccc27276eda0e69b0995f9320c0 |
refs/heads/master | <repo_name>insafnouira/nav-menu-react<file_sep>/src/routes.js
import React,{Component} from 'react';
import {Route,Link} from 'react-router-dom';
import './App.css'
class Routes extends Component {
Home = () => (
<h1>Home here</h1>
)
Services = () => (
<div className='nested-services'>
<Link className='link' to="/services/for-entrepreneurs">For entrepreneurs</Link> <br/>
<Link className='link' to="/services/for-students">For students</Link> <br/>
<Link className='link' to="/services/for-hobbyists">For hobbyists</Link>
<div>
<Route path="/services/for-entrepreneurs" render={() => 'entrepreneurs'} />
<Route path="/services/for-students" render={() => 'students'} />
<Route path="/services/for-hobbyists" render={() => ' hobbyists'} />
</div>
</div>
)
Contact = () => (
<h1>Contacts here</h1>
)
render() {
return (
<div>
<Route exact path="/" component={this.Home} />
<Route path="/services" component={this.Services} />
<Route path="/contact" component={this.Contact} />
</div>
);
}
}
export default Routes; | 21af4c16203820383c3a59c7edd69ed50b79974a | [
"JavaScript"
] | 1 | JavaScript | insafnouira/nav-menu-react | dc8a6d3e9e06fedd55eb303cec24f43451634683 | f6a0397c3d52773b09a28cb98c00f04c64053845 |
refs/heads/master | <repo_name>sunaynagoel/montyhall<file_sep>/R/monty-hall-problem.R
#' @title
#' Create a new Monty Hall Problem game.
#'
#' @description
#' `create_game()` generates a new game that consists of two doors
#' with goats behind them, and one with a car.
#'
#' @details
#' The game setup replicates the game on the TV show "Let's
#' Make a Deal" where there are three doors for a contestant
#' to choose from, one of which has a car behind it and two
#' have goats. The contestant selects a door, then the host
#' opens a door to reveal a goat, and then the contestant is
#' given an opportunity to stay with their original selection
#' or switch to the other unopened door. There was a famous
#' debate about whether it was optimal to stay or switch when
#' given the option to switch, so this simulation was created
#' to test both strategies.
#'
#' @param ... no arguments are used by the function.
#'
#' @return The function returns a length 3 character vector
#' indicating the positions of goats and the car.
#'
#' @examples
#' create_game()
#'
#' @export
create_game <- function()
{
a.game <- sample( x=c("goat","goat","car"), size=3, replace=F )
return( a.game )
}
#' @title
#'
#' Contestant selects a door out of three available.
#'
#' @description
#'
#' `select_door()` allows the user to makes a choice of a door
#' "1,2, or 3"
#'
#' @details
#'
#' The select_door() let users pick a door. In this function, one of the door
#' out of three is selected at random and the choice is stored in a vector.
#' At this point the contestant does not know what is behind the door s/he
#' has selceted.
#'
#' @param
#'
#' No arguments are used by the function.
#'
#' @return
#'
#' The function returns a numberic vector of length one, incdicating
#' the door number the contestant has chosen.
#'
#' @examples
#' select_door()
#'
#' @export
select_door <- function( )
{
doors <- c(1,2,3)
a.pick <- sample( doors, size=1 )
return( a.pick ) # number between 1 and 3
}
#' @title
#'
#' The host opens a goat door.
#'
#' @description
#'
#' The host opens a door which was not constestant's original choice and
#' has a goat behind it.
#'
#' @details
#'
#' The function open_goat_door() uses two 'if' loops to decide which
#' one of the goat to open. If the contestant's original pick is a 'car',
#' the function randomly selects one of the goats doors. If the contestant's
#' original pick is a 'goat', the function eliminates the contestant's choice
#' door and the car door, to returns a goat door.
#'
#' @param
#'
#' The function take two arguments
#' 1. Game vector- character vector of length three containig
#' position of car and goats.
#' 2. a.pick- contains contestant's original pick (numberic vector
#' of length one containing number between 1-3).
#'
#' @return
#'
#' The function returns a numeric vector of length one containing a
#' number between 1 -3.
#'
#' @examples
#'
#' open_goat_door(game, a.pick)
#'
#'
#' @export
open_goat_door <- function( game, a.pick )
{
doors <- c(1,2,3)
# if contestant selected car,
# randomly select one of two goats
if( game[ a.pick ] == "car" )
{
goat.doors <- doors[ game != "car" ]
opened.door <- sample( goat.doors, size=1 )
}
if( game[ a.pick ] == "goat" )
{
opened.door <- doors[ game != "car" & doors != a.pick ]
}
return( opened.door ) # number between 1 and 3
}
#' @title
#'
#' Contestant decides to switch or stay with his/her original choice
#' of the door.
#'
#' @description
#'
#' The contestant has a choice to stay to his/her original choice or
#' switch doors to one of the two availble doors at this point.
#'
#' @details
#'
#' The contestant decides to stay with his/her original pick or s/he has
#' an option to switch.If the contestant decide to switch s/he can pick
#' between one of the two available doors.The function return either the
#' original pick or one of the two availble doors depending upon
#' contestant's choice.
#'
#' @param
#'
#' The function takes three arguments.
#' 1. option- We are considering that constants picks to stay
#' with original choice as defualt.
#' 2. opened.door - the goat door which is opened by the host
#' (numberic vector of length one containing number between 1-3).
#' 3. a.pick- Contestent's original pick of the door
#' (numberic vector of length one containing number between 1-3).
#'
#' @return
#'
#' Function returns a numeric vector of length one conating a number
#' between 1-3.
#'
#' @examples
#'
#' change_door(stay=T, opened.door, a.pick)
#'
#' @export
change_door <- function( stay=T, opened.door, a.pick )
{
doors <- c(1,2,3)
if( stay )
{
final.pick <- a.pick
}
if( ! stay )
{
final.pick <- doors[ doors != opened.door & doors != a.pick ]
}
return( final.pick ) # number between 1 and 3
}
#' @title
#'
#' Detemines if the contestant has won or lost the game.
#'
#' @description
#'
#' The function decides if the contestant has won or lost the
#' game depending upon his/her final pick of door.
#'
#' @details
#'
#' The function determines the result of the game. If the contestant's
#' final pick is car the s/he has won the game. If the final pick is
#' goat the s/he has lost the game.
#'
#' @param
#'
#' The function takes two arguments.
#' 1. final.pick- contestant final pick (a number between 1-3)
#' 2. game- character vector of length three containing position
#' of car and goats.
#'
#' @return
#'
#' The function returns a character vector of length one with either
#' "Win" or "lose"
#'
#' @examples
#'
#' Determine_winner( final.pick, game )
#'
#' @export
determine_winner <- function( final.pick, game )
{
if( game[ final.pick ] == "car" )
{
return( "WIN" )
}
if( game[ final.pick ] == "goat" )
{
return( "LOSE" )
}
}
#' @title
#'
#' A simulation of the Monty Hall problem game.
#'
#' @description
#'
#' This function simulates all the steps of the game and returns the result.
#'
#' @details
#'
#' This is a collection of all the steps of the game. It runs a simulation
#' of the whole game. The function returns the game result for both the
#' scenarios where the contestant has decided to stay with his/her original
#' choice and where he has decided to switch doors.
#'
#' @param
#'
#' No argumnets are required.
#'
#' @return
#'
#' The function returns a dataframe containing the strategy
#' (Stay and Switch) and the result in both the scenarios.
#'
#' @examples
#'
#' play_game()
#'
#' @export
play_game <- function( )
{
new.game <- create_game()
first.pick <- select_door()
opened.door <- open_goat_door( new.game, first.pick )
final.pick.stay <- change_door( stay=T, opened.door, first.pick )
final.pick.switch <- change_door( stay=F, opened.door, first.pick )
outcome.stay <- determine_winner( final.pick.stay, new.game )
outcome.switch <- determine_winner( final.pick.switch, new.game )
strategy <- c("stay","switch")
outcome <- c(outcome.stay,outcome.switch)
game.results <- data.frame( strategy, outcome,
stringsAsFactors=F )
return( game.results )
}
#' @title
#'
#' Runs a simulation of the Monty Hall Problem game to
#' determine the probability of win or lose.
#'
#' @description
#'
#' The function is a compliation of all the steps in playing
#' the game. It allows the user to run the simluation for any number
#' of times to determine probability of win or lose.
#'
#' @details
#'
#' This function can run the simulation any number of times. It stores
#' the result in a data frame. After running the simulation for supplied
#' number of times it calculates the probabilities of win and lose for
#' both scenarios (stay and switch).
#'
#' @param
#'
#' The Function takes a number for which the simulation needs to be
#' run as an argument.
#'
#' @return
#'
#' The function returns a data frame with probabilities of win and
#' lose for both scenarios (stay and switch).
#'
#' @examples
#'
#' play_n_games ( n=100 )
#'
#' @export
play_n_games <- function( n=100 )
{
library( dplyr )
results.list <- list() # collector
loop.count <- 1
for( i in 1:n ) # iterator
{
game.outcome <- play_game()
results.list[[ loop.count ]] <- game.outcome
loop.count <- loop.count + 1
}
results.df <- dplyr::bind_rows( results.list )
table( results.df ) %>%
prop.table( margin=1 ) %>% # row proportions
round( 2 ) %>%
print()
return( results.df )
}
| 4981a970f3a2cb083797e87b953efd2ddbc025cc | [
"R"
] | 1 | R | sunaynagoel/montyhall | 1afb07433664f345d293ba41fff790ad53071597 | 38be7666e73b159fabb7710b2fe9c1150af332de |
refs/heads/master | <file_sep>/*DULATRE, <NAME>;2014-28334;THVW*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
struct record{
int id; // holds the song id, randomly generated
char title[50]; //holds the title, cannot be emptied
char artist[50]; //holds the artist's name, can be emptied
char composer[50]; //holds the composer's name, can be emptied
char album[50]; //holds the album's title
char genre[50]; //holds the genre of the song
int rating; // hold the user define rating inclusive from 1 to 5
char remarks[50]; //holds notes of the user to the song
};
void addSong(void){
/*
Display the screen that helps to add a song to the whole library
Topmost is the banner
Followed by the generated Song Id
Then Title, Artist, Composer, Album, Genre, Rating, Remarks
Continue asking for Title if user emptied it
Continue asking if Rating is inclusive between 1 and 5
Save the new record the file record.txt by appending
Lastly, ask the user if the he/she still wishes to continue adding new record
If not, go to the navigation page
*/
int pass = 0;
while(true){
system("clear");
FILE *file;
struct record *dummy;
file = fopen("records.txt","a");
dummy = (struct record *)malloc(sizeof(struct record));
dummy->id = rand();
printf("\x1b[32mMusic Record Library\x1b[0m\n\x1b[32m of Yvonne Murelle\x1b[0m\n\n");
printf("\x1b[33mSong ID:\x1b[0m %i\n",dummy->id);
while(true){
printf("\x1b[33mTitle:\x1b[0m ");
fgets(dummy->title,50,stdin);
dummy->title[strlen(dummy->title)-1] = '\0';
if(strcmp(dummy->title,"")==0) continue;
else break;
}
printf("\x1b[33mArtist:\x1b[0m ");
fgets(dummy->artist,50,stdin);
dummy->artist[strlen(dummy->artist)-1] = '\0';
printf("\x1b[33mComposer:\x1b[0m ");
fgets(dummy->composer,50,stdin);
dummy->composer[strlen(dummy->composer)-1] = '\0';
printf("\x1b[33mAlbum:\x1b[0m ");
fgets(dummy->album,50,stdin);
dummy->album[strlen(dummy->album)-1] = '\0';
printf("\x1b[33mGenre:\x1b[0m ");
fgets(dummy->genre,50,stdin);
dummy->genre[strlen(dummy->genre)-1] = '\0';
while(true){
printf("\x1b[33mRating:\x1b[0m ");
char tempRate[10];
fgets(tempRate,10,stdin);
tempRate[strlen(tempRate)-1]='\0';
if(strcmp(tempRate,"")==0) continue;
else if(atoi(tempRate)>=1&&atoi(tempRate)<=5){
dummy->rating = atoi(tempRate);
break;
}
else continue;
}
printf("\x1b[33mRemarks:\x1b[0m ");
fgets(dummy->remarks,50,stdin);
dummy->remarks[strlen(dummy->remarks)-1] = '\0';
fwrite(&dummy->id, sizeof(dummy->id), 1, file);
fwrite(dummy->title, 50, 1, file);
fwrite(dummy->artist, 50, 1, file);
fwrite(dummy->composer, 50, 1, file);
fwrite(dummy->album, 50, 1, file);
fwrite(dummy->genre, 50, 1, file);
fwrite(&dummy->rating, sizeof(dummy->id), 1, file);
fwrite(dummy->remarks, 50, 1, file);
fclose(file);
free(dummy);
char c;
printf("\x1b[33m\n\nAdd another one song(y/n)? \x1b[0m");
scanf("%c",&c);
if(c=='y'||c=='Y') pass = 0;
else pass = 1;
if(pass == 1){
system("clear");
break;
}
getchar();
}
}
void listSong(int filter,char *ptr){
/*
Opens the file record.txt and reads the file by every song record.
Accept two(2) parameters namely filter and ptr
filter use to direct to the proper field to search the substring
ptr pointer to the substring
Render all the information if the substring match to the chosen field except for the Song ID
If the user choose the display all the songs the Song ID would also be displayed
*/
FILE *file;
struct record *dummy;
file = fopen("records.txt","rb");
if (file == NULL){
printf("\nThere is no Song Library Yet!\nCreate One First");
}
else{
dummy = (struct record *)malloc(sizeof(struct record));
while(fread(&dummy->id, sizeof(dummy->id), 1, file)){
fread(dummy->title, 50, 1, file);
fread(dummy->artist, 50, 1, file);
fread(dummy->composer, 50, 1, file);
fread(dummy->album, 50, 1, file);
fread(dummy->genre, 50, 1, file);
fread(&dummy->rating, sizeof(dummy->rating), 1, file);
fread(dummy->remarks, 50, 1, file);
// printf("number %i",atoi(ptr));
if((filter==1)&&(strstr(dummy->title,ptr))){
printf("\n\x1b[33mTitle:\x1b[0m %s\n",dummy->title);
printf("\x1b[33mArtist:\x1b[0m %s\n",dummy->artist);
printf("\x1b[33mComposer:\x1b[0m %s\n",dummy->composer);
printf("\x1b[33mAlbum:\x1b[0m %s\n",dummy->album);
printf("\x1b[33mGenre:\x1b[0m %s\n",dummy->genre);
printf("\x1b[33mRating:\x1b[0m %d\n",dummy->rating);
printf("\x1b[33mRemarks:\x1b[0m %s\n",dummy->remarks);
}
else if((filter==2)&&(strstr(dummy->artist,ptr))){
printf("\n\x1b[33mTitle:\x1b[0m %s\n",dummy->title);
printf("\x1b[33mArtist:\x1b[0m %s\n",dummy->artist);
printf("\x1b[33mComposer:\x1b[0m %s\n",dummy->composer);
printf("\x1b[33mAlbum:\x1b[0m %s\n",dummy->album);
printf("\x1b[33mGenre:\x1b[0m %s\n",dummy->genre);
printf("\x1b[33mRating:\x1b[0m %d\n",dummy->rating);
printf("\x1b[33mRemarks:\x1b[0m %s\n",dummy->remarks);
}
else if((filter==3)&&(strstr(dummy->composer,ptr))){
printf("\n\x1b[33mTitle:\x1b[0m %s\n",dummy->title);
printf("\x1b[33mArtist:\x1b[0m %s\n",dummy->artist);
printf("\x1b[33mComposer:\x1b[0m %s\n",dummy->composer);
printf("\x1b[33mAlbum:\x1b[0m %s\n",dummy->album);
printf("\x1b[33mGenre:\x1b[0m %s\n",dummy->genre);
printf("\x1b[33mRating:\x1b[0m %d\n",dummy->rating);
printf("\x1b[33mRemarks:\x1b[0m %s\n",dummy->remarks);
}
else if((filter==4)&&(strstr(dummy->album,ptr))){
printf("\n\x1b[33mTitle:\x1b[0m %s\n",dummy->title);
printf("\x1b[33mArtist:\x1b[0m %s\n",dummy->artist);
printf("\x1b[33mComposer:\x1b[0m %s\n",dummy->composer);
printf("\x1b[33mAlbum:\x1b[0m %s\n",dummy->album);
printf("\x1b[33mGenre:\x1b[0m %s\n",dummy->genre);
printf("\x1b[33mRating:\x1b[0m %d\n",dummy->rating);
printf("\x1b[33mRemarks:\x1b[0m %s\n",dummy->remarks);
}
else if((filter==5)&&(strstr(dummy->genre,ptr))){
printf("\n\x1b[33mTitle:\x1b[0m %s\n",dummy->title);
printf("\x1b[33mArtist:\x1b[0m %s\n",dummy->artist);
printf("\x1b[33mComposer:\x1b[0m %s\n",dummy->composer);
printf("\x1b[33mAlbum:\x1b[0m %s\n",dummy->album);
printf("\x1b[33mGenre:\x1b[0m %s\n",dummy->genre);
printf("\x1b[33mRating:\x1b[0m %d\n",dummy->rating);
printf("\x1b[33mRemarks:\x1b[0m %s\n",dummy->remarks);
}
else if((filter==6)&&(dummy->rating>=atoi(ptr))){
printf("\n\x1b[33mTitle:\x1b[0m %s\n",dummy->title);
printf("\x1b[33mArtist:\x1b[0m %s\n",dummy->artist);
printf("\x1b[33mComposer:\x1b[0m %s\n",dummy->composer);
printf("\x1b[33mAlbum:\x1b[0m %s\n",dummy->album);
printf("\x1b[33mGenre:\x1b[0m %s\n",dummy->genre);
printf("\x1b[33mRating:\x1b[0m %d\n",dummy->rating);
printf("\x1b[33mRemarks:\x1b[0m %s\n",dummy->remarks);
}
else if(filter==7){
printf("\n\x1b[33mSong Id:\x1b[0m %d\n",dummy->id);
printf("\x1b[33mTitle:\x1b[0m %s\n",dummy->title);
printf("\x1b[33mArtist:\x1b[0m %s\n",dummy->artist);
printf("\x1b[33mComposer:\x1b[0m %s\n",dummy->composer);
printf("\x1b[33mAlbum:\x1b[0m %s\n",dummy->album);
printf("\x1b[33mGenre:\x1b[0m %s\n",dummy->genre);
printf("\x1b[33mRating:\x1b[0m %d\n",dummy->rating);
printf("\x1b[33mRemarks:\x1b[0m %s\n",dummy->remarks);
}
}
}
free(dummy);
fclose(file);
}
void listSongChannel(void){
/*
Gateway for the listSong function after analyzing and processing the given inputted query by the user.
Display the possible choice of query to be inputted the user.
The query is divided into two, token and string
The token is choosing the right field to where to search the substring
The string holds the substring
The listSongChannel passes two parameters to listSong
filter contain the equivalent for the given field
string holds the substring to pass
Ask the user at the end if he/she still want to continue searching
If not navigate to navigation screen
*/
char *token=NULL;
int pass = 1;
char str[50];
while(true){
system("clear");
printf("\x1b[32mMusic Record Library\x1b[0m\n\x1b[32m of Yvonne Murelle\x1b[0m\n\n");
printf("\x1b[33mPossible Query: \x1b[0m\n");
printf(" \x1b[34mTitle <query>\x1b[0m\n");
printf(" \x1b[34mArtist <query>\x1b[0m\n");
printf(" \x1b[34mComposer <query>\x1b[0m\n");
printf(" \x1b[34mAlbum <query>\x1b[0m\n");
printf(" \x1b[34mGenre <query>\x1b[0m\n");
printf(" \x1b[34mRating <query>\x1b[0m\n");
printf(" \x1b[34mAll\x1b[0m\n\n");
printf("\x1b[33mEnter your query:\x1b[0m ");
fgets(str,50,stdin);
if(strcmp(str,"")==0) continue;
else str[strlen(str)-1] = '\0';
char *string = str;
token = strsep(&string," ");
int a;
for(a=0;a<strlen(token);a++) token[a] = toupper(token[a]);
if(strcmp(token,"TITLE")==0&&string!=NULL) listSong(1,string);
else if(strcmp(token,"ARTIST")==0&&string!=NULL) listSong(2,string);
else if(strcmp(token,"COMPOSER")==0&&string!=NULL) listSong(3,string);
else if(strcmp(token,"GENRE")==0&&string!=NULL) listSong(4,string);
else if(strcmp(token,"ALBUM")==0&&string!=NULL) listSong(5,string);
else if(strcmp(token,"RATING")==0&&string!=NULL) listSong(6,string);
else if(strcmp(token,"ALL")==0) listSong(7,string);
else;
char c;
printf("\x1b[33m\nAnother list of songs(y/n)? \x1b[0m");
scanf("%c",&c);
if(c=='y'||c=='Y') pass = 0;
else pass = 1;
if(pass == 1){
system("clear");
break;
}
getchar();
}
}
void updateSong(){
/*
Display the screen that helps the user to update a song
The song could be choose by inputting the title after the screen was render
The screen also follows the convention, banner at the topmost
If the song's title inputted matches a record get the record every information and display it to the user one by one as guide for the user for updating
The user may not wish to update a information by leaving the entry field blank.
After getting the updated informations save the informations/data to the file records.txt
At the end ask the user if the he/she still wants to continue updating
If not navigate to the navigation screen
*/
FILE *file;
int pass = 0;
while(true){
struct record *dummy,*dummyUpdate;
file = fopen("records.txt","r+");
if (file == NULL){
printf("\nThere is no Song Library Yet!\nCreate One First");
}
else{
char searching[50];
dummy = (struct record *)malloc(sizeof(struct record));
system("clear");
printf("\x1b[32mMusic Record Library\x1b[0m\n\x1b[32m of Yvonne Murelle\x1b[0m\n\n");
printf("\x1b[33mSearch Song: \x1b[0m");
fgets(searching,50,stdin);
if(strcmp(searching,"")==0) printf("Nothing to search");
else searching[strlen(searching)-1] = '\0';
while(fread(&dummy->id, sizeof(dummy->id), 1, file)){
fread(dummy->title, 50, 1, file);
fread(dummy->artist, 50, 1, file);
fread(dummy->composer, 50, 1, file);
fread(dummy->album, 50, 1, file);
fread(dummy->genre, 50, 1, file);
fread(&dummy->rating, sizeof(dummy->rating), 1, file);
fread(dummy->remarks, 50, 1, file);
// if(strcmp(dummy->title,searching)==0){
if(strstr(dummy->title,searching)){
dummyUpdate = (struct record *)malloc(sizeof(struct record));
printf("\x1b[33mTitle\x1b[0m \x1b[34m(%s)\x1b[0m\x1b[33m:\x1b[0m ",dummy->title);
fgets(dummyUpdate->title,50,stdin);
dummyUpdate->title[strlen(dummyUpdate->title)-1]='\0';
printf("\x1b[33mArtist\x1b[0m \x1b[34m(%s)\x1b[0m\x1b[33m:\x1b[0m ",dummy->artist);
fgets(dummyUpdate->artist,50,stdin);
dummyUpdate->artist[strlen(dummyUpdate->artist)-1]='\0';
printf("\x1b[33mComposer\x1b[0m \x1b[34m(%s)\x1b[0m\x1b[33m:\x1b[0m ",dummy->composer);
fgets(dummyUpdate->composer,50,stdin);
dummyUpdate->composer[strlen(dummyUpdate->composer)-1]='\0';
printf("\x1b[33mAlbum\x1b[0m \x1b[34m(%s)\x1b[0m\x1b[33m:\x1b[0m ",dummy->album);
fgets(dummyUpdate->album,50,stdin);
dummyUpdate->album[strlen(dummyUpdate->album)-1]='\0';
printf("\x1b[33mGenre\x1b[0m \x1b[34m(%s)\x1b[0m\x1b[33m:\x1b[0m ",dummy->genre);
fgets(dummyUpdate->genre,50,stdin);
dummyUpdate->genre[strlen(dummyUpdate->genre)-1]='\0';
while(true){
printf("\x1b[33mRating\x1b[0m \x1b[34m(%i)\x1b[0m\x1b[33m:\x1b[0m ",dummy->rating);
char tempRate[10];
fgets(tempRate,10,stdin);
tempRate[strlen(tempRate)-1]='\0';
if(strcmp(tempRate,"")==0){
dummyUpdate->rating = dummy->rating;
break;
}
else if(atoi(tempRate)<1&&atoi(tempRate)>5) continue;
else{
dummyUpdate->rating = atoi(tempRate);
break;
}
}
printf("\x1b[33mRemarks\x1b[0m \x1b[34m(%s)\x1b[0m\x1b[33m:\x1b[0m ",dummy->remarks);
fgets(dummyUpdate->remarks,50,stdin);
dummyUpdate->remarks[strlen(dummyUpdate->remarks)-1]='\0';
fseek(file, -308, SEEK_CUR);
fwrite(&dummy->id, sizeof(dummy->id), 1, file);
if(strcmp(dummyUpdate->title,"")!=0) fwrite(dummyUpdate->title, 50, 1, file);
else fwrite(dummy->title, 50, 1, file);
if(strcmp(dummyUpdate->artist,"")!=0) fwrite(dummyUpdate->artist, 50, 1, file);
else fwrite(dummy->artist, 50, 1, file);
if(strcmp(dummyUpdate->composer,"")!=0) fwrite(dummyUpdate->composer, 50, 1, file);
else fwrite(dummy->composer, 50, 1, file);
if(strcmp(dummyUpdate->album,"")!=0) fwrite(dummyUpdate->album, 50, 1, file);
else fwrite(dummy->album, 50, 1, file);
if(strcmp(dummyUpdate->genre,"")!=0) fwrite(dummyUpdate->genre, 50, 1, file);
else fwrite(dummy->genre, 50, 1, file);
fwrite(&dummyUpdate->rating, sizeof(dummyUpdate->rating), 1, file);
if(strcmp(dummyUpdate->remarks,"")!=0) fwrite(dummyUpdate->remarks, 50, 1, file);
else fwrite(dummy->remarks, 50, 1, file);
break;
}
}
}
free(dummy);
fclose(file);
char c;
printf("\x1b[33m\nUpdate again(y/n)? \x1b[0m");
scanf("%c",&c);
if(c=='y'||c=='Y') pass = 0;
else pass = 1;
if(pass == 1){
system("clear");
break;
}
getchar();
}
}
int main(void){
/*
Display the navigation screen
Topmost is the banner
Serve the 3 group command as menu
The user picks the assign number for the command to navigate to the command screen
Number 4 to exit/terminate the program
*/
while(true){
int pass=1,choice;
system("clear");
printf("\x1b[32mMusic Record Library\x1b[0m\n\x1b[32m of Yvonne Murelle\x1b[0m\n\n");
printf("\x1b[33mChoose what to do: \x1b[0m\n");
printf(" \x1b[34m1] Add a Song\x1b[0m\n");
printf(" \x1b[34m2] List Songs\x1b[0m\n");
printf(" \x1b[34m3] Update a Song record\x1b[0m\n");
printf(" \x1b[34m4] Exit\x1b[0m\n");
printf("\n\x1b[33mEnter your choice: \x1b[0m");
scanf("%d", &choice);
switch (choice){
case 1:
getchar();
addSong();
break;
case 2:
getchar();
listSongChannel();
break;
case 3:
getchar();
updateSong();
break;
case 4:
return 0;
}
getchar();
}
}<file_sep>#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <stdbool.h>
#include <math.h>
#include <stdbool.h>
void num1(void){
char str[10];
int counter,zero=0,pair=0;
printf("Enter number: ");
scanf("%s",str);
printf("%s! has ",str);
counter=atoi(str)+1;
while(counter!=0){
counter--;
if(counter==0) break;
sprintf(str,"%d",counter);
switch(str[strlen(str)-1]-'0'){
case 0:
zero++;
break;
case 5:
pair++;
if(pair==2){
pair=0;
zero++;
}
break;
case 2:
pair++;
if(pair==2){
pair=0;
zero++;
}
break;
}
}
printf("%i rightmost 0's\n",zero);
return;
}
void num2(void){
int x1,y1,x2,y2,x3,y3,x4,y4;
int collector[100],x=0,y,counter;
char temp[10];
char container[100];
while(true){
printf("Enter x1,y1,x2,y2,x3,y3,x4,y4\n");
printf("Separate each input by a comma: ");
scanf("%s",container);
int index,pass=0;
for(index=0,counter=0,pass=0,y=0;index<=strlen(container);index++){
switch(container[index]){
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
case '0':
case '-':
temp[x] = container[index];
x++;
continue;
case ',':
case '\0':
if(atoi(temp)!=0||temp[0]=='0'){
temp[x]='\0';
x=0;
counter++;
collector[y]=atoi(temp);
y++;
temp[x]='k';
continue;
}
else{
pass=1;
break;
}
default:
pass=1;
break;
}
}
if(pass==1||counter!=8){
printf("\nPlease input properly!\n");
continue;
}
break;
}
for(x=0;x<8;x++)
x1 = collector[0];
y1 = collector[1];
x2 = collector[2];
y2 = collector[3];
x3 = collector[4];
y3 = collector[5];
x4 = collector[6];
y4 = collector[7];
float m1,m2;
m1 = (y2-y1)/(x2-x1);
m2 = (y4-y3)/(x4-x3);
if(m1==m2) printf("NO INTERSECTION!");
else{
float xint,yint;
xint = (m1*x1-y1-m2*x3+y3)/(m1-m2);
yint = m1*(xint-x1)+y1;
printf("(%f,%f)\n",xint,yint);
}
return;
}
int primeFinder(int number){
float limit;
int y;
limit = sqrt(number);
for(y=2;y<=limit;y++){
if(number%y==0){
return 1;
}
}
return 0;
}
void num3(void){
int x,n,temp;
int key[100],count[100];
int a=0;
printf("Enter number: ");
scanf("%i",&n);
temp = n;
key[a] = 1;
count[a] = 1;
for(x=2;x<=sqrt(temp)&&n>x;x++){
if(primeFinder(x)==0){
while(n%x==0){
n = n/x;
if(key[a]!=x){
a++;
count[a]=0;
}
key[a] = x;
count[a] = count[a] + 1;
}
}
}
int z,pass=1;
printf("%i =",temp);
int product=1;
for(z=1;z<a+1;z++){
if(pass==1){
printf(" %i^%i",key[z],count[z]);
pass=0;
}
else printf(" x %i^%i",key[z],count[z]);
product = product*pow(key[z],count[z]);
}
printf(" x %i^%i",n,1);
printf("\n");
return;
}
struct node5{
int coe;
int pos;
struct node5* next;
};
void num5(void){
char fPoly[50],sPoly[50];
struct node5 *fCon=NULL,*fHead=NULL,*sCon=NULL,*sHead=NULL;
printf("Enter 1st polynomial: ");
scanf(" %s",fPoly);
printf("Enter 2nd polynomial: ");
scanf(" %s",sPoly);
char *token1;
int counter1 = 0;
token1 = strtok(fPoly,",");
while(token1!=NULL){
fCon = (struct node5 *)malloc(sizeof(struct node5));
fCon->coe = atoi(token1);
counter1++;
fCon->pos = counter1;
fCon->next = fHead;
fHead = fCon;
token1 = strtok(NULL,",");
}
char *token2;
int counter2 = 0;
token2 = strtok(sPoly,",");
while(token2!=NULL){
sCon = (struct node5 *)malloc(sizeof(struct node5));
sCon->coe = atoi(token2);
counter2++;
sCon->pos = counter2;
sCon->next = sHead;
sHead = sCon;
token2 = strtok(NULL,",");
}
struct node5 *pCon=NULL,*pHead=NULL;
int max=0;
while(fCon){
while(sCon){
pCon = (struct node5 *)malloc(sizeof(struct node5));
pCon->coe = fCon->coe*sCon->coe;
if(max<counter1-fCon->pos+counter2-sCon->pos) max = counter1-fCon->pos+counter2-sCon->pos;
pCon->pos = counter1-fCon->pos+counter2-sCon->pos;
pCon->next = pHead;
pHead = pCon;
sCon = sCon->next;
}
sCon = sHead;
fCon = fCon->next;
}
fCon = fHead;
int temp = 0,add = 0;
int pass=max;
while(max!=-1){
while(pCon){
if(max==pCon->pos){
add += pCon->coe;
}
pCon = pCon->next;
}
if(pass==max) printf("%i^%i ",add,max);
else if(max==0) printf("+ %i",add);
else printf("+ %i^%i ",add,max);
add = 0;
pCon = pHead;
max--;
}
printf("\n");
free(fCon);
free(sCon);
return;
}
void num6(void){
int n,i;
printf("Enter n: ");
scanf("%i",&n);
printf("Enter i: ");
scanf("%i",&i);
int x,binary=0;
for(x=1;x<=i;x++){
if(n%x==0){
if(binary==0)
binary=1;
else
binary=0;
}
}
printf("Binary: %i\n",binary);
return;
}
int factorChecker(int num1,int num2){
if(num1>num2){
int temp=num2;
num2 = num1;
num1 = temp;
}
int x;
for(x=2;x<=num1;x++){
if((num1%x==0)&&(num2%x==0)){
return 0;
}
}
return 1;
}
void num7(void){
int n;
printf("Enter n: ");
scanf("%i",&n);
int x;
for(x=1;x<n;x++){
int ans = factorChecker(x,n);
if(ans==1)
printf("%i/%i,",x,n);
}
printf("\n");
return;
}
int getDistance(int x1,int y1,int x2,int y2){
return sqrt(pow(x2-x1,2)+pow(y2-y1,2));
}
void num8(void){
char xcontainer[100],xtemp[10];
int xcollector[100];
int x=0,y,counter;
printf("Enter x-components(then press enter): ");
while(true){
scanf("%s",xcontainer);
int index,pass=0;
for(index=0,counter=0,pass=0,y=0;index<=strlen(xcontainer);index++){
switch(xcontainer[index]){
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
case '0':
case '-':
xtemp[x] = xcontainer[index];
x++;
continue;
case ',':
case '\0':
if(atoi(xtemp)!=0||xtemp[0]=='0'){
xtemp[x]='\0';
x=0;
counter++;
xcollector[y]=atoi(xtemp);
y++;
xtemp[x]='k';
continue;
}
else{
pass=1;
break;
}
default:
pass=1;
break;
}
}
break;
}
int tempCounter = counter;
char ycontainer[100],ytemp[10];
int ycollector[100];
printf("Enter y-components(then press enter): ");
while(true){
scanf("%s",ycontainer);
int index,pass=0;
for(index=0,counter=0,pass=0,y=0;index<=strlen(ycontainer);index++){
switch(ycontainer[index]){
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
case '0':
case '-':
ytemp[x] = ycontainer[index];
x++;
continue;
case ',':
case '\0':
if(atoi(ytemp)!=0||ytemp[0]=='0'){
ytemp[x]='\0';
x=0;
counter++;
ycollector[y]=atoi(ytemp);
y++;
ytemp[x]='k';
continue;
}
else{
pass=1;
break;
}
default:
pass=1;
break;
}
}
if(pass==1||counter!=tempCounter){
printf("Enter y-components(then press enter): ");
continue;
}
break;
}
int a=0,b=0,index1=0,index2=0;
int min = getDistance(xcollector[a],ycollector[a],xcollector[a++],ycollector[a++]);
for(a=0;a<tempCounter;a++){
for(b=a;b<tempCounter;b++){
if(a==b){
continue;
}
else{
int temp = getDistance(xcollector[a],ycollector[a],xcollector[b],ycollector[b]);
if(temp<min){
min = temp;
index1 = a;
index2 = b;
}
}
}
}
printf("Shortest Distance of (%i,%i) and (%i,%i) is %i\n",xcollector[index1],ycollector[index1],xcollector[index2],ycollector[index2],min);
return;
}
long long int combination(int n,int r){
if(r==0||n==r){
return 1;
}
else{
long long int ans=n,x,den=r;
for(x=n-1;x>(n-r);x--){
ans *= x;
}
for(x=r-1;x>1;x--){
den *= x;
}
return ans/den;
}
}
void num9(void){
int n;
printf("Enter n: ");
scanf("%i",&n);
int x;
for(x=0;x<=n;x++){
printf("%llu ",combination(n,x));
}
printf("\n");
return;
}
void num10(void){
int n,x;
printf("Enter a number: ");
scanf("%i",&n);
for(x=n/1000;x>0;x--){
printf("M");
n -= 1000;
}
for(x=n/500;x>0;x--){
printf("D");
n -= 500;
}
for(x=n/100;x>0;x--){
printf("C");
n -= 100;
}
for(x=n/50;x>0;x--){
printf("L");
n -= 50;
}
for(x=n/10;x>0;x--){
printf("X");
n -= 10;
}
for(x=n/5;x>0;x--){
printf("V");
n -= 5;
}
for(x=n/1;x>0;x--){
printf("I");
n -= 1;
}
printf("\n");
return;
}
void frac(int top,int bot){
printf(" %i/%i",top,bot);
}
void subtract(int *top1,int *bot1,int top2,int bot2){
int top = *top1*bot2 - top2**bot1;
int bot = *bot1*bot2;
int x;
for(x=2;x<=top||x<=bot;x++){
if((top%x==0)&&(bot%x==0)){
top = top/x;
bot = bot/x;
x=2;
}
}
*top1 = top;
*bot1 = bot;
}
void num11(void){
int top,bot,origTop,origBot;
printf("Enter numerator: ");
scanf("%i",&top);
printf("Enter denominator: ");
scanf("%i",&bot);
origTop = top;
origBot = bot;
int x,pass=1,min=1;
while(min<1000){
for(x=min+1;top!=1&&x<1001;x++){
if(x>1000||top/bot<1/1000){
printf(" end");
break;
}
int tempTop=top,tempBot=bot;
if(top*x>bot)subtract(&top,&bot,1,x);
if(tempTop!=top,tempBot!=bot){
if(pass==1){
min = x;
pass=0;
}
frac(1,x);
if(top==1){
frac(top,bot);
}
if(x>1000||top/bot<1/1000){
printf(" end");
break;
}
tempTop=top;
tempBot=top;
}
}
pass = 1;
top = origTop;
bot = origBot;
printf("\n");
}
return;
}
void num12(void){
int n,x,plus=1;
printf("Enter Denomination: ");
scanf("%i",&n);
printf("%i = ",n);
if((x=n/1000)>=1){
printf("(%i) 1000",x);
plus = 0;
n -= x*1000;
}
if((x=n/500)>=1){
if(plus==0) printf(" + (%i) 500",x);
else{
printf("(%i) 500",x);
plus = 0;
}
n -= x*500;
}
if((x=n/200)>=1){
if(plus==0) printf(" + (%i) 200",x);
else{
printf("(%i) 200",x);
plus = 0;
}
n -= x*200;
}
if((x=n/100)>=1){
if(plus==0) printf(" + (%i) 100",x);
else{
printf("(%i) 100",x);
plus = 0;
}
n -= x*100;
}
if((x=n/50)>=1){
if(plus==0) printf(" + (%i) 50",x);
else{
printf("(%i) 50",x);
plus = 0;
}
n -= x*50;
}
if((x=n/20)>=1){
if(plus==0) printf(" + (%i) 20",x);
else{
printf("(%i) 20",x);
plus = 0;
}
n -= x*20;
}
if((x=n/10)>=1){
if(plus==0)printf(" + (%i) 10",x);
else{
printf("(%i) 10",x);
plus = 0;
}
n -= x*10;
}
if((x=n/5)>=1){
if(plus==0) printf(" + (%i) 5",x);
else{
printf("(%i) 5",x);
plus = 0;
}
n -= x*5;
}
if((x=n/1)>=1){
if(plus==0) printf(" + (%i) 1",x);
else{
printf("(%i) 1",x);
plus = 0;
}
n -= x*1;
}
printf("\n");
return;
}
struct num13{
int num1;
int num2;
int sum;
struct num13 *next;
};
struct ans13{
int ans;
struct ans13 *next;
};
void num13(void){
char num1[100],num2[100];
printf("Enter num1: ");
fgets(num1,100,stdin);
printf("Enter num2: ");
fgets(num2,100,stdin);
if(strlen(num1)>strlen(num2)){
int x = strlen(num1)-strlen(num2)+1;
while(x>0){
char d[100]="0";
strcpy(num2,strcat(d,num2));
x--;
}
}
else if(strlen(num1)<strlen(num2)){
int x = strlen(num2)-strlen(num1);
while(x>0){
char d[100]="0";
strcpy(num1,strcat(d,num1));
x--;
}
}
else;
int x=0;
struct num13 *head=NULL,*current;
while(num2[x]!='\n'||num1[x]!='\n'){
current = malloc(sizeof(struct num13));
current->num1 = num1[x]-'0';
current->num2 = num2[x]-'0';
current->next = head;
head = current;
x++;
}
int excess = 0;
while(current){
if(current->num1+current->num2+excess>=10){
current->sum=current->num1+current->num2+excess-10;
excess=1;
}
else{
current->sum=current->num1+current->num2+excess;
excess = 0;
}
current = current->next;
}
current=head;
struct ans13 *myAns,*myHead=NULL;
while(current){
myAns = malloc(sizeof(struct ans13));
myAns->ans = current->sum;
myAns->next = myHead;
myHead = myAns;
current = current->next;
}
printf("answer: ");
if(excess==1) printf("1");
while(myAns){
printf("%i",myAns->ans);
myAns = myAns->next;
}
return;
}
void convertToBinary(int num){
int newNum=0;
int counter=0;
while(num!=0){
newNum = newNum+(num%2)*pow(10,counter);
num = num/2;
counter++;
}
printf("Binary: %i\n",newNum);
return;
}
void convertToOctal(int num){
int newNum=0;
int counter=0;
while(num!=0){
newNum = newNum+(num%8)*pow(10,counter);
num = num/8;
counter++;
}
printf("Octal: %i\n",newNum);
return;
}
void convertToHexadical(int num){
char str[50];
int counter=0;
while(num!=0){
if(num%16<=9)
str[counter] = num%16+'0';
else{
switch(num%16){
case 10:
str[counter] = 'a';
break;
case 11:
str[counter] = 'b';
break;
case 12:
str[counter] = 'c';
break;
case 13:
str[counter] = 'd';
break;
case 14:
str[counter] = 'e';
break;
case 15:
str[counter] = 'f';
break;
}
}
num = num/16;
counter++;
}
printf("Hexadecimal: ");
while(counter>=0){
printf("%c",str[counter]);
counter--;
}
printf("\n");
return;
}
void num14(void)
{
int num,base;
printf("Enter a Number: ");
scanf(" %i",&num);
printf("Enter the Base: ");
scanf(" %i",&base);
switch(base){
case 2:
convertToBinary(num);
break;
case 8:
convertToOctal(num);
break;
case 16:
convertToHexadical(num);
break;
}
return;
}
struct num15{
int number;
int finish;
struct num15* next;
};
void numm15(void){
struct num15 *current=NULL, *head=NULL;
char str[100];
char *token;
int countLeft=0;
printf("Enter: ");
scanf("%s",str);
token = strtok(str,",");
while(token){
countLeft++;
current = malloc(sizeof(struct num15));
current->number = atoi(token);
current->next = head;
head = current;
token = strtok(NULL,",");
}
int min=0,pass=0;
while(countLeft!=0){
while(current){
if(current->finish!=1){
min = current->number;
break;
}
current = current->next;
}
current = head;
while(current){
if(current->number<min&¤t->finish!=1){
min = current->number;
}
current = current->next;
}
current = head;
while(current){
if(current->number==min){
if(pass!=0) printf(",%i",min);
else{
printf("%i",min);
pass = 1;
}
current->finish = 1;
countLeft--;
}
current = current->next;
}
current = head;
}
printf("\n");
return;
}
struct Circle{
int r;
int y;
int x;
struct Circle *next;
};
struct temp{
int x;
struct temp *next;
};
int intersectCircle(int x1,int x2,int y1,int y2,int r1,int r2){
int pass=0;
if(pow(r1+r2,2)>=pow(x1-x2,2)+pow(y1-y2,2)&&pow(x1-x2,2)+pow(y1-y2,2)>=pow(r1-r2,2)) pass=1;
return pass;
}
void num16(void){
struct Circle *current,*current2,*head=NULL;
struct temp *tem,*tempHead=NULL;
int counter = 1;
char str[256];
printf("Enter x: ");
fgets(str,256,stdin);
str[strlen(str)-1] = '\0';
char* token= strtok(str, ",");
while (token) {
tem = (struct temp *)malloc(sizeof(struct temp));
tem->x = atoi(token);
tem->next = tempHead;
tempHead = tem;
token = strtok(NULL, ",");
}
while(tem){
current = (struct Circle *)malloc(sizeof(struct Circle));
current->x = tem->x;
current->next = head;
head = current;
tem = tem->next;
}
printf("Enter y: ");
fgets(str,256,stdin);
str[strlen(str)-1] = '\0';
token= strtok(str, ",");
while(current){
current->y = atoi(token);
current = current->next;
token = strtok(NULL, ",");
}
current = head;
printf("Enter r: ");
fgets(str,256,stdin);
str[strlen(str)-1] = '\0';
token= strtok(str, ",");
while(current){
current->r = atoi(token);
current = current->next;
token = strtok(NULL, ",");
}
current = head;
current2 = current;
int max = 0;
int great = 0,gx,gy,gr;
while(current){
while(current2){
int pass = intersectCircle(current->x,current2->x,current->y,current2->y,current->r,current2->r);
if(pass==1){
max++;
}
current2 = current2->next;
}
current2 = head;
if(great<max){
great = max;
gx = current->x;
gy = current->y;
gr = current->r;
}
max = 0;
current = current->next;
}
printf("(%i,%i,%i) with %i intersection to other circles\n",gx,gy,gr,great-1);
free(current);
free(head);
free(tem);
free(tempHead);
return;
}
void num17(void){
struct Circle *current,*head=NULL;
struct temp *tem,*tempHead=NULL;
int counter = 1;
char str[256];
printf("Enter x: ");
fgets(str,256,stdin);
str[strlen(str)-1] = '\0';
char* token= strtok(str, ",");
while (token) {
tem = (struct temp *)malloc(sizeof(struct temp));
tem->x = atoi(token);
tem->next = tempHead;
tempHead = tem;
token = strtok(NULL, ",");
}
while(tem){
current = (struct Circle *)malloc(sizeof(struct Circle));
current->x = tem->x;
current->next = head;
head = current;
tem = tem->next;
}
printf("Enter y: ");
fgets(str,256,stdin);
str[strlen(str)-1] = '\0';
token= strtok(str, ",");
while(current){
current->y = atoi(token);
current = current->next;
token = strtok(NULL, ",");
}
current = head;
printf("Enter r: ");
fgets(str,256,stdin);
str[strlen(str)-1] = '\0';
token= strtok(str, ",");
while(current){
current->r = atoi(token);
current = current->next;
token = strtok(NULL, ",");
}
current = head;
float x1,x2,xf,y1,y2,yf,r1,r2,rf,d;
x1 = current->x;
y1 = current->y;
r1 = current->r;
current = current->next;
while(current){
x2 = current->x;
y2 = current->y;
r2 = current->r;
if(r2>r1){
float temp;
temp = r2;
r2 = r1;
r1 = temp;
temp = x2;
x2 = x1;
x1 = temp;
temp = y2;
y2 = y1;
y1 = temp;
}
d = sqrt(pow(x2-x1,2)+pow(y2-y1,2));
if((r1+r2+d)>2*r1){
rf = (d+r1+r2)/2;
xf = (x1+x2)/2;
yf = (y1+y2)/2;
x1 = xf;
y1 = yf;
r1 = rf;
}
current = current->next;
}
current = head;
printf("\n(%f,%f,%f)\n",x1,y1,r1);
free(current);
// free(head);
free(tem);
free(tempHead);
return;
}
void getKeys(char l){
if(l=='a') printf("2");
else if(l=='b') printf("22");
else if(l=='c') printf("222");
else if(l=='d') printf("3");
else if(l=='e') printf("33");
else if(l=='f') printf("333");
else if(l=='g') printf("4");
else if(l=='h') printf("44");
else if(l=='i') printf("444");
else if(l=='j') printf("5");
else if(l=='k') printf("55");
else if(l=='l') printf("555");
else if(l=='m') printf("6");
else if(l=='n') printf("66");
else if(l=='o') printf("666");
else if(l=='p') printf("7");
else if(l=='q') printf("77");
else if(l=='r') printf("777");
else if(l=='s') printf("7777");
else if(l=='t') printf("8");
else if(l=='u') printf("88");
else if(l=='v') printf("888");
else if(l=='w') printf("9");
else if(l=='x') printf("99");
else if(l=='y') printf("999");
else if(l=='z') printf("9999");
else if(l=='\n') printf("\n");
else printf("0");
}
void num18(void){
char str[1000];
printf("Enter String: ");
scanf(" %s",str);
int len = strlen(str),x;
for(x=0;x<len;x++) getKeys(str[x]);
return;
}
void num19(void)
{
char string[100];
int sched[100], current, i, j, k;
printf("Enter schedule");
fgets(string,100,stdin);
i = 0;
j = 0;
while (i < strlen(string))
{
if ( isdigit(string[i]) && string[i + 1] == ':' && isdigit(string[i + 2]) && isdigit(string[i + 3]) && string[i + 4] == 'p' )
{
int a = string[i], b = string[i + 2], c = string[i + 3];
current = (a - 48)*100 + (b - 48)*10 + (c - 48) + 1200;
sched[j] = current;
j++;
i = i + 5;
}
else if ( isdigit(string[i]) && string[i + 1] == ':' && isdigit(string[i + 2]) && isdigit(string[i + 3]))
{
int a = string[i], b = string[i + 2], c = string[i + 3];
current = (a - 48)*100 + (b - 48)*10 + (c - 48);
sched[j] = current;
j++;
i = i + 4;
}
else if ( isdigit(string[i]) && isdigit(string[i + 1]) > 0 && string[i + 2] == ':' && isdigit(string[i + 3]) && isdigit(string[i + 4]))
{
int a = string[i], b = string[i + 1], c = string[i + 3], d = string[i + 4];
current = (a - 48)*1000 + (b - 48)*100 + (c - 48)*10 + (d - 48);
sched[j] = current;
j++;
i = i + 5;
}
else if ( isdigit(string[i]) && isdigit(string[i + 1]) > 0 && isdigit(string[i + 2]) > 0 && isdigit(string[i + 3]))
{
int a = string[i], b = string[i + 1], c = string[i + 2], d = string[i + 3];
current = (a - 48)*1000 + (b - 48)*100 + (c - 48)*10 + (d - 48);
sched[j] = current;
j++;
i = i + 4;
}
else if ( isdigit(string[i]) && isdigit(string[i + 1]) == 0 && isdigit(string[i + 2]) == 0 && string[i + 3] == 'p')
{
int a = string[i], b = string[i + 1], c = string[i + 2];
current = (a - 48)*100 + (b - 48)*10 + (c - 48) + 1200;
sched[j] = current;
j++;
i = i + 4;
}
else if ( isdigit(string[i]) && isdigit(string[i + 1]) > 0 && isdigit(string[i + 2]) > 0 && string[i + 3] == 'p')
{
int a = string[i], b = string[i + 1], c = string[i + 2];
current = (a - 48)*100 + (b - 48)*10 + (c - 48) + 1200;
sched[j] = current;
j++;
i = i + 4;
}
else if ( isdigit(string[i]) && isdigit(string[i + 1]) > 0 && isdigit(string[i + 2]) > 0)
{
int a = string[i], b = string[i + 1], c = string[i + 2];
current = (a - 48)*100 + (b - 48)*10 + (c - 48);
sched[j] = current;
j++;
i = i + 3;
}
else if ( isdigit(string[i]) && isdigit(string[i + 1]) > 0)
{
int a = string[i], b = string[i + 1];
current = (a - 48)*1000 + (b - 48)*100;
sched[j] = current;
j++;
i = i + 2;
}
else if ( isdigit(string[i]) && string[i + 1] == 'p')
{
int a = string[i];
current = (a - 48)*100 + 1200;
sched[j] = current;
j++;
i = i + 2;
}
else if ( isdigit(string[i]) )
{
int a = string[i];
current = (a - 48)*100;
sched[j] = current;
j++;
i++;
}
else
{
i++;
}
}
k = 0;
while (k < j)
{
i = 0;
while(i < (j - 1))
{
if (sched[i] > sched[i + 1])
{
int mem;
mem = sched[i];
sched[i] = sched[i + 1];
sched[i + 1] = mem;
}
i++;
}
k++;
}
i =1;
while (i < j - 1)
{
if (sched[i] >= 1300 && 1300 <= sched[i + 1])
{
printf("%dp - %dp, ", sched[i] - 1200, sched[i+ 1] - 1200);
i = i + 2;
}
else if (sched[i] >= 1200 && sched[i + 1] >= 1300)
{
printf("%dp - %dp, ", sched[i], sched[i + 1] - 1200);
i = i + 2;
}
else if (sched[i] >= 1200 && sched[i + 1] >= 1200)
{
printf("%dp - %dp, ", sched[i], sched[i + 1]);
i = i + 2;
}
else if (sched[i + 1] >= 1300)
{
printf("%da - %dp, ", sched[i], sched[i + 1] - 1200);
i = i + 2;
}
else if (sched[i + 1] >= 1200)
{
printf("%da - %dp, ", sched[i], sched[i + 1]);
i = i + 2;
}
else
{
printf("%da - %da, ", sched[i], sched[i + 1]);
i = i + 2;
}
}
if (sched[j - 1] != 2000)
{
if (sched[j - 1] >= 1300)
{
printf("%dp - 8p", sched[j - 1] - 1200);
}
else if (sched[j - 1] >= 1200)
{
printf("%dp - 8p", sched[j - 1]);
}
else
{
printf("%da - 800p", sched[j - 1]);
}
}
printf("\n");
return;
}
struct storage{
char word[100];
int count;
struct storage *next;
};
void num20(void){
char str[1000];
FILE *fp;
struct storage *current=NULL, *head=NULL;
fp = fopen("20.txt","w");
printf("Enter string: ");
fgets(str,1000,stdin);
fputs(str,fp);
fclose(fp);
fp = fopen("20.txt","r");
char c;
do{
c = fscanf(fp,"%s",str);
if(c!=EOF){
int pass = 0;
while(current){
if(strcmp(current->word,str)==0){
current->count = current->count + 1;
pass = 1;
current = head;
break;
}
current = current->next;
}
if(pass==0){
current =malloc(sizeof(struct storage));
strcpy(current->word,str);
current->count = 1;
current->next = head;
head = current;
}
}
}while(c!=EOF);
while(current){
if(current->next)
printf("%s %i, ",current->word,current->count);
else
printf("%s %i ",current->word,current->count);
current = current->next;
}
return;
}
int main(void){
while(true){
printf("\n\nCS 11 Project Menu: \n");
printf("\t1 Rightmost zoroes\n");
printf("\t2 Intersection of line\n");
printf("\t3 Prime Factorization\n");
printf("\t4 Subset\n");
printf("\t5 Product of two polynomials\n");
printf("\t6 Mabu\n");
printf("\t7 Fraction less than 1\n");
printf("\t8 Shortest Distance\n");
printf("\t9 Pascals Triangle\n");
printf("\t10 Roman Numerals\n");
printf("\t11 Egyptian Fraction\n");
printf("\t12 Least Number of Denominations\n");
printf("\t13 Sum of two numbers\n");
printf("\t14 Decimal number converter\n");
printf("\t15 Sorting numbers\n");
printf("\t16 Intersection of circle\n");
printf("\t17 Smallest Circle\n");
printf("\t18 Keypad\n");
printf("\t19 Break time\n");
printf("\t20 Word frequency\n");
printf("\t21 Exit Program\n");
printf("Choice: ");
int ans;
scanf("%i",&ans);
printf("\n\n\n");
switch(ans){
case 1:
num1();
break;
case 2:
num2();
break;
case 3:
num3();
break;
case 4:
printf("Unfinished Business! :(\n");
break;
case 5:
num5();
break;
case 6:
num6();
break;
case 7:
num7();
break;
case 8:
num8();
break;
case 9:
num9();
break;
case 10:
num10();
break;
case 11:
num11();
break;
case 12:
num12();
break;
case 13:
getchar();
num13();
break;
case 14:
num14();
break;
case 15:
numm15();
break;
case 16:
getchar();
num16();
break;
case 17:
getchar();
num17();
break;
case 18:
num18();
break;
case 19:
getchar();
num19();
break;
case 20:
getchar();
num20();
break;
case 21:
return 0;
break;
default:
return 0;
break;
}
}
return 0;
}<file_sep>/*
DULATRE,<NAME>
2014-28334
Section: CS11-THVW
Sorted Rational Roots of a Univariate Polynomial
*/
#include <stdio.h>
#include <math.h>
#include <stdbool.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#define wspace scanf("%*[^\n]")
void factors(double collector[10][100],int num,int y){
/*
Get the factors of num
and populate the layer of collector[y][~]
*/
int index=0,x;
for(x=1;x<=sqrt(num);x++){
if(num%x==0){
collector[y][index]=x;
index++;
if(x!=(num/x)){
collector[y][index]=num/x;
index++;
}
}
}
}
void distribute(double collector[10][100]){
int x,y,index=0;
/*
Pairs the factors of the layer collector[2][~]to collector[3][~],
collector[4][~] quotient of collector[2][~]/collector[3][~],
collector[6][~] gets the value of collector[2][~],
collector[7][~] gets the value of collector[2][~],
*/
for(y=0;collector[3][y]!=0;y++){
for(x=0;collector[2][x]!=0;x++){
collector[4][index]=collector[2][x]/collector[3][y];
collector[6][index]=collector[2][x];
collector[7][index]=collector[3][y];
index++;
}
}
}
void sortHighLow(double collector[10][100]){
int x,y,index=0,limit=0,save_index;
float max;
/*
Generate the negative counterpart of the possible roots
and sort them into highest to lowest
and put them to appropriate collector layers for storage.
*/
for(x=0;collector[4][x]!=0;x++) limit++;
for(x=0;x<=limit;x++){
for(y=0,max=0;y<=limit;y++){
if(max<collector[4][y]){
max = collector[4][y];
save_index = y;
}
}
collector[5][index]=max;
collector[2][index]=collector[6][save_index];
collector[3][index]=collector[7][save_index];
index++;
collector[5][index]=-max;
collector[2][index]=-collector[6][save_index];
collector[3][index]=collector[7][save_index];
if(collector[5][index-1]==collector[5][index]) index=index-2;
collector[4][save_index] = 0;
index++;
}
}
void sortLowHigh(double collector[10][100],int limit){
int index=0,correct;
float temp;
while(true){//sort the answer form lowest to answer
if(index=limit-1){
index = 0;
correct = 0;
}else;
int a = collector[8][index];
int b = collector[8][index+1];
if(collector[2][a]/collector[3][a]>collector[2][b]/collector[3][b]){
temp = collector[8][index+1];
collector[8][index+1] = collector[8][index];
collector[8][index] = temp;
}
else correct++;
index++;
if(correct==limit-1) break;
}
for(index=0;index<limit;index++){//loop that display the sorted roots
int a = collector[8][index];
int b = collector[8][index-1];
if((collector[2][b]<0) && (collector[2][a]>0) && (collector[1][0]==0)){//checks if zero is a root
printf("0,");
}
printf("%.0f/%.0f,",collector[2][a],collector[3][a]);
}
}
void checker(double collector[10][100],int limit){
float answer=0;
int x,y,z=0;
/*
Isolate the roots from the array of possible roots
if there is only one root > immediately display the root
if there is none > display appropriate message
otherwise if will pass the roots to sortLowHigh() with the numbers of root
*/
for(y=0;collector[5][y]!=0;y++){
for(x=0,answer=0;x<=limit;x++){
answer = answer + collector[1][x]*pow(collector[5][y],x);
}
if(answer<0) answer = -answer;
else;
if(floor(answer*pow(10,6))<=1){
collector[8][z] = y;
z++;
}
}
if(z==1){
int a = collector[8][0];
printf("\n\x1b[32mThe rational roots of the input polynomial are: \n\x1b[0m");
printf("%.0f/%.0f",collector[2][a],collector[3][a]);
}
else if(z==0){
printf("\nThe input polynomial has no rational roots.");
}
else{
printf("\n\x1b[32mThe rational roots of the input polynomial are: \n\x1b[0m");
sortLowHigh(collector,z);
}
}
int main(void){
double collector[10][100];//this is the main variable cuz it holds the whole process
char container[100],answer[10],degree[30],temp[20];
int x=0,y=0,counter=0,rx,ry;
while(true){//this loop will continue until the user wish end the program by not by inputting 'yes'
system("clear");//code that will clear the screen
for(rx=0;rx<10;rx++){ //loop that will reset the collector
for(ry=0;ry<100;ry++) collector[rx][ry] = 0;
}
printf("\x1b[32mEnter the highest degree of the input polynomial: \x1b[0m");
while(true){
/*
This loop will continue ask the user to input positive integer
Otherwise, it will display appropriate error msg
*/
scanf("%s",degree);
wspace;
if(atoi(degree)<0){
system("clear");
printf("\x1b[31mPlease input a positive integer!\x1b[0m\n");
printf("\x1b[32m\nEnter the highest degree of the input polynomial: \x1b[0m");
continue;
}
else if(strcmp(degree,"0")==0){
system("clear");
printf("\x1b[31mZero is neither a positive or negative integer!\x1b[0m\n");
printf("\x1b[31mPlease input a positive integer!\x1b[0m\n");
printf("\x1b[32m\nEnter the highest degree of the input polynomial: \x1b[0m");
continue;
}
else if(atoi(degree)==0){
system("clear");
printf("\x1b[31mCharacters are never been positive integer at all!\x1b[0m\n");
printf("\x1b[31mPlease input a positive integer!\x1b[0m\n");
printf("\x1b[32m\nEnter the highest degree of the input polynomial: \x1b[0m");
continue;
}
break;
}
printf("\n\x1b[32mEnter %i integer coefficients starting from the 0th degree.\x1b[0m\n",atoi(degree)+1);
printf("\x1b[32mSeparate each input by a comma: \x1b[0m");
while(true){
/*
This loop will continue ask the user to enter coefficients properly
and store the coefficients in the array collector[1]
Otherwise, it will display appropriate error msg
*/
scanf("%s",container);
wspace;
int index,pass=0;
for(index=0,counter=0,pass=0,y=0;index<=strlen(container);index++){
switch(container[index]){
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
case '0':
case '-':
temp[x] = container[index];
x++;
continue;
case ',':
case '\0':
if(atoi(temp)!=0||temp[0]=='0'){
temp[x]='\0';
x=0;
counter++;
collector[1][y]=atoi(temp);
y++;
temp[x]='k';
continue;
}
else{
pass=1;
break;
}
default:
pass=1;
break;
}
}
if(pass==1||counter!=atoi(degree)+1){
printf("\x1b[31m\nPlease input properly!\n\x1b[0m");
printf("\x1b[32mEnter %i integer coefficients starting from the 0th degree.\n\x1b[0m",atoi(degree)+1);
printf("\x1b[32mSeparate each input by a comma: \x1b[0m");
continue;
}
break;
}
int z=0;
while(true){//checks if the first coefficient entered is 0
if(collector[1][z]==0){
z++;
continue;
}
else break;
}
factors(collector,abs(collector[1][z]),2);
factors(collector,abs(collector[1][atoi(degree)]),3);
distribute(collector);
sortHighLow(collector);
checker(collector,atoi(degree));
printf("\n\n\x1b[32mInput new polynomial? \x1b[0m");
scanf("%s",answer);
wspace;
int a;
for(a=0;a<strlen(answer);a++) answer[a] = toupper(answer[a]);//converts each letter in answer to Capital Letter
if(strcmp(answer,"YES")==0) continue;
else break; //exit the while loop if others the user input other strings other than YES
}
system("clear");
printf("\x1b[32mBYE!\x1b[0m\n");
return 0;
} | c464a08115dbc63f3e223d94447992127f1724c2 | [
"C"
] | 3 | C | kldulatre/CS11 | b46cd45bd9ef9890e7289f7ab19c84171086f408 | 61ac632256ec08beb8602972c384e2e0eec844c8 |
refs/heads/master | <repo_name>jeed300/SG90<file_sep>/MT_X1.py
import pigpio
import time
pi = pigpio.pi()
def setup():
pi.set_servo_pulsewidth(4, 1300) #armall center1300
time.sleep(3)
pi.set_servo_pulsewidth(13, 1500) #armhight 1500
time.sleep(3)
pi.set_servo_pulsewidth(5, 1000) #arm position
time.sleep(3)
pi.set_servo_pulsewidth(6,800) #arm grab
time.sleep(3)
def main():
print("setup start...")
setup()
print("setup end...")
print("X start!")
pi.set_servo_pulsewidth(13, 2000)
time.sleep(3)
print("X arm get end...")
<file_sep>/Main_Screen/python/mv_bw.py
import RPi.GPIO as GPIO
import time
import smbus
I2C_ADDR = 0x3f # LCD Device
LCD_WIDTH = 16 # Maximum characters per line
LCD_CHR = 1 # MODE: Sending data
LCD_CMD = 0 # MODE: Sending command
LCD_LINE_1 = 0x80 # LCD RAM address for the 1st line
LCD_LINE_2 = 0xC0 # LCD RAM address for the 2nd line
LCD_LINE_3 = 0x94 # LCD RAM address for the 3rd line
LCD_LINE_4 = 0xD4 # LCD RAM address for the 4th line
LCD_BACKLIGHT = 0x08 # ON
#LCD_BACKLIGHT = 0x00 # OFF
ENABLE = 0b00000100
# Timing constants
E_PULSE = 0.0005
E_DELAY = 0.0005
# Open I2C interface
bus = smbus.SMBus(1) # Rev 2 Pi uses 1
MOTOR1_F = 23
MOTOR1_B = 24
MOTOR2_F = 27
MOTOR2_B = 22
def setup():
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BCM)
GPIO.setup(MOTOR1_F, GPIO.OUT, initial=GPIO.LOW)
GPIO.setup(MOTOR1_B, GPIO.OUT, initial=GPIO.LOW)
GPIO.setup(MOTOR2_F, GPIO.OUT, initial=GPIO.LOW)
GPIO.setup(MOTOR2_B, GPIO.OUT, initial=GPIO.LOW)
print("Finished set up...")
def lcd_init():
# Initialize display
lcd_byte(0x33, LCD_CMD)
lcd_byte(0x32, LCD_CMD)
lcd_byte(0x06, LCD_CMD)
lcd_byte(0x0C, LCD_CMD)
lcd_byte(0x28, LCD_CMD)
lcd_byte(0x01, LCD_CMD)
time.sleep(E_DELAY)
def lcd_byte(bits, mode):
bits_high = mode | (bits & 0xF0) | LCD_BACKLIGHT
bits_low = mode | ((bits << 4) & 0xF0) | LCD_BACKLIGHT
bus.write_byte(I2C_ADDR, bits_high)
lcd_toggle_enable(bits_high)
bus.write_byte(I2C_ADDR, bits_low)
lcd_toggle_enable(bits_low)
def lcd_toggle_enable(bits):
time.sleep(E_DELAY)
bus.write_byte(I2C_ADDR, (bits | ENABLE))
time.sleep(E_PULSE)
bus.write_byte(I2C_ADDR, (bits & ~ENABLE))
time.sleep(E_DELAY)
def lcd_string(message, line):
message = message.ljust(LCD_WIDTH, " ")
lcd_byte(line, LCD_CMD)
for i in range(LCD_WIDTH):
lcd_byte(ord(message[i]), LCD_CHR)
# main function
def main():
print("Start...")
setup()
# Initialize lcd display
lcd_init()
# lcd_string("Hello", LCD_LINE_1)
# lcd_string(" RPC", LCD_LINE_2)
# time.sleep(2)
# lcd_string("Provided by", LCD_LINE_1)
# lcd_string("PICason", LCD_LINE_2)
# time.sleep(2)
GPIO.output(MOTOR1_F, GPIO.LOW)
GPIO.output(MOTOR2_F, GPIO.LOW)
GPIO.output(MOTOR1_B, GPIO.HIGH)
GPIO.output(MOTOR2_B, GPIO.HIGH)
print("MOTOR moving backward...")
lcd_string("MOTOR backward ", LCD_LINE_1)
# time.sleep(5)
# GPIO.output(MOTOR1_F, GPIO.LOW)
# GPIO.output(MOTOR2_F, GPIO.LOW)
# print("MOTOR stopping...")
# lcd_string("MOTOR STOP ", LCD_LINE_1)
# time.sleep(2)
# Execute methods
if __name__ == '__main__':
try:
main()
except KeyboardInterrupt:
pass
finally:
print("finished mv_bw.py")
<file_sep>/Main_Screen/php/move_backward.php
<?php exec('sudo python ../python/mv_bw.py'); ?>
<html>
<head>
<title>Let's Start RPC</title>
<link rel="stylesheet" type="text/css" href="../css/style.css">
</head>
<body>
<div class="switch">
<div class="body">
<div class="volume"></div>
<div class="screen">
<div class="stream">
<!-- Display a stream on here. -->
<img src="http://192.168.10.135:8081">
</div>
<!--
<div class="logo">
<div class="icon">
<div class="icon-part left">
</div>
<div class="icon-part right"></div>
</div>
<h1><span>Nintendo</span>Switch</h1>
</div>
-->
</div>
</div>
<div class="joy-con left">
<div class="button-group">
<div class="button arrow up">
<form method="post" action="move_forward.php">
<input type="submit" name="btn_forward" value="forward">
</form>
</div>
<div class="button arrow right">
<form method="post" action="move_right.php">
<input type="submit" name="btn_right" value="right">
</form>
</div>
<div class="button arrow down">
<form method="post" action="move_backward.php">
<input type="submit" name="btn_down" value="backward">
</form>
</div>
<div class="button arrow left">
<form method="post" action="move_left.php">
<input type="submit" name="btn_left" value="left">
</form>
</div>
</div>
<div class="stick"></div>
<div class="select"></div>
<div class="capture">
<form method="post" action="move_stop.php">
<input type="submit" name="btn_stop" value="stop">
</form>
</div>
<div class="shoulder l"></div>
</div>
<div class="joy-con right">
<div class="button-group">
<div class="button letter" data-letter="X"></div>
<div class="button letter" data-letter="Y"></div>
<div class="button letter" data-letter="A"></div>
<div class="button letter" data-letter="B">
<!-- <form method="post" action="move_stop.php">
<input type="submit" name="btn_stop" value="stop">
</form> -->
</div>
</div>
<div class="stick"></div>
<div class="start"></div>
<div class="home"></div>
<div class="shoulder r"></div>
</div>
</div>
</body>
</html>
<file_sep>/MT_A1.py
import pigpio
import time
pi = pigpio.pi()
def setup():
pi.set_servo_pulsewidth(4, 1300) #armall center1300
time.sleep(3)
pi.set_servo_pulsewidth(13, 2000) #armhight 1500
time.sleep(3)
pi.set_servo_pulsewidth(5, 1500) #arm position
time.sleep(3)
pi.set_servo_pulsewidth(6,1500) #arm grab
time.sleep(3)
def main():
print("setup start...")
setup()
print("setup end...")
print("A start!")
print("arm get start...")
pi.set_servo_pulsewidth(4,1300)
time.sleep(3)
pi.set_servo_pulsewidth(13, 1500)
time.sleep(3)
pi.set_servo_pulsewidth(5, 1000)
time.sleep(3)
pi.set_servo_pulsewidth(6,800)
time.sleep(3)
print("A arm get end...") | a13bbcd06a0c20c0180390250258c961ede09ea8 | [
"Python",
"PHP"
] | 4 | Python | jeed300/SG90 | 33bba251f6854d10295717717d5b8b374257a201 | 5867463aa84ed31d723f88aca1044c2817db77e1 |
refs/heads/main | <file_sep>import pandas as pd
import requests
import bs4 as BeautifulSoup
url = 'https://tanvir-anzum.web.app'
page = requests.get(url)
pageContent = page.content
soup= BeautifulSoup.BeautifulSoup(page.content, 'html.parser')
link_list = soup.find_all('a')
for link in link_list:
if 'href' in link.attrs:
print(str(link.attrs['href']+'\n'))
| 0738871242fe86da040a6cdb157c7f5e13df8fdb | [
"Python"
] | 1 | Python | Anjum-cse/BeautifulSoup-in-Python | da9f21293a40b6e331a4265d1d1ab34ae25971e4 | f6176140279da4c3cc1e61dd79e32fda3836fefb |
refs/heads/main | <file_sep>import Head from 'next/head'
import { Layout } from '../components/Layout'
import episodes from '../data/podcasts.json'
import { AudioPlayer } from '../components/AudioPlayer'
const Episodes = () => {
return (
<div>
<h1 className="text-2xl font-semibold text-gray-800">About:</h1>
<p className="text-gray-500 font-normal">
In this podcast I discuss how startups are increasingly impacting the
financial climate. I talk to a wide range of industry leaders, chatting
about topic that range from new crypto soultions to discussions about
why V.C. money is, or is not benificial for seed stage companies.
</p>
<h1 className="mt-4 text-2xl font-semibold text-gray-800">Episodes:</h1>
{episodes.map((episode, i) => (
<AudioPlayer key={i} index={i + 1} {...episode} />
))}
</div>
)
}
const Bibliography = () => {
return (
<div>
<h1 className="text-2xl font-semibold text-gray-800">
Annotated Bibliography:
</h1>
<div className="mt-4">
<h3 className="font-semibold">
<NAME>. 2012. “How to get startup ideas.” <NAME>.
</h3>
<a
href="http://www.paulgraham.com/startupideas.html"
className="text-indigo-500"
target="_blank"
>
http://www.paulgraham.com/startupideas.html
</a>
<p>
In this essay Graham talks about how to make a successful startup
idea. The basic idea behind it is identifying a problem you face in
your everyday life. Graham believes that the best startup ideas come
from necessity; they are organic and come from a lack of solutions in
the market. In the end, he gets to the root of how unglorious early
startup life really is, mentioning long hours and strenuous
situations.
</p>
</div>
<div className="mt-4">
<h3 className="font-semibold">
<NAME>. “JPMorgan Chase Moves to Be First Big U.S. Bank
With Its Own Cryptocurrency.” New York Times.
</h3>
<a
className="text-indigo-400"
target="_blank"
href="https://www.nytimes.com/2019/02/14/business/dealbook/jpmorgan-cryptocurrency-bitcoin.html"
>
https://www.nytimes.com/2019/02/14/business/dealbook/jpmorgan-cryptocurrency-bitcoin.htmlnpx
</a>
<p>
The content of this new story is really important, and the sub-context
is really interesting to look at. When we studied in class what
creates a bubble, one of the reasons is a financial-technical
innovation. What we see here from one of the oldest banks, J.P.
Morgan, is the integration of their own "stablecoin". The coin will
match the dollar and allow a new easy of access to transferring money.
I do think, despite the upsides, this is a slippery slope. When a
stablecoin is minted, is a dollar must always be held in a bank
account, to give the coin value. If we see banks go out and start
trading your money, it could leave stablecoin in a very dangerous
spot. I also wonder how they will deal with the ledger, a{' '}
<i>public</i> database of all transactions that happen, based on
ethereum. This could clearly lead to some pretty serious privacy
concerns that the author mentions.
</p>
</div>
<div className="mt-4">
<h3 className="font-semibold">
<NAME>. “Why The Best Startups Are Created In An Economic
Downturn.” <NAME>.
</h3>
<a
className="text-indigo-400"
target="_blank"
href="https://www.danmartell.com/why-the-best-startups-are-created-in-an-economic-downturn/"
>
https://www.danmartell.com/why-the-best-startups-are-created-in-an-economic-downturn/
</a>
<p>
This piece by <NAME> struck me how an economic downturn forces
the talent pool to shrink, which then makes the employees better. He
also claims a downturn forces people who are “true entrepreneurs” to
show their true colors and create a high-quality startup, out of
necessity and urgency. This idea is similar to that of <NAME>, in
that, the best businesses are created out of a real world problem.
</p>
</div>
<div className="mt-4">
<h3 className="font-semibold">
Duhigg, Charles. “How Venture Capitalists Are Deforming Capitalism.”
The New Yorker.
</h3>
<a
className="text-indigo-400"
target="_blank"
href="https://www.newyorker.com/magazine/2020/11/30/how-venture-capitalists-are-deforming-capitalism"
>
https://www.newyorker.com/magazine/2020/11/30/how-venture-capitalists-are-deforming-capitalism
</a>
<p>
Duhigg gives a great anecdote by mentioning WeWork, a company that
originally looked promising to many investors, mainly Softbank.
Softbank is infamous for outbidding competitors by a vast margin. This
hikes up the evaluation, and disguises the underlying problems, which,
in WeWork's cases, were quite significant.
</p>
</div>
<div className="mt-4">
<h3 className="font-semibold">
Florida, Richard. “The Benefits of High-Tech Job Growth Don’t Trickle
Down.” Bloomburg CityLab.
</h3>
<a
className="text-indigo-400"
target="_blank"
href="https://www.bloomberg.com/news/articles/2019-08-08/low-wage-workers-lose-out-when-tech-jobs-gain"
>
https://www.bloomberg.com/news/articles/2019-08-08/low-wage-workers-lose-out-when-tech-jobs-gain
</a>
<p>
A term you hear a lot nowadays, "trickle-down economics", may not work
in tech, according to a new study. Mr. Florida dives into the study,
stating that while teachers create a multiple of 2 low-pay jobs for
every one teaching position, while those in tech only make 0.7. This
makes sense, unlike more physical high-pay jobs (store managers,
general managers) which can create smaller paying offshoots (janitors,
cashiers). Tech is all done online, which means all the customer needs
to interact with the business is a computer.
</p>
</div>
<div className="mt-4">
<h3 className="font-semibold">
Castillo, <NAME>. “Visa Partners With Ethereum Digital-Dollar
Startup That Raised $271 Million.” Forbes.
</h3>
<a
className="text-indigo-400"
target="_blank"
href="https://www.forbes.com/sites/michaeldelcastillo/2020/12/02/visa-partners-with-ethereum-digital-dollar-startup-that-raised-271-million/?sh=6ac7b4a14b1f"
>
https://www.forbes.com/sites/michaeldelcastillo/2020/12/02/visa-partners-with-ethereum-digital-dollar-startup-that-raised-271-million/?sh=6ac7b4a14b1f
</a>
<p>
This news story reports on a recent partnership between one of the
creators of USDC, a newly minted stablecoin, and Visa. What this means
for customers of Visa is that they can begin to integrate USDC, which
is based on ethereum, another form of bitcoin into their software.
USDC is almost the opposite of bitcoin, it matches the US dollar
exactly. The reason why this is very exciting is because that it is a
crypto coin, it isn't subject to the same fees that would come with
sending money in a more traditional way (eg. wire transfer).
</p>
</div>
<div className="mt-4">
<h3 className="font-semibold">
<NAME>. “Innovation and Startups in Silicon Valley: An Ecosystem
Approach.” Accelerators in Silicon Valley, by <NAME>, Amsterdam
University Press, Amsterdam, 2017, pp. 37–62. JSTOR.
</h3>
<a
className="text-indigo-400"
target="_blank"
href="https://www.jstor.org/stable/j.ctt1zrvhk7.7"
>
https://www.jstor.org/stable/j.ctt1zrvhk7.7
</a>
<p>
I think Ester brings up a great point here. Society's growing reliance
on the innovation spurred by silicon valley has created a dangerous
precedent moving forward. He goes on to echo a lot of the points made
by <NAME>, restating that early startup life is often not all it
is chalked up to be. He says the most efficient way to run a startup
is just getting something out of the door, something I've heard often
in my research.
</p>
</div>
<div className="mt-4">
<h3 className="font-semibold">
<NAME>. “The Cautionary Tale of <NAME>umann and WeWork.” New
York Times.
</h3>
<a
className="text-indigo-400"
target="_blank"
href="https://www.nytimes.com/2020/10/23/books/review/billion-dollar-loser-adam-neumann-wework-reeves-wiedeman.html"
>
https://www.nytimes.com/2020/10/23/books/review/billion-dollar-loser-adam-neumann-wework-reeves-wiedeman.html
</a>
<p>
This piece is a must-read for anyone interested in startups, and how
they fail. Similar to the unit "how markets fail", this piece by Kirn
tells the "cautionary" tale of WeWork. A company plagued by
overvaluation and under-deliverance. This created a large divide, and
forced WeWork to be "the landlord and tenet". Their dramatic growth,
with a less-than optimal business plan, all lead to the failure of
WeWork.
</p>
</div>
<div className="mt-4">
<h3 className="font-semibold">
Strebulaev, <NAME>., and <NAME>. 2015. “How Much Does Venture
Capital Drive the U.S. Economy?” Stanford Business.
</h3>
<a
className="text-indigo-400"
target="_blank"
href="https://www.gsb.stanford.edu/insights/how-much-does-venture-capital-drive-us-economy"
>
https://www.gsb.stanford.edu/insights/how-much-does-venture-capital-drive-us-economy
</a>
<p>
In this article the authors discuss the impact of VC money on the US
economy. VC money has infiltrated all of our institutions, with the
private equity sector being the most impacted. In fact, VC funds
invest in a staggering 0.19% of all new US business.
</p>
</div>
<div className="mt-4">
<h3 className="font-semibold">
<NAME>. 2016. “16 Definitions on the Economics of VC.”
<NAME>.
</h3>
<a
className="text-indigo-400"
target="_blank"
href="https://a16z.com/2016/09/11/vc-economics/"
>
https://a16z.com/2016/09/11/vc-economics/
</a>
<p>
This article dives more into how the money flows in and out of VC
funds. The funds starting with LP’s (limited partners) which source
money from various institutions. It also goes on to mention how
important VC money is in funding fast-moving and revolutionary tech
solutions.
</p>
</div>
</div>
)
}
export default function Home() {
return (
<>
<Head>
<title><NAME> Econ Podcast</title>
<link rel="icon" href="/favicon.ico" />
<link rel="stylesheet" href="https://rsms.me/inter/inter.css" />
</Head>
<Layout
tabs={{
Episodes,
Bibliography,
}}
/>
</>
)
}
<file_sep>import React, { useEffect, useRef, useState } from 'react'
import { format } from 'date-fns'
import Image from 'next/image'
const toDateString = (seconds) => {
const date = new Date(null)
date.setSeconds(seconds)
return format(date, 'mm:ss')
}
export const AudioPlayer = ({ audio, cover, title, description, index }) => {
const [isPlaying, setPlaying] = useState(false)
const [progress, setProgress] = useState(0)
const [timestamp, setTimestamp] = useState(0)
const audioPlayerRef = useRef()
const timelineRef = useRef()
const clickedTime = (e) => {
const clickPositionInPage = e.pageX
const timelineStart = timelineRef.current.getBoundingClientRect().left
const timelineWidth = timelineRef.current.offsetWidth
const clickPositionInBar = clickPositionInPage - timelineStart
const timePerPixel = audioPlayerRef.current.duration / timelineWidth
return timePerPixel * clickPositionInBar
}
const handleTimeUpdate = React.useCallback((e) => {
if (timelineRef.current) {
const ratio = e.target.currentTime / e.target.duration
const position =
timelineRef.current.offsetWidth * ratio - timelineRef.current.offsetLeft
setProgress(position)
setTimestamp(Math.floor(e.target.currentTime))
}
}, [])
const handleMouseMove = React.useCallback((e) => {
const clickedPixelTime = clickedTime(e)
console.log(clickedPixelTime, audioPlayerRef.current.duration)
if (clickedPixelTime < audioPlayerRef.current.duration - 5) {
audioPlayerRef.current.currentTime = clickedPixelTime
}
})
const handleMouseUp = React.useCallback(() => {
window.removeEventListener('mousemove', handleMouseMove)
window.removeEventListener('mouseup', handleMouseUp)
})
const handleMouseDown = React.useCallback(() => {
window.addEventListener('mousemove', handleMouseMove)
window.addEventListener('mouseup', handleMouseUp)
}, [])
useEffect(() => {
audioPlayerRef.current.addEventListener('timeupdate', handleTimeUpdate)
return () => {
audioPlayerRef.current &&
audioPlayerRef.current.removeEventListener(
'timeupdate',
handleTimeUpdate,
)
}
}, [audioPlayerRef.current])
return (
<>
<audio src={audio} ref={audioPlayerRef} />
<div className="bg-gray-100 w-full rounded p-4 flex items-center mt-2">
<Image
width={100}
height={100}
className="w-24 h-24 object-cover rounded"
src={cover}
/>
<div className="flex flex-col ml-4 w-full">
<div className="flex items-center">
<div className="flex flex-col">
<span className="font-bold uppercase text-gray-500">
Episode {index}
</span>
<span className="tracking-tight text-xl font-semibold text-gray-900">
{title}
</span>
</div>
<a href={audio} target="_blank" className="ml-auto h-6 w-6">
<svg
xmlns="http://www.w3.org/2000/svg"
fill="none"
viewBox="0 0 24 24"
stroke="currentColor"
className="text-indigo-500 hover:text-indigo-400 transition-colors"
>
<path
strokeLinecap="round"
strokeLinejoin="round"
strokeWidth={2}
d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4"
/>
</svg>
</a>
</div>
<div className="w-full flex justify-center">
<button
className="h-8 w-8 focus:outline-none"
onClick={() => {
if (isPlaying) {
audioPlayerRef.current.pause()
setPlaying(false)
} else {
audioPlayerRef.current.play()
setPlaying(true)
}
}}
>
{isPlaying ? (
<svg
xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 20 20"
fill="currentColor"
className="text-indigo-500 hover:text-indigo-400 transition-colors"
>
<path
fillRule="evenodd"
d="M18 10a8 8 0 11-16 0 8 8 0 0116 0zM7 8a1 1 0 012 0v4a1 1 0 11-2 0V8zm5-1a1 1 0 00-1 1v4a1 1 0 102 0V8a1 1 0 00-1-1z"
clipRule="evenodd"
/>
</svg>
) : (
<svg
xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 20 20"
fill="currentColor"
className="text-indigo-500 hover:text-indigo-400 transition-colors"
>
<path
fillRule="evenodd"
d="M10 18a8 8 0 100-16 8 8 0 000 16zM9.555 7.168A1 1 0 008 8v4a1 1 0 001.555.832l3-2a1 1 0 000-1.664l-3-2z"
clipRule="evenodd"
/>
</svg>
)}
</button>
<div className="relative w-full flex items-center ml-2">
<div
ref={timelineRef}
className="overflow-hidden h-2 w-full text-xs flex rounded bg-indigo-200"
>
<div
style={{ width: `${progress}px` }}
className="flex flex-col text-center whitespace-nowrap text-white justify-center bg-indigo-500"
>
<button
onMouseDown={handleMouseDown}
style={{ marginLeft: `calc(${progress}px - 0.5rem)` }}
className="absolute bg-white rounded-full w-4 h-4 shadow-sm transition duration-250 ease-in-out transform focus:outline-none hover:scale-110"
></button>
</div>
</div>
<span className="ml-2 text-gray-500 text-sm font-medium">
{toDateString(timestamp)}
</span>
</div>
</div>
<p className="text-sm text-gray-600 font-normal">{description}</p>
</div>
</div>
</>
)
}
| afa04b1632bc8baa544d138f0e4286115c54e356 | [
"JavaScript"
] | 2 | JavaScript | lucas8/econ-podcast | 003026ce8d5fc3a1e448582f75c582d61787118f | 8d2858b520ca9e805896f6c5f66c88c187b17dff |
refs/heads/master | <file_sep>using System;
namespace OOP2
{
class Program
{
static void Main(string[] args)
{
GercekMusteri gercekMusteri = new GercekMusteri();
gercekMusteri.MusteriNo = "1xxx";
gercekMusteri.Id = 1;
gercekMusteri.Adi = "Gxxxxx";
gercekMusteri.Soyadi = "Bxxxxx";
gercekMusteri.TcNo = "3xxxxxxxxxxx";
TuzelMusteri tuzelMusteri = new TuzelMusteri();
tuzelMusteri.MusteriNo = "2xxxxx";
tuzelMusteri.Id = 2;
tuzelMusteri.SirketAdi = "Rxxxxx";
tuzelMusteri.VergiNo = "Çxxxxxx";
Musteri yeniMusteri1 = new GercekMusteri();
Musteri yeniMusteri2 = new TuzelMusteri();
MusteriManager musteriManager = new MusteriManager();
musteriManager.Ekle(gercekMusteri);
musteriManager.Ekle(tuzelMusteri);
musteriManager.Ekle(yeniMusteri1);
musteriManager.Ekle(yeniMusteri2);
}
}
}
| 9d6b178096308f4fa988de82d21cb84492173b41 | [
"C#"
] | 1 | C# | Gulsahbb/OOP2 | adbadeeff4fb3077cd63ff255da5293437967cba | b1a10ca6f3cb83b9b1edf7fee29de253fa7fbe6d |
refs/heads/master | <repo_name>SunlayGGX/RobotRebellionWithoutAssets<file_sep>/Source/RobotRebellion/Tool/UtilitaryFunctionLibrary.h
// Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "Kismet/BlueprintFunctionLibrary.h"
#include "UtilitaryFunctionLibrary.generated.h"
/**
*
*/
UCLASS()
class ROBOTREBELLION_API UUtilitaryFunctionLibrary : public UBlueprintFunctionLibrary
{
GENERATED_BODY()
public:
/*
Duplicate an object (exact copy) from a default object. The default objecct will be casted to the objInstance type.
ex :
while(!UUtilitaryFunctionLibrary::duplicateObjectFromDefault(&objInstance, objDefaultStatic, this, TEXT("youhou")))
{
//...
}
*/
template<class Object>
static bool duplicateObjectFromDefault(Object** out, const TSubclassOf<Object>& in, UObject* objectAttachedTo)
{
Object* intermediary = DuplicateObject(in.GetDefaultObject(), objectAttachedTo);
if (intermediary != NULL)
{
*out = intermediary;
return true;
}
return false;
}
/*
Create an object (exact copy) from a default object. Named version.
ex :
while(!UUtilitaryFunctionLibrary::createObjectFromDefault<objInstanceType>(&objInstance, objDefaultStatic, this, TEXT("youhou")))
{
//...
}
*/
template<class Casted, class Object>
static bool createObjectFromDefault(Object** out, const TSubclassOf<Object>& in, UObject* objectAttachedTo, FName name, EObjectFlags RF_flag = RF_Dynamic | RF_ArchetypeObject)
{
Object* intermediary = NewObject<Casted>(objectAttachedTo, name, RF_flag, Cast<Casted>(in.GetDefaultObject()));
if (intermediary != NULL)
{
*out = intermediary;
return true;
}
return false;
}
/*
Create an object (exact copy) from a default object. Same as createObjectFromDefault but with no name specified
*/
template<class Casted, class Object>
static bool createObjectFromDefault(Object** out, const TSubclassOf<Object>& in, UObject* objectAttachedTo, EObjectFlags RF_flag = RF_Dynamic | RF_ArchetypeObject)
{
return createObjectFromDefault<Casted, Object>(out, in, objectAttachedTo, NAME_None, RF_flag);
}
/*
Create an object (exact copy) from a default object. PTR version
ex :
while(!UUtilitaryFunctionLibrary::createObjectFromDefault<objInstanceType>(&objInstance, objDefaultStatic, this, TEXT("youhou")))
{
//...
}
*/
template<class Casted, class Object>
static bool createObjectFromDefault(Object** out, Object* in, UObject* objectAttachedTo, FName name, EObjectFlags RF_flag = RF_Dynamic | RF_ArchetypeObject)
{
Casted* castedIn = Cast<Casted>(in);
if (castedIn)
{
Object* intermediary = NewObject<Casted>(objectAttachedTo, name, RF_flag, castedIn);
if (intermediary != NULL)
{
*out = intermediary;
return true;
}
}
return false;
}
/*
Create an object (exact copy) from a default object. Nameless version
*/
template<class Casted, class Object>
static bool createObjectFromDefault(Object** out, Object* in, UObject* objectAttachedTo, EObjectFlags RF_flag = RF_Dynamic | RF_ArchetypeObject)
{
return createObjectFromDefault<Casted, Object>(out, in, objectAttachedTo, NAME_None, RF_flag);
}
/*
Create an object (exact copy) from a default object. No attachement here. Nameless version
*/
template<class Casted, class Object>
static bool createObjectFromDefaultWithoutAttach(Object** out, UClass* in, FName name = NAME_None)
{
Object* intermediary = NewObject<Casted>((UObject*)GetTransientPackage(), in, name);
if (intermediary != NULL)
{
*out = intermediary;
return true;
}
return false;
}
/*
Randomly applies an effect method from those specified with the parameters equal or above the 3rd parameters
params :
- printMessage : bool => true to print what is the effect (in the order passed by parameter)
- object : the object to those we want to apply methods
- the remaining parameters : method pointer of the object class type. MUST TAKE NO ARGUMENTS
*/
template<size_t count, class ObjectTypeToTest, class ... DelegateObj>
static void randomApplyObjectMethod(bool printMessage, ObjectTypeToTest& object, DelegateObj ... func)
{
constexpr int32 totalSize = sizeof...(func);
if (totalSize == 0)
{
return;
}
decltype(ObtainFirstElemOnAVariadic(func...)) delegateArray[totalSize] = { func... };
float coefficient = (static_cast<float>(totalSize) - 0.001f) / (static_cast<float>(RAND_MAX));
if (printMessage)
{
for (size_t iter = 0; iter < count; ++iter)
{
int32 randomisator = getRandWithCoeff(coefficient);
PRINT_MESSAGE_ON_SCREEN_UNCHECKED(FColor::Blue, "Executing method : " + FString::FromInt(randomisator));
(object.*delegateArray[randomisator])();
}
}
else
{
for (size_t iter = 0; iter < count; ++iter)
{
int32 randomisator = getRandWithCoeff(coefficient);
(object.*delegateArray[randomisator])();
}
}
}
template<class FirstElem, class ... OtherElem>
static constexpr FirstElem ObtainFirstElemOnAVariadic(const FirstElem& first, const OtherElem& ... other)
{
return first;
}
template<class OwnerType, class PtrMethodType>
static void bindServerClientMethodPtr(OwnerType owner, PtrMethodType& ptr, PtrMethodType serverMethod, PtrMethodType clientMethod)
{
ptr = ((owner->Role < ROLE_Authority) ? clientMethod : serverMethod);
}
/*Get the time in milliseconds of the method execution. Pass a lambda*/
template<class Method, class ... Args>
static double profilingTimeFor(Method method, Args&& ... args)
{
double start = FPlatformTime::Seconds();
method(std::forward<Args>(args)...);
double end = FPlatformTime::Seconds();
return (end - start) * 1000.0;
}
/************************************************************************/
/* UFUNCTION */
/************************************************************************/
template<class ReturnType>
UFUNCTION()
static FORCEINLINE ReturnType getRandWithCoeff(ReturnType coeff)
{
return static_cast<ReturnType>(FMath::Rand()) * coeff;
}
static FORCEINLINE void drawObligatoryPersistentLineInWorld(
UWorld* world,
const FVector& start,
const FVector& end,
const FColor& color,
float thickness,
float duration
)
{
if(world->PersistentLineBatcher)
{
world->PersistentLineBatcher->DrawLine(start, end, color, SDPG_Foreground, thickness, duration);
}
}
template<class ActorType>
UFUNCTION()
static FORCEINLINE FVector getBarycenter(const TArray<ActorType*>& actors)
{
FVector bary = FVector::ZeroVector;
for (int32 iter = 0; iter < actors.Num(); ++iter)
{
bary += actors[iter]->GetActorLocation();
}
return bary / actors.Num();
}
};
<file_sep>/Source/RobotRebellion/IA/Navigation/NavigationVolumeGraph.cpp
#include "RobotRebellion.h"
#include "NavigationVolumeGraph.h"
#include "EditorGraphVolume.h"
#include "VolumeIdProvider.h"
struct NodeRecordSingleton
{
int32 m_id;
NodeRecordSingleton* m_fromNode; // Storing pointer is easier for path reversing
float m_costSoFar;
float m_heuristic;
//float m_estimatedTotalCost; // store the cost so far + heuristic
NodeRecordSingleton(int32 id, NodeRecordSingleton* fromNode, float cost, float heuristic)
: m_id{id}, m_fromNode{fromNode}, m_costSoFar{cost}, m_heuristic{heuristic}
{}
float estimatedCost() const
{
return m_heuristic + m_costSoFar;
}
static bool lessOperator(const NodeRecordSingleton &a, const NodeRecordSingleton &b)
{
return a.estimatedCost() < b.estimatedCost();
}
};
NavigationVolumeGraph::NavigationVolumeGraph()
: m_edges{},
m_edgesCosts{},
m_indexEdgesForNode{},
m_isBuilt{false},
m_NodeAmountExpected{184}
{
// default graph is empty
}
NavigationVolumeGraph::~NavigationVolumeGraph()
{
clearGraph();
}
void NavigationVolumeGraph::clearGraph()
{
m_edgesCosts.Empty();
m_edges.Empty();
m_indexEdgesForNode.Empty();
m_nodes.Empty();
m_isBuilt = false;
VolumeIdProvider::getInstance().reset();
}
int32 NavigationVolumeGraph::getNodeAmount()
{
return m_nodes.Num();
}
int32 NavigationVolumeGraph::getEdgeAmount()
{
return m_edges.Num() / 2;
}
bool NavigationVolumeGraph::isReadyToUse()
{
return m_isBuilt;
}
void NavigationVolumeGraph::addNode(AEditorGraphVolume *newVolume)
{
if(newVolume)
{
m_nodes.Add(newVolume);
}
PRINT_MESSAGE_ON_SCREEN(FColor::Emerald, FString::FromInt(m_nodes.Num())
+ "/"
+ FString::FromInt(m_NodeAmountExpected) + " Nodes");
if(m_nodes.Num() == m_NodeAmountExpected)
{
PRINT_MESSAGE_ON_SCREEN(FColor::Emerald, "BUILD")
build();
}
}
void NavigationVolumeGraph::build()
{
if(m_isBuilt)
{
return;
}
m_isBuilt = true;
// TODO sort node arrray by
PRINT_MESSAGE_ON_SCREEN(FColor::Emerald, "building the graphe");
// Reserve memory for what we can
m_indexEdgesForNode.Reserve(m_nodes.Num() + 1);
m_indexEdgesForNode.AddUninitialized(m_nodes.Num() + 1);
// Sort nodes by id
sortNodeArray();
// go through all node and copy every data needed
m_indexEdgesForNode[0] = 0;
for(int32 index{}; index < m_nodes.Num(); ++index)
{
AEditorGraphVolume* currentVolume = m_nodes[index];
if(index != currentVolume->getId())
{
PRINT_MESSAGE_ON_SCREEN(FColor::Red, "id error. Index should equals node id.");
return;
}
// Maybe just exclude the last one from the loop
if((index + 1) < m_nodes.Num()) // exclude last node rework to avoid an if for every node
{
m_indexEdgesForNode[index + 1] = m_indexEdgesForNode[index] + currentVolume->m_neighbour.Num();
}
// Report outgoing edges -> Fill m_edges && Edges_cost
m_edges.AddUninitialized(currentVolume->m_neighbour.Num());
m_edgesCosts.AddUninitialized(currentVolume->m_neighbour.Num());
for(int32 neighbourIndex{}; neighbourIndex < currentVolume->m_neighbour.Num(); ++neighbourIndex)
{
// TODO
m_edges[m_indexEdgesForNode[index] + neighbourIndex] = currentVolume->m_neighbour[neighbourIndex];
m_edgesCosts[m_indexEdgesForNode[index] + neighbourIndex]
= FVector::Dist(currentVolume->m_neighbour[neighbourIndex]->GetActorLocation(),
currentVolume->GetActorLocation());
}
}
m_indexEdgesForNode[m_nodes.Num()] = m_edges.Num();
// For test draw the graph - just comment to avoid graph drawing at the start
drawConnections(m_nodes[0]->GetWorld());
}
void NavigationVolumeGraph::sortNodeArray()
{
// TODO sort node arrray by
PRINT_MESSAGE_ON_SCREEN(FColor::Emerald, "\t sorting node by id...");
TArray<AEditorGraphVolume*> temporaryArray;
temporaryArray.AddUninitialized(m_nodes.Num());
for(int32 index{}; index < m_nodes.Num(); ++index)
{
temporaryArray[(m_nodes[index]->getId())] = m_nodes[index];
}
m_nodes = temporaryArray;
PRINT_MESSAGE_ON_SCREEN(FColor::Emerald, "\t sorting node by id...Done");
}
TArray<FVector> NavigationVolumeGraph::processAStar(int32 startId, int32 endId) const
{
//using struct to store intel
TArray<NodeRecordSingleton*> openList{};
openList.Heapify(NodeRecordSingleton::lessOperator);
TArray<NodeRecordSingleton*> closeList{};
//init first node
openList.HeapPush(new NodeRecordSingleton(startId, nullptr, 0.f,
FVector::Dist(m_nodes[startId]->GetActorLocation(), m_nodes[endId]->GetActorLocation())),
NodeRecordSingleton::lessOperator);
NodeRecordSingleton* currentNode{};
int32 currentNodeId = INDEX_NONE;
while(openList.Num() > 0)
{
//get the most promising node
openList.HeapPop(currentNode, NodeRecordSingleton::lessOperator);
currentNodeId = currentNode->m_id;
if(currentNodeId == endId) // end a star at the first goal occurence
{
break;
}
// expand to current node neighbour
int32 startNeighbourIndex = m_indexEdgesForNode[currentNodeId];
int32 endNeighbourIndex = m_indexEdgesForNode[currentNodeId + 1];
for(int32 neighbourIndex = startNeighbourIndex; neighbourIndex < endNeighbourIndex; ++neighbourIndex)
{
int32 neighbourId = m_edges[neighbourIndex]->getId();
// Check in close list (if in it just continue cause we dont want the best path)
if(closeList.ContainsByPredicate(
[neighbourId](NodeRecordSingleton* a) {return a->m_id == neighbourId; }))
{
continue;
}
// Check in open list
float neighbourCost = currentNode->m_costSoFar + m_edgesCosts[neighbourIndex];
NodeRecordSingleton** nodeRecordOpenList = openList.FindByPredicate([neighbourId](NodeRecordSingleton* a) {return a->m_id == neighbourId; });
if(nodeRecordOpenList)
{
if(neighbourCost < (*nodeRecordOpenList)->m_costSoFar)
{
// update cost so far and from id
(*nodeRecordOpenList)->m_fromNode = currentNode;
(*nodeRecordOpenList)->m_costSoFar = neighbourCost;
// Sort the array fast to keep it fast. Issue with predicate when using heapSort
openList.Heapify(NodeRecordSingleton::lessOperator);
}
continue;
}
// Then we know it's a fully unvisited node
float heuristic{};// TODO - Calcul Heuristic
heuristic = FVector::Dist(m_nodes[neighbourId]->GetActorLocation(), m_nodes[endId]->GetActorLocation());
openList.HeapPush(new NodeRecordSingleton(neighbourId, currentNode, neighbourCost, heuristic), NodeRecordSingleton::lessOperator);
}
closeList.Emplace(currentNode);
}
if(currentNodeId != endId)
{ // No path found
return TArray<FVector>{};
}
// process the path in a reverse way
TArray<FVector> path;
while(currentNode->m_id != startId)
{
path.Emplace(m_nodes[currentNode->m_id]->GetActorLocation());
currentNode = currentNode->m_fromNode;
}
//finally push first node ID
path.Emplace(m_nodes[startId]->GetActorLocation());
//Clear memory
for(NodeRecordSingleton* currNode : openList)
{
delete currNode;
}
for(NodeRecordSingleton* currNode : closeList)
{
delete currNode;
}
return path;
}
int32 NavigationVolumeGraph::getOverlappingVolumeId(const FVector &point)const
{
// TODO - Use finally some sort of hierarchical volume cluster to process faster
// Go through all volume an find the one
for(int index{}; index < m_nodes.Num(); ++index)
{
if(m_nodes[index]->contains(point))
{
return m_nodes[index]->getId();
}
}
// No volume found
return -1;
}
int32 NavigationVolumeGraph::getBelowVolume(FVector& point, float offset) const
{
float minDist = 9E+16f;
int32 idVolume{};
bool volumeFind = false;
for(int index{}; index < m_nodes.Num(); ++index)
{
float dist = m_nodes[index]->isBelow(point);
if(dist >= 0.f && dist < minDist )
{
minDist = dist;
volumeFind = true;
idVolume = index;
}
}
if(volumeFind)
{
point.Z = m_nodes[idVolume]->GetActorLocation().Z
+ m_nodes[idVolume]->m_box->GetScaledBoxExtent().Z
- offset;
return idVolume;
}
return -1;
}
int32 NavigationVolumeGraph::getNearestVolume(FVector& point, float offset, bool useCenter) const
{
float minDist = 9E+16f;
int32 idVolume{};
for(int index{}; index < m_nodes.Num(); ++index)
{
float dist = FVector::DistSquared(m_nodes[index]->GetActorLocation(), point);
if(dist < minDist)
{ // if distance is inferior to last min dist just update it
minDist = dist;
idVolume = index;
}
}
if(useCenter)
{
point = m_nodes[idVolume]->GetActorLocation();
return idVolume;
}
else
{
// Cast ray form point to center to get impact point
FHitResult hitActors(ForceInit);
FCollisionQueryParams TraceParams(TEXT("SteeringTrace"), true);
TraceParams.bTraceAsyncScene = true;
// atm only should only proc on static mesh
FVector centerLocation = m_nodes[idVolume]->GetActorLocation();
m_nodes[idVolume]->GetWorld()->LineTraceSingleByChannel(hitActors, point, centerLocation, ECC_GameTraceChannel9, TraceParams);
DRAW_DEBUG_LINE(m_nodes[idVolume]->GetWorld(), point, centerLocation, FColor::Emerald);
// get direction and normalize it
FVector direction = centerLocation - point;
direction.Normalize();
point = hitActors.ImpactPoint + (offset * direction);
return idVolume;
}
// find nearest point overllaped in the volume
}
////////////////////////////////////////////////////////////////////////
// DEBUG //
////////////////////////////////////////////////////////////////////////
void NavigationVolumeGraph::writeGraph() const
{
FString temp = "edges cost : ";
for(int32 i{}; i < m_edgesCosts.Num(); ++i)
{
temp += FString::SanitizeFloat(m_edgesCosts[i]);
temp += " ";
}
PRINT_MESSAGE_ON_SCREEN(FColor::Emerald, temp);
temp = "edges";
for(int32 i{}; i < m_edges.Num(); ++i)
{
temp += FString::FromInt(m_edges[i]->getId());
temp += " ";
}
PRINT_MESSAGE_ON_SCREEN(FColor::Emerald, temp);
temp = "index : ";
for(int32 i{}; i < m_indexEdgesForNode.Num(); ++i)
{
temp += FString::FromInt(m_indexEdgesForNode[i]);
temp += " ";
}
PRINT_MESSAGE_ON_SCREEN(FColor::Emerald, temp);
PRINT_MESSAGE_ON_SCREEN(FColor::Emerald, " and " + FString::FromInt(m_indexEdgesForNode.Num()) + " Node");
PRINT_MESSAGE_ON_SCREEN(FColor::Emerald, "contains : " + FString::FromInt(m_edges.Num()) + " edges.");
PRINT_MESSAGE_ON_SCREEN(FColor::Emerald, "Writing graph data structure");
}
void NavigationVolumeGraph::drawConnections(const UWorld* world) const
{
if (m_showConnection)
{
// TODO draw all connection (use the edges list for that)
for(int32 indexOfEdges{}; indexOfEdges < m_indexEdgesForNode.Num() - 1; ++indexOfEdges)
{
FVector startPosition = m_nodes[indexOfEdges]->GetActorLocation();
int32 startIndex = m_indexEdgesForNode[indexOfEdges];
int32 endIndex;
if(indexOfEdges + 1 == m_indexEdgesForNode.Num())
{
endIndex = m_edges.Num();
}
else
{
endIndex = m_indexEdgesForNode[indexOfEdges + 1];
}
for(int32 edgesIndex = startIndex; edgesIndex < endIndex; ++edgesIndex)
{
DrawDebugLine(world, startPosition, m_edges[edgesIndex]->GetActorLocation(),
FColor::Emerald, false, 30.f, 0, 5.f);
}
}
}
}<file_sep>/Source/RobotRebellion/Gameplay/Weapon/Projectile.cpp
// Fill out your copyright notice in the Description page of Project Settings.
#include "RobotRebellion.h"
#include "Projectile.h"
#include "Character/RobotRebellionCharacter.h"
#include "Gameplay/Damage/Damage.h"
#include "Gameplay/Damage/DamageCoefficientLogic.h"
#include "Global/GlobalDamageMethod.h"
#include "Tool/UtilitaryFunctionLibrary.h"
// Sets default values
AProjectile::AProjectile()
{
// Set this actor to call Tick() every frame. You can turn this off to improve performance if you don't need it.
PrimaryActorTick.bCanEverTick = true;
// Create Sphere for collision shape
m_collisionComp = CreateDefaultSubobject<USphereComponent>(TEXT("SphereComp"));
m_collisionComp->OnComponentHit.AddDynamic(this, &AProjectile::OnHit);
m_collisionComp->BodyInstance.SetCollisionProfileName("Projectile");
RootComponent = m_collisionComp;
//Projectile Movement datas
m_projectileMovement = CreateDefaultSubobject<UProjectileMovementComponent>(TEXT("ProjectileComp"));
m_projectileMovement->UpdatedComponent = m_collisionComp;
m_projectileMovement->InitialSpeed = 3000.f;
m_projectileMovement->MaxSpeed = 3000.f;
m_projectileMovement->bRotationFollowsVelocity = true;
m_projectileMovement->bShouldBounce = false;
bReplicates = true;
bNetUseOwnerRelevancy = true;
//Life Time
InitialLifeSpan = 2.0f;
}
// Called when the game starts or when spawned
void AProjectile::BeginPlay()
{
Super::BeginPlay();
}
// Called every frame
void AProjectile::Tick(float DeltaTime)
{
Super::Tick(DeltaTime);
}
void AProjectile::InitProjectileParams(const FVector& shootDirection, float distanceRange)
{
if(m_projectileMovement)
{
float bulletSpeed = m_projectileMovement->InitialSpeed;
// Adjust velocity with direction
m_projectileMovement->Velocity = shootDirection * bulletSpeed;
//t = d / v
this->SetLifeSpan(distanceRange / bulletSpeed);
}
}
void AProjectile::GetLifetimeReplicatedProps(TArray< FLifetimeProperty > & OutLifetimeProps) const
{
Super::GetLifetimeReplicatedProps(OutLifetimeProps);
DOREPLIFETIME(AProjectile, m_owner);
//DOREPLIFETIME_CONDITION(AProjectile, m_bPressedCrouch, COND_SkipOwner);
}
void AProjectile::OnRep_MyOwner()
{
setOwner(m_owner);
}
void AProjectile::setOwner(ARobotRebellionCharacter *newOwner)
{
m_owner = newOwner;
// Propriétaire réseau pour les appels RPC.
SetOwner(newOwner);
}
void AProjectile::OnHit(class UPrimitiveComponent* ThisComp, class AActor* OtherActor, class UPrimitiveComponent*
OtherComp, FVector NormalImpulse, const FHitResult& Hit)
{
//PRINT_MESSAGE_ON_SCREEN_UNCHECKED(FColor::Blue, TEXT("Hit"));
if(Role == ROLE_Authority)
{
UWorld* world = this->GetWorld();
if(world)
{
FHitResult hitResult;
FVector direction = this->m_projectileMovement->Velocity;
direction.Normalize();
FVector start = this->GetActorLocation();// +shootDirection * (m_collisionComp->GetScaledSphereRadius() + 0.001f);
FVector end = start + direction * m_collisionComp->GetScaledSphereRadius() * 2.f;
ARobotRebellionCharacter* targetTouched = nullptr;
FCollisionQueryParams collisionQueryParams;
collisionQueryParams.bTraceComplex = true;
collisionQueryParams.AddIgnoredActor({ this });
collisionQueryParams.AddIgnoredComponents({
TWeakObjectPtr<UPrimitiveComponent>{ ThisComp }
});
if(world->LineTraceSingleByChannel(
hitResult,
start,
end,
ECC_GameTraceChannel10,
collisionQueryParams
))
{
this->inflictDamageLogic(OtherActor, hitResult);
}
else
{
this->inflictDamageLogic(OtherActor, Hit);
}
}
Destroy();
//PRINT_MESSAGE_ON_SCREEN_UNCHECKED(FColor::Blue, TEXT("Destroy on Server"));
}
}
void AProjectile::inflictDamageLogic(AActor* otherActor, const FHitResult& hit)
{
ARobotRebellionCharacter* receiver = Cast<ARobotRebellionCharacter>(otherActor);
if(receiver && m_owner != receiver && !receiver->isDead())
{
if(!receiver->isImmortal())
{
bool isCritical = false;
DamageCoefficientLogic coeff;
PRINT_MESSAGE_ON_SCREEN_UNCHECKED(FColor::Red, hit.BoneName.ToString());
if(coeff.establishCritical(hit.BoneName))
{
PRINT_MESSAGE_ON_SCREEN_UNCHECKED(FColor::Yellow, "Critical");
coeff.criticalHit();
isCritical = true;
}
if(!receiver->m_isInCombat)
{
PRINT_MESSAGE_ON_SCREEN_UNCHECKED(FColor::Yellow, "Engagement");
coeff.engagementHit();
}
Damage damage{ m_owner, receiver };
Damage::DamageValue currentDamage = damage(
&UGlobalDamageMethod::normalHitWithWeaponComputed,
coeff.getCoefficientValue()
);
setReceiverInCombat(receiver);
if(isCritical)
{
receiver->inflictDamage(currentDamage, ELivingTextAnimMode::TEXT_ANIM_BOING_BIGGER_TEXT_ON_CRITICAL, FColor::Orange);
}
else
{
receiver->inflictDamage(currentDamage);
}
}
//else // COMMENTED FOR CHEAT CODE
//{
// receiver->displayAnimatedText("IMMORTAL OBJECT", FColor::Purple, ELivingTextAnimMode::TEXT_ANIM_NOT_MOVING);
//}
}
}
void AProjectile::setReceiverInCombat(ARobotRebellionCharacter* receiver)
{
ANonPlayableCharacter* ennemy = Cast<ANonPlayableCharacter>(receiver);
if(ennemy)
{
if(receiver->m_canKillItsAllies || Cast<APlayableCharacter>(m_owner))
{
ACustomAIControllerBase* controller = Cast<ACustomAIControllerBase>(ennemy->GetController());
if(controller)
{
controller->setTarget(m_owner);
}
}
else
{
ACustomAIControllerBase* ennemyController = Cast<ACustomAIControllerBase>(ennemy->GetController());
if (ennemyController)
{
if(m_owner->m_canTransmitItsTarget)
{
ACustomAIControllerBase* ownerController = Cast<ACustomAIControllerBase>(m_owner->GetController());
if(ownerController)
{
ennemyController->setTarget(ownerController->getTarget());
}
}
ennemy->goAway(m_owner->GetActorLocation(), 130.f);
}
}
}
}
void AProjectile::simulateInstantRealMethod(const FVector& shootDirection, float distance)
{
UWorld* world = this->GetWorld();
if(world)
{
FHitResult hitResult;
FVector start = this->GetActorLocation();// +shootDirection * (m_collisionComp->GetScaledSphereRadius() + 0.001f);
FVector end = start + shootDirection * distance;
ARobotRebellionCharacter* targetTouched = nullptr;
FCollisionQueryParams collisionQueryParams;
collisionQueryParams.bTraceComplex = true;
collisionQueryParams.AddIgnoredActor({ this });
if(world->LineTraceSingleByChannel(
hitResult,
start,
end,
ECC_GameTraceChannel10,
collisionQueryParams
))
{
targetTouched = Cast<ARobotRebellionCharacter>(hitResult.GetActor());
if(targetTouched)
{
this->inflictDamageLogic(targetTouched, hitResult);
}
end = hitResult.ImpactPoint;
}
else if(
world->LineTraceSingleByChannel(
hitResult,
start,
end,
ECC_GameTraceChannel1,
collisionQueryParams
))
{
targetTouched = Cast<ARobotRebellionCharacter>(hitResult.GetActor());
if(targetTouched)
{
this->inflictDamageLogic(targetTouched, hitResult);
}
end = hitResult.ImpactPoint;
}
this->drawProjectileLineMethod(world, start, end);
multiDrawLineOnClients(start, end);
}
}
void AProjectile::simulateInstant(const FVector& shootDirection, float distance)
{
if(Role < ROLE_Authority)
{
serverSimulateInstant(shootDirection, distance);
}
else
{
simulateInstantRealMethod(shootDirection, distance);
}
this->suicide();
}
void AProjectile::serverSimulateInstant_Implementation(const FVector& shootDirection, float distance)
{
this->simulateInstantRealMethod(shootDirection, distance);
this->destroyOnClients();
}
bool AProjectile::serverSimulateInstant_Validate(const FVector& shootDirection, float distance)
{
return true;
}
void AProjectile::drawProjectileLineMethod(UWorld* world, const FVector& start, const FVector& end)
{
UUtilitaryFunctionLibrary::drawObligatoryPersistentLineInWorld(world, start, end, FColor::White, 1.f, 1.f);
}
void AProjectile::multiDrawLineOnClients_Implementation(const FVector& start, const FVector& end)
{
this->drawProjectileLineMethod(this->GetWorld(), start, end);
}
void AProjectile::suicide()
{
this->Destroy(true);
}
void AProjectile::destroyOnClients_Implementation()
{
this->suicide();
}<file_sep>/Source/RobotRebellion/IA/Controller/DroneAIController.cpp
// Fill out your copyright notice in the Description page of Project Settings.
#include "RobotRebellion.h"
#include "DroneAIController.h"
#include "Character/King.h"
#include "Character/RobotRebellionCharacter.h"
#include "Character/NonPlayableCharacter.h"
#include "Character/PlayableCharacter.h"
#include "Character/Drone.h"
#include "Gameplay/Weapon/Kaboom.h"
#include "Components/SplineComponent.h"
#include "IA/Navigation/NavigationVolumeGraph.h"
#define VERY_LITTLE 5.0f
DEFINE_LOG_CATEGORY(DroneLog);
ADroneAIController::ADroneAIController() : ACustomAIControllerBase()
{
PrimaryActorTick.bCanEverTick = true;
m_splinePath = CreateDefaultSubobject<USplineComponent>(TEXT("Path"));
m_splinePath->DefaultUpVector = {0.f, 0.f, 1.f};
//m_splinePath->SetSelectedSplineSegmentColor(FLinearColor::Blue);
// EDITOR MODE ONLY - PACKAGE COMPILE ERROR
//m_splinePath->ScaleVisualizationWidth = 30.f;
//m_splinePath->bShouldVisualizeScale = true;
//m_splinePath->bAllowDiscontinuousSpline = false;
m_idleTimer = 0.f;
m_actionFinished = true;
m_king = nullptr;
}
void ADroneAIController::BeginPlay()
{
Super::BeginPlay();
m_bestBombLocation = FVector::ZeroVector;
m_currentTime = 0.f;
m_debugCooldownDisplayTime = 1.5f;
m_state = DRONE_WAITING; //for testing
if (APawn* drone = GetPawn()) //not so sure who spawn before who. So checking is the best
{
m_destination = drone->GetActorLocation();
}
else
{
m_destination = m_defaultDroneSpawnPositionIfProblem;
}
m_coeffKing = 3.f;
m_deccelPercentPath = 1.f - m_accelPercentPath;
m_deccelerationCoefficient = (m_accelPercentPath == 0.f) ? 0.001f : 1.f - m_deccelPercentPath;
m_timeIdleRotationMove = 0.f;
m_idleTranslationSpeed = FMath::CeilToFloat(m_idleTranslationSpeed) * PI; //Must be a multiple of PI
this->saveDroneLocalization();
this->resetTripPoint();
}
void ADroneAIController::Tick(float deltaTime)
{
Super::Tick(deltaTime);
this->updateFrameProperties(deltaTime);
this->IAUpdate(deltaTime);
}
void ADroneAIController::updateFrameProperties(float deltaTime)
{
m_currentTime += deltaTime;
m_timeSinceLastUpdate = deltaTime;
this->updateEnnemiesCampInfo();
this->updateAlliesCampInfo();
}
void ADroneAIController::updateEnnemiesCampInfo()
{
m_ennemyInScene = 0;
m_ennemyNear = 0;
m_ennemyNearBarycenter = FVector::ZeroVector;
const float squaredDetectRange = m_detectionDistance * m_detectionDistance;
TArray<AActor*> npcCharact;
UGameplayStatics::GetAllActorsOfClass(GetWorld(), ANonPlayableCharacter::StaticClass(), npcCharact);
int32 npcCount = npcCharact.Num();
for(int32 iter = 0; iter < npcCount; ++iter)
{
AActor* current = npcCharact[iter];
AKing* king = Cast<AKing>(current);
if(king)
{
m_king = king;
continue;
}
ADrone* drone = Cast<ADrone>(current);
if(!drone)
{
++m_ennemyInScene;
FVector ennemyPosition = GetPawn()->GetActorLocation();
if(FVector::DistSquared(current->GetActorLocation(), ennemyPosition) < squaredDetectRange)
{
++m_ennemyNear;
m_ennemyNearBarycenter += ennemyPosition;
}
}
}
if(m_ennemyNear != 0)
{
m_ennemyNearBarycenter /= m_ennemyNear;
}
else
{
m_ennemyNearBarycenter = GetPawn()->GetActorLocation();
}
}
void ADroneAIController::updateAlliesCampInfo()
{
m_alliesAliveCount = 0;
m_alliesInScene = UGameplayStatics::GetGameMode(GetWorld())->GetNumPlayers();
m_groupBarycenter = FVector::ZeroVector;
for(int noplayer = 0; noplayer < m_alliesInScene; ++noplayer)
{
APlayableCharacter* currentPlayer = Cast<APlayableCharacter>(UGameplayStatics::GetPlayerCharacter(GetWorld(), noplayer));
if(currentPlayer && !currentPlayer->isDead())
{
++m_alliesAliveCount;
m_groupBarycenter += currentPlayer->GetActorLocation();
}
}
if(m_alliesAliveCount != 0)
{
m_groupBarycenter /= m_alliesAliveCount;
}
else
{
m_groupBarycenter = GetPawn()->GetActorLocation();
}
}
void ADroneAIController::saveDroneLocalization()
{
m_realDroneOrient = GetPawn()->GetActorForwardVector();
}
void ADroneAIController::resetIdleRotationGoal()
{
m_idleForwardGoal = FMath::VRandCone(m_realDroneOrient, m_idleAngle);
m_timeIdleRotationMove = 0.f;
}
void ADroneAIController::resetIdleTranslationGoal()
{
m_idleTranslationDirection = FMath::VRandCone(FVector::UpVector, PI);
}
void ADroneAIController::resetTripPoint()
{
m_totalTripPoint = 1.f;
m_currentTripPoint = 1;
}
void ADroneAIController::receiveBomb()
{
if(Role >= ROLE_Authority)
{
ADrone * drone = Cast<ADrone>(this->GetPawn());
if(drone)
{
drone->reload();
//m_gotBomb = true;
}
return;
}
serverReceiveBomb();
}
void ADroneAIController::serverReceiveBomb_Implementation()
{
ADrone * drone = Cast<ADrone>(this->GetPawn());
if(drone)
{
drone->reload();
}
//m_gotBomb = true;
}
bool ADroneAIController::serverReceiveBomb_Validate()
{
return true;
}
bool ADroneAIController::HasABomb()
{
return Cast<ADrone>(GetPawn())->isLoaded();
//return m_gotBomb;
}
float ADroneAIController::getAttackScore()
{
ADrone* owner = Cast<ADrone>(this->GetPawn());
CheckEnnemyNear(m_detectionDistance);
float score{};
if(!owner->isLoaded() || m_sensedEnnemies.Num() == 0)
{ // Cannot attack cause no bomb
return 0.f;
}
//Test all positions
float bestScoreBomb{};
int32 indexBestBomb{};
for(int i = 0; i < m_sensedEnnemies.Num(); i++)
{
FVector ennemyPos = m_sensedEnnemies[i]->GetActorLocation();
float bombScore = getBombScore(ennemyPos);
if(bombScore > bestScoreBomb)
{
bestScoreBomb = bombScore;
indexBestBomb = i;
}
}
m_bestBombLocation = m_sensedEnnemies[indexBestBomb]->GetActorLocation();
score = 0.6f * bestScoreBomb;
float temp = m_alliesAliveCount * 3.f;
temp = temp == 0 ? 1.f : temp;
temp = (m_sensedEnnemies.Num() / temp);
temp = temp > 1 ? 1.f : temp;
score += 0.3f * temp;
if(getNbBombPlayers())
{
score += 0.1f; // Add 20%
}
return score;
}
float ADroneAIController::getFollowScore()
{
float score;
score = 1 - 320000.f / (0.1f + (GetPawn()->GetActorLocation() - m_groupBarycenter).SizeSquared()); //Change later
score = (score < 0.f) ? 0.f : score;
score *= score;
if(isInCombat())
{
score *= score;
}
return score;
}
float ADroneAIController::getReloadScore()
{
// No Bomb
if(Cast<ADrone>(this->GetPawn())->isLoaded() || (getNbBombPlayers() == 0)) // no reloading possible
{
return 0.0f;
}
else
{
float score = 1.0f;
FVector dronePosition = GetPawn()->GetActorLocation();
m_safeZone = findSafeZone();
float distSafeZoneToPos = 0.f;
if(isInCombat())
{
//if not in combat, combat score always =1, else it's closer to 1 if many ennemies
score *= (1.f - (m_alliesAliveCount / (4.f * m_ennemyNear)));
}
else
{
distSafeZoneToPos = FVector::DistSquaredXY(m_safeZone, dronePosition);
score *= FVector::DistSquaredXY(m_groupBarycenter, dronePosition)
/ distSafeZoneToPos;
distSafeZoneToPos = FMath::Sqrt(distSafeZoneToPos);
}
score *= (1.f - getNbEnnemiesInZone(m_safeZone) / (0.1f + distSafeZoneToPos)); //ZoneScore
if (score < 0.f)
{
return 0.f;
}
return score;
}
}
float ADroneAIController::getWaitingScore()
{
/*ADrone* drone = Cast<ADrone>(GetPawn());
return 1.f - getAttackScore();*/
return m_waitingThreshold;
}
float ADroneAIController::getDropScore()
{
float score = 0.f;
ADrone* drone = Cast<ADrone>(this->GetPawn());
FVector dronePosition = drone->GetActorLocation();
//PRINT_MESSAGE_ON_SCREEN(FColor::White, FString::Printf(TEXT("DROP DISTANCE: %f"), FVector(dronePosition - m_destination).Size()));
if(m_state == DRONE_COMBAT && this->isArrivedAtDestination() && drone->isLoaded())
{
score = getBombScore(m_bestBombLocation);
}
return score;
}
bool ADroneAIController::isInCombat()
{
// TODO - Check if ennemy are attacking players or players attacking ennemy
return (m_ennemyNear > 0);
}
int ADroneAIController::getNbEnnemiesInZone(const FVector& zoneCenter)
{
CheckEnnemyNearPosition(zoneCenter, m_detectionDistance);
return (m_sensedEnnemies.Num());
}
EPathFollowingRequestResult::Type ADroneAIController::stopDroneMoves(ADrone* drone)
{
drone->GetMovementComponent()->Velocity = FVector::ZeroVector;
FRotator droneRotation = drone->GetActorRotation();
droneRotation.Pitch = 0.f;
drone->SetActorRotation(droneRotation);
this->saveDroneLocalization();
this->resetTripPoint();
return EPathFollowingRequestResult::AlreadyAtGoal;
}
EPathFollowingRequestResult::Type ADroneAIController::MoveToTarget()
{
ADrone* drone = Cast<ADrone>(GetPawn());
if(m_finalPath.Num() == 0)
{
return this->stopDroneMoves(drone);
}
FVector actorLocation = drone->GetActorLocation();
FVector directionToTarget = m_finalPath.Top() - actorLocation;
FVector& velocity = drone->GetMovementComponent()->Velocity;
// Check if we have reach the current point
while(
m_finalPath.Num() != 0 &&
(FVector::DotProduct(directionToTarget, velocity) < 0.f ||
directionToTarget.SizeSquared() < m_epsilonSquaredDistanceTolerance))
{
directionToTarget = m_finalPath.Pop(false) - actorLocation;
++m_currentTripPoint;
}
float directionVectSquaredSize = directionToTarget.SizeSquared();
if(m_finalPath.Num() == 0 && directionVectSquaredSize < m_epsilonSquaredDistanceTolerance)
{// Already at the goal
return this->stopDroneMoves(drone);
}
float tripCompletion = this->getTravelCompletionPercentage();
float speedCoefficient =
(tripCompletion < m_accelPercentPath) ? tripCompletion / m_accelPercentPath :
(tripCompletion > m_deccelPercentPath) ? (1.f - tripCompletion) / m_deccelerationCoefficient :
1.f;
constexpr const float minSpeedCoeff = 0.05f;
if (speedCoefficient < minSpeedCoeff)
{
speedCoefficient = minSpeedCoeff;
}
if(directionVectSquaredSize > 1.f)
{
directionToTarget /= FMath::Sqrt(directionVectSquaredSize);
}
/*PRINT_MESSAGE_ON_SCREEN_UNCHECKED(
FColor::Yellow,
FString::Printf(
TEXT("Travel Speed : %f Completion : %f pathP : %f curr : %d"),
speedCoefficient,
tripCompletion,
m_totalTripPoint,
m_currentTripPoint
)
);*/
velocity = directionToTarget * m_droneVelocity * speedCoefficient;
FVector velocityDownNormalized = velocity.GetSafeNormal();
if(FVector::DotProduct(directionToTarget, FVector::UpVector) < 0.5f) // the drone not going up with a angle of more than 45 degree
{
velocityDownNormalized.Z -= speedCoefficient; //to make the drone nose point to down
velocityDownNormalized.Normalize();
drone->SetActorRotation(
FQuat::FastLerp(drone->GetActorForwardVector().ToOrientationQuat(), velocityDownNormalized.ToOrientationQuat(), 0.1f)
);
}
return EPathFollowingRequestResult::RequestSuccessful;
}
void ADroneAIController::internalMakeIdleRotation()
{
FVector droneForwardVector = GetPawn()->GetActorForwardVector();
if(!(m_idleForwardGoal - droneForwardVector).IsNearlyZero(0.05f))
{
GetPawn()->SetActorRotation(
FQuat::FastLerp(droneForwardVector.ToOrientationQuat(), m_idleForwardGoal.ToOrientationQuat(), m_idleAngleSpeed)
);
}
else
{
this->resetIdleRotationGoal();
}
}
void ADroneAIController::internalMakeIdleTranslation()
{
float sinCoeff = m_idleTranslationGain * FMath::Sin(m_idleTimer * m_idleTranslationSpeed);
APawn* drone = GetPawn();
FVector currentPosition = drone->GetActorLocation();
FVector wantedPosition = m_destination + m_idleTranslationDirection * sinCoeff;
FVector deltaPosition = wantedPosition - currentPosition;
float dist = deltaPosition.SizeSquared();
//to avoid jumping teleportation, we straph to destination (dumb asservissement simulation)
if (dist > 1.f)
{
wantedPosition = currentPosition + deltaPosition * m_timeSinceLastUpdate; // pf = pi + v * dt
//FVector forwardVector = drone->GetActorForwardVector();
//constexpr const float coeff = 0.01f;
//deltaPosition.Z -= dist * ((FVector::DotProduct(forwardVector, deltaPosition) >= 0.f) ? coeff : -coeff); //nose point to down
//deltaPosition.Normalize();
//drone->SetActorRotation(
// FQuat::FastLerp(forwardVector.ToOrientationQuat(), deltaPosition.ToOrientationQuat(), 0.1f)
//);
}
//else we caught up to the idle movement translation
drone->SetActorLocation(wantedPosition);
}
void ADroneAIController::makeIdleMove()
{
this->internalMakeIdleTranslation();
this->internalMakeIdleRotation();
}
void ADroneAIController::setDestination(const FVector& newDestinationPosition)
{
m_destination = newDestinationPosition;
this->processPath();
}
void ADroneAIController::updateTargetedHeight() USE_NOEXCEPT
{
switch(m_state)
{
case DRONE_RECHARGE:
m_targetedHeight = m_reloadHeight; //m_targetToFollow->GetActorLocation().Z;
break;
default:
m_targetedHeight = m_destination.Z + m_stationaryElevation;
}
}
void ADroneAIController::IAUpdate(float deltaTime)
{
if(!m_actionFinished && m_currentTime < m_cooldown)
{
(this->*m_performAction)();
}
else
{
// Eval UT and initialise Action
chooseNextAction();
m_idleTimer = 0.f;
switch(m_state)
{
case DRONE_WAITING:
setWaiting();
break;
case DRONE_MOVING:
// TODO - Take king in consideration
setFollowGroup();
break;
case DRONE_COMBAT:
setFollowFireZone();
break;
case DRONE_RECHARGE:
setFollowSafeZone();
break;
}
m_currentTime = 0.f;
}
#ifdef ENABLE_DRONE_DEBUG_DISPLAY
if(m_showDestination)
{
DrawDebugSphere(
GetWorld(),
m_destination,
24,
32,
FColor(0, 0, 255)
);
}
#endif //ENABLE_DRONE_DEBUG_DISPLAY
}
void ADroneAIController::dropBomb()
{
ADrone * drone = Cast<ADrone>(this->GetPawn());
FVector test = drone->GetActorLocation();
if(drone)
{
// Check if there is still living enemy in the drop zone
TArray<TEnumAsByte<EObjectTypeQuery>> ObjectTypes{
UEngineTypes::ConvertToObjectType(ECC_GameTraceChannel3), // Robots
UEngineTypes::ConvertToObjectType(ECC_GameTraceChannel4), // Sovec
UEngineTypes::ConvertToObjectType(ECC_GameTraceChannel6), // Beasts
};
TArray<AActor*> ActorsToIgnore{drone};
TArray<FHitResult> OutHits;
FVector dropLocation = drone->GetActorLocation();
dropLocation.Z -= m_stationaryElevation;
UKismetSystemLibrary::SphereTraceMultiForObjects(
GetWorld(),
dropLocation,
dropLocation,
drone->getBombRadius(),
ObjectTypes,
false,
ActorsToIgnore,
EDrawDebugTrace::None,
OutHits,
true
);
if(OutHits.Num())
{
drone->drop();
}
}
}
void ADroneAIController::findDropZone()
{
//TODO: Improve this a lot, instead of first ennemy!
// Example: Voronoi Diagram+Fortune's algorithm generation+Delaunay Triangulation / circum-circles ?
}
void ADroneAIController::followKing()
{
this->setDestination(
(m_groupBarycenter * m_alliesAliveCount + m_coeffKing * m_king->GetActorLocation()) /
(m_alliesAliveCount + m_coeffKing)
);
}
void ADroneAIController::followGroup()
{
// TODO - follow the path
if(MoveToTarget() == EPathFollowingRequestResult::AlreadyAtGoal)
{
m_actionFinished = true;
}
}
void ADroneAIController::followFireZone()
{
ADrone* drone = Cast<ADrone>(GetPawn());
if(MoveToTarget() == EPathFollowingRequestResult::AlreadyAtGoal)
{
if(m_canDropBomb)
{
dropBomb();
m_actionFinished = true;
}
m_canDropBomb = !m_canDropBomb;
}
}
void ADroneAIController::followSafeZone()
{
if(m_idleTimer > m_updateSafeZoneCooldownTime)
{
m_actionFinished = true;
return;
}
if(this->HasABomb())// || m_idleTimer > m_updateSafeZoneCooldownTime)
{
FVector newHeight = GetPawn()->GetActorLocation();
newHeight.Z = m_stationaryElevation;
setDestination(newHeight);
m_performAction = &ADroneAIController::followGroup;
return;
}
if(MoveToTarget() == EPathFollowingRequestResult::AlreadyAtGoal)
{
this->makeIdleMove();
if (m_idleTimer < 0.01f)
{
this->resetIdleTranslationGoal();
}
m_idleTimer += m_timeSinceLastUpdate;
m_timeIdleRotationMove += m_timeSinceLastUpdate;
if (m_timeIdleRotationMove > m_idleRotationResetTime)
{
this->resetIdleRotationGoal();
}
}
}
void ADroneAIController::waiting()
{
this->makeIdleMove();
//m_actionFinished = true;
if(m_idleTimer < 0.01f)
{
this->resetIdleTranslationGoal();
}
m_idleTimer += m_timeSinceLastUpdate;
m_timeIdleRotationMove += m_timeSinceLastUpdate;
if(m_timeIdleRotationMove > m_idleRotationResetTime)
{
this->resetIdleRotationGoal();
}
}
void ADroneAIController::setFollowGroup()
{
m_actionFinished = false;
this->m_performAction = &ADroneAIController::followGroup;
this->setDestination({m_groupBarycenter.X, m_groupBarycenter.Y, m_stationaryElevation});
// TODO - find and set the destination
}
void ADroneAIController::setFollowKing()
{
if(m_king) //The king is here
{
this->m_performAction = &ADroneAIController::followKing;
m_actionFinished = false;
// TODO - find and set the destination
}
else
{
setFollowGroup(); //if no king, stay with group
}
}
void ADroneAIController::setFollowFireZone()
{
m_actionFinished = false;
m_canDropBomb = false;
this->m_performAction = &ADroneAIController::followFireZone;
this->setDestination({
m_bestBombLocation.X,
m_bestBombLocation.Y,
m_bestBombLocation.Z + m_stationaryElevation
});
}
void ADroneAIController::setFollowSafeZone()
{
m_actionFinished = false;
this->m_performAction = &ADroneAIController::followSafeZone;
m_safeZone = findSafeZone();
setDestination(m_safeZone);
}
void ADroneAIController::setWaiting()
{
//wait for the drone to deccelerate entirely before waiting if it is currently moving
if (GetPawn()->GetMovementComponent()->Velocity == FVector::ZeroVector)
{
m_actionFinished = false;
this->m_performAction = &ADroneAIController::waiting;
// TODO - find and set the destination
}
}
void ADroneAIController::chooseNextAction()
{
float scoresArray[DRONE_ACTION_COUNT] = {
getWaitingScore(),
getFollowScore(),
getAttackScore(),
getReloadScore()
};
if(m_currentTime >= m_debugCooldownDisplayTime && m_isDebugEnabled)
{
ADrone * drone = Cast<ADrone>(this->GetPawn());
drone->displayScore(scoresArray);
}
#ifdef ENABLE_PRINT_ON_SCREEN
GEngine->AddOnScreenDebugMessage(15, 5.f, FColor::White, "waitScore : " + FString::SanitizeFloat(scoresArray[DRONE_WAITING]));
GEngine->AddOnScreenDebugMessage(16, 5.f, FColor::White, "followScore : " + FString::SanitizeFloat(scoresArray[DRONE_MOVING]));
GEngine->AddOnScreenDebugMessage(18, 5.f, FColor::White, "attackScore : " + FString::SanitizeFloat(scoresArray[DRONE_COMBAT]));
GEngine->AddOnScreenDebugMessage(17, 5.f, FColor::White, "reloadScore : " + FString::SanitizeFloat(scoresArray[DRONE_RECHARGE]));
#endif //ENABLE_PRINT_ON_SCREEN
float bestScore = -1.f;
for(int iter = 0; iter < DRONE_ACTION_COUNT; ++iter)
{
if(scoresArray[iter] > bestScore)
{
bestScore = scoresArray[iter];
switch(iter)
{
case DRONE_MOVING:
m_state = DRONE_MOVING;
break;
case DRONE_COMBAT:
m_state = DRONE_COMBAT;
break;
case DRONE_RECHARGE:
m_state = DRONE_RECHARGE;
break;
case DRONE_WAITING:
default:
m_state = DRONE_WAITING;
}
}
}
}
void ADroneAIController::CheckEnnemyNear(float range)
{
this->CheckEnnemyNearPosition(this->GetPawn()->GetActorLocation(), range);
}
void ADroneAIController::CheckEnnemyNearPosition(const FVector& position, float range)
{
//TODO: Ray cast instead... Drone currently sees through walls...
TArray<TEnumAsByte<EObjectTypeQuery>> ObjectTypes{
UEngineTypes::ConvertToObjectType(ECC_GameTraceChannel3), // Robots
UEngineTypes::ConvertToObjectType(ECC_GameTraceChannel4), // Sovec
UEngineTypes::ConvertToObjectType(ECC_GameTraceChannel6), // Beasts
};
TArray<AActor*> ActorsToIgnore{this->GetPawn()};
TArray<FHitResult> OutHits;
m_sensedEnnemies.Reset();
if(UKismetSystemLibrary::SphereTraceMultiForObjects(
GetWorld(),
position,
position,
range,
ObjectTypes,
false,
ActorsToIgnore,
SPHERECAST_DISPLAY_ONE_FRAME,
OutHits,
true
))
{
for(int32 i = 0; i < OutHits.Num(); i++)
{
FHitResult& hit = OutHits[i];
ARobotRebellionCharacter* RRCharacter = Cast<ARobotRebellionCharacter>(hit.GetActor());
if(NULL != RRCharacter)
{
if(RRCharacter->isDead() || !RRCharacter->isVisible())
{
continue;
}
m_sensedEnnemies.Add(RRCharacter);
}
}
}
}
int ADroneAIController::getNbBombPlayers()
{
int bombCount = 0;
int nbPlayers = m_alliesAliveCount;
for(int noplayer = 0; noplayer < nbPlayers; ++noplayer)
{
APlayableCharacter* currentPlayer = Cast<APlayableCharacter>(UGameplayStatics::GetPlayerCharacter(GetWorld(), noplayer));
bombCount += currentPlayer->getBombCount();
}
return bombCount;
}
float ADroneAIController::getBombScore(const FVector& position)
{
ADrone* owner = Cast<ADrone>(this->GetPawn());
float playerWillBeKilled = 0.f;
float numberFriendlyAttacked = 0.f;
float gameEndIsNear = 0.f; // TODO
float enemiesAttacked = 0.f;
float enemiesKilled{};
//CHECK DAMAGED TARGETS
TArray<TEnumAsByte<EObjectTypeQuery>> ObjectTypes{
UEngineTypes::ConvertToObjectType(ECC_GameTraceChannel2), // Players
UEngineTypes::ConvertToObjectType(ECC_GameTraceChannel3), // Robots
UEngineTypes::ConvertToObjectType(ECC_GameTraceChannel4), // Sovec
UEngineTypes::ConvertToObjectType(ECC_GameTraceChannel6), // Beasts
UEngineTypes::ConvertToObjectType(ECC_GameTraceChannel7), // King
};
TArray<AActor*> ActorsToIgnore{owner};
TArray<FHitResult> OutHits;
if(UKismetSystemLibrary::SphereTraceMultiForObjects(
GetWorld(),
position,
position,
owner->getBombRadius(),
ObjectTypes,
false,
ActorsToIgnore,
EDrawDebugTrace::None,
OutHits,
true
))
{
int32 hitCount = OutHits.Num();
for(int32 i = 0; i < hitCount; i++)
{
FHitResult& hit = OutHits[i];
ARobotRebellionCharacter* RRCharacter = Cast<ARobotRebellionCharacter>(hit.GetActor());
if(NULL != RRCharacter)
{
if(RRCharacter->isDead() || !RRCharacter->isVisible())
{
continue;
}
AKing* king = Cast<AKing>(RRCharacter);
if(king)
{
return 0.f; // just dont shoot the king
}
if(Cast<APlayableCharacter>(RRCharacter)) //is a player
{
numberFriendlyAttacked += 1.f;
if(RRCharacter->getHealth() < owner->getBombBaseDamage())
{
//playerWillBeKilled += 1.f;
// TODO - See if the bomb end the fight
return 0.f;
}
}
else
{
if(RRCharacter->getHealth() < owner->getBombBaseDamage())
{
++enemiesKilled;
}
++enemiesAttacked;
}
}
}
}
float score = 0.40f * (enemiesKilled / enemiesAttacked);
score += 0.35f * (enemiesAttacked / m_sensedEnnemies.Num());
score += 0.25f * ((4.f - numberFriendlyAttacked) / 4.f);
//score = (1.f - playerWillBeKilled - gameEndIsNear) * ((1.f / (numberFriendlyAttacked + 1.f) + ennemIsAttacked / getNbEnnemiesInScene()) / c_Normalize);
//float temp = FMath::Clamp((m_sensedEnnemies.Num() - getNbAliveAllies()) / 4.f, 0.f, 1.f);
float minimalEnemyNumber = 4.f;
float temp = enemiesAttacked / minimalEnemyNumber;
temp = temp > 1.f ? 1.f : temp;
return temp * score; //> temp ? temp : score;
}
FVector ADroneAIController::findSafeZone()
{
FVector zoneCenter = (5.f * m_groupBarycenter - m_ennemyNearBarycenter) / 4.f;
zoneCenter.Z = m_reloadHeight;
return zoneCenter;
}
void ADroneAIController::clearSplinePath()
{
m_splinePath->ClearSplinePoints(false);
}
void ADroneAIController::updateSplinePath(float tension)
{
this->clearSplinePath();
const int32 lastPointIndex = m_smoothedPath.Num() - 1;
for(int32 iter = 0; iter < lastPointIndex; ++iter)
{
m_splinePath->AddSplinePoint(m_smoothedPath[iter], ESplineCoordinateSpace::World, false);
}
//update spline at the very end. It is useless to update it before.
m_splinePath->AddSplinePoint(m_smoothedPath[lastPointIndex], ESplineCoordinateSpace::World, true);
m_splinePath->GetSplinePointsPosition().AutoSetTangents(tension);
}
void ADroneAIController::smoothPath()
{
// Smooth the path beginning at the end point
int32 currentIndex{};
int32 nextIndex{};
int32 previousIndex{1};
int32 previousCurrentIndex{1};
// Smooth the path beginning at the start point
m_smoothedPath.Reset();
currentIndex = m_path.Num() - 1;
m_smoothedPath.Emplace(m_path[currentIndex]);
while(currentIndex > 0)
{
nextIndex = currentIndex;
bool canGoTo = true;
while(canGoTo)
{
nextIndex--;
if(nextIndex == -1)
{
canGoTo = false;
}
else
{
canGoTo = testFlyFromTo(m_path[currentIndex], m_path[nextIndex]);
}
}
++nextIndex;
if(nextIndex == previousIndex && previousCurrentIndex == currentIndex)
{
UE_LOG(DroneLog, Log, TEXT("m_smoothedPath:%d"), m_smoothedPath.Num());
break;
}
previousIndex = nextIndex;
previousCurrentIndex = currentIndex;
m_smoothedPath.Emplace(m_path[nextIndex]);
//re -loop from the last index
currentIndex = nextIndex;
}
this->updateSplinePath(m_splineTension);
this->splineForecast();
}
bool ADroneAIController::testFlyFromTo(const FVector& startPoint, const FVector& endPoint)
{
TArray<TEnumAsByte<EObjectTypeQuery>> ObjectTypes{UEngineTypes::ConvertToObjectType(ECC_WorldStatic)};
TArray<AActor*> ActorsToIgnore{GetPawn()};
AKaboom* bomb = Cast<ADrone>(GetPawn())->m_currentBomb;
if(bomb)
{
ActorsToIgnore.Emplace(bomb);
}
TArray<FHitResult> hitActors;
float offset = 5.f;
float radius = Cast<ADrone>(GetPawn())->GetCapsuleComponent()->GetUnscaledCapsuleHalfHeight() - offset;
bool Result = UKismetSystemLibrary::SphereTraceMultiForObjects(GetWorld(),
startPoint,
endPoint,
radius,
ObjectTypes,
false,
ActorsToIgnore,
EDrawDebugTrace::None,
hitActors,
true);
return hitActors.Num() == 0;
}
void ADroneAIController::debugDrawPath() const
{
#ifdef ENABLE_DRONE_DEBUG_DISPLAY
//path
if(m_showOriginPath)
{
this->debugElementaryDrawPath(m_path, FColor::Red);
}
// smoothed path
if(m_showSmoothedPath)
{
this->debugElementaryDrawPath(m_smoothedPath, FColor::Green);
}
// final path
if(m_showFinalPath)
{
this->debugElementaryDrawPath(m_finalPath, FColor::Blue);
}
#endif //ENABLE_DRONE_DEBUG_DISPLAY
}
void ADroneAIController::debugElementaryDrawPath(const TArray<FVector>& pathToDraw, const FColor& lineColor) const
{
int32 lastTracedPathPoint = pathToDraw.Num() - 1;
UWorld* world = GetPawn()->GetWorld();
for(int32 index{}; index < lastTracedPathPoint; ++index)
{
DrawDebugLine(world, pathToDraw[index], pathToDraw[index + 1], lineColor, false, 15.f, 0, 5.f);
}
}
void ADroneAIController::processPath()
{
NavigationVolumeGraph& myGraph = NavigationVolumeGraph::getInstance();
FVector droneLocation = GetPawn()->GetActorLocation();
int32 currentLocId = myGraph.getOverlappingVolumeId(droneLocation);
float offset = Cast<ADrone>(GetPawn())->GetCapsuleComponent()->GetUnscaledCapsuleHalfHeight() + 10.f;
int32 targetId;
if(currentLocId == -1)
{
currentLocId = myGraph.getBelowVolume(droneLocation, offset);
}
if(currentLocId != -1)
{
targetId = myGraph.getOverlappingVolumeId(m_destination);
if(targetId != -1)
{
m_path.Reset();
// test if destination is possible
if(isLocationFree(m_destination))
{
m_path.Add(m_destination);
}
m_path.Append(myGraph.processAStar(currentLocId, targetId));
m_path.Emplace(droneLocation);
PRINT_MESSAGE_ON_SCREEN_UNCHECKED(FColor::Emerald, "new target id : " + FString::FromInt(targetId));
smoothPath();
debugDrawPath();
}
else
{
targetId = myGraph.getBelowVolume(m_destination, offset);
if(targetId != -1)
{
m_path.Reset();
if(isLocationFree(m_destination))
{
m_path.Add(m_destination);
}
m_path.Append(myGraph.processAStar(currentLocId, targetId)); // always begin at id 0 node
m_path.Emplace(droneLocation);
PRINT_MESSAGE_ON_SCREEN_UNCHECKED(FColor::Emerald, "start id : " + FString::FromInt(currentLocId));
PRINT_MESSAGE_ON_SCREEN_UNCHECKED(FColor::Emerald, "new target id : " + FString::FromInt(targetId));
smoothPath();
debugDrawPath();
}
else
{
// No volume found
}
}
}
else
{
// agent is out of the navigation volume swtich to steering behaviour
FVector steeringLocation = droneLocation;
targetId = myGraph.getNearestVolume(steeringLocation, offset);
FHitResult hitActors{ForceInit};
TArray<AActor*> actorsToIgnore{this};
AKaboom* bomb = Cast<ADrone>(GetPawn())->m_currentBomb;
if(bomb)
{
actorsToIgnore.Emplace(bomb);
}
// Cast to check if there is an obstacle between agent and sterring destination
if(UKismetSystemLibrary::SphereTraceSingleForObjects(GetWorld(),
droneLocation,
steeringLocation,
offset,
{UEngineTypes::ConvertToObjectType(ECC_WorldStatic)},
false,
actorsToIgnore,
SPHERECAST_DISPLAY_DURATION,
hitActors,
true))
{
// there is an obstacle -> just teleport the agent to the steering location
GetPawn()->SetActorLocation(steeringLocation);
}
else
{
m_path.Reset();
m_path.Emplace(steeringLocation);
m_path.Emplace(droneLocation);
smoothPath();
//debugDrawPath();
}
}
}
bool ADroneAIController::isLocationFree(const FVector& loc)
{
float offset = 10.f;
float radius = Cast<ADrone>(GetPawn())->GetCapsuleComponent()->GetUnscaledCapsuleHalfHeight() + offset;
TArray<TEnumAsByte<EObjectTypeQuery>> ObjectTypes{UEngineTypes::ConvertToObjectType(ECC_WorldStatic)};
TArray<AActor*> ActorsToIgnore{GetPawn()};
AKaboom* bomb = Cast<ADrone>(GetPawn())->m_currentBomb;
if(bomb)
{
ActorsToIgnore.Emplace(bomb);
}
TArray<FHitResult> hitActors;
bool Result = UKismetSystemLibrary::SphereTraceMultiForObjects(GetWorld(),
loc,
loc,
radius,
ObjectTypes,
false,
ActorsToIgnore,
EDrawDebugTrace::None,
hitActors,
true);
return hitActors.Num() == 0;
}
void ADroneAIController::splineForecast()
{
const int32 totalPointCount = m_splinePath->GetNumberOfSplinePoints() * m_splinePointCountIntraSegment;
const float timeStep = m_splinePath->Duration / static_cast<float>(totalPointCount);
m_finalPath.Reset(totalPointCount);
float currentTime = m_splinePath->Duration;
const int32 lastPoint = totalPointCount - 1;
m_finalPath.Add(m_splinePath->GetLocationAtTime(currentTime, ESplineCoordinateSpace::World));
currentTime -= timeStep;
for(int32 iter = 1; iter < lastPoint; ++iter)
{
m_finalPath.Add(m_splinePath->GetLocationAtTime(currentTime, ESplineCoordinateSpace::World));
currentTime -= timeStep;
}
m_finalPath.Add(m_splinePath->GetLocationAtTime(0.f, ESplineCoordinateSpace::World));
if(m_noisyTravelRandom != 0.f)
{
int32 noisyPathToModifyCount = m_finalPath.Num() - 1;
for(int32 iter = 1; iter < noisyPathToModifyCount; ++iter)
{
internalNoisyTravelTransfertMethod(m_finalPath[iter], m_finalPath[iter + 1]);
}
}
/*
m_currentTripPoint / m_totalTripPoint = formerTravelCompletion
m_currentTripPoint + (m_finalPath.Num() + 1) = m_totalTripPoint
=> equation system with 2 unknown => m_currentTripPoint and m_totalTripPoint
*/
float formerTravelCompletion = this->getTravelCompletionPercentage();
if(formerTravelCompletion > m_deccelPercentPath)
{
//invert to be on the acceleration phase => reacceleration
formerTravelCompletion = 1.f - formerTravelCompletion;
}
float notTravelledCompletion = 1.f - formerTravelCompletion;
constexpr const float minEpsilon = 0.001f;
if(notTravelledCompletion < minEpsilon) //security check
{
notTravelledCompletion = minEpsilon;
}
m_totalTripPoint = static_cast<float>(m_finalPath.Num() + 1) / notTravelledCompletion;
m_currentTripPoint = static_cast<int32>(m_totalTripPoint * formerTravelCompletion) + 1;
if(m_currentTripPoint < 1 || m_currentTripPoint > m_totalTripPoint) //something went wrong
{
m_currentTripPoint = 1;
m_totalTripPoint = static_cast<float>(m_finalPath.Num() + 1);
}
}
void ADroneAIController::internalNoisyTravelTransfertMethod(FVector& inOutPoint, const FVector& nextPoint)
{
FVector perp1;
FVector perp2;
inOutPoint.FindBestAxisVectors(perp1, perp2);
float minNoisyTravelRandom = -m_noisyTravelRandom;
perp1 *= FMath::RandRange(minNoisyTravelRandom, m_noisyTravelRandom);
perp2 *= FMath::RandRange(minNoisyTravelRandom, m_noisyTravelRandom);
inOutPoint += (perp1 + perp2);
}<file_sep>/Source/RobotRebellion/Gameplay/Weapon/ShortRangeWeapon.cpp
// Fill out your copyright notice in the Description page of Project Settings.
#include "RobotRebellion.h"
#include "ShortRangeWeapon.h"
#include "Character/RobotRebellionCharacter.h"
#include "../../Global/GlobalDamageMethod.h"
#include "../Damage/Damage.h"
#include "../Damage/DamageCoefficientLogic.h"
#include "Kismet/KismetSystemLibrary.h"
#include "Components/CapsuleComponent.h"
#include "UObjectGlobals.h"
/************************************************************************/
/* CONSTRUCTORS */
/************************************************************************/
UShortRangeWeapon::UShortRangeWeapon() :UWeaponBase()
{
m_weaponForwardRange = 75.f;
m_weaponVerticallyRange = 75.f;
}
/************************************************************************/
/* METHODS */
/************************************************************************/
void UShortRangeWeapon::cppAttack(ARobotRebellionCharacter* user)
{
USoundCue* missSound;
USoundCue* hitSound;
switch(user->GetLocation())
{
case ELocation::BIGROOM:
missSound = m_missBigRoomSound;
hitSound = m_hitBigRoomSound;
break;
case ELocation::CORRIDOR:
missSound = m_missCorridorSound;
hitSound = m_hitCorridorSound;
break;
case ELocation::SMALLROOM:
missSound = m_missSmallRoomSound;
hitSound = m_hitSmallRoomSound;
break;
default:
missSound = m_missOutsideSound;
hitSound = m_hitOutsideSound;
}
if(canAttack())
{
bool alreadyHit = false;
//Sphere for short range collision
FVector MultiSphereStart = user->GetActorLocation() + FVector(0.f, 0.f, -m_weaponVerticallyRange) + m_weaponForwardRange*user->GetActorForwardVector();
FVector MultiSphereEnd = MultiSphereStart + FVector(0.f, 0.f, 2.f * m_weaponVerticallyRange);
//Considered Actors
TArray<TEnumAsByte<EObjectTypeQuery>> ObjectTypes;
ObjectTypes.Add(UEngineTypes::ConvertToObjectType(ECC_Pawn));
//Ignored actors, only user
TArray<AActor*> ActorsToIgnore;
ActorsToIgnore.Add(user);
//Result
TArray<FHitResult> OutHits;
if(UKismetSystemLibrary::SphereTraceMultiForObjects(
user->GetWorld(),
MultiSphereStart,
MultiSphereEnd,
m_weaponForwardRange * user->GetActorForwardVector().Size(),
ObjectTypes,
false,
ActorsToIgnore,
EDrawDebugTrace::None,
OutHits,
true
))
{
ARobotRebellionCharacter** exReceiver = nullptr;
int32 outCount = OutHits.Num();
if(outCount <= 0)
{
playSound(missSound, user);
}
else
{
for(int32 noEnnemy = 0; noEnnemy < outCount; ++noEnnemy)
{
FHitResult hit = OutHits[noEnnemy];
ARobotRebellionCharacter* receiver = Cast<ARobotRebellionCharacter>(hit.GetActor());
if(receiver && exReceiver != &receiver && !receiver->isDead())
{
this->inflictDamageLogic(receiver, hit);
exReceiver = &receiver;
}
}
//playSound(m_hitSound, user);
playSound(hitSound, user);
}
}
else
{
playSound(missSound, user);
}
reload();
}
}
void UShortRangeWeapon::cppAttack(ARobotRebellionCharacter* user, ARobotRebellionCharacter* ennemy)
{
cppAttack(user);
}
void UShortRangeWeapon::inflictDamageLogic(ARobotRebellionCharacter* receiver, const FHitResult& hit)
{
if(!receiver->isImmortal())
{
DamageCoefficientLogic coeff;
FVector ownerToReceiver = receiver->GetActorLocation() - m_owner->GetActorLocation();
ownerToReceiver.Normalize();
if(FVector::DotProduct(ownerToReceiver, receiver->GetActorForwardVector()) > 0.25f)
{
PRINT_MESSAGE_ON_SCREEN_UNCHECKED(FColor::Yellow, "BackStab");
coeff.backstab();
}
Damage damage{ Cast<ARobotRebellionCharacter>(m_owner), receiver };
Damage::DamageValue damageValue = damage(&UGlobalDamageMethod::normalHitWithWeaponComputed, coeff.getCoefficientValue());
receiver->inflictDamage(damageValue);
}
}
FString UShortRangeWeapon::rangeToFString() const USE_NOEXCEPT
{
return "Short Range weapon";
}
void UShortRangeWeapon::playSound_Implementation(USoundCue* sound, AActor* originator)
{
if(sound && originator)
{
UGameplayStatics::SpawnSoundAttached(sound, originator->GetRootComponent());
}
}<file_sep>/Source/RobotRebellion/IA/Character/SovecCharacter.cpp
// Fill out your copyright notice in the Description page of Project Settings.
#include "RobotRebellion.h"
#include "SovecCharacter.h"
#include "../../Gameplay/Weapon/WeaponInventory.h"
ASovecCharacter::ASovecCharacter()
{
GetCapsuleComponent()->BodyInstance.SetCollisionProfileName("Sovec");
m_weaponInventory = CreateDefaultSubobject<UWeaponInventory>(TEXT("WeaponInventory"));
}
<file_sep>/Source/RobotRebellion/Gameplay/Spell/Effects/SpawnEffect.cpp
// Fill out your copyright notice in the Description page of Project Settings.
#include "RobotRebellion.h"
#include "Character/NonPlayableCharacter.h"
#include "SpawnEffect.h"
void USpawnEffect::BeginPlay()
{
Super::BeginPlay();
}
void USpawnEffect::TickComponent(float DeltaTime, ELevelTick TickType, FActorComponentTickFunction* ThisTickFunction)
{
Super::TickComponent(DeltaTime, TickType, ThisTickFunction);
}
void USpawnEffect::exec(ARobotRebellionCharacter* caster, ARobotRebellionCharacter* target)
{
FVector spawnLocation = target->GetActorLocation() + m_offsetFromImpactPoint;
AActor* temp = GetWorld()->SpawnActor<AActor>(m_actorClassToSpawn, spawnLocation, FRotator{0.f});
if(temp)
{
temp->SetLifeSpan(m_actorLifeTime);
// If actor is a pawn with controller we need to manually spawn it
if(m_hasDefaultAIController)
{
// try to cast to NonPlayableCharacter
ANonPlayableCharacter* npc = Cast<ANonPlayableCharacter>(temp);
if(npc)
{
npc->SpawnDefaultController();
}
}
TArray<UProjectileMovementComponent*> movementComp;
temp->GetComponents<UProjectileMovementComponent>(movementComp);
if(movementComp.Num() > 0) // then we could set initiale speed
{
movementComp[0]->MaxSpeed = m_MaxSpeed;
movementComp[0]->Velocity = m_startSpeed;
}
}
}
void USpawnEffect::exec(const FVector& impactPoint, ARobotRebellionCharacter* caster)
{
// TODO - Spawn the actor!
// update position
FVector spawnLocation = impactPoint + m_offsetFromImpactPoint;
AActor* temp = GetWorld()->SpawnActor<AActor>(m_actorClassToSpawn, spawnLocation, FRotator{0.f});
if(temp)
{
temp->SetLifeSpan(m_actorLifeTime);
if(caster != nullptr)
{
temp->SetOwner(caster);
}
// If actor is a pawn with controller we need to manually spawn it
if(m_hasDefaultAIController)
{
// try to cast to NonPlayableCharacter
ANonPlayableCharacter* npc = Cast<ANonPlayableCharacter>(temp);
if(npc)
{
npc->SpawnDefaultController();
}
}
TArray<UProjectileMovementComponent*> movementComp;
temp->GetComponents<UProjectileMovementComponent>(movementComp);
if(movementComp.Num() > 0) // then we could set initiale speed
{
movementComp[0]->MaxSpeed = m_MaxSpeed;
movementComp[0]->Velocity = m_startSpeed;
}
}
}<file_sep>/Source/RobotRebellion/Gameplay/Weapon/LongRangeWeapon.cpp
// Fill out your copyright notice in the Description page of Project Settings.
#include "RobotRebellion.h"
#include "LongRangeWeapon.h"
#include "Projectile.h"
#include "AudioDevice.h"
#include "Kismet/KismetMathLibrary.h"
#include "Character/RobotRebellionCharacter.h"
#include "Character/PlayableCharacter.h"
ULongRangeWeapon::ULongRangeWeapon() :
UWeaponBase()
{}
void ULongRangeWeapon::fireMethod(AProjectile* projectile, const FVector& fireDirection)
{
if(projectile->isRaycast())
{
projectile->simulateInstant(fireDirection, m_WeaponRadiusRange);
}
else
{
projectile->InitProjectileParams(fireDirection, m_WeaponRadiusRange);
}
}
void ULongRangeWeapon::cppAttack(ARobotRebellionCharacter* user)
{
bool canFire = canAttack();
if(canFire && m_projectileClass != NULL)
{
// Retrieve the camera location and rotation
FVector cameraLocation;
FRotator muzzleRotation;
user->GetActorEyesViewPoint(cameraLocation, muzzleRotation);
// m_muzzleOffset is in camera space coordinate => must be transformed to world space coordinate.
const FVector MuzzleLocation = cameraLocation + FTransform(muzzleRotation).TransformVector(m_muzzleOffset);
//muzzleRotation.Pitch += LIFT_OFFSET; // lift the fire a little
UWorld* const World = user->GetWorld();
if(World)
{
FActorSpawnParameters spawnParams;
spawnParams.Owner = user;
spawnParams.Instigator = user->Instigator;
// spawn a projectile
AProjectile* const projectile = World->SpawnActor<AProjectile>(
m_projectileClass,
MuzzleLocation,
muzzleRotation,
spawnParams
);
if(projectile)
{
projectile->setOwner(user);
FVector fireDirection = user->aim(muzzleRotation.Vector());
USoundCue* sound = m_longRangeWeaponOutsideFireSound;
// Fire
fireMethod(projectile, fireDirection);
APlayableCharacter* player = Cast<APlayableCharacter>(user);
if(player)
{
switch(player->GetLocation())
{
case ELocation::BIGROOM:
sound = m_longRangeWeaponBigRoomFireSound;
break;
case ELocation::CORRIDOR:
sound = m_longRangeWeaponCorridorFireSound;
break;
case ELocation::SMALLROOM:
sound = m_longRangeWeaponSmallRoomFireSound;
break;
default:
sound = m_longRangeWeaponOutsideFireSound;
}
}
playSound(sound, user);
reload();
}
}
}
}
void ULongRangeWeapon::cppAttack(ARobotRebellionCharacter* user, ARobotRebellionCharacter* ennemy)
{
bool canFire = canAttack();
if(canFire && m_projectileClass != NULL)
{
// Retrieve the camera location and rotation
FVector cameraLocation;
FRotator muzzleRotation;
user->GetActorEyesViewPoint(cameraLocation, muzzleRotation);
// m_muzzleOffset is in camera space coordinate => must be transformed to world space coordinate.
const FVector MuzzleLocation = cameraLocation + FTransform(muzzleRotation).TransformVector(m_muzzleOffset);
//muzzleRotation.Pitch += LIFT_OFFSET; // lift the fire a little
UWorld* const World = user->GetWorld();
if(World)
{
FActorSpawnParameters spawnParams;
spawnParams.Owner = user;
spawnParams.Instigator = user->Instigator;
// spawn a projectile
AProjectile* const projectile = World->SpawnActor<AProjectile>(
m_projectileClass,
MuzzleLocation,
muzzleRotation,
spawnParams
);
if(projectile)
{
projectile->setOwner(user);
// Fire
const FVector fireDirection = user->aim(UKismetMathLibrary::GetForwardVector(
UKismetMathLibrary::FindLookAtRotation(user->GetActorLocation(), ennemy->GetActorLocation())));
fireMethod(projectile, fireDirection);
USoundCue* sound;
// Fire
fireMethod(projectile, fireDirection);
switch(user->GetLocation())
{
case ELocation::BIGROOM:
sound = m_longRangeWeaponBigRoomFireSound;
break;
case ELocation::CORRIDOR:
sound = m_longRangeWeaponCorridorFireSound;
break;
case ELocation::SMALLROOM:
sound = m_longRangeWeaponSmallRoomFireSound;
break;
default:
sound = m_longRangeWeaponOutsideFireSound;
}
playSound(sound, user);
reload();
}
}
}
}
FString ULongRangeWeapon::rangeToFString() const USE_NOEXCEPT
{
return "Long Range weapon";
}
void ULongRangeWeapon::playSound_Implementation(USoundCue* sound, AActor* originator)
{
if(sound && originator)
{
UGameplayStatics::SpawnSoundAttached(sound, originator->GetRootComponent());
}
}<file_sep>/Source/RobotRebellion/SmallRoomTriggerBox.cpp
// Fill out your copyright notice in the Description page of Project Settings.
#include "RobotRebellion.h"
#include "SmallRoomTriggerBox.h"
#include "Character/RobotRebellionCharacter.h"
ASmallRoomTriggerBox::ASmallRoomTriggerBox()
{
//GetCollisionComponent()->OnComponentHit.AddDynamic(this, &ABigRoomTriggerBox::onOverlapBegin);
GetCollisionComponent()->OnComponentBeginOverlap.AddDynamic(this, &ASmallRoomTriggerBox::onOverlapBegin);
}
void ASmallRoomTriggerBox::BeginPlay()
{
Super::BeginPlay();
}
void ASmallRoomTriggerBox::onOverlapBegin(UPrimitiveComponent* var1, AActor* var2, UPrimitiveComponent* var3,
int32 OtherBodyIndex, bool bFromSweep, const FHitResult& SweepResult)
{
ARobotRebellionCharacter* player = Cast<ARobotRebellionCharacter>(var2);
if(player)
{
PRINT_MESSAGE_ON_SCREEN_UNCHECKED(FColor::Red, "TRIGGER SMALLROOM");
player->setLocation(ELocation::OUTSIDE);
}
}
<file_sep>/Source/RobotRebellion/IA/Controller/EnnemiAIController.h
// Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "CustomAIControllerBase.h"
#include "EnnemiAIController.generated.h"
/**
*
*/
UCLASS()
class ROBOTREBELLION_API AEnnemiAIController : public ACustomAIControllerBase
{
GENERATED_BODY()
public:
void CheckEnnemyNear(float range) override;
void AttackTarget() const override;
};
<file_sep>/Source/RobotRebellion/UI/OptionsMenuWidget.h
// Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "UI/CustomRobotRebellionUserWidget.h"
//#include "Engine/HairWorksMaterial.h"
#include "OptionsMenuWidget.generated.h"
/**
*
*/
UCLASS()
class ROBOTREBELLION_API UOptionsMenuWidget : public UCustomRobotRebellionUserWidget
{
GENERATED_BODY()
private:
//UHairWorksMaterial* m_hairworksMaterial;
public:
UOptionsMenuWidget();
UFUNCTION(BlueprintCallable, Category = "Menu")
void OptionsMenuCheckBox1(bool checkBoxStatus);
UFUNCTION(BlueprintCallable, Category = "Menu")
void OptionsMenuCheckBox2(bool checkBoxStatus);
UFUNCTION(BlueprintCallable, Category = "Menu")
void OptionsMenuCheckBox3(bool checkBoxStatus);
UFUNCTION(BlueprintCallable, Category = "Menu")
void OptionsMenuCheckBox4(bool checkBoxStatus);
UFUNCTION(BlueprintCallable, Category = "Menu")
void OptionsMenuCheckBox5(bool checkBoxStatus);
};
<file_sep>/Source/RobotRebellion/IA/BT/IsTargetInRangeBTTaskNode.cpp
// Fill out your copyright notice in the Description page of Project Settings.
#include "RobotRebellion.h"
#include "IsTargetInRangeBTTaskNode.h"
#include "../Controller/CustomAIControllerBase.h"
#include "Character/RobotRebellionCharacter.h"
#include "../../Gameplay/Weapon/WeaponInventory.h"
#include "../../Gameplay/Weapon/WeaponBase.h"
UIsTargetInRangeBTTaskNode::UIsTargetInRangeBTTaskNode()
{}
EBTNodeResult::Type UIsTargetInRangeBTTaskNode::ExecuteTask(UBehaviorTreeComponent& OwnerComp, uint8* NodeMemory)
{
ACustomAIControllerBase* AIController = Cast<ACustomAIControllerBase>(OwnerComp.GetOwner());
if(AIController)
{
ARobotRebellionCharacter* pawn = Cast<ARobotRebellionCharacter>(AIController->GetPawn());
if(pawn)
{
if(pawn->m_weaponInventory && pawn->m_weaponInventory->getCurrentWeapon())
{
float weaponRangeDistance = pawn->m_weaponInventory->getCurrentWeapon()->m_WeaponRadiusRange;
if(weaponRangeDistance != m_detectingRange)
{
m_detectingRange = weaponRangeDistance;
}
}
}
}
EBTNodeResult::Type NodeResult = EBTNodeResult::Failed;
// If the controller doesn't have a target, the task is a fail
if(AIController->hasALivingTarget())
{
FVector currentTargetLocation = AIController->getTarget()->GetActorLocation();
FVector ennemiLocation = AIController->GetPawn()->GetActorLocation();
ARobotRebellionCharacter* ennemiCharacter = Cast<ARobotRebellionCharacter>(AIController->GetCharacter());
FVector distanceBetween = currentTargetLocation - ennemiLocation;
if(ennemiCharacter->m_weaponInventory)
{
if(distanceBetween.Size() < m_detectingRange) // Ensure the target is at the correct distance
//&& ennemiCharacter->m_weaponInventory->getCurrentWeapon()->canAttack()) // Ensure the AI weapon are reloaded
{
NodeResult = EBTNodeResult::Succeeded;
}
}
}
return NodeResult;
}
void UIsTargetInRangeBTTaskNode::TickTask(UBehaviorTreeComponent& OwnerComp, uint8* NodeMemory, float DeltaSeconds)
{}
FString UIsTargetInRangeBTTaskNode::GetStaticDescription() const
{
return TEXT("Attack the targeted target");
}<file_sep>/Source/RobotRebellion/IA/Character/GunTurretCharacter.cpp
// Fill out your copyright notice in the Description page of Project Settings.
#include "RobotRebellion.h"
#include "GunTurretCharacter.h"
#include "../../Gameplay/Weapon/WeaponInventory.h"
AGunTurretCharacter::AGunTurretCharacter()
{
// Use same collision as player to allow hostiles to attack
GetCapsuleComponent()->BodyInstance.SetCollisionProfileName("Player");
// TODO - initialize with the right weapon :)
m_weaponInventory = CreateDefaultSubobject<UWeaponInventory>(TEXT("WeaponInventory"));
}
<file_sep>/Source/RobotRebellion/IA/Controller/EnnemiAIController.cpp
// Fill out your copyright notice in the Description page of Project Settings.
#include "RobotRebellion.h"
#include "EnnemiAIController.h"
#include "Character/RobotRebellionCharacter.h"
#include "Character/NonPlayableCharacter.h"
#include "Character/PlayableCharacter.h"
#include "Character/King.h"
#include "IA/Character/SovecCharacter.h"
#include "IA/Character/BeastCharacter.h"
#include "Gameplay/Weapon/WeaponInventory.h"
#include "Gameplay/Weapon/WeaponBase.h"
#include "Global/EntityDataSingleton.h"
#include "IA/Character/RobotsCharacter.h"
#include "AIController.h"
#include "Tool/UtilitaryMacros.h"
#include "runtime/AIModule/Classes/BehaviorTree/BlackboardComponent.h"
#include "Runtime/AIModule/Classes/BrainComponent.h"
#include "Kismet/KismetSystemLibrary.h"
#include "Kismet/KismetMathLibrary.h"
//#include "UnrealString.h"
void AEnnemiAIController::CheckEnnemyNear(float range)
{
APawn *currentPawn = GetPawn();
FVector MultiSphereStart = currentPawn->GetActorLocation();
TArray<TEnumAsByte<EObjectTypeQuery>> ObjectTypes{
UEngineTypes::ConvertToObjectType(ECC_GameTraceChannel2), // Players
UEngineTypes::ConvertToObjectType(ECC_GameTraceChannel4), // Sovec
UEngineTypes::ConvertToObjectType(ECC_GameTraceChannel6) // Beasts
};
TArray<AActor*> ActorsToIgnore{ currentPawn };
TArray<FHitResult> OutHits;
if(UKismetSystemLibrary::SphereTraceMultiForObjects(GetWorld(),
MultiSphereStart,
MultiSphereStart,
range,
ObjectTypes,
false,
ActorsToIgnore,
this->debugDrawTraceShowingMode(),
OutHits,
true))
{
int32 countHit = OutHits.Num();
for(int32 i = 0; i < countHit; i++)
{
FHitResult& Hit = OutHits[i];
ARobotRebellionCharacter* RRCharacter = Cast<ARobotRebellionCharacter>(Hit.GetActor());
if(RRCharacter &&
!RRCharacter->isDead() &&
RRCharacter->isVisible())
{
setTarget(RRCharacter);
break;
}
}
}
else
{
setTarget(nullptr);
}
}
void AEnnemiAIController::AttackTarget() const
{
ANonPlayableCharacter* ennemiCharacter = Cast<ANonPlayableCharacter>(GetCharacter());
if(this->getTarget())
{
FVector hitDirection = UKismetMathLibrary::GetForwardVector(
UKismetMathLibrary::FindLookAtRotation(GetPawn()->GetActorLocation(), this->getTarget()->GetActorLocation()));
hitDirection.Z = 0.f;
hitDirection.Normalize();
FVector front = GetPawn()->GetActorForwardVector();
front.Z = 0.f;
front.Normalize();
FVector vert = FVector::CrossProduct(front, hitDirection);
float moveDirection = vert.Z;
float sinAngle = vert.Size();
if(moveDirection > 0.f)
{
GetPawn()->AddActorLocalRotation(FQuat(FVector(0.f, 0.f, 1.f), asinf(sinAngle)), true); //Correct
}
else
{
GetPawn()->AddActorLocalRotation(FQuat(FVector(0.f, 0.f, 1.f), asinf(-sinAngle)), true);
}
ennemiCharacter->m_weaponInventory->getCurrentWeapon()->cppAttack(ennemiCharacter, this->getTarget());
}
else
{
ennemiCharacter->m_weaponInventory->getCurrentWeapon()->cppAttack(ennemiCharacter);
}
}
<file_sep>/Source/RobotRebellion/Gameplay/Attributes/Attributes.h
// Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "Components/ActorComponent.h"
#include "Attributes.generated.h"
#define GENERATED_USING_AND_METHODS_FROM_Attributes(attributeName, operator) public: \
float getHealth() const USE_NOEXCEPT { return attributeName##operator##getHealth(); } \
float getMaxHealth() const USE_NOEXCEPT { return attributeName##operator##getMaxHealth(); } \
float getMana() const USE_NOEXCEPT { return attributeName##operator##getMana(); } \
float getMaxMana() const USE_NOEXCEPT { return attributeName##operator##getMaxMana(); } \
float getStrength() const USE_NOEXCEPT { return attributeName##operator##getStrength(); } \
float getDefense() const USE_NOEXCEPT { return attributeName##operator##getDefense(); } \
float getAgility() const USE_NOEXCEPT { return attributeName##operator##getAgility(); } \
float getShield() const USE_NOEXCEPT { return attributeName##operator##getShield(); } \
void setHealth(float newValue) USE_NOEXCEPT { attributeName##operator##setHealth(newValue); } \
void setMaxHealth(float newValue) USE_NOEXCEPT { attributeName##operator##setMaxHealth(newValue); } \
void setMana(float newValue) USE_NOEXCEPT { attributeName##operator##setMana(newValue); } \
void setMaxMana(float newValue) USE_NOEXCEPT { attributeName##operator##setMaxMana(newValue); } \
void setStrength(float newValue) USE_NOEXCEPT { attributeName##operator##setStrength(newValue); } \
void setDefense(float newValue) USE_NOEXCEPT { attributeName##operator##setDefense(newValue); } \
void setAgility(float newValue) USE_NOEXCEPT { attributeName##operator##setAgility(newValue); } \
void removeShield(float newValue) USE_NOEXCEPT { attributeName##operator##removeShield(newValue); } \
bool isDead() const USE_NOEXCEPT { return !attributeName##operator##isImmortal() && attributeName##operator##isDead(); } \
void setImmortal(bool isImmortal) const USE_NOEXCEPT { attributeName##operator##setImmortal(isImmortal); } \
bool isImmortal() const USE_NOEXCEPT { return attributeName##operator##isImmortal(); } \
void consumeMana(float manaAmount) USE_NOEXCEPT { return attributeName##operator##consumeMana(manaAmount); }
UCLASS(ClassGroup = (Custom), Blueprintable, meta = (BlueprintSpawnableComponent))
class ROBOTREBELLION_API UAttributes : public UActorComponent
{
GENERATED_BODY()
protected:
/************************************************************************/
/* UPROPERTY */
/************************************************************************/
UPROPERTY(EditAnywhere, Replicated, BlueprintReadWrite, Category = Attribute)
float m_health;
UPROPERTY(EditAnywhere, Replicated, BlueprintReadWrite, Category = Attribute)
float m_maxHealth;
UPROPERTY(EditAnywhere, Replicated, BlueprintReadWrite, Category = Attribute)
float m_mana;
UPROPERTY(EditAnywhere, Replicated, BlueprintReadWrite, Category = Attribute)
float m_maxMana;
UPROPERTY(EditAnywhere, Replicated, BlueprintReadWrite, Category = Attribute)
float m_strength;
UPROPERTY(EditAnywhere, Replicated, BlueprintReadWrite, Category = Attribute)
float m_defense;
UPROPERTY(EditAnywhere, Replicated, BlueprintReadWrite, Category = Attribute)
float m_agility;
UPROPERTY(EditAnywhere, Replicated, BlueprintReadWrite, Category = Attribute)
float m_shield;
/************************************************************************/
/* PROPERTY */
/************************************************************************/
void(UAttributes::*m_inflictDamageDelegate)(float);
void(UAttributes::*m_restoreHealthDelegate)(float);
void(UAttributes::*m_restoreManaDelegate)(float);
public:
/************************************************************************/
/* METHODS */
/************************************************************************/
// Sets default values for this component's properties
UAttributes();
// Called when the game starts
virtual void BeginPlay() override;
// Called every frame
virtual void TickComponent(float DeltaTime, ELevelTick TickType, FActorComponentTickFunction* ThisTickFunction) override;
void GetLifetimeReplicatedProps(TArray< FLifetimeProperty > & OutLifetimeProps) const override;
/************************************************************************/
/* GETTER */
/************************************************************************/
/*******HEALTH********/
//get the current health
float getHealth() const USE_NOEXCEPT
{
return m_health;
}
//get the maximum health
float getMaxHealth() const USE_NOEXCEPT
{
return m_maxHealth;
}
/*******MANA********/
//get the current mana value
float getMana() const USE_NOEXCEPT
{
return m_mana;
}
//get the maximum mana value
float getMaxMana() const USE_NOEXCEPT
{
return m_maxMana;
}
/*******STRENGTH********/
//get the current strength
float getStrength() const USE_NOEXCEPT
{
return m_strength;
}
/*******DEFENSE********/
// get the current defense
float getDefense() const USE_NOEXCEPT
{
return m_defense;
}
/*******AGILITY********/
// get the current agility
float getAgility() const USE_NOEXCEPT
{
return m_agility;
}
/*******SHIELD********/
// get the current shield
float getShield() const USE_NOEXCEPT
{
return m_shield;
}
/************************************************************************/
/* SETTER */
/************************************************************************/
/*******HEALTH********/
//set the current health
void setHealth(float newValue) USE_NOEXCEPT
{
m_health = (newValue > m_maxHealth) ? m_maxHealth : ((newValue < 0.f) ? 0.f : newValue);
}
//set the maximum value of health
void setMaxHealth(float newValue) USE_NOEXCEPT;
/*******MANA********/
// set the current mana value
void setMana(float newValue) USE_NOEXCEPT
{
m_mana = (newValue > m_maxMana) ? m_maxMana : ((newValue < 0.f) ? 0.f : newValue);
}
//set the maximum mana value
void setMaxMana(float newValue) USE_NOEXCEPT;
/*******STRENGTH********/
// set the current strength value
void setStrength(float newValue) USE_NOEXCEPT
{
m_strength = newValue;
}
/*******DEFENSE********/
// set the current defense value
void setDefense(float newValue) USE_NOEXCEPT
{
m_defense = newValue;
}
/*******AGILITY********/
// set the current agility value
void setAgility(float newValue) USE_NOEXCEPT
{
m_agility = newValue;
}
/*******SHIELD********/
// set the current shield value
void setShield(float newValue) USE_NOEXCEPT
{
m_shield = newValue;
}
/************************************************************************/
/* UTILITARY */
/************************************************************************/
//Inflict damage, reduce the current health value and if damage > health, health goes to 0
void inflictDamage(float damage)
{
(this->*m_inflictDamageDelegate)(damage);
}
void consumeMana(float manaAmount);
//restore current mana value and if the value to restore is over max_mana, mana goes to max_mana
void restoreMana(float valueToRestore)
{
(this->*m_restoreManaDelegate)(valueToRestore);
}
//restore current health value and if the value to restore is over max_health, health goes to max_health
void restoreHealth(float valueToRestore)
{
(this->*m_restoreHealthDelegate)(valueToRestore);
}
//return true if the player's current health is 0, false otherwise.
bool isDead() const USE_NOEXCEPT
{
return m_health == 0;
}
void setImmortal(bool isImmortal) USE_NOEXCEPT;
bool isImmortal() const USE_NOEXCEPT;
// Add some shield (Do not use negative value, use removeShield)
void addShield(float amount)
{
m_shield += amount;
}
// Remove some shield
void removeShield(float amount);
private:
void inflictDamageMortal(float damage);
void restoreHealthMortal(float restoreValue)
{
setHealth(m_health + restoreValue);
}
void restoreManaMortal(float restoreValue)
{
setMana(m_mana + restoreValue);
}
void immortalMethod(float)
{
PRINT_MESSAGE_ON_SCREEN(FColor::Magenta, "IMMORTAL OBJECT");
}
};
<file_sep>/Source/RobotRebellion/Character/King.h
// Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "NonPlayableCharacter.h"
#include "King.generated.h"
/**
*
*/
UCLASS()
class ROBOTREBELLION_API AKing : public ANonPlayableCharacter
{
GENERATED_BODY()
public:
AKing();
virtual void BeginPlay() override;
virtual void Tick(float deltaTime) override;
virtual void cppOnDeath() override;
//////////////////////////////////////UPROPERTY////////////////////
//King
UPROPERTY(EditDefaultsOnly, Category = drone)
TSubclassOf<class ADroneAIController> m_droneControllerClass;
};
<file_sep>/Source/RobotRebellion/Character/Soldier.h
// Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "PlayableCharacter.h"
#include "Soldier.generated.h"
/**
*
*/
UCLASS()
class ROBOTREBELLION_API ASoldier : public APlayableCharacter
{
GENERATED_BODY()
public:
ASoldier();
EClassType getClassType() const USE_NOEXCEPT override
{
return EClassType::SOLDIER;
}
};
<file_sep>/Source/RobotRebellion/Gameplay/Spell/SphereCastSpell.h
// Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "Gameplay/Spell/Spell.h"
#include "SphereCastSpell.generated.h"
/**
*
*/
UCLASS()
class ROBOTREBELLION_API USphereCastSpell : public USpell
{
GENERATED_BODY()
public:
/** the distance betweent the start location and the end location of the spherecast */
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = SphereCastSpell)
float m_length;
/** radius of the casted shpere*/
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = SphereCastSpell)
float m_sphereRadius;
/** acctor spawnable for effect visual*/
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = VisualEffect)
TSubclassOf<AActor> m_effectActor;
/** specifie if the effect must be moved away from the caster*/
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = VisualEffect)
float m_offset;
/** specifie if the effect must be moved away from the caster*/
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = VisualEffect)
bool m_useEffect;
public:
USphereCastSpell();
virtual void BeginPlay() override;
virtual void cast() override;
// Apply Effects on a target that have to be a RobotRebellion Character
void applyEffect(class ARobotRebellionCharacter* affectedTarget);
// Aplly Effects on a specific location
void applyEffect(FVector impactPoint);
private:
FVector getRealAimingVector(const ARobotRebellionCharacter* caster);
};
<file_sep>/Source/RobotRebellion/Gameplay/Spell/Effects/ProjectileEffect.cpp
// Fill out your copyright notice in the Description page of Project Settings.
#include "RobotRebellion.h"
#include "ProjectileEffect.h"
#include "Gameplay/Spell/ThrowSpell.h"
AProjectileEffect::AProjectileEffect() : AProjectile()
{
m_collisionComp->OnComponentHit.Clear();
m_collisionComp->OnComponentHit.AddDynamic(this, &AProjectileEffect::OnHit);
}
void AProjectileEffect::initMovement(const FVector& shootDirection)
{
if(m_projectileMovement)
{
// Adjust velocity with direction
m_projectileMovement->Velocity = shootDirection * m_projectileMovement->InitialSpeed;
}
}
void AProjectileEffect::setParent(UThrowSpell* effect)
{
m_parentSpell = effect;
}
void AProjectileEffect::OnHit(UPrimitiveComponent* ThisComp, AActor* OtherActor, UPrimitiveComponent* OtherComp, FVector NormalImpulse, const FHitResult& Hit)
{
if(m_hasEffect)
{
spawnEffect();
}
if(Role == ROLE_Authority)
{
m_parentSpell->onHit(ThisComp, OtherActor, OtherComp, NormalImpulse, Hit);
Destroy();
}
else
{
Destroy();
}
}
void AProjectileEffect::GetLifetimeReplicatedProps(TArray<FLifetimeProperty>& OutLifetimeProps) const
{
Super::GetLifetimeReplicatedProps(OutLifetimeProps);
//DOREPLIFETIME(AProjectile, m_owner);
}
void AProjectileEffect::spawnEffect()
{
m_particleSystemComp = UGameplayStatics::SpawnEmitterAtLocation(GetWorld(), m_particleSystem,
GetActorLocation() + m_effectOffset, GetActorRotation(), true);
m_particleSystemComp->SetRelativeScale3D(m_effectScale);
if(Role >= ROLE_Authority)
{
multiSpawnEffect(GetActorLocation());
}
}
void AProjectileEffect::multiSpawnEffect_Implementation(FVector location)
{
m_particleSystemComp = UGameplayStatics::SpawnEmitterAtLocation(GetWorld(), m_particleSystem,
location + m_effectOffset, GetActorRotation(), true);
m_particleSystemComp->SetRelativeScale3D(m_effectScale);
}
bool AProjectileEffect::multiSpawnEffect_Validate(FVector location)
{
return true;
}<file_sep>/Source/RobotRebellion/Tool/IsSingleton.h
// Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#define GENERATED_USING_FROM_IsSingleton(ObjectClassName) private: \
friend class IsSingleton<ObjectClassName>; \
public: \
using IsSingleton<ObjectClassName>::getInstance; \
/**
*
*/
template<class Object>
class ROBOTREBELLION_API IsSingleton
{
private:
static Object m_instance;
protected:
IsSingleton() = default;
public:
virtual ~IsSingleton() = default;
private:
IsSingleton(IsSingleton&) = delete;
IsSingleton& operator=(IsSingleton&) = delete;
protected:
static Object& getInstance() noexcept
{
return m_instance;
}
};
template<class Object> Object IsSingleton<Object>::m_instance;<file_sep>/Source/RobotRebellion/IA/Navigation/NavigationVolumeGraph.h
#pragma once
#include "../../Tool/IsSingleton.h"
#include "RobotRebellion.h"
/**
*
*/
class ROBOTREBELLION_API NavigationVolumeGraph : private IsSingleton<NavigationVolumeGraph>
{
GENERATED_USING_FROM_IsSingleton(NavigationVolumeGraph);
private:
NavigationVolumeGraph();
public:
TArray<class AEditorGraphVolume*> m_edges; // stores every out edges for every vertices size : 2m
TArray<float> m_edgesCosts; // Stores every cost for every edges size : 2m
TArray<int32> m_indexEdgesForNode; // Store where edges begin(into previous array) for every vertice size : n
TArray<AEditorGraphVolume*> m_nodes; // used to store all node in order to build the graph
bool m_isBuilt;
int32 m_NodeAmountExpected;
bool m_showConnection;
public:
~NavigationVolumeGraph();
// Add a new node to the graph
void addNode(class AEditorGraphVolume* newNode);
// Build the graph from m_nodes.
void build();
// Execute A* between the start node and the end node.
// Return every waypoint (including start point) if path found
// if not return an empty array
// TODO - when intergrate it in the project : take a ref to a TArray instead of returning new TArray
TArray<FVector> processAStar(int32 startId, int32 endId) const;
// Return the id of the volume that contains the given point
int32 getOverlappingVolumeId(const FVector &point) const;
// Return the id of the volum below the point and update the point in order to be overlapped by volume
int32 getBelowVolume(FVector& point, float offset) const;
// Return the id of the nearest volume and set the point to the found volume center
int32 getNearestVolume(FVector& point, float offset, bool useCenter = true) const;
int32 getNodeAmount();
int32 getEdgeAmount();
bool isReadyToUse();
// Debug function to write basics intels on the graph
void writeGraph() const;
//Debug Function to show all connections
void drawConnections(const UWorld* world) const;
//empty the graph from everything
void clearGraph();
private:
// sort node by id, change m_nodes array
void sortNodeArray();
};
<file_sep>/Source/RobotRebellion/Gameplay/Weapon/ShortRangeWeapon.h
// Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "WeaponBase.h"
#include "ShortRangeWeapon.generated.h"
/**
*
*/
UCLASS()
class ROBOTREBELLION_API UShortRangeWeapon : public UWeaponBase
{
GENERATED_BODY()
private:
/************************************************************************/
/* UPROPERTY */
/************************************************************************/
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Range", meta = (AllowPrivateAccess = "true"))
float m_weaponForwardRange;
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Range", meta = (AllowPrivateAccess = "true"))
float m_weaponVerticallyRange;
public:
UPROPERTY(EditDefaultsOnly, BlueprintReadWrite, Category = "Sounds")
USoundCue* m_missOutsideSound;
UPROPERTY(EditDefaultsOnly, BlueprintReadWrite, Category = "Sounds")
USoundCue* m_missBigRoomSound;
UPROPERTY(EditDefaultsOnly, BlueprintReadWrite, Category = "Sounds")
USoundCue* m_missSmallRoomSound;
UPROPERTY(EditDefaultsOnly, BlueprintReadWrite, Category = "Sounds")
USoundCue* m_missCorridorSound;
//UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = Sound)
// USoundCue* m_hitSound;
// Weapon Fire Sound
UPROPERTY(EditDefaultsOnly, BlueprintReadWrite, Category = "Sounds")
USoundCue* m_hitOutsideSound;
UPROPERTY(EditDefaultsOnly, BlueprintReadWrite, Category = "Sounds")
USoundCue* m_hitBigRoomSound;
UPROPERTY(EditDefaultsOnly, BlueprintReadWrite, Category = "Sounds")
USoundCue* m_hitSmallRoomSound;
UPROPERTY(EditDefaultsOnly, BlueprintReadWrite, Category = "Sounds")
USoundCue* m_hitCorridorSound;
/************************************************************************/
/* CONSTRUCTORS */
/************************************************************************/
UShortRangeWeapon();
/************************************************************************/
/* UFUNCTION */
/************************************************************************/
UFUNCTION(BlueprintCallable, Category = "General")
virtual EWeaponRange getWeaponRange() const USE_NOEXCEPT override
{
return EWeaponRange::SHORT_RANGE_WEAPON;
}
UFUNCTION(NetMulticast, Reliable)
virtual void playSound(USoundCue* sound, AActor* originator) override;
/************************************************************************/
/* METHODS */
/************************************************************************/
virtual void cppAttack(class ARobotRebellionCharacter* user) override;
virtual void cppAttack(ARobotRebellionCharacter* user, ARobotRebellionCharacter* ennemy) override;
//virtual void playSound(ARobotRebellionCharacter* user) override;
virtual FString rangeToFString() const USE_NOEXCEPT;
virtual void inflictDamageLogic(ARobotRebellionCharacter* receiver, const FHitResult& hit);
};
<file_sep>/Source/RobotRebellion/IA/BT/CheckEnnemyNearBTService.h
// Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "BehaviorTree/BTService.h"
#include "CheckEnnemyNearBTService.generated.h"
/**
*
*/
UCLASS()
class ROBOTREBELLION_API UCheckEnnemyNearBTService : public UBTService
{
GENERATED_BODY()
public:
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Check Radius Settings")
float m_radiusRange;
UCheckEnnemyNearBTService();
/** Will be called at each tick update */
virtual void TickNode(UBehaviorTreeComponent& OwnerComp, uint8* NodeMemory,
float DeltaSeconds) override;
};
<file_sep>/Source/RobotRebellion/Character/PlayableCharacter.cpp
// Fill out your copyright notice in the Description page of Project Settings.
#include "RobotRebellion.h"
#include "PlayableCharacter.h"
#include "Gameplay/Damage/Damage.h"
#include "Global/GlobalDamageMethod.h"
#include "UI/GameMenu.h"
#include "Gameplay/Weapon/WeaponBase.h"
#include "Gameplay/Weapon/WeaponInventory.h"
#include "CustomPlayerController.h"
#include "IA/Controller/DroneAIController.h"
#include "Gameplay/Item/PickupActor.h"
#include "Gameplay/Debug/RobotRobellionSpawnerClass.h"
#include "Assassin.h"
#include "Wizard.h"
#include "Soldier.h"
#include "Healer.h"
#include "Drone.h"
#include "IA/Character/RobotsCharacter.h"
#include "Tool/UtilitaryMacros.h"
#include "Global/EntityDataSingleton.h"
#include "Global/WorldInstanceEntity.h"
#include "Kismet/HeadMountedDisplayFunctionLibrary.h"
#define TYPE_PARSING(TypeName) "Type is "## #TypeName
#define STAND_UP_HEIGHT 70.f
#define CROUCH_HEIGHT -10.f
APlayableCharacter::APlayableCharacter() : ARobotRebellionCharacter()
{
// Set size for collision capsule
GetCapsuleComponent()->InitCapsuleSize(42.f, 96.0f);
// set our turn rates for input
BaseTurnRate = 45.f;
BaseLookUpRate = 45.f;
// Don't rotate when the controller rotates. Let that just affect the camera.
bUseControllerRotationPitch = false;
bUseControllerRotationYaw = false;
bUseControllerRotationRoll = false;
// Configure character movement
GetCharacterMovement()->bOrientRotationToMovement = true; // Character moves in the direction of input...
GetCharacterMovement()->RotationRate = FRotator(0.0f, 540.0f, 0.0f); // ...at this rotation rate
GetCharacterMovement()->JumpZVelocity = 600.f;
GetCharacterMovement()->AirControl = 0.2f;
GetCharacterMovement()->bOrientRotationToMovement = false;
// Create a camera boom (pulls in towards the player if there is a collision)
CameraBoom = CreateDefaultSubobject<USpringArmComponent>(TEXT("CameraBoom"));
CameraBoom->SetupAttachment(RootComponent);
CameraBoom->bUsePawnControlRotation = true; // Rotate the arm based on the controller
// Slight camera offset to aid with object selection
CameraBoom->TargetOffset = FVector(0.f, 0.f, STAND_UP_HEIGHT);
// Create a follow camera
FollowCamera = CreateDefaultSubobject<UCameraComponent>(TEXT("FollowCamera"));
FollowCamera->SetupAttachment(CameraBoom, USpringArmComponent::SocketName); // Attach the camera to the end of the boom and let the boom adjust to match the controller orientation
FollowCamera->bUsePawnControlRotation = false; // Camera does not rotate relative to arm
// Note: The skeletal mesh and anim blueprint references on the Mesh component (inherited from Character)
// are set in the derived blueprint asset named MyCharacter (to avoid direct content references in C++)
m_spawner = CreateDefaultSubobject<URobotRobellionSpawnerClass>(TEXT("SpawnerClass"));
m_weaponInventory = CreateDefaultSubobject<UWeaponInventory>(TEXT("WeaponInventory"));
m_spellKit = CreateDefaultSubobject<USpellKit>(TEXT("SpellKit"));
m_moveForwardSpeed = 0.f;
m_moveStraphSpeed = 0.f;
m_bPressedCrouch = false;
m_bPressedRun = false;
MinUseDistance = 75.0f;
MaxUseDistance = 250.0f;
PrimaryActorTick.bCanEverTick = true;
//GetCapsuleComponent()->SetCollisionObjectType(ECC_GameTraceChannel2);
GetCapsuleComponent()->BodyInstance.SetCollisionProfileName("Players");
m_fpsMesh = CreateDefaultSubobject<USkeletalMeshComponent>(TEXT("FPS Mesh"));
m_fpsMesh->SetupAttachment(GetCapsuleComponent());
m_fpsMesh->SetVisibility(false);
//Revive
m_isReviving = false;
this->deactivatePhysicsKilledMethodPtr = &APlayableCharacter::doesNothing;
/*m_isBurnEffectEnabled = true;*/
}
void APlayableCharacter::SetupPlayerInputComponent(class UInputComponent* PlayerInputComponent)
{
CameraBoom->SocketOffset = m_mireOffset;
// Set up gameplay key bindings
check(PlayerInputComponent);
inputOnLiving(PlayerInputComponent);
}
void APlayableCharacter::BeginPlay()
{
Super::BeginPlay();
m_manaPotionsCount = m_nbManaPotionStart;
m_bombCount = m_nbBombStart;
m_healthPotionsCount = m_nbHealthPotionStart;
CameraBoom->TargetArmLength = m_TPSCameraDistance; // The camera follows at this distance behind the character
m_tpsMode = true;
// InputMode UI to select classes
APlayerController* MyPC = Cast<APlayerController>(GetController());
if(MyPC)
{
this->EnablePlayInput(false);
}
}
void APlayableCharacter::Tick(float DeltaTime)
{
Super::Tick(DeltaTime);
if(Controller && Controller->IsLocalController())
{
AActor* usable = Cast<AActor>(GetUsableInView());
// Terminer le focus sur l'objet pr�c�dent
if(focusedPickupActor != usable)
{
m_isReviving = false;
m_currentRevivingTime = 0.f;
//PRINT_MESSAGE_ON_SCREEN(FColor::Red, "Lost Focused");
bHasNewFocus = true;
}
// Assigner le nouveau focus (peut �tre nul)
focusedPickupActor = usable;
// D�marrer un nouveau focus si Usable != null;
if(usable && usable->GetName() != "Floor")
{
if(bHasNewFocus)
{
bHasNewFocus = false;
// only debug utility
//PRINT_MESSAGE_ON_SCREEN(FColor::Yellow, TEXT("Focus"));
}
if(m_isReviving)
{
m_currentRevivingTime += DeltaTime;
if(m_currentRevivingTime >= m_requiredTimeToRevive)
{
m_isReviving = false;
m_currentRevivingTime = 0.f;
APlayableCharacter* charac = Cast<APlayableCharacter>(focusedPickupActor);
if(charac)
{
cppPreRevive(charac);
}
}
}
}
}
(this->*deactivatePhysicsKilledMethodPtr)();
this->updateIfInCombat();
//PRINT_MESSAGE_ON_SCREEN_UNCHECKED(FColor::Red, "Combat : " + FString::FromInt(m_isInCombat));
}
void APlayableCharacter::updateIfInCombat()
{
EntityDataSingleton& data = EntityDataSingleton::getInstance();
TArray<ARobotsCharacter*>& robots = data.m_robotArray;
uint32 robotCount = robots.Num();
for(uint32 iter = 0; iter < robotCount; ++iter)
{
ARobotsCharacter* rob = robots[iter];
if(rob && !rob->IsPendingKillOrUnreachable() && rob->m_isInCombat)
{
m_isInCombat = true;
return;
}
}
m_isInCombat = false;
}
void APlayableCharacter::TurnAtRate(float Rate)
{
// calculate delta for this frame from the rate information
AddControllerYawInput(Rate * BaseTurnRate * GetWorld()->GetDeltaSeconds());
}
void APlayableCharacter::LookUpAtRate(float Rate)
{
// calculate delta for this frame from the rate information
AddControllerPitchInput(Rate * BaseLookUpRate * GetWorld()->GetDeltaSeconds());
}
void APlayableCharacter::MoveForward(float value)
{
if(Controller != NULL)
{
// find out which way is forward
const FRotator Rotation = Controller->GetControlRotation();
const FRotator YawRotation(0.f, Rotation.Yaw, 0.f);
// get forward vector
const FVector direction = FRotationMatrix(YawRotation).GetUnitAxis(EAxis::X);
if(value == 0.f)
{
m_moveForwardSpeed -= m_decelerationCoeff * m_maxVelocity;
if(m_moveForwardSpeed < 0.f)
{
m_moveForwardSpeed = 0.f;
}
}
else
{
m_strafForwardMemory = value;
if(m_moveForwardSpeed <= m_maxVelocity)
{
m_moveForwardSpeed += m_accelerationCoeff * m_maxVelocity;
if(m_moveForwardSpeed > m_maxVelocity)
{
m_moveForwardSpeed = m_maxVelocity;
}
}
else //we're already sup -> the only way to go there was to decrease max velocity
{
m_moveForwardSpeed -= m_decelerationCoeff * m_maxVelocity;
}
}
AddMovementInput(direction, m_moveForwardSpeed * m_strafForwardMemory * 0.5f);
//PRINT_MESSAGE_ON_SCREEN_UNCHECKED(FColor::Blue, FString::Printf(TEXT("Forward : Value Input : %f\nVelocity : %f"), value, m_moveForwardSpeed));
}
}
void APlayableCharacter::MoveRight(float value)
{
if(Controller != NULL)
{
// find out which way is forward
const FRotator Rotation = Controller->GetControlRotation();
const FRotator YawRotation(0.f, Rotation.Yaw, 0.f);
// get forward vector
const FVector direction = FRotationMatrix(YawRotation).GetUnitAxis(EAxis::Y);
if(value == 0.f)
{
m_moveStraphSpeed -= m_decelerationCoeff * m_maxVelocity;
if(m_moveStraphSpeed < 0.f)
{
m_moveStraphSpeed = 0.f;
}
}
else
{
m_strafRightMemory = value;
if(m_moveStraphSpeed <= m_maxVelocity)
{
m_moveStraphSpeed += m_accelerationCoeff * m_maxVelocity;
if(m_moveStraphSpeed > m_maxVelocity)
{
m_moveStraphSpeed = m_maxVelocity;
}
}
else //we're already sup -> the only way to go there was to decrease max velocity
{
m_moveStraphSpeed -= m_decelerationCoeff * m_maxVelocity;
}
}
AddMovementInput(direction, m_moveStraphSpeed * m_strafRightMemory * 0.5f);
//PRINT_MESSAGE_ON_SCREEN_UNCHECKED(FColor::Blue, FString::Printf(TEXT("Strafe : Value Input : %f\nVelocity : %f"), value, m_moveStraphSpeed));
}
}
///// SERVER
void APlayableCharacter::GetLifetimeReplicatedProps(TArray< FLifetimeProperty > & OutLifetimeProps) const
{
Super::GetLifetimeReplicatedProps(OutLifetimeProps);
DOREPLIFETIME_CONDITION(APlayableCharacter, m_bPressedCrouch, COND_SkipOwner);
DOREPLIFETIME_CONDITION(APlayableCharacter, m_bPressedRun, COND_SkipOwner);
DOREPLIFETIME_CONDITION(APlayableCharacter, m_bombCount, COND_OwnerOnly);
DOREPLIFETIME_CONDITION(APlayableCharacter, m_healthPotionsCount, COND_OwnerOnly);
DOREPLIFETIME_CONDITION(APlayableCharacter, m_manaPotionsCount, COND_OwnerOnly);
//try spell replication
DOREPLIFETIME_CONDITION(APlayableCharacter, m_spellKit, COND_OwnerOnly);
}
void APlayableCharacter::ExecuteCommand(FString command) const
{
APlayerController* MyPC = Cast<APlayerController>(Controller);
if(MyPC)
{
MyPC->ConsoleCommand(command, true);
PRINT_MESSAGE_ON_SCREEN(FColor::Red, command);
}
}
///// JUMP
void APlayableCharacter::OnStartJump()
{
if(m_bPressedCrouch)
{
OnCrouchToggle();
}
else
{
bPressedJump = true;
}
}
void APlayableCharacter::OnStopJump()
{
bPressedJump = false;
}
///// SPRINT
void APlayableCharacter::OnStartSprint()
{
if(m_bPressedCrouch)
{
OnCrouchToggle();
}
else
{
//increase move speed
m_maxVelocity = m_maxRunVelocity;
m_bPressedRun = true;
if(Role < ROLE_Authority)
{
ServerSprintActivate(m_bPressedRun);
}
}
}
void APlayableCharacter::OnStopSprint()
{
//decrease move speed
m_maxVelocity = m_maxWalkVelocity;
m_bPressedRun = false;
// Si nous sommes sur un client
if(Role < ROLE_Authority)
{
ServerSprintActivate(m_bPressedRun);
}
}
void APlayableCharacter::ServerSprintActivate_Implementation(bool NewRunning)
{
if(NewRunning)
{
OnStartSprint();
}
else
{
OnStopSprint();
}
}
bool APlayableCharacter::ServerSprintActivate_Validate(bool NewRunning)
{
return true;
}
void APlayableCharacter::OnRep_SprintButtonDown()
{
if(m_bPressedRun == true)
{
OnStartSprint();
}
else
{
OnStopSprint();
}
}
/////CROUCH
void APlayableCharacter::ServerCrouchToggle_Implementation(bool NewCrouching)
{
OnCrouchToggle();
}
bool APlayableCharacter::ServerCrouchToggle_Validate(bool NewCrouching)
{
return true;
}
void APlayableCharacter::OnRep_CrouchButtonDown()
{
if(m_bPressedCrouch == true)
{
Crouch();
}
else
{
UnCrouch();
}
}
void APlayableCharacter::OnCrouchToggle()
{
// Not crouched and not running -> can Crouch
if(!IsRunning())
{
if(!m_bPressedCrouch)
{
m_bPressedCrouch = true;
m_maxVelocity = m_maxCrouchVelocity;
CameraBoom->TargetOffset.Z = CROUCH_HEIGHT;
this->BaseEyeHeight = CROUCH_HEIGHT;
Crouch();
}
else
{
m_bPressedCrouch = false;
m_maxVelocity = m_maxWalkVelocity;
CameraBoom->TargetOffset.Z = STAND_UP_HEIGHT;
this->BaseEyeHeight = STAND_UP_HEIGHT;
UnCrouch();
}
}
// Si nous sommes sur un client
if(Role < ROLE_Authority)
{
ServerCrouchToggle(true); // le param n'a pas d'importance pour l'instant
}
}
//////FIRE/////
void APlayableCharacter::mainFire()
{
// Essayer de tirer un projectile
if(Role < ROLE_Authority)
{
serverMainFire(); // le param n'a pas d'importance pour l'instant
}
else
{
m_weaponInventory->getCurrentWeapon()->cppAttack(this);
}
}
void APlayableCharacter::serverMainFire_Implementation()
{
mainFire();
}
bool APlayableCharacter::serverMainFire_Validate()
{
return true;
}
//DEAD
//Function to call in BP, can't do it with macro
bool APlayableCharacter::isDeadBP()
{
return isDead();
}
////// SPELL CAST /////
bool APlayableCharacter::castSpellServer_Validate(int32 index)
{
return true;
}
void APlayableCharacter::castSpellServer_Implementation(int32 index)
{
castSpell(index);
}
void APlayableCharacter::castSpell(int32 index)
{
m_spellKit->cast(index);
}
//TYPE
EClassType APlayableCharacter::getClassType() const USE_NOEXCEPT
{
return EClassType::NONE;
}
EClassType APlayableCharacter::getType() const USE_NOEXCEPT
{
return this->getClassType();
}
/////////UI
void APlayableCharacter::openTopWidget()
{
APlayerController* MyPC = Cast<APlayerController>(Controller);
if(MyPC)
{
auto myHud = Cast<AGameMenu>(MyPC->GetHUD());
if(myHud->TopWidgetImpl->IsVisible())
{
closeTopWidget();
return;
}
bool gameStarted = false;
UWorld* w = this->GetWorld();
TArray<AActor*> entity;
UGameplayStatics::GetAllActorsOfClass(w, AWorldInstanceEntity::StaticClass(), entity);
if(entity.Num() > 0)
{
gameStarted = Cast<AWorldInstanceEntity>(entity[0])->getGameStarted();
}
if(gameStarted)
{
Cast<AWorldInstanceEntity>(myHud->TopWidgetImpl);
myHud->TopWidgetImpl->setReturnInGameVisible(true);
}
myHud->DisplayWidget(myHud->TopWidgetImpl);
giveInputGameMode(false);
}
}
void APlayableCharacter::closeTopWidget()
{
APlayerController* MyPC = Cast<APlayerController>(Controller);
if(MyPC)
{
auto myHud = Cast<AGameMenu>(MyPC->GetHUD());
myHud->HideWidget(myHud->TopWidgetImpl);
giveInputGameMode(true);
}
}
void APlayableCharacter::openLobbyWidget()
{
APlayerController* MyPC = Cast<APlayerController>(Controller);
if(MyPC)
{
auto myHud = Cast<AGameMenu>(MyPC->GetHUD());
if(myHud->LobbyImpl->IsVisible())
{
closeLobbyWidget();
return;
}
myHud->DisplayWidget(myHud->LobbyImpl);
giveInputGameMode(false);
}
}
void APlayableCharacter::closeLobbyWidget()
{
APlayerController* MyPC = Cast<APlayerController>(Controller);
if(MyPC)
{
auto myHud = Cast<AGameMenu>(MyPC->GetHUD());
myHud->HideWidget(myHud->LobbyImpl);
//TODO: BUGBUG
if(myHud->TopWidgetImpl->IsVisible())
{
closeTopWidget();
}
giveInputGameMode(true);
}
}
void APlayableCharacter::closeSelectionWidget()
{
APlayerController* MyPC = Cast<APlayerController>(this->GetController());
if(MyPC)
{
auto myHud = Cast<AGameMenu>(MyPC->GetHUD());
myHud->HideWidget(myHud->ClassSelectionWidgetImpl);
myHud->DisplayWidget(myHud->HUDCharacterImpl);
giveInputGameMode(true);
}
}
void APlayableCharacter::closeOptionWidget()
{
APlayerController* MyPC = Cast<APlayerController>(Controller);
if(MyPC)
{
auto myHud = Cast<AGameMenu>(MyPC->GetHUD());
myHud->HideWidget(myHud->OptionsWidgetImpl);
//giveInputGameMode(true);
myHud->DisplayWidget(myHud->TopWidgetImpl);
giveInputGameMode(false);
}
}
void APlayableCharacter::giveInputGameMode(bool status)
{
ACustomPlayerController* MyPC = Cast<ACustomPlayerController>(this->GetController());
if(MyPC)
{
EnablePlayInput(status);
MyPC->setInputMode(status);
}
}
///////// SWITCH WEAPON
void APlayableCharacter::switchWeapon()
{
if(Role < ROLE_Authority)
{
serverSwitchWeapon(); // le param n'a pas d'importance pour l'instant
m_weaponInventory->switchWeapon(); // switch weapon locally to show it on HUD
}
else
{
FString message = m_weaponInventory->toFString() + TEXT(" Go to : ");
m_weaponInventory->switchWeapon();
message += m_weaponInventory->toFString();
PRINT_MESSAGE_ON_SCREEN(FColor::Yellow, message);
}
}
void APlayableCharacter::interactBegin()
{
interact(GetUsableInView());
}
void APlayableCharacter::interact(AActor* focusedActor)
{
if(Role >= ROLE_Authority)
{
APickupActor* Usable = Cast<APickupActor>(focusedActor);
APlayableCharacter* deadBody = Cast<APlayableCharacter>(focusedActor);
ADrone* drone = Cast<ADrone>(focusedActor);
if(Usable) //focusedActor is an Usable Object
{
if(Usable->getObjectType() == EObjectType::MANA_POTION)
{
if(m_manaPotionsCount < m_nbManaPotionMax)
{
clientInteract(Usable);
++m_manaPotionsCount;
}
}
else if(Usable->getObjectType() == EObjectType::HEALTH_POTION)
{
if(m_healthPotionsCount < m_nbHealthPotionMax)
{
clientInteract(Usable);
++m_healthPotionsCount;
}
}
else if(Usable->getObjectType() == EObjectType::BOMB)
{
if(m_bombCount < m_nbBombMax)
{
clientInteract(Usable);
++m_bombCount;
}
}
else
{
PRINT_MESSAGE_ON_SCREEN(FColor::Blue, TEXT("INVALID OBJECT"));
}
}
else if(deadBody && deadBody->isDead() && m_currentRevivingTime < m_requiredTimeToRevive) //Focused Actor is a corpse
{
PRINT_MESSAGE_ON_SCREEN(FColor::Blue, TEXT("Dead Body"));
clientRevive();
m_isReviving = true;
}
else if(drone)
{
ADroneAIController* droneController = Cast<ADroneAIController>(drone->GetController());
if(droneController)
{
PRINT_MESSAGE_ON_SCREEN(FColor::Purple, "InteractDroneControler");
giveBombToDrone(droneController);
}
}
}
else
{
serverInteract(focusedActor);
}
}
void APlayableCharacter::serverInteract_Implementation(AActor* focusedActor)
{
this->interact(focusedActor);
}
bool APlayableCharacter::serverInteract_Validate(AActor* focusedActor)
{
return true;
}
void APlayableCharacter::interactEnd()
{
m_isReviving = false;
m_currentRevivingTime = 0.f;
}
void APlayableCharacter::giveBombToDrone(ADroneAIController* drone)
{
if(Role >= ROLE_Authority)
{
if(!drone->HasABomb() && m_bombCount > 0)
{
drone->receiveBomb();
--m_bombCount;
PRINT_MESSAGE_ON_SCREEN(FColor::Purple, "ServergiveBombToDrone");
}
return;
}
PRINT_MESSAGE_ON_SCREEN(FColor::Purple, "giveBombToDrone");
serverGiveBombToDrone(drone);
}
void APlayableCharacter::serverGiveBombToDrone_Implementation(ADroneAIController* drone)
{
if(!drone->HasABomb() && m_bombCount > 0)
{
drone->receiveBomb();
--m_bombCount;
PRINT_MESSAGE_ON_SCREEN(FColor::Red, "ServergiveBombToDrone");
}
}
bool APlayableCharacter::serverGiveBombToDrone_Validate(ADroneAIController* drone)
{
return true;
}
void APlayableCharacter::serverSwitchWeapon_Implementation()
{
this->switchWeapon();
}
void APlayableCharacter::clientInteract_Implementation(APickupActor* Usable)
{
Usable->OnPickup(this);
}
void APlayableCharacter::OnPickup(APawn * InstigatorPawn)
{
PRINT_MESSAGE_ON_SCREEN(FColor::Yellow, "focusActor")
}
void APlayableCharacter::updateAllCharacterBillboard_Implementation(UCameraComponent* camToFollow)
{
TArray<AActor*> OutArray;
UGameplayStatics::GetAllActorsOfClass(GetWorld(), ARobotRebellionCharacter::StaticClass(), OutArray);
for(AActor* charc : OutArray)
{
ARobotRebellionCharacter* RRCharac = Cast<ARobotRebellionCharacter>(charc);
if(RRCharac)
{
RRCharac->setBillboardInstanceNewCamera(camToFollow);
}
}
}
void APlayableCharacter::clientRevive_Implementation()
{
m_isReviving = true;
}
bool APlayableCharacter::serverSwitchWeapon_Validate()
{
return true;
}
/************************************************************************/
/* DEBUG / CHEAT */
/************************************************************************/
void APlayableCharacter::onDebugCheat()
{
if(Role == ROLE_Authority)
{
if(this->isImmortal())
{
this->setImmortal(false);
}
else
{
this->setImmortal(true);
}
PRINT_MESSAGE_ON_SCREEN_UNCHECKED(FColor::Cyan, FString::Printf(TEXT("Immortality Status : %d"), this->isImmortal()));
}
else
{
serverOnDebugCheat();
}
}
bool APlayableCharacter::serverOnDebugCheat_Validate()
{
return true;
}
void APlayableCharacter::serverOnDebugCheat_Implementation()
{
onDebugCheat();
}
FString APlayableCharacter::typeToString() const USE_NOEXCEPT
{
static const FString typeLookUpTable[] = {
TYPE_PARSING(None),
TYPE_PARSING(Soldier),
TYPE_PARSING(Assassin),
TYPE_PARSING(Healer),
TYPE_PARSING(Wizard)
};
return typeLookUpTable[static_cast<uint8>(getClassType())];
}
void APlayableCharacter::changeInstanceTo(EClassType toType)
{
m_spawner->spawnAndReplace(this, toType);
UWorld* w = this->GetWorld();
TArray<AActor*> entity;
UGameplayStatics::GetAllActorsOfClass(w, AWorldInstanceEntity::StaticClass(), entity);
if(entity.Num() > 0)
{
Cast<AWorldInstanceEntity>(entity[0])->setStartGameMode();
}
}
void APlayableCharacter::changeToAssassin()
{
changeInstanceTo(EClassType::ASSASSIN);
}
void APlayableCharacter::changeToHealer()
{
changeInstanceTo(EClassType::HEALER);
}
void APlayableCharacter::changeToSoldier()
{
changeInstanceTo(EClassType::SOLDIER);
}
void APlayableCharacter::changeToWizard()
{
changeInstanceTo(EClassType::WIZARD);
}
void APlayableCharacter::inputOnLiving(class UInputComponent* PlayerInputComponent)
{
if(PlayerInputComponent)
{
PlayerInputComponent->BindAction("Jump", IE_Pressed, this, &APlayableCharacter::OnStartJump);
PlayerInputComponent->BindAction("Jump", IE_Released, this, &APlayableCharacter::OnStopJump);
PlayerInputComponent->BindAxis("MoveForward", this, &APlayableCharacter::MoveForward);
PlayerInputComponent->BindAxis("MoveRight", this, &APlayableCharacter::MoveRight);
// We have 2 versions of the rotation bindings to handle different kinds of devices differently
// "turn" handles devices that provide an absolute delta, such as a mouse.
// "turnrate" is for devices that we choose to treat as a rate of change, such as an analog joystick
PlayerInputComponent->BindAxis("Turn", this, &APawn::AddControllerYawInput);
PlayerInputComponent->BindAxis("TurnRate", this, &APlayableCharacter::TurnAtRate);
PlayerInputComponent->BindAxis("LookUp", this, &APawn::AddControllerPitchInput);
PlayerInputComponent->BindAxis("LookUpRate", this, &APlayableCharacter::LookUpAtRate);
//Crouch & Sprint
PlayerInputComponent->BindAction("Crouch", IE_Released, this, &APlayableCharacter::OnCrouchToggle);
PlayerInputComponent->BindAction("Sprint", IE_Pressed, this, &APlayableCharacter::OnStartSprint);
PlayerInputComponent->BindAction("Sprint", IE_Released, this, &APlayableCharacter::OnStopSprint);
//FIRE
PlayerInputComponent->BindAction("MainFire", IE_Pressed, this, &APlayableCharacter::mainFire);
/* Removed cause feature cut
PlayerInputComponent->BindAction("SecondFire", IE_Pressed, this, &APlayableCharacter::secondFire);
*/
//ESCAPE
PlayerInputComponent->BindAction("Escape", IE_Pressed, this, &APlayableCharacter::openTopWidget);
//SWITCH WEAPON
PlayerInputComponent->BindAction("SwitchWeapon", IE_Pressed, this, &APlayableCharacter::switchWeapon);
//INTERACT
PlayerInputComponent->BindAction("Interact", IE_Pressed, this, &APlayableCharacter::interactBegin);
PlayerInputComponent->BindAction("Interact", IE_Released, this, &APlayableCharacter::interactEnd);
//SPELLS
PlayerInputComponent->BindAction("Spell1", IE_Pressed, this, &APlayableCharacter::castSpellInputHanlder<0>);
PlayerInputComponent->BindAction("Spell2", IE_Pressed, this, &APlayableCharacter::castSpellInputHanlder<1>);
PlayerInputComponent->BindAction("Spell3", IE_Pressed, this, &APlayableCharacter::castSpellInputHanlder<2>);
/* Removed cause feature cut
PlayerInputComponent->BindAction("Spell4", IE_Pressed, this, &APlayableCharacter::castSpellInputHanlder<3>);
*/
//USE OBJECTS
PlayerInputComponent->BindAction("LifePotion", IE_Pressed, this, &APlayableCharacter::useHealthPotion);
PlayerInputComponent->BindAction("ManaPotion", IE_Pressed, this, &APlayableCharacter::useManaPotion);
//VIEW
/* Remove to ensure we dont switch to FPV during presentation
PlayerInputComponent->BindAction("SwitchView", IE_Pressed, this, &APlayableCharacter::switchView);
*/
//CHANGE MAP
PlayerInputComponent->BindAction("Debug_GotoDesert", IE_Released, this, &APlayableCharacter::gotoDesert);
PlayerInputComponent->BindAction("Debug_GotoRuins", IE_Released, this, &APlayableCharacter::gotoRuins);
PlayerInputComponent->BindAction("Debug_GotoGym", IE_Released, this, &APlayableCharacter::gotoGym);
PlayerInputComponent->BindAction("Debug_CheatCode", IE_Released, this, &APlayableCharacter::onDebugCheat);
////Fire Effect
PlayerInputComponent->BindAction("DisableFireEffect", IE_Pressed, this, &APlayableCharacter::disableFireEffect);
/************************************************************************/
/* DEBUG */
/************************************************************************/
inputDebug(PlayerInputComponent);
}
}
void APlayableCharacter::inputOnDying(class UInputComponent* PlayerInputComponent)
{
if(PlayerInputComponent)
{
//ESCAPE
PlayerInputComponent->BindAction("Escape", IE_Pressed, this, &APlayableCharacter::openTopWidget);
/************************************************************************/
/* DEBUG */
/************************************************************************/
inputDebug(PlayerInputComponent);
}
}
void APlayableCharacter::inputDebug(class UInputComponent* PlayerInputComponent)
{
//Class change
PlayerInputComponent->BindAction("Debug_ChangeToAssassin", IE_Pressed, this, &APlayableCharacter::changeToAssassin);
PlayerInputComponent->BindAction("Debug_ChangeToHealer", IE_Pressed, this, &APlayableCharacter::changeToHealer);
PlayerInputComponent->BindAction("Debug_ChangeToSoldier", IE_Pressed, this, &APlayableCharacter::changeToSoldier);
PlayerInputComponent->BindAction("Debug_ChangeToWizard", IE_Pressed, this, &APlayableCharacter::changeToWizard);
//Display Drone UT Scores
PlayerInputComponent->BindAction("Debug_DroneDisplay", IE_Pressed, this, &APlayableCharacter::enableDroneDisplay);
}
void APlayableCharacter::cppPreRevive(APlayableCharacter* characterToRevive)
{
if(Role >= ROLE_Authority)
{
characterToRevive->restoreHealth(characterToRevive->getMaxHealth() / 2);
PRINT_MESSAGE_ON_SCREEN(FColor::Red, "Prerevive");
return;
}
this->serverCppPreRevive(characterToRevive);
}
void APlayableCharacter::serverCppPreRevive_Implementation(APlayableCharacter* characterToRevive)
{
cppPreRevive(characterToRevive);
}
bool APlayableCharacter::serverCppPreRevive_Validate(APlayableCharacter* characterToRevive)
{
return true;
}
void APlayableCharacter::cppOnRevive()
{
this->EnablePlayInput(true);
this->activatePhysics(true);
PRINT_MESSAGE_ON_SCREEN(FColor::Blue, TEXT("Revive"));
}
void APlayableCharacter::cppOnDeath()
{
if(!this->GetMovementComponent()->IsFalling())
{
this->activatePhysics(false);
}
else
{
this->deactivatePhysicsKilledMethodPtr = &APlayableCharacter::deactivatePhysicsWhenKilled;
}
this->EnablePlayInput(false);
this->m_alterationController->removeAllAlteration();
this->m_currentRevivingTime = 0.f;
}
void APlayableCharacter::deactivatePhysicsWhenKilled()
{
if(this->GetMovementComponent()->IsFalling())
{
return;
}
this->activatePhysics(false);
this->deactivatePhysicsKilledMethodPtr = &APlayableCharacter::doesNothing;
}
void APlayableCharacter::EnablePlayInput(bool enable)
{
APlayerController* playerController = Cast<APlayerController>(GetController());
if(playerController && playerController->InputComponent)
{
UInputComponent* newPlayerController = CreatePlayerInputComponent();
if(enable)
{
inputOnLiving(newPlayerController);
}
else
{
inputOnDying(newPlayerController);
}
playerController->InputComponent = newPlayerController;
}
if(Role >= ROLE_Authority)
{
clientEnableInput(enable);
}
}
GENERATE_IMPLEMENTATION_METHOD_AND_DEFAULT_VALIDATION_METHOD(APlayableCharacter, clientEnableInput, bool enableInput)
{
APlayerController* playerController = Cast<APlayerController>(GetController());
if(playerController && playerController->InputComponent)
{
UInputComponent* newPlayerController = CreatePlayerInputComponent();
if(enableInput)
{
inputOnLiving(newPlayerController);
}
else
{
inputOnDying(newPlayerController);
}
playerController->InputComponent = newPlayerController;
}
}
AActor* APlayableCharacter::GetUsableInView()
{
FVector CamLoc;
FVector eyeLoc;
FRotator CamRot;
FRotator eyeRot;
if(Controller == NULL)
{
return NULL;
}
GetActorEyesViewPoint(eyeLoc, eyeRot);
Controller->GetPlayerViewPoint(CamLoc, CamRot);
const FVector Direction = CamRot.Vector();
const FVector TraceStart = GetActorLocation() + Direction * MinUseDistance + FVector(0.0f, 0.0f, BaseEyeHeight);
const FVector TraceEnd = TraceStart + (Direction * MaxUseDistance);
FCollisionQueryParams TraceParams(FName(TEXT("TraceUsableActor")), true, this);
TraceParams.bTraceAsyncScene = true;
TraceParams.bReturnPhysicalMaterial = false;
//TraceParams.bTraceComplex = true;
FHitResult Hit(ForceInit);
GetWorld()->LineTraceSingleByChannel(Hit, TraceStart, TraceEnd, ECC_WorldStatic, TraceParams);
//TODO: Comment or remove once implemented in post-process.
//DrawDebugLine(GetWorld(), TraceStart, TraceEnd, FColor::Red, false, 1.0f);
return (Hit.GetActor());
}
//////INVENTORY///////
void APlayableCharacter::useHealthPotion()
{
if(Role < ROLE_Authority)
{
serverUseHealthPotion();
}
else if(m_healthPotionsCount > 0 && getHealth() < getMaxHealth())
{
restoreHealth(m_healthPerPotion);
--m_healthPotionsCount;
}
}
void APlayableCharacter::serverUseHealthPotion_Implementation()
{
useHealthPotion();
}
bool APlayableCharacter::serverUseHealthPotion_Validate()
{
return true;
}
void APlayableCharacter::useManaPotion()
{
if(Role < ROLE_Authority)
{
serverUseManaPotion();
}
else if(m_manaPotionsCount > 0 && getMana() < getMaxMana())
{
restoreMana(m_manaPerPotion);
--m_manaPotionsCount;
}
}
void APlayableCharacter::serverUseManaPotion_Implementation()
{
useManaPotion();
}
bool APlayableCharacter::serverUseManaPotion_Validate()
{
return true;
}
void APlayableCharacter::setManaPotionCount(int nbPotions)
{
if(nbPotions > m_nbManaPotionMax)
{
m_manaPotionsCount = m_nbManaPotionMax;
}
else
{
m_manaPotionsCount = nbPotions;
}
}
void APlayableCharacter::setHealthPotionCount(int nbPotions)
{
if(nbPotions > m_nbHealthPotionMax)
{
m_healthPotionsCount = m_nbHealthPotionMax;
}
else
{
m_healthPotionsCount = nbPotions;
}
}
void APlayableCharacter::setBombCount(int nbBombs)
{
if(nbBombs > m_nbBombMax)
{
m_bombCount = m_nbBombMax;
}
else
{
m_bombCount = nbBombs;
}
}
void APlayableCharacter::loseBomb()
{
m_bombCount = 0;
PRINT_MESSAGE_ON_SCREEN(FColor::Turquoise, TEXT("BombLost"));
if(Role < ROLE_Authority)
{
serverLoseBomb();
}
}
void APlayableCharacter::serverLoseBomb_Implementation()
{
loseBomb();
}
bool APlayableCharacter::serverLoseBomb_Validate()
{
return true;
}
void APlayableCharacter::gotoDesert()
{
if(Role == ROLE_Authority)
{
GetWorld()->ServerTravel("/Game/ThirdPersonCPP/Maps/Desert", true, true);
}
else
{
serverGotoDesert();
}
}
void APlayableCharacter::gotoRuins()
{
if(Role == ROLE_Authority)
{
GetWorld()->ServerTravel("/Game/ThirdPersonCPP/Maps/Ruins", true, true);
}
else
{
serverGotoRuins();
}
}
void APlayableCharacter::gotoGym()
{
if(Role == ROLE_Authority)
{
GetWorld()->ServerTravel("/Game/ThirdPersonCPP/Maps/ThirdPersonExampleMap", true, true);
}
else
{
serverGotoGym();
}
}
void APlayableCharacter::serverGotoDesert_Implementation()
{
gotoDesert();
}
bool APlayableCharacter::serverGotoDesert_Validate()
{
return true;
}
void APlayableCharacter::serverGotoGym_Implementation()
{
gotoGym();
}
bool APlayableCharacter::serverGotoGym_Validate()
{
return true;
}
void APlayableCharacter::serverGotoRuins_Implementation()
{
gotoRuins();
}
bool APlayableCharacter::serverGotoRuins_Validate()
{
return true;
}
void APlayableCharacter::switchView()
{
if(m_tpsMode)
{
CameraBoom->TargetArmLength = m_FPSCameraDistance;
}
else
{
CameraBoom->TargetArmLength = m_TPSCameraDistance;
}
m_tpsMode = !m_tpsMode;
UMeshComponent* characterMesh = FindComponentByClass<UMeshComponent>();
if(m_isInvisible)
{
if(characterMesh)
{
characterMesh->SetVisibility(false);
m_fpsMesh->SetVisibility(false);
}
}
else
{
if(characterMesh)
{
characterMesh->SetVisibility(m_tpsMode);
m_fpsMesh->SetVisibility(!m_tpsMode);
}
}
}
UMeshComponent * APlayableCharacter::getCurrentViewMesh()
{
UMeshComponent* characterMesh = FindComponentByClass<UMeshComponent>();
return m_tpsMode ? characterMesh : m_fpsMesh;
}
void APlayableCharacter::activatePhysics(bool mustActive)
{
if(mustActive)
{
//this->GetCapsuleComponent()->CreatePhysicsState();
GetCapsuleComponent()->BodyInstance.SetCollisionProfileName("Players");
}
else
{
//this->GetCapsuleComponent()->DestroyPhysicsState();
GetCapsuleComponent()->BodyInstance.SetCollisionProfileName("Dead");
}
if(Role >= ROLE_Authority)
{
multiActivatePhysics(mustActive);
}
}
bool APlayableCharacter::multiActivatePhysics_Validate(bool mustActive)
{
return true;
}
void APlayableCharacter::multiActivatePhysics_Implementation(bool mustActive)
{
if(mustActive)
{
//this->GetCapsuleComponent()->CreatePhysicsState();
GetCapsuleComponent()->BodyInstance.SetCollisionProfileName("Players");
}
else
{
//this->GetCapsuleComponent()->DestroyPhysicsState();
GetCapsuleComponent()->BodyInstance.SetCollisionProfileName("Dead");
}
}
void APlayableCharacter::enableDroneDisplay()
{
ADroneAIController* droneController = nullptr;
TArray<AActor*> drone;
UGameplayStatics::GetAllActorsOfClass(GetWorld(), ADroneAIController::StaticClass(), drone);
if(drone.Num() > 0) //The king is here
{
droneController = Cast<ADroneAIController>(drone.Top());
}
if(droneController)
{
droneController->enableDroneDisplay(!droneController->isDebugEnabled());
}
}
void APlayableCharacter::updateHUD(EClassType classType)
{
// If HUD already create destroy it and create a new one
APlayerController* MyPC = Cast<APlayerController>(GetController());
if(MyPC)
{
auto myHud = Cast<AGameMenu>(MyPC->GetHUD());
if(myHud)
{
myHud->HUDCharacterImpl->updateClass(classType);
}
}
}
void APlayableCharacter::disableFireEffect()
{
if(m_worldEntity->IsBurnEffectEnabled())
{
m_worldEntity->setIsBurnEffectEnabled(false);
PRINT_MESSAGE_ON_SCREEN(FColor::Black, "effect disabled");
}
else
{
m_worldEntity->setIsBurnEffectEnabled(true);
PRINT_MESSAGE_ON_SCREEN(FColor::Black, "effect enabled");
}
}
<file_sep>/Source/RobotRebellion/Character/TrainingDummyCharacter.h
// Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "NonPlayableCharacter.h"
#include "TrainingDummyCharacter.generated.h"
/**
* Just A simple trainning dummy class
*/
UCLASS()
class ROBOTREBELLION_API ATrainingDummyCharacter : public ANonPlayableCharacter
{
GENERATED_BODY()
public:
ATrainingDummyCharacter();
};
<file_sep>/Source/RobotRebellion/IA/Navigation/GraphHandler.cpp
// Fill out your copyright notice in the Description page of Project Settings.
#include "RobotRebellion.h"
#include "GraphHandler.h"
#include "NavigationVolumeGraph.h"
// Sets default values
AGraphHandler::AGraphHandler()
{
// Set this actor to call Tick() every frame. You can turn this off to improve performance if you don't need it.
PrimaryActorTick.bCanEverTick = true;
}
// Called when the game starts or when spawned
void AGraphHandler::BeginPlay()
{
Super::BeginPlay();
}
// Called every frame
void AGraphHandler::Tick( float DeltaTime )
{
Super::Tick( DeltaTime );
}
void AGraphHandler::EndPlay(const EEndPlayReason::Type EndPlayReason)
{
NavigationVolumeGraph::getInstance().clearGraph();
}
<file_sep>/Source/RobotRebellion/UI/ReviveTimerWidget.h
// Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "UI/RobotRebellionWidget.h"
#include "ReviveTimerWidget.generated.h"
/**
*
*/
UCLASS()
class ROBOTREBELLION_API UReviveTimerWidget : public URobotRebellionWidget
{
GENERATED_BODY()
public:
//For blueprint : 3 output : ratio, health and maxHealth
UFUNCTION(BlueprintCallable, Category = "Update Methods")
void getTimerRatio(float& ratio, float& currentTime, float& requiredTime) const;
};
<file_sep>/Source/RobotRebellion/IA/Character/BeastCharacter.h
// Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "Character/NonPlayableCharacter.h"
#include "BeastCharacter.generated.h"
/**
*
*/
UCLASS()
class ROBOTREBELLION_API ABeastCharacter : public ANonPlayableCharacter
{
GENERATED_BODY()
public:
ABeastCharacter();
};
<file_sep>/Source/RobotRebellion/Global/GlobalDamageMethod.cpp
// Fill out your copyright notice in the Description page of Project Settings.
#include "RobotRebellion.h"
#include "GlobalDamageMethod.h"
Damage::DamageValue UGlobalDamageMethod::normalHit(const ARobotRebellionCharacter* assailant, const ARobotRebellionCharacter* receiver)
{
float intermediary = assailant->getStrength() - receiver->getDefense();
if (intermediary < 1.f)
{
intermediary = 1.f;
}
intermediary *= FMath::Sqrt(assailant->getAgility() / receiver->getAgility());
return static_cast<Damage::DamageValue>(intermediary);
}
Damage::DamageValue UGlobalDamageMethod::normalHitWithWeaponComputed(const ARobotRebellionCharacter* assailant, const ARobotRebellionCharacter* receiver)
{
Damage::DamageValue intermediary = UGlobalDamageMethod::normalHit(assailant, receiver);
intermediary *= assailant->getCurrentEquippedWeapon()->m_weaponDamageCoefficient;
intermediary += assailant->getCurrentEquippedWeapon()->m_weaponBaseDamage;
return static_cast<Damage::DamageValue>(intermediary);
}
Damage::DamageValue UGlobalDamageMethod::droneDamageComputed(const ARobotRebellionCharacter* assailant, const ARobotRebellionCharacter* receiver)
{
float intermediary = (assailant->getStrength() - receiver->getDefense()) * 10.f;
if(intermediary < 1.f)
{
intermediary = 1.f;
}
return static_cast<Damage::DamageValue>(intermediary);
}
<file_sep>/Source/RobotRebellion/IA/Controller/CustomAIControllerBase.cpp
// Fill out your copyright notice in the Description page of Project Settings.
#include "RobotRebellion.h"
#include "CustomAIControllerBase.h"
#include "Character/RobotRebellionCharacter.h"
#include "Global/EntityDataSingleton.h"
ACustomAIControllerBase::ACustomAIControllerBase()
{
PrimaryActorTick.bCanEverTick = true;
m_targetToFollow = nullptr;
}
void ACustomAIControllerBase::BeginPlay()
{
Super::BeginPlay();
m_showDebugSphereTrace = !!EntityDataSingleton::getInstance().m_showEnnemyDetectionSphere;
}
FVector ACustomAIControllerBase::getTargetToFollowLocation() const
{
return m_targetToFollow ? m_targetToFollow->GetActorLocation() : FVector::ZeroVector;
}
bool ACustomAIControllerBase::hasALivingTarget() const USE_NOEXCEPT
{
return this->hasTarget() && !m_targetToFollow->IsActorBeingDestroyed() && !m_targetToFollow->isDead();
}
EPathFollowingRequestResult::Type ACustomAIControllerBase::MoveToTarget()
{
EPathFollowingRequestResult::Type MoveToActorResult = MoveToActor(Cast<AActor>(m_targetToFollow));
return MoveToActorResult;
}
bool ACustomAIControllerBase::isInCombat()
{
return Cast<ARobotRebellionCharacter>(GetPawn())->m_isInCombat;
}
void ACustomAIControllerBase::setTarget(class ARobotRebellionCharacter* attacker)
{
m_targetToFollow = attacker;
Cast<ARobotRebellionCharacter>(GetPawn())->m_isInCombat = (attacker != nullptr);
}
void ACustomAIControllerBase::aim(FVector& inOutFireDirection) const USE_NOEXCEPT
{
inOutFireDirection.Y += FMath::RandRange(-m_aimYMaxFallOffAngle, m_aimYMaxFallOffAngle);
inOutFireDirection.Z += FMath::RandRange(-m_aimZMaxFallOffAngle, m_aimZMaxFallOffAngle) + m_aimZOffsetFallOffAngle;
inOutFireDirection.Normalize();
}<file_sep>/Source/RobotRebellion/Gameplay/Spell/Effects/DamageEffect.cpp
// Fill out your copyright notice in the Description page of Project Settings.
#include "RobotRebellion.h"
#include "DamageEffect.h"
//#include "../../../Damage/Damage.h"
//#include "../../../Tool/Algorithm.h"
#include "Character/RobotRebellionCharacter.h"
UDamageEffect::UDamageEffect()
: m_hpPercent{}, m_flatDamage{}, m_reducedDamage{}
{
PrimaryComponentTick.bCanEverTick = true;
}
void UDamageEffect::BeginPlay()
{
Super::BeginPlay();
}
void UDamageEffect::TickComponent(float DeltaTime, ELevelTick TickType, FActorComponentTickFunction* ThisTickFunction)
{
Super::TickComponent(DeltaTime, TickType, ThisTickFunction);
}
void UDamageEffect::exec(class ARobotRebellionCharacter* caster, ARobotRebellionCharacter* target)
{
inflictEffectDamage(target, caster);
}
void UDamageEffect::exec(const FVector& impactPoint, ARobotRebellionCharacter* caster)
{
//Considered Actors
TArray<TEnumAsByte<EObjectTypeQuery>> ObjectTypes{
UEngineTypes::ConvertToObjectType(ECC_GameTraceChannel2), // Players
UEngineTypes::ConvertToObjectType(ECC_GameTraceChannel3) // Robots
};
//Ignored actors
TArray<AActor*> ActorsToIgnore;
//Result
TArray<FHitResult> OutHits;
if(UKismetSystemLibrary::SphereTraceMultiForObjects(
caster->GetWorld(),
impactPoint,
impactPoint,
m_zoneRadius,
ObjectTypes,
false,
ActorsToIgnore,
SPHERECAST_DISPLAY_DURATION,
OutHits,
true
))
{
ARobotRebellionCharacter** exReceiver = nullptr;
int32 outCount = OutHits.Num();
for(int32 noEnnemy = 0; noEnnemy < outCount; ++noEnnemy)
{
FHitResult hit = OutHits[noEnnemy];
ARobotRebellionCharacter* receiver = Cast<ARobotRebellionCharacter>(hit.GetActor());
if(receiver && exReceiver != &receiver && !receiver->isDead())
{
if(!receiver->isImmortal())
{
inflictEffectDamage(receiver, caster);
}
}
}
}
}
void UDamageEffect::inflictEffectDamage(ARobotRebellionCharacter* target, class ARobotRebellionCharacter* caster)
{
// Very simple way to deals damage
float damage = m_flatDamage;
damage += target->getMaxHealth() * m_hpPercent;
float coef = caster->getStrength() / target->getDefense();
coef = coef > 1.0f ? 1.0f : coef;
damage += coef * m_reducedDamage;
target->inflictDamage(damage);
}
<file_sep>/Source/RobotRebellion/IA/Controller/CustomAIControllerBase.h
// Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "AIController.h"
#include "CustomAIControllerBase.generated.h"
/**
*
*/
UCLASS()
class ROBOTREBELLION_API ACustomAIControllerBase : public AAIController
{
GENERATED_BODY()
private:
class ARobotRebellionCharacter* m_targetToFollow;
protected:
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Debug")
bool m_showDebugSphereTrace;
public:
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Attack", meta = (ClampMin = 0.f))
float m_aimYMaxFallOffAngle;
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Attack", meta = (ClampMin = 0.f))
float m_aimZMaxFallOffAngle;
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Attack")
float m_aimZOffsetFallOffAngle;
protected:
FVector getTargetToFollowLocation() const;
public:
ACustomAIControllerBase();
virtual ~ACustomAIControllerBase() = default;
virtual void BeginPlay() override;
FORCEINLINE bool hasTarget() const USE_NOEXCEPT
{
return m_targetToFollow != NULL;
}
FORCEINLINE ARobotRebellionCharacter* getTarget() const USE_NOEXCEPT
{
return m_targetToFollow;
}
bool isInCombat();
void setTarget(class ARobotRebellionCharacter* attacker);
bool hasALivingTarget() const USE_NOEXCEPT;
FORCEINLINE EDrawDebugTrace::Type debugDrawTraceShowingMode() const USE_NOEXCEPT
{
return m_showDebugSphereTrace ? EDrawDebugTrace::ForDuration : EDrawDebugTrace::None;
}
/*
* VIRTUAL METHODS
*/
virtual EPathFollowingRequestResult::Type MoveToTarget();
virtual void CheckEnnemyNear(float range) PURE_VIRTUAL(ACustomAIControllerBase::CheckEnnemyNear, );
virtual void CheckEnnemyNear(FVector position, float range) PURE_VIRTUAL(ACustomAIControllerBase::CheckEnnemyNear, );
virtual void AttackTarget() const PURE_VIRTUAL(ACustomAIControllerBase::AttackTarget, );
//aim at the fire direction and modify it needed.
virtual void aim(FVector& inOutFireDirection) const USE_NOEXCEPT;
};
<file_sep>/Source/RobotRebellion/Gameplay/Item/PickupActor.cpp
// Fill out your copyright notice in the Description page of Project Settings.
#include "RobotRebellion.h"
#include "PickupActor.h"
// Sets default values
APickupActor::APickupActor()
{
// Set this actor to call Tick() every frame. You can turn this off to improve performance if you don't need it.
PrimaryActorTick.bCanEverTick = true;
bReplicates = true;
bReplicateMovement = true;
MeshComp = CreateDefaultSubobject<UStaticMeshComponent>(TEXT("Mesh"));
RootComponent = MeshComp;
MeshComp->SetSimulatePhysics(true);
}
// Called when the game starts or when spawned
void APickupActor::BeginPlay()
{
Super::BeginPlay();
}
// Called every frame
void APickupActor::Tick( float DeltaTime )
{
Super::Tick( DeltaTime );
}
void APickupActor::OnBeginFocus()
{
// Highlight PostProcess
MeshComp->SetRenderCustomDepth(true);
}
void APickupActor::OnEndFocus()
{
// Stop Highlight PostProcess
MeshComp->SetRenderCustomDepth(false);
}
void APickupActor::OnPickup(APawn * InstigatorPawn)
{
//Nothing. To be derived.
PRINT_MESSAGE_ON_SCREEN(FColor::Cyan, TEXT("PickedUp"));
if (Role == ROLE_Authority)
{
Destroy();
}
}
<file_sep>/Source/RobotRebellion/IA/BT/AttackTargetBTTaskNode.cpp
// Fill out your copyright notice in the Description page of Project Settings.
#include "RobotRebellion.h"
#include "AttackTargetBTTaskNode.h"
#include "../Controller/CustomAIControllerBase.h"
#include "Character/NonPlayableCharacter.h"
UAttackTargetBTTaskNode::UAttackTargetBTTaskNode()
{
NodeName = "AttackTarget";
bNotifyTick = true;
}
EBTNodeResult::Type UAttackTargetBTTaskNode::ExecuteTask(UBehaviorTreeComponent& OwnerComp, uint8*
NodeMemory)
{
ACustomAIControllerBase* AIController = Cast<ACustomAIControllerBase>(OwnerComp.GetOwner());
EBTNodeResult::Type NodeResult = EBTNodeResult::Succeeded;
AIController->AttackTarget();
return NodeResult;
}
void UAttackTargetBTTaskNode::TickTask(class UBehaviorTreeComponent& OwnerComp, uint8* NodeMemory,
float DeltaSeconds)
{
ACustomAIControllerBase* AIController = Cast<ACustomAIControllerBase>(OwnerComp.GetOwner());
AIController->AttackTarget();
}
FString UAttackTargetBTTaskNode::GetStaticDescription() const
{
return TEXT("Attack the targeted target");
}
<file_sep>/Source/RobotRebellion/Gameplay/Spell/Effects/TeleportationEffect.cpp
// Fill out your copyright notice in the Description page of Project Settings.
#include "RobotRebellion.h"
#include "TeleportationEffect.h"
#include "Character/RobotRebellionCharacter.h"
void UTeleportationEffect::BeginPlay()
{
Super::BeginPlay();
}
void UTeleportationEffect::TickComponent(float DeltaTime, ELevelTick TickType, FActorComponentTickFunction* ThisTickFunction)
{
Super::TickComponent(DeltaTime, TickType, ThisTickFunction);
}
void UTeleportationEffect::exec(ARobotRebellionCharacter* caster, ARobotRebellionCharacter* target)
{
// Get new position
FVector targetLoc = target->GetActorLocation();
FVector targetFrontVector = target->GetActorForwardVector();
// Process offset base on the max collision box extent between x and y (dont bother with height) of both actor
FVector targetCollisionCylinder = target->GetSimpleCollisionCylinderExtent();
float offset = targetCollisionCylinder.X > targetCollisionCylinder.Y ? targetCollisionCylinder.X : targetCollisionCylinder.Y;
FVector casterCollisionCylinder = target->GetSimpleCollisionCylinderExtent();
offset += casterCollisionCylinder.X > casterCollisionCylinder.Y ? casterCollisionCylinder.X : casterCollisionCylinder.Y;
FVector teleportationLoc = targetLoc + (offset * (-targetFrontVector));
// Get new rotation (the caster shouold face the target back) -> target frontVector Quat
FQuat newRotation = target->GetActorForwardVector().Rotation().Quaternion();
// Inverse front vector and add offset
PRINT_MESSAGE_ON_SCREEN_UNCHECKED(FColor::Emerald,
"targetPos = " + targetLoc.ToString() + " TeleportLocation = " + teleportationLoc.ToString());
caster->SetActorLocation(teleportationLoc);
caster->SetActorRotation(newRotation, ETeleportType::TeleportPhysics);
}
void UTeleportationEffect::exec(const FVector& impactPoint, ARobotRebellionCharacter* caster)
{
// No one hit, just go to the "impact point"
caster->SetActorLocation(impactPoint);
}
<file_sep>/Source/RobotRebellion/Gameplay/Spell/SelfSpell.cpp
// Fill out your copyright notice in the Description page of Project Settings.
#include "RobotRebellion.h"
#include "SelfSpell.h"
#include "Gameplay/Spell/Effects/Effect.h"
#include "Character/RobotRebellionCharacter.h"
USelfSpell::USelfSpell() : USpell()
{
}
void USelfSpell::BeginPlay()
{
Super::BeginPlay();
}
void USelfSpell::cast()
{
if(!canCast())
{
PRINT_MESSAGE_ON_SCREEN(FColor::Emerald,
"Cooldown : " + FString::FromInt(m_nextAllowedCastTimer - FPlatformTime::Seconds()));
return;
}
ARobotRebellionCharacter* caster = Cast<ARobotRebellionCharacter>(GetOwner());
if(caster)
{
applyEffect(caster);
// the spell is successfully cast consumme mana and launch CD
caster->consumeMana(m_manaCost);
m_nextAllowedCastTimer = FPlatformTime::Seconds() + m_cooldown;
}
}
void USelfSpell::applyEffect(ARobotRebellionCharacter* affectedTarget)
{
PRINT_MESSAGE_ON_SCREEN(FColor::Emerald, TEXT("ApplicateEffect on target"));
for(int i = 0; i < m_effects.Num(); ++i)
{
m_effects[i]->exec(Cast<ARobotRebellionCharacter>(GetOwner()), affectedTarget);
}
}
<file_sep>/Source/RobotRebellion/UI/CustomRobotRebellionUserWidget.cpp
// Fill out your copyright notice in the Description page of Project Settings.
#include "RobotRebellion.h"
#include "CustomRobotRebellionUserWidget.h"
#include "Character/RobotRebellionCharacter.h"
#include "Character/PlayableCharacter.h"
#include "Gameplay/Spell/SpellKit.h"
#include "Kismet/KismetMathLibrary.h"
void UCustomRobotRebellionUserWidget::updateClass_Implementation(EClassType classType)
{
// Does Nothing
}
EClassType UCustomRobotRebellionUserWidget::getPlayerClass() const
{
APlayableCharacter* character = Cast<APlayableCharacter>(GetOwningPlayerPawn());
if(character)
{
return character->getClassType();
}
else
{
return EClassType::NONE;
}
}
void UCustomRobotRebellionUserWidget::getHealthRatio(float& ratio, float& ratioShield, float& health, float& shield, float& maxHealth) const
{
ARobotRebellionCharacter* character = Cast<ARobotRebellionCharacter>(GetOwningPlayerPawn());
if(character)
{
health = character->getHealth();
shield = character->getShield();
maxHealth = character->getMaxHealth();
ratio = health / maxHealth;
ratioShield = (health + shield) / maxHealth;
}
else
{
health = 0.f;
maxHealth = 0.f;
ratio = 0.f;
}
}
void UCustomRobotRebellionUserWidget::getManaRatio(float& ratio, float& mana, float& maxMana) const
{
ARobotRebellionCharacter* character = Cast<ARobotRebellionCharacter>(GetOwningPlayerPawn());
if(character)
{
mana = character->getMana();
maxMana = character->getMaxMana();
ratio = mana / maxMana;
}
else
{
mana = 0.f;
maxMana = 0.f;
ratio = 0.f;
}
}
FString UCustomRobotRebellionUserWidget::healthParseToScreen(float health, float shield, float maxHealth) const
{
if(shield > 0)
{
return FString::FromInt(health) + TEXT("(") + FString::FromInt(shield) + TEXT(")") + TEXT("/") + FString::FromInt(maxHealth);
}
else
{
return FString::FromInt(health) + TEXT("/") + FString::FromInt(maxHealth);
}
}
FString UCustomRobotRebellionUserWidget::manaParseToScreen(float mana, float maxMana) const
{
return FString::FromInt(mana) + TEXT("/") + FString::FromInt(maxMana);
}
TArray<FString> UCustomRobotRebellionUserWidget::cooldownParseToScreen() const
{
// get every actual cooldown - Maybe replicate cooldown on client!
APlayableCharacter* character = Cast<APlayableCharacter>(GetOwningPlayerPawn());
TArray<FString> cooldownsStr{};
if(character)
{ // Try to reach spell kit comp
TArray<USpellKit*> spellKitComps;
character->GetComponents<USpellKit>(spellKitComps);
if(spellKitComps.Num() > 0)
{
TArray<float> cooldownsF = spellKitComps[0]->getCooldowns();
for(int index{}; index < cooldownsF.Num(); ++index)
{
cooldownsStr.Emplace(processFloatCooldown(cooldownsF[index]));
}
}
}
return cooldownsStr;
}
FString UCustomRobotRebellionUserWidget::processFloatCooldown(float value) const
{
if(value > 0.f)
{
if(value >= 1.1f)
{
// Only print second
int32 valueInt = UKismetMathLibrary::FTrunc(value + 1.f);
return FString::FromInt(valueInt);
}
else if(value >= 1.f)
{// Only print 1
return FString{"1"};
}
else
{
// print second value
int32 valueInt = UKismetMathLibrary::FTrunc(value * 10.f);
return FString::SanitizeFloat(static_cast<float>(valueInt) / 10.f);
}
}
else
{
return FString{};
}
}
FString UCustomRobotRebellionUserWidget::bombParseToScreen() const
{
APlayableCharacter* character = Cast<APlayableCharacter>(GetOwningPlayerPawn());
if(character)
{
if(character->m_bombCount == character->m_nbBombMax)
{
return FString{"MAX"};
}
else
{
return FString::FromInt(character->m_bombCount);
}
}
else
{
return FString{};
}
}
FString UCustomRobotRebellionUserWidget::healthPotsParseToScreen() const
{
APlayableCharacter* character = Cast<APlayableCharacter>(GetOwningPlayerPawn());
if(character)
{
if(character->m_healthPotionsCount == character->m_nbHealthPotionMax)
{
return FString{"MAX"};
}
else
{
return FString::FromInt(character->m_healthPotionsCount);
}
}
else
{
return FString{};
}
}
FString UCustomRobotRebellionUserWidget::manaPotsParseToScreen() const
{
APlayableCharacter* character = Cast<APlayableCharacter>(GetOwningPlayerPawn());
if(character)
{
if(character->m_manaPotionsCount == character->m_nbManaPotionMax)
{
return FString{"MAX"};
}
else
{
return FString::FromInt(character->m_manaPotionsCount);
}
}
return FString{};
}
bool UCustomRobotRebellionUserWidget::isMainWeaponEquipped()const
{
APlayableCharacter* character = Cast<APlayableCharacter>(GetOwningPlayerPawn());
if(character)
{
return character->m_weaponInventory->isMainWeaponEquipped();
}
return true;
}
<file_sep>/Source/RobotRebellion/Global/GameInstaller.h
// Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "../Tool/IsSingleton.h"
#include "../Tool/IdentifiableObj.h"
/**
*
*/
class ROBOTREBELLION_API GameAlterationInstaller : private IsSingleton<GameAlterationInstaller>
{
private:
GENERATED_USING_FROM_IsSingleton(GameAlterationInstaller);
public:
TMap<uint32, TSubclassOf<class UAlterationBase>*> m_alterationModelMap;
public:
template<class AlterationType>
void installAlteration(TSubclassOf<class UAlterationBase>* alteration)
{
m_alterationModelMap.Add(IdentifiableObject<AlterationType>::ID.m_value,
alteration
);
}
template<class AlterationType>
TSubclassOf<class UAlterationBase>* getAlterationDefault() const USE_NOEXCEPT
{
return m_alterationModelMap[IdentifiableObject<AlterationType>::ID.m_value];
}
};
<file_sep>/Source/RobotRebellion/IA/Character/RobotsCharacter.h
// Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "Character/NonPlayableCharacter.h"
#include "RobotsCharacter.generated.h"
/**
* The robots ennemy default class
*/
UCLASS()
class ROBOTREBELLION_API ARobotsCharacter : public ANonPlayableCharacter
{
GENERATED_BODY()
public:
ARobotsCharacter();
};
<file_sep>/Source/RobotRebellion/Gameplay/Item/ManaPotionActor.cpp
// Fill out your copyright notice in the Description page of Project Settings.
#include "RobotRebellion.h"
#include "ManaPotionActor.h"
void AManaPotionActor::OnPickup(APawn* InstigatorPawn)
{
//Nothing. To be derived.
PRINT_MESSAGE_ON_SCREEN(FColor::Purple, TEXT("Mana potion PickedUp"));
if (Role == ROLE_Authority)
{
Destroy();
}
}
<file_sep>/Source/RobotRebellion/IA/Navigation/EditorGraphVolume.cpp
// Fill out your copyright notice in the Description page of Project Settings.
#include "RobotRebellion.h"
#include "EditorGraphVolume.h"
#include "NavigationVolumeGraph.h"
#include "VolumeIdProvider.h"
#include "Global/EntityDataSingleton.h"
// Sets default values
AEditorGraphVolume::AEditorGraphVolume()
: AActor(), m_isVisibleInGame{true}
{
// Set this actor to call Tick() every frame. You can turn this off to improve performance if you don't need it.
PrimaryActorTick.bCanEverTick = true;
// Init box comp to have editor visual feedback
m_box = CreateDefaultSubobject<UBoxComponent>(TEXT("BoxComp"));
m_box->SetCollisionEnabled(ECollisionEnabled::NoCollision); // disable collision
// Enable collision for steering ray cast
m_box->SetCollisionResponseToChannel(ECollisionChannel::ECC_GameTraceChannel9, ECollisionResponse::ECR_Block);
}
// Called when the game starts or when spawned
void AEditorGraphVolume::BeginPlay()
{
Super::BeginPlay();
m_id = VolumeIdProvider::getInstance().getNextId();
registerNode();
m_isVisibleInGame = !!EntityDataSingleton::getInstance().m_showVolumeBox;
m_box->SetHiddenInGame(!m_isVisibleInGame); // enable to be shown in game
}
// Called every frame
void AEditorGraphVolume::Tick(float DeltaTime)
{
Super::Tick(DeltaTime);
}
// Graph registration
void AEditorGraphVolume::registerNode()
{
// Only register node if its the server
if(Role == ROLE_Authority)
{
NavigationVolumeGraph::getInstance().addNode(this);
}
}
bool AEditorGraphVolume::contains(const FVector& point)const
{
FVector volumeCenter = GetActorLocation();
FVector extent = m_box->GetScaledBoxExtent();
int32 maxZ, maxY, maxX, minZ, minY, minX;
maxZ = volumeCenter.Z + extent.Z;
maxY = volumeCenter.Y + extent.Y;
maxX = volumeCenter.X + extent.X;
minZ = volumeCenter.Z - extent.Z;
minY = volumeCenter.Y - extent.Y;
minX = volumeCenter.X - extent.X;
if( point.Z < maxZ
&& point.Y < maxY
&& point.X < maxX
&& point.Z > minZ
&& point.Y > minY
&& point.X > minX)
{
return true;
}
return false;
}
float AEditorGraphVolume::isBelow(const FVector& point) const
{
FVector volumeCenter = GetActorLocation();
FVector extent = m_box->GetScaledBoxExtent();
int32 maxY, maxX, minY, minX;
maxY = volumeCenter.Y + extent.Y;
maxX = volumeCenter.X + extent.X;
minY = volumeCenter.Y - extent.Y;
minX = volumeCenter.X - extent.X;
if(point.Y < maxY
&& point.X < maxX
&& point.Y > minY
&& point.X > minX)
{
return fabs(point.Z - volumeCenter.Z);
}
return -1.f;
}<file_sep>/Source/RobotRebellion/Gameplay/Weapon/Projectile.h
// Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "GameFramework/Actor.h"
#include "Projectile.generated.h"
class ARobotRebellionCharacter;
UCLASS()
class ROBOTREBELLION_API AProjectile : public AActor
{
GENERATED_BODY()
public:
//////////////////////////////////////////////////////////////////////////ADDED MEMBERS /////
////OWNER////
UPROPERTY(Transient, ReplicatedUsing = OnRep_MyOwner)
ARobotRebellionCharacter * m_owner;
/** Movement component */
UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = Movement)
UProjectileMovementComponent* m_projectileMovement;
//// Collision ////
UPROPERTY(VisibleDefaultsOnly, Category = Projectile)
USphereComponent* m_collisionComp;
public:
// Sets default values for this actor's properties
AProjectile();
// Called when the game starts or when spawned
virtual void BeginPlay() override;
// Called every frame
virtual void Tick( float DeltaSeconds ) override;
UFUNCTION()
void OnRep_MyOwner();
void setOwner(ARobotRebellionCharacter *newOwner);
// On hit function called every collision
UFUNCTION()
virtual void OnHit(class UPrimitiveComponent* ThisComp, class AActor* OtherActor, class UPrimitiveComponent*
OtherComp, FVector NormalImpulse, const FHitResult& Hit);
void setReceiverInCombat(ARobotRebellionCharacter* receiver);
/** Initialize velocity */
virtual void InitProjectileParams(const FVector& shootDirection, float distanceRange);
//ON HIT
/* UFUNCTION()
void OnHit(class UPrimitiveComponent* ThisComp, class AActor* OtherActor, class UPrimitiveComponent*
OtherComp, FVector NormalImpulse, const FHitResult& Hit);*/
////Server
void GetLifetimeReplicatedProps(TArray< FLifetimeProperty > & OutLifetimeProps) const override;
virtual void inflictDamageLogic(class AActor* OtherActor, const FHitResult& Hit);
void simulateInstant(const FVector& shootDirection, float distance);
void simulateInstantRealMethod(const FVector& shootDirection, float distanceRange);
UFUNCTION(Reliable, Server, WithValidation)
void serverSimulateInstant(const FVector& shootDirection, float distanceRange);
UFUNCTION(NetMulticast, Reliable)
void multiDrawLineOnClients(const FVector& start, const FVector& end);
void drawProjectileLineMethod(UWorld* world, const FVector& start, const FVector& end);
void suicide();
UFUNCTION(NetMulticast, Reliable)
void destroyOnClients();
FORCEINLINE virtual bool isRaycast() const USE_NOEXCEPT
{
return false;
}
};
<file_sep>/Source/RobotRebellion/UI/CustomRobotRebellionUserWidget.h
// Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "UI/RobotRebellionWidget.h"
#include "Character/ClassType.h"
#include "CustomRobotRebellionUserWidget.generated.h"
/**
*
*/
UCLASS(Blueprintable)
class ROBOTREBELLION_API UCustomRobotRebellionUserWidget : public URobotRebellionWidget
{
GENERATED_BODY()
private:
FString processFloatCooldown(float value) const;
public:
//For blueprint : 4 output : ratio, health, shield and maxHealth
UFUNCTION(BlueprintNativeEvent, Category = "UpdateMethod")
void updateClass(EClassType classType);
//For blueprint : 4 output : ratio, health, shield and maxHealth
UFUNCTION(BlueprintCallable, Category = "UpdateMethod")
EClassType getPlayerClass() const;
//For blueprint : 4 output : ratio, health, shield and maxHealth
UFUNCTION(BlueprintCallable, Category = "UpdateMethod")
void getHealthRatio(float& ratio, float& ratioShield, float& health, float& shield, float& maxHealth) const;
//For blueprint : 3 output : ratio, mana and maxMana
UFUNCTION(BlueprintCallable, Category = "UpdateMethod")
void getManaRatio(float& ratio, float& mana, float& maxMana) const;
//Parse into FString = health / healthMax
UFUNCTION(BlueprintCallable, Category = "UpdateMethod")
FString healthParseToScreen(float health, float shield, float maxHealth) const;
//Parse into FString = mana / manaMax
UFUNCTION(BlueprintCallable, Category = "UpdateMethod")
FString manaParseToScreen(float mana, float maxMana) const;
// Parse cooldown into cooldown for every spell
UFUNCTION(BlueprintCallable, Category = "UpdateMethod")
TArray<FString> cooldownParseToScreen() const;
// Parse cooldown into
UFUNCTION(BlueprintCallable, Category = "UpdateMethod")
FString bombParseToScreen() const;
// Parse health pots amount
UFUNCTION(BlueprintCallable, Category = "UpdateMethod")
FString healthPotsParseToScreen() const;
// Parse mana pots amount
UFUNCTION(BlueprintCallable, Category = "UpdateMethod")
FString manaPotsParseToScreen() const;
// Check witch weapon is equipped return true if it's the main
UFUNCTION(BlueprintCallable, Category = "UpdateMethod")
bool isMainWeaponEquipped()const;
};
<file_sep>/Source/RobotRebellion/IA/Navigation/EditorGraphVolume.h
// Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "GameFramework/Actor.h"
#include "EditorGraphVolume.generated.h"
UCLASS()
class ROBOTREBELLION_API AEditorGraphVolume : public AActor
{
GENERATED_BODY()
private:
/** Unique ID that defines a navigationVolume, automatically calculed
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = Volume)*/
int32 m_id;
public:
/** An array to all volume that are connected to this one */
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = Volume)
TArray<AEditorGraphVolume*> m_neighbour;
/** used to set the size of the volume, an to have a visual feedback*/
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = Volume)
UBoxComponent* m_box;
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = Debug)
bool m_isVisibleInGame;
public:
// Sets default values for this actor's properties
AEditorGraphVolume();
// Called when the game starts or when spawned
virtual void BeginPlay() override;
// Called every frame
virtual void Tick(float DeltaSeconds) override;
int32 getId() const
{
return m_id;
}
// Return true if the volume overlap the given point
bool contains(const FVector& point) const;
// Return the distance if the volume below the point
// else return -1;
float isBelow(const FVector& point) const;
private:
// register the volume into the graph
void registerNode();
};
<file_sep>/Source/RobotRebellion/IA/Controller/RobotRusherController.h
// Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "IA/Controller/EnnemiAIController.h"
#include "RobotRusherController.generated.h"
/**
*
*/
UCLASS()
class ROBOTREBELLION_API ARobotRusherController : public AEnnemiAIController
{
GENERATED_BODY()
};
<file_sep>/Source/RobotRebellion/IA/BT/MoveToShootLocBTTaskNode.cpp
// Fill out your copyright notice in the Description page of Project Settings.
#include "RobotRebellion.h"
#include "MoveToShootLocBTTaskNode.h"
#include "../Controller/CustomAIControllerBase.h"
#include "../Controller/RobotShooterController.h"
UMoveToShootLocBTTaskNode::UMoveToShootLocBTTaskNode()
{
NodeName = "MoveToShootLoc";
bNotifyTick = true;
}
EBTNodeResult::Type UMoveToShootLocBTTaskNode::ExecuteTask(UBehaviorTreeComponent& OwnerComp, uint8*
NodeMemory)
{
ACustomAIControllerBase* AIController = Cast<ACustomAIControllerBase>(OwnerComp.GetOwner());
EBTNodeResult::Type NodeResult = EBTNodeResult::Failed;
// If the controller doesn't have a target, the task is a fail
if(AIController->hasALivingTarget())
{
NodeResult = EBTNodeResult::Succeeded;
ARobotShooterController* shooterController = Cast<ARobotShooterController>(AIController);
if(shooterController)
{
// update shoot position
shooterController->updateShootLocation();
shooterController->uncrouch();
// TODO - Switch to moveToShootLocation!
EPathFollowingRequestResult::Type MoveToActorResult = shooterController->moveToShootLocation();
}
else
{
EPathFollowingRequestResult::Type MoveToActorResult = AIController->MoveToTarget();
}
}
return NodeResult;
}
void UMoveToShootLocBTTaskNode::TickTask(class UBehaviorTreeComponent& OwnerComp, uint8* NodeMemory,
float DeltaSeconds)
{
ACustomAIControllerBase* AIController = Cast<ACustomAIControllerBase>(OwnerComp.GetOwner());
if(AIController->hasTarget())
{
EPathFollowingRequestResult::Type MoveToActorResult = AIController->MoveToTarget();
if(MoveToActorResult == EPathFollowingRequestResult::AlreadyAtGoal)
{
FinishLatentTask(OwnerComp, EBTNodeResult::Succeeded);
}
}
}
FString UMoveToShootLocBTTaskNode::GetStaticDescription() const
{
return TEXT("Follow the targeted target");
}
<file_sep>/Source/RobotRebellion/Global/EntityDataSingleton.h
// Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "Tool/IsSingleton.h"
/**
*
*/
class ROBOTREBELLION_API EntityDataSingleton : private IsSingleton<EntityDataSingleton>
{
GENERATED_USING_FROM_IsSingleton(EntityDataSingleton)
public:
TArray<class ARobotsCharacter*> m_robotArray;
TArray<class APlayableCharacter*> m_playableCharacterArray;
class AKing* m_king;
class ADrone* m_drone;
int8 m_showVolumeBox : 1;
int8 m_showEnnemyDetectionSphere : 1;
int8 fill : 6;
private:
class AKing* m_serverKing;
class ADrone* m_serverDrone;
public:
void update(const class UWorld* world);
void clean();
//Retrieve the king on the server side. Return nullptr if we're on client side.
//Gives an AActor* (i.e this) for the method to check on what side we are...
FORCEINLINE class AKing* getServerKing(AActor* askingActor) const
{
return retrieveIfRoleCorrect(askingActor, m_serverKing);
}
//Retrieve the drone on the server side. Return nullptr if we're on client side.
//Gives an AActor* (i.e this) for the method to check on what side we are...
FORCEINLINE class ADrone* getServerDrone(AActor* askingActor) const
{
return retrieveIfRoleCorrect(askingActor, m_serverDrone);
}
private:
template<class Base, class GenericType>
bool updateType(Base* current, GenericType*& typeToUpdate)
{
GenericType* temp = Cast<GenericType>(current);
if (temp)
{
typeToUpdate = temp;
return true;
}
typeToUpdate = nullptr;
return false;
}
template<class Base, class GenericType>
bool updateType(Base* current, TArray<GenericType*>& typeToUpdate)
{
GenericType* temp = Cast<GenericType>(current);
if(temp)
{
typeToUpdate.Emplace(temp);
return true;
}
return false;
}
template<class AskedClass>
AskedClass* retrieveIfRoleCorrect(AActor* askingActor, AskedClass* toSend) const
{
if(askingActor->GetRootComponent()->GetOwnerRole() >= ROLE_Authority)
{
return toSend;
}
return nullptr;
}
};<file_sep>/Source/RobotRebellion/IA/Navigation/GraphHandler.h
// Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "GameFramework/Actor.h"
#include "GraphHandler.generated.h"
UCLASS()
class ROBOTREBELLION_API AGraphHandler : public AActor
{
GENERATED_BODY()
public:
// Sets default values for this actor's properties
AGraphHandler();
// Called when the game starts or when spawned
virtual void BeginPlay() override;
// Called every frame
virtual void Tick( float DeltaSeconds ) override;
// Called to clear the graph at the end of the game
virtual void EndPlay(const EEndPlayReason::Type EndPlayReason) override;
};
<file_sep>/Source/RobotRebellion/IA/Controller/BossAIController.cpp
// Fill out your copyright notice in the Description page of Project Settings.
#include "RobotRebellion.h"
#include "BossAIController.h"
#include "Global/EntityDataSingleton.h"
#include "Character/PlayableCharacter.h"
#include "Character/RobotRebellionCharacter.h"
#include "Character/Drone.h"
#include "Character/King.h"
#include "Gameplay/Weapon/WeaponBase.h"
#include "Kismet/KismetMathLibrary.h"
ABossAIController::ABossAIController()
{
PrimaryActorTick.bCanEverTick = true;
}
void ABossAIController::BeginPlay()
{
Super::BeginPlay();
this->initializeLifeThreshold();
}
void ABossAIController::Tick(float deltaTime)
{
if (this->IsPendingKillOrUnreachable())
{
return;
}
Super::Tick(deltaTime);
m_updateTargetTime += deltaTime;
if(m_updateTargetTime < m_updateTargetCooldownTime)
{
return;
}
m_updateTargetTime = 0.f;
this->internalCheckEnnemy();
}
void ABossAIController::internalCheckEnnemy()
{
ARobotRebellionCharacter* boss = Cast<ARobotRebellionCharacter>(GetPawn());
if (boss)
{
this->computeTarget(boss->getCurrentEquippedWeapon()->m_WeaponRadiusRange);
}
}
void ABossAIController::CheckEnnemyNear(float range)
{
//...
}
void ABossAIController::AttackTarget() const
{
ANonPlayableCharacter* boss = Cast<ANonPlayableCharacter>(GetPawn());
if(this->getTarget())
{
FVector hitDirection = UKismetMathLibrary::GetForwardVector(
UKismetMathLibrary::FindLookAtRotation(boss->GetActorLocation(), this->getTarget()->GetActorLocation())
);
hitDirection.Z = 0.f;
hitDirection.Normalize();
FVector front = boss->GetActorForwardVector();
front.Z = 0.f;
front.Normalize();
FVector vert = FVector::CrossProduct(front, hitDirection);
float sinAngle = vert.Size();
if(vert.Z < 0.f)
{
sinAngle = -sinAngle;
}
boss->AddActorLocalRotation(FQuat({ 0.f, 0.f, 1.f }, asinf(sinAngle)), true);
boss->getCurrentEquippedWeapon()->cppAttack(boss, this->getTarget());
}
else
{
boss->getCurrentEquippedWeapon()->cppAttack(boss);
}
}
void ABossAIController::initializeLifeThreshold()
{
constexpr const float MIN_THRESHOLD = 0.15f;
constexpr const float MAX_THRESHOLD = 0.55f;
constexpr const float DELTA_THRESHOLD = MAX_THRESHOLD - MIN_THRESHOLD;
m_lifeThreshold = m_difficulty * DELTA_THRESHOLD + MIN_THRESHOLD;
}
float ABossAIController::computeIndividualDistScoring(const FVector& bossPosition, const ARobotRebellionCharacter* individual, float rangeSquared) const
{
FVector potentialTargetPosition = individual->GetActorLocation();
float deltaDist = FVector::DistSquared(bossPosition, potentialTargetPosition) - rangeSquared;
if(deltaDist < 0.f)
{
return 1.f;
}
float score = 1.f - (m_overRangeMalusCoefficient * deltaDist / m_fallOffRangeCoefficient);
return score < 0.f ? 0.f : score;
}
void ABossAIController::computeTarget(float range)
{
if (this->getTarget() && !this->getTarget()->isVisible())
{
this->setTarget(nullptr);
this->StopMovement();
}
FVector currentPosition = GetPawn()->GetActorLocation();
range *= range;
const EntityDataSingleton& datas = EntityDataSingleton::getInstance();
const TArray<APlayableCharacter*>& players = datas.m_playableCharacterArray;
//////////////////////////////////////////////////////////////////////////
//Array
static constexpr const float classificationArray[] = {
0.8f, // Soldat
0.5f, // Assassin
0.4f, // Healer
1.f, // Wizard
0.45f // King
};
//////////////////////////////////////////////////////////////////////////
//Methods
auto getLifeRatioFunc = [](const ARobotRebellionCharacter* individual) {
return individual->getHealth() / individual->getMaxHealth();
};
auto computeLifeScore = [getLifeRatioFunc](const ARobotRebellionCharacter* individual, float difficulty) {
float lifeRatio = getLifeRatioFunc(individual);
return
difficulty * (1.f - lifeRatio) +
(1.f - difficulty) * lifeRatio;
};
auto getDiversScore = [&datas](const ARobotRebellionCharacter* individual) {
const APlayableCharacter* isPlayer = Cast<APlayableCharacter>(individual);
bool droneLoaded = datas.m_drone->isLoaded();
if (isPlayer)
{
return
((!droneLoaded) ? 0.5f : 0.f) +
(isPlayer->getReviveTimer() ? 0.5f : 0.f);
}
return droneLoaded ? 1.f : 0.f;
};
auto getClassifiedScore = [](const ARobotRebellionCharacter* individual, const float* classificationArray) {
const APlayableCharacter* carac = Cast<APlayableCharacter>(individual);
if (carac)
{
return classificationArray[static_cast<int32>(carac->getType()) - 1];
}
return classificationArray[4];
};
auto computeIndividualScore =
[this, computeLifeScore, getClassifiedScore, getDiversScore, ¤tPosition, range]
(const ARobotRebellionCharacter* individual, const float* classificationArray) {
return
0.51f * this->computeIndividualDistScoring(currentPosition, individual, range) +
0.26f * computeLifeScore(individual, this->m_difficulty) +
0.19f * getClassifiedScore(individual, classificationArray) +
0.06f * getDiversScore(individual) +
0.01f * FMath::RandRange(0.f, 1.f); //to make a difference with someone with the exact same score
};
//////////////////////////////////////////////////////////////////////////
//Computation
int32 playerAlive = 0;
float maxPlayerScore = 0.f;
ARobotRebellionCharacter* chosenPlayer = nullptr;
for(APlayableCharacter* player : players)
{
if(!player->isDead() && player->isVisible())
{
++playerAlive;
float playersScoreTemp = computeIndividualScore(player, classificationArray);
if(playersScoreTemp > maxPlayerScore)
{
maxPlayerScore = playersScoreTemp;
chosenPlayer = player;
};
}
}
//The more the players, the more the boss will target players. Tweeked by difficulty.
maxPlayerScore =
0.81f * maxPlayerScore +
0.19f * (m_difficulty * static_cast<float>(playerAlive) / static_cast<float>(players.Num()));
float kingScore = -1.f;
if (datas.m_king)
{
kingScore = computeIndividualScore(datas.m_king, classificationArray);
}
ARobotRebellionCharacter* boss = Cast<ARobotRebellionCharacter>(GetPawn());
float bossLifeRatio = getLifeRatioFunc(boss);
//uncomment if you want to tweek difficulty at runtime
//this->initializeLifeThreshold();
//more hp the boss has, more it will target players. Tweeked by difficulty
if (bossLifeRatio < m_lifeThreshold)
{
maxPlayerScore *= 0.70f;
}
maxPlayerScore *= m_basePlayersCoefficient;
kingScore *= m_baseKingCoefficient;
this->setTarget((maxPlayerScore > kingScore && chosenPlayer) ? chosenPlayer : datas.getServerKing(this));
PRINT_MESSAGE_ON_SCREEN_UNCHECKED(FColor::Yellow, FString::Printf(TEXT("Player : %f, King : %f"), maxPlayerScore, kingScore));
}<file_sep>/Source/RobotRebellion/Gameplay/Weapon/Kaboom.cpp
// Fill out your copyright notice in the Description page of Project Settings.
#include "RobotRebellion.h"
#include "Kaboom.h"
#include "Character/RobotRebellionCharacter.h"
#include "Character/Drone.h"
#include "Gameplay/Damage/Damage.h"
#include "Gameplay/Damage/DamageCoefficientLogic.h"
#include "Global/GlobalDamageMethod.h"
#include "Kismet/KismetSystemLibrary.h"
AKaboom::AKaboom()
{
// Set this actor to call Tick() every frame. You can turn this off to improve performance if you don't need it.
PrimaryActorTick.bCanEverTick = false;
// Create Sphere for collision shape
m_collisionComp = CreateDefaultSubobject<USphereComponent>(TEXT("SphereComp"));
m_collisionComp->OnComponentHit.AddDynamic(this, &AKaboom::onHit);
m_collisionComp->BodyInstance.SetCollisionProfileName("Projectile");
m_collisionComp->InitSphereRadius(5.0f);
m_kaboomMesh = CreateDefaultSubobject<UStaticMeshComponent>(TEXT("Kaboom Mesh"));
m_kaboomMesh->SetupAttachment(m_collisionComp);
RootComponent = m_collisionComp;
m_explosionPCS = CreateDefaultSubobject<UParticleSystemComponent>(TEXT("Explosion PCS"));
m_explosionPCS->bAutoActivate = false;
m_explosionPCS->bAutoDestroy = false;
m_explosionPCS->SetupAttachment(RootComponent);
bReplicates = true;
bNetUseOwnerRelevancy = true;
m_destroyMethod = &AKaboom::noMethod;
this->initializeDamagedObjectList();
this->initializeKaboomMovementComponent();
this->deactivateBomb();
}
void AKaboom::BeginPlay()
{
Super::BeginPlay();
}
void AKaboom::Tick(float deltaTime)
{
Super::Tick(deltaTime);
(this->*m_destroyMethod)();
}
void AKaboom::initializeDamagedObjectList()
{
m_objectTypesToConsider = {
UEngineTypes::ConvertToObjectType(ECC_GameTraceChannel2), // Players
UEngineTypes::ConvertToObjectType(ECC_GameTraceChannel3), // Robots
UEngineTypes::ConvertToObjectType(ECC_GameTraceChannel4), // Sovec
UEngineTypes::ConvertToObjectType(ECC_GameTraceChannel6) // Beasts
};
}
void AKaboom::initializeKaboomMovementComponent()
{
m_kaboomMovement = CreateDefaultSubobject<UProjectileMovementComponent>(TEXT("Kaboom Movement"));
m_kaboomMovement->UpdatedComponent = m_collisionComp;
m_kaboomMovement->InitialSpeed = 0.f;
m_kaboomMovement->MaxSpeed = 1000.f;
m_kaboomMovement->bRotationFollowsVelocity = true;
m_kaboomMovement->bShouldBounce = false;
m_kaboomMovement->Bounciness = 0.f;
}
void AKaboom::dropingPhysicSetting(bool reenablePhysic)
{
m_collisionComp->SetAllPhysicsAngularVelocity(FVector::ZeroVector);
m_collisionComp->SetAllPhysicsLinearVelocity(FVector::ZeroVector);
m_collisionComp->SetSimulatePhysics(reenablePhysic);
m_collisionComp->SetEnableGravity(reenablePhysic);
}
void AKaboom::attachToDrone(ADrone* drone)
{
if (drone)
{
this->AttachToActor(drone, FAttachmentTransformRules::KeepRelativeTransform);
this->dropingPhysicSetting(false);
m_linkedDrone = drone;
}
}
void AKaboom::detachFromDrone()
{
if (m_linkedDrone)
{
this->DetachFromActor(FDetachmentTransformRules::KeepWorldTransform);
this->dropingPhysicSetting(true);
}
}
void AKaboom::detonationImplementation()
{
if(Role < ROLE_Authority)
{
return;
}
FVector actorLocation = GetActorLocation();
TArray<FHitResult> OutHits;
if(m_linkedDrone && UKismetSystemLibrary::SphereTraceMultiForObjects(
GetWorld(),
actorLocation,
actorLocation,
m_detonationRadius,
m_objectTypesToConsider,
false,
{ this },
SPHERECAST_DISPLAY_DURATION,
OutHits,
true
))
{
for(int32 iter = 0; iter < OutHits.Num(); ++iter)
{
FHitResult Hit = OutHits[iter];
ARobotRebellionCharacter* targetInDistress = Cast<ARobotRebellionCharacter>(Hit.GetActor());
if(targetInDistress)
{
DamageCoefficientLogic coeff;
Damage damage{ m_linkedDrone, targetInDistress };
Damage::DamageValue currentDamage = damage(
&UGlobalDamageMethod::droneDamageComputed,
coeff.getCoefficientValue()
);
targetInDistress->inflictDamage(currentDamage + m_baseDamage);
}
}
}
UGameplayStatics::SpawnSoundAttached(m_boomSound, GetRootComponent());
multiExplosionOnEveryone();
}
void AKaboom::realDestroy()
{
m_explosionPCS->DeactivateSystem();
m_explosionPCS->DestroyComponent();
this->BeginDestroy();
}
void AKaboom::multiExplosionOnEveryone_Implementation()
{
this->deactivateBomb();
m_destroyMethod = &AKaboom::realDestroy;
this->m_kaboomMesh->SetVisibility(false);
UGameplayStatics::SpawnSoundAttached(m_boomSound, GetRootComponent());
m_explosionPCS->SetRelativeScale3D(m_explosionEffectScale);
m_explosionPCS->ActivateSystem();
}<file_sep>/Source/RobotRebellion/Global/WorldInstanceEntity.cpp
// Fill out your copyright notice in the Description page of Project Settings.
#include "RobotRebellion.h"
#include "WorldInstanceEntity.h"
// Sets default values
AWorldInstanceEntity::AWorldInstanceEntity()
{
// Set this actor to call Tick() every frame. You can turn this off to improve performance if you don't need it.
PrimaryActorTick.bCanEverTick = true;
m_gameMode = ECurrentGameMode::INTRO;
m_previousGameMode = ECurrentGameMode::NONE;
m_bossIsDead = false;
m_gameIsStarted = false;
m_isShieldAnimated = true;
}
// Called when the game starts or when spawned
void AWorldInstanceEntity::BeginPlay()
{
Super::BeginPlay();
GameAlterationInstaller& installer = GameAlterationInstaller::getInstance();
installer.installAlteration<UStunAlteration>(&m_stunDefault);
installer.installAlteration<UInvisibilityAlteration>(&m_invisibleDefault);
installer.installAlteration<UShieldAlteration>(&m_shieldDefault);
EntityDataSingleton& datas = EntityDataSingleton::getInstance();
datas.m_showVolumeBox = this->m_showVolumeBox;
datas.m_showEnnemyDetectionSphere = this->m_showEnnemyDetectionSphere;
NavigationVolumeGraph& navGraph = NavigationVolumeGraph::getInstance();
navGraph.m_showConnection = this->m_showVolumeConnection;
m_isBurnEffectEnabled = true;
setupAudioComponents();
}
// Called every frame
void AWorldInstanceEntity::Tick(float DeltaTime)
{
Super::Tick(DeltaTime);
EntityDataSingleton& data = EntityDataSingleton::getInstance();
data.update(this->GetWorld());
bool playerInCombat = false;
//UWorld* w = this->GetWorld();
//ARobotRebellionGameMode* gameMode = Cast<ARobotRebellionGameMode>(w->GetAuthGameMode());
//auto data = gameMode->data;data.m_playableCharacterArray.Num()
for(int i = 0; i < data.m_playableCharacterArray.Num(); i++)
{
APlayableCharacter* playableCharacter = data.m_playableCharacterArray[i];
if(playableCharacter->m_isInCombat)
{
playerInCombat = true;
break;
}
}
if(playerInCombat && m_gameMode != ECurrentGameMode::BOSS)
{
m_gameMode = ECurrentGameMode::COMBAT;
}
else if(m_gameIsStarted && m_gameMode != ECurrentGameMode::BOSS)
{
m_gameMode = ECurrentGameMode::AMBIENT;
}
if(m_bossIsDead)
{
m_gameMode = ECurrentGameMode::WIN;
}
if(m_gameMode != m_previousGameMode)
{
AudioManager& audioMan = AudioManager::getInstance();
switch(m_gameMode)
{
case ECurrentGameMode::INTRO:
audioMan.playBackgroundMusic(m_introAudioComp);
break;
case ECurrentGameMode::NONE:
case ECurrentGameMode::AMBIENT:
audioMan.playBackgroundMusic(m_ambientAudioComp);
break;
case ECurrentGameMode::COMBAT:
audioMan.playBackgroundMusic(m_combatAudioComp);
break;
case ECurrentGameMode::BOSS:
audioMan.playBackgroundMusic(m_bossAudioComp);
break;
case ECurrentGameMode::WIN:
audioMan.playBackgroundMusic(m_winAudioComp);
break;
case ECurrentGameMode::LOSE:
audioMan.playBackgroundMusic(m_loseAudioComp);
break;
}
}
m_previousGameMode = m_gameMode;
}
void AWorldInstanceEntity::setBossGameMode()
{
if (Role<ROLE_Authority)
{
serverSetBossGameMode();
}
m_gameMode = ECurrentGameMode::BOSS;
if (Role>=ROLE_Authority)
{
multiSetBossGameMode();
}
}
void AWorldInstanceEntity::serverSetBossGameMode_Implementation()
{
serverSetBossGameMode();
}
bool AWorldInstanceEntity::serverSetBossGameMode_Validate()
{
return true;
}
void AWorldInstanceEntity::multiSetBossGameMode_Implementation()
{
m_gameMode = ECurrentGameMode::BOSS;
}
// void AWorldInstanceEntity::Tick(float DeltaTime)
void AWorldInstanceEntity::setBossDead()
{
if(Role < ROLE_Authority)
{
serverSetBossDead();
}
m_bossIsDead = true;
if(Role >= ROLE_Authority)
{
multiSetBossDead();
}
}
void AWorldInstanceEntity::serverSetBossDead_Implementation()
{
setBossDead();
}
bool AWorldInstanceEntity::serverSetBossDead_Validate()
{
return true;
}
void AWorldInstanceEntity::multiSetBossDead_Implementation()
{
m_bossIsDead = true;
}
void AWorldInstanceEntity::setStartGameMode()
{
if (Role<ROLE_Authority)
{
serverSetStartGameMode();
}
m_gameIsStarted = true;
if(Role >= ROLE_Authority)
{
multiSetStartGameMode();
}
}
void AWorldInstanceEntity::serverSetStartGameMode_Implementation()
{
setStartGameMode();
}
bool AWorldInstanceEntity::serverSetStartGameMode_Validate()
{
return true;
}
void AWorldInstanceEntity::multiSetStartGameMode_Implementation()
{
m_gameIsStarted = true;
}
void AWorldInstanceEntity::setupAudioComponents()
{
if(Role < ROLE_Authority)
{
serverSetupAudioComponents();
//return;
}
this->internalSetupAudioComponents();
if(Role >= ROLE_Authority)
{
multiSetupAudioComponents();
}
}
void AWorldInstanceEntity::serverSetupAudioComponents_Implementation()
{
setupAudioComponents();
}
bool AWorldInstanceEntity::serverSetupAudioComponents_Validate()
{
return true;
}
void AWorldInstanceEntity::multiSetupAudioComponents_Implementation()
{
this->internalSetupAudioComponents();
}
void AWorldInstanceEntity::internalSetupAudioComponents()
{
if(m_introSounds && !m_introAudioComp)
{
m_introAudioComp = NewObject<UAudioComponent>(this);
m_introAudioComp->SetSound(m_introSounds);
}
if(m_ambientSounds && !m_ambientAudioComp)
{
m_ambientAudioComp = NewObject<UAudioComponent>(this);
m_ambientAudioComp->SetSound(m_ambientSounds);
}
if(m_combatSounds && !m_combatAudioComp)
{
m_combatAudioComp = NewObject<UAudioComponent>(this);
m_combatAudioComp->SetSound(m_combatSounds);
}
if(m_bossSounds && !m_bossAudioComp)
{
m_bossAudioComp = NewObject<UAudioComponent>(this);
m_bossAudioComp->SetSound(m_bossSounds);
}
if(m_winSounds && !m_winAudioComp)
{
m_winAudioComp = NewObject<UAudioComponent>(this);
m_winAudioComp->SetSound(m_winSounds);
}
if(m_loseSounds && !m_loseAudioComp)
{
m_loseAudioComp = NewObject<UAudioComponent>(this);
m_loseAudioComp->SetSound(m_loseSounds);
}
}
<file_sep>/Source/RobotRebellion/Global/WorldInstanceEntity.h
// Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "GameFramework/Actor.h"
#include "WorldInstanceEntity.generated.h"
UENUM(BlueprintType)
enum class ECurrentGameMode : uint8
{
NONE,
INTRO,
AMBIENT,
COMBAT,
BOSS,
WIN,
LOSE,
GAME_MODE_COUNT
};
UCLASS()
class ROBOTREBELLION_API AWorldInstanceEntity : public AActor
{
GENERATED_BODY()
private:
UPROPERTY(VisibleDefaultsOnly)
ECurrentGameMode m_gameMode;
ECurrentGameMode m_previousGameMode;
bool m_bossIsDead;
bool m_gameIsStarted;
bool m_isBurnEffectEnabled;
bool m_isShieldAnimated;
public:
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Debug Display")
bool m_showVolumeBox;
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Debug Display")
bool m_showVolumeConnection;
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Debug Display")
bool m_showEnnemyDetectionSphere;
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Alteration Default")
TSubclassOf<class UAlterationBase> m_invisibleDefault;
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Alteration Default")
TSubclassOf<class UAlterationBase> m_stunDefault;
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Alteration Default")
TSubclassOf<class UAlterationBase> m_shieldDefault;
UPROPERTY(VisibleDefaultsOnly)
UAudioComponent* m_introAudioComp;
UPROPERTY(VisibleDefaultsOnly)
UAudioComponent* m_ambientAudioComp;
UPROPERTY(VisibleDefaultsOnly)
UAudioComponent* m_combatAudioComp;
UPROPERTY(VisibleDefaultsOnly)
UAudioComponent* m_bossAudioComp;
UPROPERTY(VisibleDefaultsOnly)
UAudioComponent* m_winAudioComp;
UPROPERTY(VisibleDefaultsOnly)
UAudioComponent* m_loseAudioComp;
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Soundcues")
USoundCue* m_introSounds;
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Soundcues")
USoundCue* m_ambientSounds;
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Soundcues")
USoundCue* m_combatSounds;
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Soundcues")
USoundCue* m_bossSounds;
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Soundcues")
USoundCue* m_winSounds;
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Soundcues")
USoundCue* m_loseSounds;
// Sets default values for this actor's properties
AWorldInstanceEntity();
// Called when the game starts or when spawned
virtual void BeginPlay() override;
// Called every frame
virtual void Tick(float DeltaSeconds) override;
FORCEINLINE bool getGameStarted() const USE_NOEXCEPT
{
return m_gameIsStarted;
}
void setBossGameMode();
UFUNCTION(Reliable, Server, WithValidation)
void serverSetBossGameMode();
UFUNCTION(Reliable, NetMulticast)
void multiSetBossGameMode();
void setBossDead();
UFUNCTION(Reliable, Server, WithValidation)
void serverSetBossDead();
UFUNCTION(Reliable, NetMulticast)
void multiSetBossDead();
void setStartGameMode();
UFUNCTION(Reliable, Server, WithValidation)
void serverSetStartGameMode();
UFUNCTION(Reliable, NetMulticast)
void multiSetStartGameMode();
void setupAudioComponents();
UFUNCTION(Reliable, Server, WithValidation)
void serverSetupAudioComponents();
UFUNCTION(Reliable, NetMulticast)
void multiSetupAudioComponents();
FORCEINLINE bool IsBurnEffectEnabled() const USE_NOEXCEPT
{
return m_isBurnEffectEnabled;
}
FORCEINLINE void setIsBurnEffectEnabled(bool enable)
{
m_isBurnEffectEnabled = enable;
}
FORCEINLINE bool isShieldAnimated() const USE_NOEXCEPT
{
return m_isShieldAnimated;
}
FORCEINLINE void setShieldAnimation(bool enable)
{
m_isShieldAnimated = enable;
}
private:
void internalSetupAudioComponents();
};
<file_sep>/Source/RobotRebellion/Character/Healer.h
// Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "PlayableCharacter.h"
#include "Healer.generated.h"
/**
*
*/
UCLASS()
class ROBOTREBELLION_API AHealer : public APlayableCharacter
{
GENERATED_BODY()
public:
AHealer();
EClassType getClassType() const USE_NOEXCEPT override
{
return EClassType::HEALER;
}
};
<file_sep>/Source/RobotRebellion/Gameplay/Spell/ThrowSpell.h
// Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "Spell.h"
#include "ThrowSpell.generated.h"
/**
* Implement logic for spell which invoke a projectile with an initiale speed
* The projectil will trigger an onhit effect.
* this effect could be targeted or just use an impact
*/
UCLASS()
class ROBOTREBELLION_API UThrowSpell : public USpell
{
GENERATED_BODY()
public:
// True if we want to impact the affected character
// False if we just use the impact position
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Throw Settings")
bool m_isTargetThrow;
/** offset on the pitch rotation to emulate nade throw */
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Throw Settings")
float m_liftOffset;
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Throw Settings")
FVector m_muzzleOffset;
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Throw Settings")
TSubclassOf<class AProjectileEffect> m_projectileClass;
public:
UThrowSpell();
virtual void BeginPlay() override;
virtual void cast() override;
// Call by the projectile once it hit smth
void onHit(class UPrimitiveComponent*, class AActor*, class UPrimitiveComponent*, FVector, const FHitResult&);
// Apply Effects on a target that have to be a RobotRebellion Character
void applyEffect(class ARobotRebellionCharacter* affectedTarget);
// Aplly Effects on a specific location
void applyEffect(FVector impactPoint);
};
<file_sep>/Source/RobotRebellion/Gameplay/Debug/RobotRobellionSpawnerClass.h
// Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "Components/ActorComponent.h"
#include "../../Character/ClassType.h"
#include "RobotRobellionSpawnerClass.generated.h"
UCLASS( ClassGroup=(Custom), meta=(BlueprintSpawnableComponent) )
class ROBOTREBELLION_API URobotRobellionSpawnerClass : public UActorComponent
{
GENERATED_BODY()
public:
/************************************************************************/
/* UPROPERTY */
/************************************************************************/
UPROPERTY(EditAnywhere, BlueprintReadWrite)
TSubclassOf<class APlayableCharacter> m_assassinActor;
UPROPERTY(EditAnywhere, BlueprintReadWrite)
TSubclassOf<APlayableCharacter> m_healerActor;
UPROPERTY(EditAnywhere, BlueprintReadWrite)
TSubclassOf<APlayableCharacter> m_soldierActor;
UPROPERTY(EditAnywhere, BlueprintReadWrite)
TSubclassOf<APlayableCharacter> m_wizardActor;
/************************************************************************/
/* METHODS */
/************************************************************************/
// Sets default values for this component's properties
URobotRobellionSpawnerClass();
// Called when the game starts
virtual void BeginPlay() override;
// Called every frame
virtual void TickComponent( float DeltaTime, ELevelTick TickType, FActorComponentTickFunction* ThisTickFunction ) override;
/************************************************************************/
/* UFUNCTION */
/************************************************************************/
UFUNCTION(Reliable, Server, WithValidation)
void serverSpawnAndReplace(APlayableCharacter* owner, EClassType typeToChange);
//Replace the player with a new character. Specify the player and the new type of character.
UFUNCTION(BlueprintCallable, Category = "")
void spawnAndReplace(APlayableCharacter* owner, EClassType typeToChange);
};
<file_sep>/Source/RobotRebellion/Gameplay/Item/HealthPotionActor.h
// Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "PickupActor.h"
#include "HealthPotionActor.generated.h"
/**
*
*/
UCLASS()
class ROBOTREBELLION_API AHealthPotionActor : public APickupActor
{
GENERATED_BODY()
public:
void OnPickup(APawn* InstigatorPawn) override;
virtual EObjectType getObjectType() const USE_NOEXCEPT override
{
return EObjectType::HEALTH_POTION;
}
};
<file_sep>/Source/RobotRebellion/Character/BossRobot.cpp
// Fill out your copyright notice in the Description page of Project Settings.
#include "RobotRebellion.h"
#include "BossRobot.h"
#include "Global/WorldInstanceEntity.h"
ABossRobot::ABossRobot()
{
GetCapsuleComponent()->BodyInstance.SetCollisionProfileName("Robots");
m_weaponInventory = CreateDefaultSubobject<UWeaponInventory>(TEXT("WeaponInventory"));
}
void ABossRobot::BeginPlay()
{
Super::BeginPlay();
UWorld* world = this->GetWorld();
TArray<AActor*> entity;
UGameplayStatics::GetAllActorsOfClass(world, AWorldInstanceEntity::StaticClass(), entity);
if(entity.Num() > 0)
{
Cast<AWorldInstanceEntity>(entity[0])->setBossGameMode();
}
}
void ABossRobot::cppOnDeath()
{
UWorld* world = this->GetWorld();
TArray<AActor*> entity;
UGameplayStatics::GetAllActorsOfClass(world, AWorldInstanceEntity::StaticClass(), entity);
if(entity.Num() > 0)
{
Cast<AWorldInstanceEntity>(entity[0])->setBossDead();
}
Super::cppOnDeath();
}<file_sep>/Source/RobotRebellion/Global/AudioManager.h
#pragma once
#include "Tool/IsSingleton.h"
class ROBOTREBELLION_API AudioManager : private IsSingleton<AudioManager>
{
GENERATED_USING_FROM_IsSingleton(AudioManager)
private:
void stopBackgroundMusicWithException(UAudioComponent* soundToNotMute);
public:
void muteAllBackgroundSoundsWithException(UAudioComponent* soundToNotMute);
void playBackgroundMusic(UAudioComponent * audioComponent);
//void setGlobalVolume(float volume);
//private:
//float m_globalVolume = 1.0;
};<file_sep>/Source/RobotRebellion/Gameplay/Spell/Effects/SpawnEffect.h
// Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "Gameplay/Spell/Effects/Effect.h"
#include "SpawnEffect.generated.h"
/**
* This is an Effect that can be added to a spell.
* This effect spawn a new AActor at the impact point + an offset
* you can set
* the offset,
* the base speed of the actor // the actor must have a projectileMovement component
* If it has lifetime
* the duration if it has life time
* if the ator should be controlled by AI controller -seems incompatible with initial speed :)
*/
UCLASS(Blueprintable)
class ROBOTREBELLION_API USpawnEffect : public UEffect
{
GENERATED_BODY()
public:
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = SpawnEffect)
TSubclassOf<AActor> m_actorClassToSpawn;
/** the actor will be spawned at the hit point translated by this offset*/
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = SpawnEffect)
FVector m_offsetFromImpactPoint;
/** Initiale speed, include the speed value not only the direction. The actor must have projectileMovementComponent to work*/
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = SpawnEffect)
FVector m_startSpeed;
/** Maximal speed*/
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = SpawnEffect)
float m_MaxSpeed;
/** Enabled spawning default controller*/
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = SpawnEffect)
bool m_hasDefaultAIController;
/** set the life time in second*/
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = SpawnEffect)
float m_actorLifeTime;
public:
// Called when the game starts
virtual void BeginPlay() override;
// Called every frame
virtual void TickComponent(float DeltaTime, ELevelTick TickType, FActorComponentTickFunction* ThisTickFunction) override;
// The behavior of the effect when it's a targeted effect
virtual void exec(class ARobotRebellionCharacter* caster, ARobotRebellionCharacter* target) override;
// The behavior of the effect when it's point effect
virtual void exec(const FVector& impactPoint, ARobotRebellionCharacter* caster = nullptr) override;
};
<file_sep>/Source/RobotRebellion/Character/Drone.h
// Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "NonPlayableCharacter.h"
#include "Drone.generated.h"
/**
*
*/
UCLASS()
class ROBOTREBELLION_API ADrone : public ANonPlayableCharacter
{
GENERATED_BODY()
public:
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Debug")
float m_debugAutoDropTimer;
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Charge")
FVector m_bombAccroch;
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Charge")
TSubclassOf<class AKaboom> m_defaultKaboomBomb;
class AKaboom* m_currentBomb;
float m_debugTimer;
public:
/************************************************************************/
/* CONSTRUCTOR */
/************************************************************************/
ADrone();
/************************************************************************/
/* GENUINE METHODS */
/************************************************************************/
virtual void BeginPlay() override;
virtual void Tick(float deltaTime) override;
void displayScore(float scores[4]);
/************************************************************************/
/* UFUNCTION */
/************************************************************************/
/*
Reload the drone with an object (here a kaboom bomb). Spawn the Kaboom actor and attach it to the drone.
The Bomb is unnactive and won't explode at collision.
Return true if the reloading was successful, false otherwise (the bomb was not created or it has already a bomb)
*/
UFUNCTION(BlueprintCallable, Category = "Action")
bool reload();
/*
Drop the object the drone currently has (here the kaboom bomb).
Does nothing if the drone has no attached object.
The bomb will be activated when launched (will explode at collision).
*/
UFUNCTION(BlueprintCallable, Category = "Action")
void drop();
/*
Get the bomb radius. Warning : check if the drone is loaded before using this method.
*/
UFUNCTION(BlueprintCallable, Category = "Action")
float getBombRadius() const USE_NOEXCEPT;
/*
Get the bomb base damage. Warning : check if the drone is loaded before using this method.
*/
UFUNCTION(BlueprintCallable, Category = "Action")
float getBombBaseDamage() const USE_NOEXCEPT;
UFUNCTION(BlueprintCallable, Category = "Action")
FORCEINLINE bool isLoaded() const USE_NOEXCEPT
{
return m_currentBomb != nullptr;
}
UFUNCTION(BlueprintCallable, Category = "Debug")
void autoDrop(float deltaTime);
};
<file_sep>/Source/RobotRebellion/Gameplay/Alteration/ShieldAlteration.cpp
// Fill out your copyright notice in the Description page of Project Settings.
#include "RobotRebellion.h"
#include "ShieldAlteration.h"
#include "Character/RobotRebellionCharacter.h"
#include "Gameplay/Attributes/Attributes.h"
UShieldAlteration::UShieldAlteration() :
UAlterationBase()
{
m_id = IdentifiableObject<UShieldAlteration>::ID;
}
void UShieldAlteration::destroyItself()
{
m_alteredOwner->getAttributes()->removeShield(m_amount);
m_alteredOwner->unspawnShieldParticle();
this->DestroyComponent();
}
void UShieldAlteration::onCreate(ARobotRebellionCharacter* alteredOwner)
{
m_alteredOwner = alteredOwner;
m_alteredOwner->spawnShieldParticle();
alteredOwner->getAttributes()->addShield(m_amount);
}
<file_sep>/Source/RobotRebellion/IA/Navigation/VolumeIdProvider.cpp
#include "RobotRebellion.h"
#include "VolumeIdProvider.h"
<file_sep>/Source/RobotRebellion/UI/LobbyUIWidget.cpp
// Fill out your copyright notice in the Description page of Project Settings.
#include "RobotRebellion.h"
#include "Character/RobotRebellionCharacter.h"
#include "Character/PlayableCharacter.h"
#include "OnlineSubsystem.h"
#include "LobbyUIWidget.h"
#include "SessionWidget.h"
void ULobbyUIWidget::initialiseOnliSubsystem()
{
m_onlineSub = IOnlineSubsystem::Get();
if(!m_onlineSub)
{
PRINT_MESSAGE_ON_SCREEN(FColor::Red, TEXT("No OnlineSubsytem found!"))
}
/** Bind function for CREATING a Session */
OnCreateSessionCompleteDelegate = FOnCreateSessionCompleteDelegate::CreateUObject(this, &ULobbyUIWidget::OnCreateSessionComplete);
OnStartSessionCompleteDelegate = FOnStartSessionCompleteDelegate::CreateUObject(this, &ULobbyUIWidget::OnStartSessionComplete);
/** Bind function for FINDING a Session */
OnFindSessionsCompleteDelegate = FOnFindSessionsCompleteDelegate::CreateUObject(this, &ULobbyUIWidget::OnFindSessionsComplete);
/** Bind function for JOINING a Session */
OnJoinSessionCompleteDelegate = FOnJoinSessionCompleteDelegate::CreateUObject(this, &ULobbyUIWidget::OnJoinSessionComplete);
/** Bind function for DESTROYING a Session */
OnDestroySessionCompleteDelegate = FOnDestroySessionCompleteDelegate::CreateUObject(this, &ULobbyUIWidget::OnDestroySessionComplete);
m_sessionSearch = MakeShareable(new FOnlineSessionSearch());
m_sessionsScrollBox = Cast<UScrollBox>(GetWidgetFromName("SessionsScrollBox"));
if(m_sessionsScrollBox)
{
PRINT_MESSAGE_ON_SCREEN(FColor::Black, TEXT("scroll Box gotten"));
}
}
void ULobbyUIWidget::setSelectedSession(int index)
{
if(m_selectedSessionIndex == index)
{
PRINT_MESSAGE_ON_SCREEN(FColor::Cyan, TEXT("Session already selected"));
return;
}
for(int i = 0; i < m_sessionsScrollBox->GetChildrenCount(); ++i)
{
Cast<USessionWidget>(m_sessionsScrollBox->GetChildAt(i))->setSelected(false);
}
Cast<USessionWidget>(m_sessionsScrollBox->GetChildAt(index))->setSelected();
m_selectedSessionIndex = index;
PRINT_MESSAGE_ON_SCREEN(FColor::Cyan, TEXT("New session selected : " + FString::FromInt(index)));
}
void ULobbyUIWidget::CreateServer(FString mapName)
{
auto currentCharacter = Cast<APlayableCharacter>(GetOwningPlayer()->GetCharacter());
FString command = "open " + mapName + "?listen";
if(currentCharacter)
{
currentCharacter->ExecuteCommand(command);
}
}
void ULobbyUIWidget::JoinServer(FString IPAdress)
{
auto currentCharacter = Cast<APlayableCharacter>(GetOwningPlayer()->GetCharacter());
FString command = "open " + IPAdress + ":7777";
if(currentCharacter)
{
currentCharacter->ExecuteCommand(command);
}
}
bool ULobbyUIWidget::HostSession()
{
ULocalPlayer* const Player = GetOwningPlayer()->GetLocalPlayer();
TSharedPtr<const FUniqueNetId> UserId = Player->GetPreferredUniqueNetId();
// Get the Session Interface, so we can call the "CreateSession" function on it
IOnlineSessionPtr Sessions = m_onlineSub->GetSessionInterface();
if(Sessions.IsValid() && UserId.IsValid())
{
/*
Fill in all the Session Settings that we want to use.
There are more with m_sessionSettings.Set(...);
For example the Map or the GameMode/Type.
*/
m_sessionSettings = MakeShareable(new FOnlineSessionSettings());
m_sessionSettings->bIsLANMatch = IS_LAN;
m_sessionSettings->bUsesPresence = USE_PRESENCE;
m_sessionSettings->NumPublicConnections = MAX_PLAYERS;
m_sessionSettings->NumPrivateConnections = MAX_PLAYERS;
m_sessionSettings->bAllowInvites = true;
m_sessionSettings->bAllowJoinInProgress = true;
m_sessionSettings->bShouldAdvertise = true;
m_sessionSettings->bAllowJoinViaPresence = USE_PRESENCE;
m_sessionSettings->bAllowJoinViaPresenceFriendsOnly = USE_PRESENCE;
//m_sessionSettings->Set(SETTING_MAPNAME, m_openMapName, EOnlineDataAdvertisementType::ViaOnlineService);
// Set the delegate to the Handle of the SessionInterface
OnCreateSessionCompleteDelegateHandle = Sessions->AddOnCreateSessionCompleteDelegate_Handle(OnCreateSessionCompleteDelegate);
// Our delegate should get called when this is complete (doesn't need to be successful!)
return Sessions->CreateSession(*UserId, m_gameSessionName, *m_sessionSettings);
}
return false;
}
void ULobbyUIWidget::FindSessions()
{
m_selectedSessionIndex = -1; // initailiaze at -1 to avoid confusion with index 0
ULocalPlayer* const Player = GetOwningPlayer()->GetLocalPlayer();
TSharedPtr<const FUniqueNetId> UserId = Player->GetPreferredUniqueNetId();
// Get the SessionInterface from our OnlineSubsystem
IOnlineSessionPtr Sessions = m_onlineSub->GetSessionInterface();
if(Sessions.IsValid() && UserId.IsValid())
{
/*
Fill in all the SearchSettings, like if we are searching for a LAN game and how many results we want to have!
*/
// m_sessionSearch = MakeShareable(new FOnlineSessionSearch());
m_sessionSearch->bIsLanQuery = IS_LAN;
m_sessionSearch->MaxSearchResults = 20;
m_sessionSearch->PingBucketSize = 50;
TSharedRef<FOnlineSessionSearch> SearchSettingsRef = m_sessionSearch.ToSharedRef();
// Set the Delegate to the Delegate Handle of the FindSession function
OnFindSessionsCompleteDelegateHandle = Sessions->AddOnFindSessionsCompleteDelegate_Handle(OnFindSessionsCompleteDelegate);
// Remove all children of the current list
m_sessionsScrollBox->ClearChildren();
// Finally call the SessionInterface function. The Delegate gets called once this is finished
Sessions->FindSessions(*UserId, SearchSettingsRef);
}
}
void ULobbyUIWidget::JoinLanSession()
{
ULocalPlayer* const Player = GetOwningPlayer()->GetLocalPlayer();
TSharedPtr<const FUniqueNetId> UserId = Player->GetPreferredUniqueNetId();
// Just a SearchResult where we can save the one we want to use, for the case we find more than one!
FOnlineSessionSearchResult SearchResult;
// If the Array is not empty, we can go through it
if(m_sessionSearch->SearchResults.Num() > 0 && m_selectedSessionIndex >= 0)
{
// To avoid something crazy, we filter sessions from ourself
if(m_sessionSearch->SearchResults[m_selectedSessionIndex].Session.OwningUserId != Player->GetPreferredUniqueNetId())
{
SearchResult = m_sessionSearch->SearchResults[m_selectedSessionIndex];
// Once we found sounce a Session that is not ours, just join it. Instead of using a for loop, you could
// use a widget where you click on and have a reference for the GameSession it represents which you can use
// here
IOnlineSessionPtr Sessions = m_onlineSub->GetSessionInterface();
if(Sessions.IsValid() && UserId.IsValid())
{
// Set the Handle again
OnJoinSessionCompleteDelegateHandle = Sessions->AddOnJoinSessionCompleteDelegate_Handle(OnJoinSessionCompleteDelegate);
// Call the "JoinSession" Function with the passed "SearchResult". The "m_sessionSearch->SearchResults" can be used to get such a
// "FOnlineSessionSearchResult" and pass it. Pretty straight forward!
Sessions->JoinSession(*UserId, m_gameSessionName, SearchResult);
}
}
}
}
void ULobbyUIWidget::DestroySessionAndLeaveGame()
{
IOnlineSessionPtr Sessions = m_onlineSub->GetSessionInterface();
if(Sessions.IsValid())
{
Sessions->AddOnDestroySessionCompleteDelegate_Handle(OnDestroySessionCompleteDelegate);
Sessions->DestroySession(m_gameSessionName);
}
}
void ULobbyUIWidget::OnCreateSessionComplete(FName SessionName, bool bWasSuccessful)
{
PRINT_MESSAGE_ON_SCREEN(FColor::Yellow, TEXT("Create Session finished starting delegate function"));
FString debugMessage = "OnCreateSessionComplete " + m_gameSessionName.ToString() + " " + FString::FromInt(bWasSuccessful);
PRINT_MESSAGE_ON_SCREEN(FColor::Red, debugMessage);
// Get the Session Interface to call the StartSession function
IOnlineSessionPtr Sessions = m_onlineSub->GetSessionInterface();
if(Sessions.IsValid())
{
// Clear the SessionComplete delegate handle, since we finished this call
Sessions->ClearOnCreateSessionCompleteDelegate_Handle(OnCreateSessionCompleteDelegateHandle);
if(bWasSuccessful)
{
// Set the StartSession delegate handle
OnStartSessionCompleteDelegateHandle = Sessions->AddOnStartSessionCompleteDelegate_Handle(OnStartSessionCompleteDelegate);
// Our StartSessionComplete delegate should get called after this
Sessions->StartSession(m_gameSessionName);
}
}
}
void ULobbyUIWidget::OnStartSessionComplete(FName SessionName, bool bWasSuccessful)
{
FString debugMessage = "OnStartSessionComplete " + m_gameSessionName.ToString() + " " + FString::FromInt(bWasSuccessful);
PRINT_MESSAGE_ON_SCREEN(FColor::Red, debugMessage);
// Get the Session Interface to clear the Delegate
IOnlineSessionPtr Sessions = m_onlineSub->GetSessionInterface();
if(Sessions.IsValid())
{
// Clear the delegate, since we are done with this call
Sessions->ClearOnStartSessionCompleteDelegate_Handle(OnStartSessionCompleteDelegateHandle);
}
// If the start was successful, we can open a NewMap if we want. Make sure to use "listen" as a parameter!
if(bWasSuccessful)
{
UGameplayStatics::OpenLevel(GetWorld(), m_openMapName, true, "listen");
}
}
void ULobbyUIWidget::OnFindSessionsComplete(bool bWasSuccessful)
{
PRINT_MESSAGE_ON_SCREEN(FColor::Red, FString::Printf(TEXT("OFindSessionsComplete bSuccess: %d"), bWasSuccessful));
// Get SessionInterface of the OnlineSubsystem
IOnlineSessionPtr Sessions = m_onlineSub->GetSessionInterface();
if(Sessions.IsValid())
{
// Clear the Delegate handle, since we finished this call
Sessions->ClearOnFindSessionsCompleteDelegate_Handle(OnFindSessionsCompleteDelegateHandle);
// Just debugging the Number of Search results. Can be displayed in UMG or something later on
PRINT_MESSAGE_ON_SCREEN(FColor::Red, FString::Printf(TEXT("Num Search Results: %d"), m_sessionSearch->SearchResults.Num()));
// If we have found at least 1 session, we just going to debug them. You could add them to a list of UMG Widgets, like it is done in the BP version!
if(m_sessionSearch->SearchResults.Num() > 0)
{
// "m_sessionSearch->SearchResults" is an Array that contains all the information. You can access the Session in this and get a lot of information.
// This can be customized later on with your own classes to add more information that can be set and displayed
for(int32 SearchIdx = 0; SearchIdx < m_sessionSearch->SearchResults.Num(); SearchIdx++)
{
// OwningUserName is just the SessionName for now. I guess you can create your own Host Settings class and GameSession Class and add a proper GameServer Name here.
// This is something you can't do in Blueprint for example!
// TODO - Afficher la liste des parties sur l'écran (dans l'UI)
USessionWidget* temp = NewObject<USessionWidget>(GetTransientPackage(), m_sessionWidgetClass);
temp->initialiseWidget(SearchIdx, this);
m_sessionsScrollBox->AddChild(temp);
PRINT_MESSAGE_ON_SCREEN(FColor::Yellow, FString::Printf(TEXT("Session Number: %d | Sessionname: %s "), SearchIdx + 1, *(m_sessionSearch->SearchResults[SearchIdx].Session.OwningUserName)));
}
}
}
}
void ULobbyUIWidget::OnJoinSessionComplete(FName SessionName, EOnJoinSessionCompleteResult::Type Result)
{
IOnlineSessionPtr Sessions = m_onlineSub->GetSessionInterface();
if(Sessions.IsValid())
{
// Clear the Delegate again
Sessions->ClearOnJoinSessionCompleteDelegate_Handle(OnJoinSessionCompleteDelegateHandle);
// Get the first local PlayerController, so we can call "ClientTravel" to get to the Server Map
// This is something the Blueprint Node "Join Session" does automatically!
APlayerController * const PlayerController = GetOwningPlayer();
// We need a FString to use ClientTravel and we can let the SessionInterface contruct such a
// String for us by giving him the SessionName and an empty String. We want to do this, because
// Every OnlineSubsystem uses different TravelURLs
FString TravelURL;
if(PlayerController && Sessions->GetResolvedConnectString(m_gameSessionName, TravelURL))
{
// Finally call the ClienTravel. If you want, you could print the TravelURL to see
// how it really looks like
PlayerController->ClientTravel(TravelURL, ETravelType::TRAVEL_Absolute);
}
}
}
void ULobbyUIWidget::OnDestroySessionComplete(FName SessionName, bool bWasSuccessful)
{
// Get the SessionInterface from the OnlineSubsystem
IOnlineSessionPtr Sessions = m_onlineSub->GetSessionInterface();
if(Sessions.IsValid())
{
// Clear the Delegate
Sessions->ClearOnDestroySessionCompleteDelegate_Handle(OnDestroySessionCompleteDelegateHandle);
// If it was successful, we just load another level (could be a MainMenu!)
if(bWasSuccessful)
{
UGameplayStatics::OpenLevel(GetWorld(), m_mainMenuMapName, true);
}
}
}
<file_sep>/Source/RobotRebellion/RobotRebellion.cpp
// Copyright 1998-2016 Epic Games, Inc. All Rights Reserved.
#include "RobotRebellion.h"
IMPLEMENT_PRIMARY_GAME_MODULE( FDefaultGameModuleImpl, RobotRebellion, "RobotRebellion" );
<file_sep>/Source/RobotRebellion/Character/PlayableCharacter.h
// Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "RobotRebellionCharacter.h"
#include "ClassType.h"
#include "../Gameplay/Spell/SpellKit.h"
#include "../Gameplay/Item/Focusable.h"
#include "PlayableCharacter.generated.h"
/**
* Playable Character for Robot Rebellion Game
*/
UCLASS()
class ROBOTREBELLION_API APlayableCharacter : public ARobotRebellionCharacter, public Focusable
{
GENERATED_BODY()
public:
/** Camera boom positioning the camera behind the character */
UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = Camera, meta = (AllowPrivateAccess = "true"))
class USpringArmComponent* CameraBoom;
/** Follow camera */
UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = Camera, meta = (AllowPrivateAccess = "true"))
class UCameraComponent* FollowCamera;
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Debug", meta = (AllowPrivateAccess = "true"))
class URobotRobellionSpawnerClass* m_spawner;
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "SpellKit", Replicated)
USpellKit* m_spellKit;
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Mesh", meta = (AllowPrivateAccess = "true"))
class USkeletalMeshComponent* m_fpsMesh;
public:
////Sprint////
UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = "Movement", ReplicatedUsing = OnRep_SprintButtonDown)
bool m_bPressedRun;
////CROUCH////
UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = "Movement", ReplicatedUsing = OnRep_CrouchButtonDown)
bool m_bPressedCrouch;
////INVENTORY
UPROPERTY(VisibleAnywhere, BlueprintReadWrite, Category = "Inventory", Replicated)
int m_healthPotionsCount;
UPROPERTY(VisibleAnywhere, BlueprintReadWrite, Category = "Inventory", Replicated)
int m_manaPotionsCount;
UPROPERTY(VisibleAnywhere, BlueprintReadWrite, Category = "Inventory", Replicated)
int m_bombCount;
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Inventory")
int m_nbHealthPotionStart;
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Inventory")
int m_nbManaPotionStart;
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Inventory")
int m_nbBombStart;
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Inventory")
int m_nbHealthPotionMax;
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Inventory")
int m_nbManaPotionMax;
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Inventory")
int m_nbBombMax;
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Inventory")
float m_healthPerPotion;
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Inventory")
float m_manaPerPotion;
//Reviving Count
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Reviving")
float m_requiredTimeToRevive;
UPROPERTY(EditAnywhere, BlueprintReadOnly, Category = "Reviving")
float m_currentRevivingTime;
UPROPERTY(EditAnywhere, BlueprintReadOnly, Category = "Reviving")
bool m_isReviving;
/** Base turn rate, in deg/sec. Other scaling may affect final turn rate. */
UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = Camera)
float BaseTurnRate;
/** Base look up/down rate, in deg/sec. Other scaling may affect final rate. */
UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = Camera)
float BaseLookUpRate;
//camera broom distance from player pawn while in tps mode
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = Camera)
float m_TPSCameraDistance;
//camera broom distance from player pawn while in fps mode
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = Camera)
float m_FPSCameraDistance;
//camera broom distance from player pawn while in tps mode
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = Camera)
FVector m_mireOffset;
// Maximal Focus distance on items.
UPROPERTY(EditDefaultsOnly, Category = "ObjectInteraction")
float MinUseDistance;
UPROPERTY(EditDefaultsOnly, Category = "ObjectInteraction")
float MaxUseDistance;
// Seulement vrai lors de la premi�re image avec un nouveau focus.
bool bHasNewFocus;
AActor* focusedPickupActor;
bool m_tpsMode;
bool m_isBurnEffectEnabled;
float m_strafForwardMemory;
float m_strafRightMemory;
void(APlayableCharacter::* deactivatePhysicsKilledMethodPtr)();
public:
APlayableCharacter();
private:
void doesNothing(){}
void deactivatePhysicsWhenKilled();
protected:
/************************************************************************/
/* METHODES */
/************************************************************************/
/** Called for forwards/backward input */
void MoveForward(float Value);
/** Called for side to side input */
void MoveRight(float Value);
/**
* Called via input to turn at a given rate.
* @param Rate This is a normalized rate, i.e. 1.0 means 100% of desired turn rate
*/
void TurnAtRate(float Rate);
/**
* Called via input to turn look up/down at a given rate.
* @param Rate This is a normalized rate, i.e. 1.0 means 100% of desired turn rate
*/
void LookUpAtRate(float Rate);
public:
// APawn interface
virtual void SetupPlayerInputComponent(class UInputComponent* PlayerInputComponent) override;
// End of APawn interface
virtual EClassType getClassType() const USE_NOEXCEPT;
/** Returns CameraBoom subobject **/
FORCEINLINE class USpringArmComponent* GetCameraBoom() const
{
return CameraBoom;
}
/** Returns FollowCamera subobject **/
FORCEINLINE class UCameraComponent* GetFollowCamera() const
{
return FollowCamera;
}
virtual void BeginPlay() override;
////Server
void GetLifetimeReplicatedProps(TArray< FLifetimeProperty > & OutLifetimeProps) const override;
void updateIfInCombat();
UFUNCTION()
void cppPreRevive(APlayableCharacter* characterToRevive);
UFUNCTION(Reliable, Server, WithValidation)
virtual void serverCppPreRevive(APlayableCharacter* characterToRevive);
UFUNCTION(BlueprintCallable, Category = "Revive")
void revive()
{
this->cppOnRevive();
}
virtual void cppOnRevive() override;
virtual void cppOnDeath() override;
void EnablePlayInput(bool enable);
void inputOnLiving(class UInputComponent* playerInput);
void inputOnDying(class UInputComponent* playerInput);
void inputDebug(class UInputComponent* playerInput);
////Command Line
UFUNCTION(BlueprintCallable, Category = "CharacterCommand")
void ExecuteCommand(FString command) const;
//////UI
void openTopWidget();
UFUNCTION(BlueprintCallable, Category = TopWidget)
void closeTopWidget();
void openLobbyWidget();
UFUNCTION(BlueprintCallable, Category = LobbyWidget)
void closeLobbyWidget();
UFUNCTION(BlueprintCallable, Category = CharacterSelection)
void closeSelectionWidget();
UFUNCTION(BlueprintCallable, Category = OptionMenu)
void closeOptionWidget();
void giveInputGameMode(bool status);
/************************************************************************/
/* UFUNCTION */
/************************************************************************/
UFUNCTION()
void OnStartJump();
// On d�sactive le bool�en bPressedJump
UFUNCTION()
void OnStopJump();
UFUNCTION()
void OnStartSprint();
UFUNCTION()
void OnStopSprint();
UFUNCTION(BlueprintCallable, Category = "Movement")
bool IsRunning()
{
return m_bPressedRun;
}
UFUNCTION(Reliable, Server, WithValidation)
void ServerSprintActivate(bool NewRunning);
UFUNCTION()
void OnRep_SprintButtonDown();
void OnCrouchToggle();
UFUNCTION(BlueprintCallable, Category = "Movement")
bool IsCrouched()
{
return m_bPressedCrouch;
}
UFUNCTION(Reliable, Server, WithValidation)
void ServerCrouchToggle(bool NewCrouching);
UFUNCTION()
void OnRep_CrouchButtonDown();
///// WORLD INFO
UFUNCTION(BlueprintCallable, Category = "World Info")
FString GetCurrentMapName()
{
return GetWorld()->GetMapName();
}
/////FIRE
UFUNCTION()
void mainFire();
UFUNCTION(Reliable, Server, WithValidation)
void serverMainFire();
//CAST SPELL
template<int32 index>
void castSpellInputHanlder()
{
if (Role < ROLE_Authority)
{
castSpellServer(index); // le param n'a pas d'importance pour l'instant
}
else
{
castSpell(index);
}
}
UFUNCTION()
void castSpell(int32 index);
UFUNCTION(Reliable, Server, WithValidation)
void castSpellServer(int32 index);
//DEATH
//Function to call in BP, can't do it with macro
UFUNCTION(BlueprintCallable, Category = "General")
bool isDeadBP();
//Type
UFUNCTION(BlueprintCallable, Category = "General")
EClassType getType() const USE_NOEXCEPT;
//Parse the class type to a string
UFUNCTION(BlueprintCallable, Category = "Debug")
FString typeToString() const USE_NOEXCEPT;
//change instance to the specified instance type. Can be executed from command line
UFUNCTION(BlueprintCallable, Category = "Debug", Exec)
void changeInstanceTo(EClassType toType);
UFUNCTION(BlueprintCallable, Category = "Debug")
void changeToAssassin();
UFUNCTION(BlueprintCallable, Category = "Debug")
void changeToHealer();
UFUNCTION(BlueprintCallable, Category = "Debug")
void changeToSoldier();
UFUNCTION(BlueprintCallable, Category = "Debug")
void changeToWizard();
UFUNCTION()
void switchWeapon();
UFUNCTION(Reliable, Server, WithValidation)
void serverSwitchWeapon();
UFUNCTION()
void interactBegin();
UFUNCTION()
void interact(AActor* focusedActor);
UFUNCTION()
void interactEnd();
UFUNCTION(Reliable, Server, WithValidation)
void serverInteract(AActor* focusedActor);
UFUNCTION(NetMulticast, Reliable)
void clientInteract(APickupActor* Usable);
UFUNCTION(NetMulticast, Reliable)
void clientRevive();
UFUNCTION(Reliable, Client, WithValidation)
void clientEnableInput(bool enableInput);
// Called every image
virtual void Tick(float DeltaSeconds) override;
AActor* GetUsableInView();
//////INVENTORY///////
void useHealthPotion();
UFUNCTION(Reliable, Server, WithValidation)
void serverUseHealthPotion();
void useManaPotion();
UFUNCTION(Reliable, Server, WithValidation)
void serverUseManaPotion();
void loseBomb();
UFUNCTION(Reliable, Server, WithValidation)
void serverLoseBomb();
//Activate the collision physic if true, deactivate otherwise
UFUNCTION(BlueprintCallable, Category = "Physics")
void activatePhysics(bool mustActive);
UFUNCTION(Reliable, NetMulticast, WithValidation)
void multiActivatePhysics(bool mustActive);
UFUNCTION()
void onDebugCheat();
UFUNCTION(Reliable, Server, WithValidation)
void serverOnDebugCheat();
UFUNCTION()
void gotoDesert();
UFUNCTION()
void gotoRuins();
UFUNCTION()
void gotoGym();
UFUNCTION(Reliable, Server, WithValidation)
void serverGotoDesert();
UFUNCTION(Reliable, Server, WithValidation)
void serverGotoRuins();
UFUNCTION(Reliable, Server, WithValidation)
void serverGotoGym();
UFUNCTION(BlueprintCallable, Category = "ReviveTimer")
float getReviveTimer() const USE_NOEXCEPT
{
return m_currentRevivingTime;
}
UFUNCTION(BlueprintCallable, Category = "ReviveTimer")
float getRequiredReviveTime() const USE_NOEXCEPT
{
return m_requiredTimeToRevive;
}
UFUNCTION(BlueprintCallable, Category = "ReviveTimer")
bool isReviving() const USE_NOEXCEPT
{
return m_isReviving;
}
UFUNCTION()
void giveBombToDrone(ADroneAIController* drone);
UFUNCTION(Reliable, Server, WithValidation)
void serverGiveBombToDrone(ADroneAIController* drone);
int getManaPotionCount()
{
return m_manaPotionsCount;
}
int getHealthPotionCount()
{
return m_healthPotionsCount;
}
int getBombCount()
{
return m_bombCount;
}
void setManaPotionCount(int nbPotion);
void setHealthPotionCount(int nbPotion);
void setBombCount(int nbBombs);
void switchView();
UMeshComponent* getCurrentViewMesh();
virtual void OnPickup(APawn* InstigatorPawn) override;
virtual void OnBeginFocus() override
{}
virtual void OnEndFocus() override
{}
void enableDroneDisplay();
UFUNCTION(Reliable, Client)
void updateAllCharacterBillboard(UCameraComponent* camToFollow);
void updateHUD(EClassType classType);
void disableFireEffect();
};
<file_sep>/Source/RobotRebellion/UI/TopWidget.cpp
// Fill out your copyright notice in the Description page of Project Settings.
#include "RobotRebellion.h"
#include "TopWidget.h"
#include "GameMenu.h"
void UTopWidget::SinglePlayerGame()
{
APlayerController * MyPC = GetOwningPlayer();
if(MyPC)
{
auto myHud = Cast<AGameMenu>(MyPC->GetHUD());
if(myHud->ClassSelectionWidgetImpl->IsVisible())
{
CloseSinglePlayerGameWidget();
//return;
}
myHud->HideWidget(myHud->TopWidgetImpl);
myHud->DisplayWidget(myHud->ClassSelectionWidgetImpl);
//giveInputGameMode(false);
}
}
void UTopWidget::CloseSinglePlayerGameWidget()
{
APlayerController * MyPC = GetOwningPlayer();
if(MyPC)
{
auto myHud = Cast<AGameMenu>(MyPC->GetHUD());
myHud->HideWidget(myHud->TopWidgetImpl);
//giveInputGameMode(true);
}
}
void UTopWidget::NetworkPlayerGame()
{
APlayerController * MyPC = GetOwningPlayer();
if(MyPC)
{
auto myHud = Cast<AGameMenu>(MyPC->GetHUD());
if(myHud->LobbyImpl->IsVisible())
{
//CloseSinglePlayerGameWidget();
//return;
}
myHud->HideWidget(myHud->TopWidgetImpl);
myHud->HideWidget(myHud->ClassSelectionWidgetImpl);
myHud->DisplayWidget(myHud->LobbyImpl);
//giveInputGameMode(false);
}
}
void UTopWidget::GameOptionsMenu()
{
APlayerController * MyPC = GetOwningPlayer();
if(MyPC)
{
auto myHud = Cast<AGameMenu>(MyPC->GetHUD());
if(myHud->OptionsWidgetImpl->IsVisible())
{
CloseGameOptionsMenu();
}
myHud->HideWidget(myHud->TopWidgetImpl);
myHud->DisplayWidget(myHud->OptionsWidgetImpl);
}
}
void UTopWidget::CloseGameOptionsMenu()
{
APlayerController * MyPC = GetOwningPlayer();
if(MyPC)
{
auto myHud = Cast<AGameMenu>(MyPC->GetHUD());
myHud->HideWidget(myHud->OptionsWidgetImpl);
}
}
void UTopWidget::setReturnInGameVisible(bool enable)
{
auto widget = this->GetWidgetFromName(TEXT("ReturnToGameButton"));
if(enable)
{
widget->SetVisibility(ESlateVisibility::Visible);
}
else
{
widget->SetVisibility(ESlateVisibility::Hidden);
}
};<file_sep>/Source/RobotRebellion/Character/NonPlayableCharacter.cpp
// Fill out your copyright notice in the Description page of Project Settings.
#include "RobotRebellion.h"
#include "NonPlayableCharacter.h"
#include "UI/TextBillboardComponent.h"
#include "IA/Controller/CustomAIControllerBase.h"
ANonPlayableCharacter::ANonPlayableCharacter() : ARobotRebellionCharacter()
{
// fill it
m_lootTable = CreateDefaultSubobject<ULootTable>(TEXT("LootTable"));
GetCharacterMovement()->bOrientRotationToMovement = false;
}
void ANonPlayableCharacter::cppOnDeath()
{
dropLoot();
this->m_alterationController->removeAllAlteration();
this->cleanFireComp();
ACustomAIControllerBase* controller = Cast<ACustomAIControllerBase>(this->GetController());
if (controller)
{
controller->setTarget(nullptr);
}
this->startTimedDestroy();
}
void ANonPlayableCharacter::GetLifetimeReplicatedProps(TArray< FLifetimeProperty > & OutLifetimeProps) const
{
Super::GetLifetimeReplicatedProps(OutLifetimeProps);
DOREPLIFETIME_CONDITION(ANonPlayableCharacter, m_isCrouch, COND_SkipOwner);
}
void ANonPlayableCharacter::dropLoot()
{
if (Role == ROLE_Authority)
{
PRINT_MESSAGE_ON_SCREEN(FColor::Black, "Drop!");
m_lootTable->dropItem(GetActorLocation());
}
else
{
serverDropLoot();
}
}
void ANonPlayableCharacter::serverDropLoot_Implementation()
{
dropLoot();
}
bool ANonPlayableCharacter::serverDropLoot_Validate()
{
return true;
}
FVector ANonPlayableCharacter::aim(const FVector& directionToShoot) const
{
FVector result = directionToShoot;
ACustomAIControllerBase* controller = Cast<ACustomAIControllerBase>(Controller);
//No ACustomAIControllerBase. Please attach one in BP if you want to fire
check(controller);
controller->aim(result);
return result;
}
void ANonPlayableCharacter::spawnEffect()
{
UGameplayStatics::SpawnEmitterAtLocation(
GetWorld(),
m_spawnParticleSystem,
GetActorLocation(),
GetActorRotation(),
true
);
if(RootComponent->GetOwnerRole() >= ROLE_Authority)
{
multiSpawnEffect();
}
}
void ANonPlayableCharacter::multiSpawnEffect_Implementation()
{
UGameplayStatics::SpawnEmitterAtLocation(
GetWorld(),
m_spawnParticleSystem,
GetActorLocation(),
GetActorRotation(),
true
);
}
bool ANonPlayableCharacter::multiSpawnEffect_Validate()
{
return true;
}
void ANonPlayableCharacter::goAway(const FVector& fromWhere, float delta)
{
ACustomAIControllerBase* controller = Cast<ACustomAIControllerBase>(Controller);
if (controller)
{
FVector actorLocation = this->GetActorLocation();
FVector fireDirection = actorLocation - fromWhere;
fireDirection.Normalize();
FVector toMove = FVector::CrossProduct(this->GetActorUpVector(), fireDirection);
toMove.Normalize();
toMove *= delta;
controller->StopMovement(); //stop the move it did before
controller->MoveToLocation(actorLocation + toMove);
}
}
<file_sep>/Source/RobotRebellion/UI/RobotRebellionWidget.cpp
// Fill out your copyright notice in the Description page of Project Settings.
#include "RobotRebellion.h"
#include "RobotRebellionWidget.h"
#include "ActiveSound.h"
#include "Character/PlayableCharacter.h"
void URobotRebellionWidget::startSound()
{
// Begin sound
playSound(m_widgetBeginSound);
// Background Loop
playSound(m_widgetLoopSound);
if(m_stopAmbiantSound && m_loopAudioComp)
{
if(GEngine)
{
const TArray<FActiveSound*> sounds = GEngine->GetActiveAudioDevice()->GetActiveSounds();
for(auto sound : sounds)
{
UAudioComponent *audioComp = UAudioComponent::GetAudioComponentFromID(sound->GetAudioComponentID());
if(audioComp)
{
if(audioComp->GetAudioComponentID() != m_loopAudioComp->GetAudioComponentID())
{
audioComp->SetVolumeMultiplier(0.f);
}
}
}
}
}
}
void URobotRebellionWidget::endSound()
{
// Stop loop
if(m_loopAudioComp && m_loopAudioComp->IsPlaying())
{
m_loopAudioComp->Stop();
}
// Closing sound
playSound(m_widgetCloseSound);
if(m_loopAudioComp && m_stopAmbiantSound)
{
if(GEngine)
{
const TArray<FActiveSound*> sounds = GEngine->GetActiveAudioDevice()->GetActiveSounds();
for(auto sound : sounds)
{
UAudioComponent *audioComp = UAudioComponent::GetAudioComponentFromID(sound->GetAudioComponentID());
if(audioComp && m_loopAudioComp)
{
if(audioComp->GetAudioComponentID() != m_loopAudioComp->GetAudioComponentID())
{
audioComp->SetVolumeMultiplier(1.f);
}
}
}
}
}
}
void URobotRebellionWidget::playSound(USoundCue * sound)
{
if(sound)
{
auto owner = GetOwningPlayer();
if(owner)
{
auto charac = owner->GetCharacter();
if(charac)
{
UGameplayStatics::SpawnSoundAttached(sound, charac->GetRootComponent());
}
}
}
}
<file_sep>/Source/RobotRebellion/RobotRebellion.h
// Copyright 1998-2016 Epic Games, Inc. All Rights Reserved.
#ifndef __ROBOTREBELLION_H__
#define __ROBOTREBELLION_H__
#include "Engine.h"
#include "Net/UnrealNetwork.h"
#include "Online.h"
// Include UMG
#include "Runtime/UMG/Public/UMG.h"
#include "Runtime/UMG/Public/UMGStyle.h"
#include "Runtime/UMG/Public/Slate/SObjectWidget.h"
#include "Runtime/UMG/Public/IUMGModule.h"
#include "Runtime/UMG/Public/Blueprint/UserWidget.h"
#include "SlateBasics.h"
#define COLLISION_PROJECTILE ECC_GameTraceChannel1
#include "Tool/UtilitaryMacros.h"
#define USE_NOEXCEPT noexcept
#endif
<file_sep>/Source/RobotRebellion/UI/LobbyUIWidget.h
// Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "UI/RobotRebellionWidget.h"
#include "ScrollBox.h"
#include "LobbyUIWidget.generated.h"
class IOnlineSubsystem;
/**
*
*/
UCLASS()
class ROBOTREBELLION_API ULobbyUIWidget : public URobotRebellionWidget
{
GENERATED_BODY()
private:
IOnlineSubsystem* m_onlineSub;
enum ServerSettings
{
MAX_PLAYERS = 4,
IS_LAN = true,
USE_PRESENCE = false
};
/*
Create Session
*/
TSharedPtr<class FOnlineSessionSettings> m_sessionSettings;
/* Delegate called when session created */
FOnCreateSessionCompleteDelegate OnCreateSessionCompleteDelegate;
/* Delegate called when session started */
FOnStartSessionCompleteDelegate OnStartSessionCompleteDelegate;
/** Handles to registered delegates for creating/starting a session */
FDelegateHandle OnCreateSessionCompleteDelegateHandle;
FDelegateHandle OnStartSessionCompleteDelegateHandle;
/*
Searching Session
*/
bool m_isFindSessionDone = false;
TSharedPtr<class FOnlineSessionSearch> m_sessionSearch;
/** Delegate for searching for sessions */
FOnFindSessionsCompleteDelegate OnFindSessionsCompleteDelegate;
/** Handle to registered delegate for searching a session */
FDelegateHandle OnFindSessionsCompleteDelegateHandle;
/*
Joining Session
*/
int m_selectedSessionIndex;
/** Delegate for joining a session */
FOnJoinSessionCompleteDelegate OnJoinSessionCompleteDelegate;
/** Handle to registered delegate for joining a session */
FDelegateHandle OnJoinSessionCompleteDelegateHandle;
/*
Destroying Session
*/
/** Delegate for destroying a session */
FOnDestroySessionCompleteDelegate OnDestroySessionCompleteDelegate;
/** Handle to registered delegate for destroying a session */
FDelegateHandle OnDestroySessionCompleteDelegateHandle;
FName m_gameSessionName = "RobotRebellionSession";
public:
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "LobbyServer | Settings")
FString m_widgetName;
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "LobbyServer | Settings")
FName m_openMapName;
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "LobbyServer | Settings")
FName m_mainMenuMapName;
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "LobbyServer | Settings")
UScrollBox* m_sessionsScrollBox;
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "LobbyServer | Settings")
TSubclassOf<class USessionWidget> m_sessionWidgetClass;
/*
* METHODS
*/
private:
/*
* Delegate methods
*/
virtual void OnCreateSessionComplete(FName SessionName, bool bWasSuccessful);
void OnStartSessionComplete(FName SessionName, bool bWasSuccessful);
void OnFindSessionsComplete(bool bWasSuccessful);
void OnJoinSessionComplete(FName SessionName, EOnJoinSessionCompleteResult::Type Result);
virtual void OnDestroySessionComplete(FName SessionName, bool bWasSuccessful);
public:
void initialiseOnliSubsystem();
void setSelectedSession(int index);
/*
Server with command line
*/
UFUNCTION(BlueprintCallable, Category = "LobbyServer | Command")
void CreateServer(FString mapName);
UFUNCTION(BlueprintCallable, Category = "LobbyServer | Command")
void JoinServer(FString IPAdress);
/*
Server with unreal session
*/
UFUNCTION(BlueprintCallable, Category = "LobbyServer | Session")
bool HostSession();
UFUNCTION(BlueprintCallable, Category = "LobbyServer | Session")
void FindSessions();
UFUNCTION(BlueprintCallable, Category = "LobbyServer | Session")
void JoinLanSession();
UFUNCTION(BlueprintCallable, Category = "LobbyServer | Session")
void DestroySessionAndLeaveGame();
UFUNCTION(BlueprintCallable, Category = "LobbyServer | Session")
bool isSessionSelected()
{
return m_selectedSessionIndex >= 0;
}
};
<file_sep>/Source/RobotRebellion/IA/Controller/RobotShooterController.cpp
// Fill out your copyright notice in the Description page of Project Settings.
#include "RobotRebellion.h"
#include "RobotShooterController.h"
#include "Character/NonPlayableCharacter.h"
#include "Gameplay/Weapon/WeaponBase.h"
void ARobotShooterController::CheckEnnemyNear(float range)
{
//debug use
m_detectionRange = range;
AEnnemiAIController::CheckEnnemyNear(range);
}
void ARobotShooterController::AttackTarget() const
{
AEnnemiAIController::AttackTarget();
}
bool ARobotShooterController::isCrouch() const
{
// TODO - return m_crouch
ANonPlayableCharacter* ennemiCharacter = Cast<ANonPlayableCharacter>(GetCharacter());
return ennemiCharacter->m_isCrouch;
}
void ARobotShooterController::crouch() const
{
// TODO - Crouch the pawn if necessary
ANonPlayableCharacter* ennemiCharacter = Cast<ANonPlayableCharacter>(GetCharacter());
ennemiCharacter->m_isCrouch = true;
ennemiCharacter->BaseEyeHeight = m_crouchEyesHeight;
}
void ARobotShooterController::uncrouch() const
{
// TODO - Uncrouch the pawn if necessary
ANonPlayableCharacter* ennemiCharacter = Cast<ANonPlayableCharacter>(GetCharacter());
ennemiCharacter->m_isCrouch = false;
ennemiCharacter->BaseEyeHeight = m_standingEyesHeight;
}
void ARobotShooterController::updateShootLocation()
{
// Get target Location
const FVector& targetLoc = getTargetToFollowLocation();
const FVector& pawnLoc = GetPawn()->GetActorLocation();
// get direction vector from target to pawn
FVector direction = pawnLoc - targetLoc;
direction.Normalize();
// process Distance from the target
ANonPlayableCharacter* ennemiCharacter = Cast<ANonPlayableCharacter>(GetCharacter());
float distanceToShoot = m_distanceToShoot *
ennemiCharacter->m_weaponInventory->getCurrentWeapon()->m_WeaponRadiusRange;
m_shootLocation = targetLoc + distanceToShoot * direction;
}
EPathFollowingRequestResult::Type ARobotShooterController::moveToShootLocation()
{
EPathFollowingRequestResult::Type MoveToActorResult = MoveToLocation(m_shootLocation);
return MoveToActorResult;
}
// DEBUG
void ARobotShooterController::drawDebug()
{
DrawDebugSphere(GetWorld(),
GetPawn()->GetActorLocation(),
m_detectionRange,
32,
FColor::Cyan,
false,
2.f, 0, 5.f);
ANonPlayableCharacter* ennemiCharacter = Cast<ANonPlayableCharacter>(GetCharacter());
float weaponRange = ennemiCharacter->m_weaponInventory->getCurrentWeapon()->m_WeaponRadiusRange;
DrawDebugSphere(GetWorld(),
GetPawn()->GetActorLocation(),
weaponRange,
32,
FColor::Red,
false,
2.f, 0, 5.f);
FColor positionColor;
if(isCrouch())
{
positionColor = FColor::Red;
}
else
{
positionColor = FColor::Blue;
}
DrawDebugSphere(GetWorld(),
GetPawn()->GetActorLocation() + FVector{0.f, 0.f, 100.f},
5.f,
12,
positionColor,
false,
2.f, 0, 5.f);
}<file_sep>/Source/RobotRebellion/Gameplay/Damage/Damage.cpp
// Fill out your copyright notice in the Description page of Project Settings.
#include "RobotRebellion.h"
#include "Damage.h"
#include "Character/RobotRebellionCharacter.h"
Damage::Damage(const ARobotRebellionCharacter*const assailant, const ARobotRebellionCharacter*const receiver) :
m_assailant{ assailant },
m_receiver{ receiver }
{
}
Damage::~Damage()
{
}
<file_sep>/Source/RobotRebellion/Gameplay/Damage/DamageCoefficientLogic.h
// Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "RobotRebellion.h"
/**
*
*/
class ROBOTREBELLION_API DamageCoefficientLogic
{
public:
static constexpr const float CRITICAL_EFFECT_MULTIPLICATOR = 2.0f;
static constexpr const float SUPER_EFFICIENT_EFFECT_MULTIPLICATOR = 1.5f;
static constexpr const float MULTIPLE_HIT_EFFECT_MULTIPLICATOR = 0.3f;
static constexpr const float ENGAGEMENT_EFFECT_MULTIPLICATOR = 1.1f;
static constexpr const float BACKSTAB_EFFECT_MULTIPLICATOR = 1.5f;
static constexpr const float MIN_COEFFICIENT_VALUE = 0.1f;
private:
float m_damageCoefficient = 1.0f;
public:
DamageCoefficientLogic() = default;
constexpr DamageCoefficientLogic(float startingValue) :
m_damageCoefficient{ startingValue }
{}
~DamageCoefficientLogic() = default;
void multiplyCoefficient(float value) USE_NOEXCEPT
{
m_damageCoefficient *= value;
}
void divideCoefficient(float value) USE_NOEXCEPT
{
m_damageCoefficient /= value;
if (m_damageCoefficient < MIN_COEFFICIENT_VALUE)
{
m_damageCoefficient = MIN_COEFFICIENT_VALUE;
}
}
//Modify the damage coefficient according to the fact that the attack was a critical hit.
void criticalHit() USE_NOEXCEPT
{
multiplyCoefficient(CRITICAL_EFFECT_MULTIPLICATOR);
}
//Modify the damage coefficient according to the fact that the attack was a backstab attack.
void backstab() USE_NOEXCEPT
{
multiplyCoefficient(BACKSTAB_EFFECT_MULTIPLICATOR);
}
//Modify the damage coefficient according to the fact that the attack grazed the target.
void graze() USE_NOEXCEPT
{
divideCoefficient(CRITICAL_EFFECT_MULTIPLICATOR);
}
//Modify the damage coefficient according to the fact that the attack was greatly efficient against the target.
void superEfficient() USE_NOEXCEPT
{
multiplyCoefficient(SUPER_EFFICIENT_EFFECT_MULTIPLICATOR);
}
//Modify the damage coefficient according to the fact that the attack was less efficient against the target.
void lessEfficient() USE_NOEXCEPT
{
divideCoefficient(SUPER_EFFICIENT_EFFECT_MULTIPLICATOR);
}
//Modify the damage coefficient according to the fact that the attack was a mutliple hit attack (reduce the unitary attack coefficient).
void multipleHit() USE_NOEXCEPT
{
multiplyCoefficient(MULTIPLE_HIT_EFFECT_MULTIPLICATOR);
}
//Modify the damage coefficient according to the fact that the attack was an engagement hit.
void engagementHit() USE_NOEXCEPT
{
multiplyCoefficient(ENGAGEMENT_EFFECT_MULTIPLICATOR);
}
//return the current coefficient value.
float getCoefficientValue() const USE_NOEXCEPT
{
return m_damageCoefficient;
}
bool establishCritical(const FName& boneName) const USE_NOEXCEPT;
};
<file_sep>/Source/RobotRebellion/Gameplay/Spell/SpellKit.cpp
// Fill out your copyright notice in the Description page of Project Settings.
#include "RobotRebellion.h"
#include "SpellKit.h"
#include "Spell.h"
#include "ThrowSpell.h"
#include "../../Tool/UtilitaryFunctionLibrary.h"
// Sets default values for this component's properties
USpellKit::USpellKit()
{
// Set this component to be initialized when the game starts, and to be ticked every frame. You can turn these features
// off to improve performance if you don't need them.
PrimaryComponentTick.bCanEverTick = true;
// ...
}
// Called when the game starts
void USpellKit::BeginPlay()
{
Super::BeginPlay();
if(GetOwner()->Role == ROLE_Authority)
{
for(int i = 0; i < m_spellsClass.Num(); ++i)
{
USpell* tempSpell;
tempSpell = NewObject<USpell>(this, m_spellsClass[i]);
tempSpell->SetIsReplicated(true);
if(tempSpell)
{
tempSpell->initializeSpell();
m_spells.Emplace(tempSpell);
}
}
}
}
// Called every frame
void USpellKit::TickComponent(float DeltaTime, ELevelTick TickType, FActorComponentTickFunction* ThisTickFunction)
{
Super::TickComponent(DeltaTime, TickType, ThisTickFunction);
// ...
}
void USpellKit::GetLifetimeReplicatedProps(TArray< FLifetimeProperty > & OutLifetimeProps) const
{
Super::GetLifetimeReplicatedProps(OutLifetimeProps);
DOREPLIFETIME_CONDITION(USpellKit, m_spells, COND_OwnerOnly);
}
void USpellKit::cast(int32 index)
{
if(index < m_spells.Num())
{
m_spells[index]->cast();
}
}
TArray<float> USpellKit::getCooldowns()
{
TArray<float> cooldowns{};
for(int32 index{}; index < m_spells.Num(); ++index)
{
cooldowns.Emplace(m_spells[index]->getCurrentCooldown());
}
return cooldowns;
}<file_sep>/Source/RobotRebellion/IA/Controller/BeastAIController.cpp
// Fill out your copyright notice in the Description page of Project Settings.
#include "RobotRebellion.h"
#include "BeastAIController.h"
#include "Kismet/KismetSystemLibrary.h"
#include "Character/NonPlayableCharacter.h"
#include "Gameplay/Weapon/WeaponInventory.h"
#include "Gameplay/Weapon/WeaponBase.h"
void ABeastAIController::CheckEnnemyNear(float range)
{
APawn *currentPawn = GetPawn();
FVector MultiSphereStart = currentPawn->GetActorLocation();
FVector MultiSphereEnd = MultiSphereStart + FVector(0, 0, 15.0f);
TArray<TEnumAsByte<EObjectTypeQuery>> ObjectTypes;
ObjectTypes.Add(UEngineTypes::ConvertToObjectType(ECC_GameTraceChannel2)); // Players
ObjectTypes.Add(UEngineTypes::ConvertToObjectType(ECC_GameTraceChannel3)); // Robots
ObjectTypes.Add(UEngineTypes::ConvertToObjectType(ECC_GameTraceChannel4)); // Sovec
TArray<AActor*> ActorsToIgnore;
ActorsToIgnore.Add(currentPawn);
TArray<FHitResult> OutHits;
bool Result = UKismetSystemLibrary::SphereTraceMultiForObjects(GetWorld(),
MultiSphereStart,
MultiSphereEnd,
range,
ObjectTypes,
false,
ActorsToIgnore,
this->debugDrawTraceShowingMode(),
OutHits,
true);
if(Result == true)
{
for(int32 i = 0; i < OutHits.Num(); i++)
{
FHitResult Hit = OutHits[i];
ARobotRebellionCharacter* RRCharacter = Cast<ARobotRebellionCharacter>(Hit.GetActor());
if(NULL != RRCharacter)
{
if(RRCharacter->isDead() || !RRCharacter->isVisible())
{
continue;
}
setTarget(RRCharacter);
break;
}
}
}
else
{
setTarget(nullptr);
}
}
void ABeastAIController::AttackTarget() const
{
ANonPlayableCharacter* ennemiCharacter = Cast<ANonPlayableCharacter>(GetCharacter());
if(ennemiCharacter)
{
ennemiCharacter->m_weaponInventory->getCurrentWeapon()->cppAttack(ennemiCharacter);
}
}<file_sep>/Source/RobotRebellion/Gameplay/Alteration/StunAlteration.cpp
// Fill out your copyright notice in the Description page of Project Settings.
#include "RobotRebellion.h"
#include "StunAlteration.h"
#include "Character/NonPlayableCharacter.h"
#include "Character/PlayableCharacter.h"
#include "AIController.h"
#include "Runtime/AIModule/Classes/BrainComponent.h"
UStunAlteration::UStunAlteration() :
UAlterationBase()
{
m_id = IdentifiableObject<UStunAlteration>::ID;
}
void UStunAlteration::destroyItself()
{
if(m_isNPC)
{
auto nonPlayableOwner = Cast<ANonPlayableCharacter>(m_alteredOwner);
if(m_alteredActorController)
{
m_alteredActorController->SetPawn(nonPlayableOwner);
AAIController* controller = Cast<AAIController>(m_alteredActorController);
if(controller)
{
auto brain = controller->GetBrainComponent();
if(brain)
{
brain->RestartLogic();
}
}
}
}
else
{
APlayableCharacter* playableOwner = Cast<APlayableCharacter>(m_alteredOwner);
if(playableOwner)
{
playableOwner->EnablePlayInput(true);
}
}
this->DestroyComponent();
}
void UStunAlteration::onCreate(ARobotRebellionCharacter* alteredOwner)
{
m_alteredOwner = alteredOwner;
m_alteredActorController = alteredOwner->Controller;
auto playableOwner = Cast<APlayableCharacter>(alteredOwner);
if(playableOwner)
{
m_isNPC = false;
playableOwner->EnablePlayInput(false);
}
else
{
auto nonPlayableOwner = Cast<ANonPlayableCharacter>(alteredOwner);
if(nonPlayableOwner)
{
m_isNPC = true;
AAIController* controller = Cast<AAIController>(m_alteredOwner->Controller);
if(controller)
{
auto brain = controller->GetBrainComponent();
if(brain)
{
brain->StopLogic("");
}
}
}
else
{
this->DestroyComponent();
}
}
}
<file_sep>/Source/RobotRebellion/UI/ReviveTimerWidget.cpp
// Fill out your copyright notice in the Description page of Project Settings.
#include "RobotRebellion.h"
#include "ReviveTimerWidget.h"
#include "../Character/PlayableCharacter.h"
void UReviveTimerWidget::getTimerRatio(float& ratio, float& currentTime, float& requiredTime) const
{
APlayableCharacter* character = Cast<APlayableCharacter>(GetOwningPlayerPawn());
if (character)
{
currentTime = character->getReviveTimer();
requiredTime = character->getRequiredReviveTime();
ratio = currentTime / requiredTime;
}
else
{
currentTime = 0.f;
requiredTime = 0.f;
ratio = 0.f;
}
}
<file_sep>/Source/RobotRebellion/Gameplay/Item/Focusable.h
// Fill out your copyright notice in the Description page of Project Settings.
#pragma once
/**
*
*/
class Focusable
{
public:
// Focusable();
// ~Focusable();
virtual void OnBeginFocus()=0;
virtual void OnEndFocus()=0;
virtual void OnPickup(APawn* InstigatorPawn)=0;
};
<file_sep>/Source/RobotRebellion/Character/TrainingDummyCharacter.cpp
// Fill out your copyright notice in the Description page of Project Settings.
#include "RobotRebellion.h"
#include "TrainingDummyCharacter.h"
ATrainingDummyCharacter::ATrainingDummyCharacter() : ANonPlayableCharacter()
{
GetCapsuleComponent()->BodyInstance.SetCollisionProfileName("Robots");
}<file_sep>/Source/RobotRebellion/UI/ELivingTextAnimMode.h
// Fill out your copyright notice in the Description page of Project Settings.
#pragma once
UENUM(BlueprintType)
enum class ELivingTextAnimMode : uint8
{
TEXT_ANIM_NOT_READY,
TEXT_ANIM_MOVING,
TEXT_ANIM_NOT_MOVING,
TEXT_ANIM_BOING_BOING,
TEXT_ANIM_BOING_BIGGER_TEXT_ON_CRITICAL
};
<file_sep>/Source/RobotRebellion/Character/King.cpp
// Fill out your copyright notice in the Description page of Project Settings.
#include "RobotRebellion.h"
#include "King.h"
#include "../IA/Controller/DroneAIController.h"
AKing::AKing() : ANonPlayableCharacter()
{
PrimaryActorTick.bCanEverTick = true;
this->setImmortal(false);
this->GetCapsuleComponent()->BodyInstance.SetCollisionProfileName("King");
this->GetCharacterMovement()->GravityScale = 0.f;
}
void AKing::BeginPlay()
{
Super::BeginPlay();
//TArray<AActor*> drones;
//UGameplayStatics::GetAllActorsOfClass(GetWorld(), m_droneControllerClass, drones);
//if (drones.Num() > 0) //The king is here
//{
// ADroneAIController* drone = Cast<ADroneAIController>(drones.Top());
// drone->setFollowKing(); //king is spawned, follow him.
//}
}
void AKing::Tick(float deltaTime)
{
Super::Tick(deltaTime);
}
void AKing::cppOnDeath()
{
//TArray<AActor*> drones;
//UGameplayStatics::GetAllActorsOfClass(GetWorld(), m_droneControllerClass, drones);
//ADroneAIController* drone = Cast<ADroneAIController>(drones.Top());
//drone->setFollowGroup(); //king is dead, follow group. Later -> Game over.
Super::cppOnDeath();
}<file_sep>/Source/RobotRebellion/Character/Location.h
#pragma once
UENUM(BlueprintType)
enum class ELocation : uint8
{
OUTSIDE,
BIGROOM,
SMALLROOM,
CORRIDOR
};<file_sep>/Source/RobotRebellion/Gameplay/Attributes/Attributes.cpp
// Fill out your copyright notice in the Description page of Project Settings.
#include "RobotRebellion.h"
#include "Attributes.h"
// Sets default values for this component's properties
UAttributes::UAttributes()
{
// Set this component to be initialized when the game starts, and to be ticked every frame. You can turn these features
// off to improve performance if you don't need them.
PrimaryComponentTick.bCanEverTick = false;
bReplicates = true;
// ...
setImmortal(false);
}
void UAttributes::GetLifetimeReplicatedProps(TArray<FLifetimeProperty>& OutLifetimeProps) const
{
Super::GetLifetimeReplicatedProps(OutLifetimeProps);
DOREPLIFETIME(UAttributes, m_health);
DOREPLIFETIME(UAttributes, m_maxHealth);
DOREPLIFETIME(UAttributes, m_mana);
DOREPLIFETIME(UAttributes, m_maxMana);
DOREPLIFETIME(UAttributes, m_strength);
DOREPLIFETIME(UAttributes, m_defense);
DOREPLIFETIME(UAttributes, m_agility);
DOREPLIFETIME(UAttributes, m_shield);
}
// Called when the game starts
void UAttributes::BeginPlay()
{
Super::BeginPlay();
// ...
}
// Called every frame
void UAttributes::TickComponent(float DeltaTime, ELevelTick TickType, FActorComponentTickFunction* ThisTickFunction)
{
Super::TickComponent(DeltaTime, TickType, ThisTickFunction);
// ...
}
void UAttributes::setMaxMana(float newValue) USE_NOEXCEPT
{
m_maxMana = newValue;
if(m_maxMana < m_mana)
{
m_mana = m_maxMana;
}
}
void UAttributes::setMaxHealth(float newValue) USE_NOEXCEPT
{
m_maxHealth = newValue;
if(m_maxHealth < m_health)
{
m_health = m_maxHealth;
}
}
void UAttributes::inflictDamageMortal(float damage)
{
if(m_shield > 0)
{
float saveDmg = damage;
damage -= m_shield;
removeShield(saveDmg);
if(damage <= 0)
{
return;
}
}
if(damage < m_health)
{
m_health -= damage;
}
else
{
m_health = 0;
}
PRINT_MESSAGE_ON_SCREEN_UNCHECKED(FColor::Yellow, TEXT("PV = " + FString::FromInt(m_health)));
}
void UAttributes::consumeMana(float manaAmount)
{
if(manaAmount < m_mana)
{
m_mana -= manaAmount;
}
else
{
m_mana = 0;
}
}
void UAttributes::setImmortal(bool isImmortal) USE_NOEXCEPT
{
if(isImmortal)
{
m_inflictDamageDelegate = &UAttributes::immortalMethod;
m_restoreHealthDelegate = &UAttributes::immortalMethod;
m_restoreManaDelegate = &UAttributes::immortalMethod;
}
else
{
m_inflictDamageDelegate = &UAttributes::inflictDamageMortal;
m_restoreHealthDelegate = &UAttributes::restoreHealthMortal;
m_restoreManaDelegate = &UAttributes::restoreManaMortal;
}
}
bool UAttributes::isImmortal() const USE_NOEXCEPT
{
return m_inflictDamageDelegate == &UAttributes::immortalMethod;
}
void UAttributes::removeShield(float amount)
{
if(amount < m_shield)
{
m_shield -= amount;
}
else
{
m_shield = 0;
}
}<file_sep>/Source/RobotRebellion/Gameplay/Weapon/RestoreHealthProjectile.h
// Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "Gameplay/Weapon/Projectile.h"
#include "RestoreHealthProjectile.generated.h"
/**
*
*/
UCLASS(Blueprintable)
class ROBOTREBELLION_API ARestoreHealthProjectile : public AProjectile
{
GENERATED_BODY()
public:
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Projectile Settings")
float m_restoredHealth;
public:
ARestoreHealthProjectile();
// Called when the game starts or when spawned
virtual void BeginPlay() override;
// Called every frame
virtual void Tick(float DeltaSeconds) override;
virtual void inflictDamageLogic(class AActor* OtherActor, const FHitResult& Hit) override;
FORCEINLINE virtual bool isRaycast() const USE_NOEXCEPT
{
return true;
}
};
<file_sep>/Source/RobotRebellion/UI/SessionWidget.h
// Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "Blueprint/UserWidget.h"
#include "SessionWidget.generated.h"
class ULobbyUIWidget;
/**
*
*/
UCLASS()
class ROBOTREBELLION_API USessionWidget : public UUserWidget
{
GENERATED_BODY()
private:
ULobbyUIWidget* m_parentWidget;
UPROPERTY(EditAnywhere, BlueprintReadOnly, Category = SessionWidget, meta = (AllowPrivateAccess = "true"))
int m_index;
public:
void initialiseWidget(int index, ULobbyUIWidget* parent);
void setSelected(bool selected = true);
UFUNCTION(BlueprintCallable, Category = SessionWidget)
void OnClicked();
UFUNCTION(BlueprintCallable, Category = SessionWidget)
int getIndex() const
{
return m_index;
}
};<file_sep>/Source/RobotRebellion/IA/Character/GunTurretCharacter.h
// Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "Character/NonPlayableCharacter.h"
#include "GunTurretCharacter.generated.h"
/**
* Soldier's Gun Turret character, used to initialize weaponInventory as we need
*/
UCLASS()
class ROBOTREBELLION_API AGunTurretCharacter : public ANonPlayableCharacter
{
GENERATED_BODY()
public:
AGunTurretCharacter();
};
<file_sep>/Source/RobotRebellion/UI/TextBillboardComponent.h
// Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "Components/BillboardComponent.h"
#include "ELivingTextAnimMode.h"
#include "TextBillboardComponent.generated.h"
/**
*
*/
UCLASS(Blueprintable)
class ROBOTREBELLION_API UTextBillboardComponent : public UBillboardComponent
{
GENERATED_BODY()
private:
/************************************************************************/
/* UPROPERTY */
/************************************************************************/
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Display", meta = (AllowPrivateAccess = "true"))
TSubclassOf<class ULivingTextRenderComponent> m_defaultRenderText;
/************************************************************************/
/*PROPERTY */
/************************************************************************/
TArray<class ULivingTextRenderComponent*> m_damageRenderedTextArray;
public:
/************************************************************************/
/* METHODS */
/************************************************************************/
UTextBillboardComponent();
virtual void GetLifetimeReplicatedProps(TArray< FLifetimeProperty > & OutLifetimeProps) const override;
/************************************************************************/
/* UFUNCTION */
/************************************************************************/
/*
General method. create and begin displaying a living (animated) text (given by text) at the specified location.
*/
UFUNCTION(BlueprintCallable, Category = "CUSTOM BillBoard Component")
void beginDisplayingText(const FVector& actorPositionInWorld, const FString& text, const FColor& colorToDisplay, ELivingTextAnimMode mode = ELivingTextAnimMode::TEXT_ANIM_MOVING);
/*
Specific method. create and begin displaying a living (animated) text (given by the integerValue) at the specified location.
*/
UFUNCTION(BlueprintCallable, Category = "CUSTOM BillBoard Component")
void beginDisplayingInteger(const FVector& actorPositionInWorld, int32 integerValue, const FColor& colorToDisplay, ELivingTextAnimMode mode = ELivingTextAnimMode::TEXT_ANIM_MOVING);
/*
Main method. Called to refresh all animation and living text. Must be called regularly
*/
UFUNCTION(BlueprintCallable, Category = "CUSTOM BillBoard Component")
void update(float deltaTime);
/*
Clear all texts and remove them
*/
UFUNCTION(BlueprintCallable, Category = "CUSTOM BillBoard Component")
void clearAllLivingTexts();
//Gives the number of living text this billboard currently has to render.
UFUNCTION(BlueprintCallable, Category = "CUSTOM BillBoard Component")
FORCEINLINE int32 livingTextCountToRender() const USE_NOEXCEPT
{
return m_damageRenderedTextArray.Num();
}
//return true if this blackboard is empty (has no living text to display)
UFUNCTION(BlueprintCallable, Category = "CUSTOM BillBoard Component")
FORCEINLINE bool nothingToRender() const USE_NOEXCEPT
{
return livingTextCountToRender() == 0;
}
};
<file_sep>/Source/RobotRebellion/Gameplay/Spell/Effects/Effect.h
// Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "Components/ActorComponent.h"
#include "Effect.generated.h"
/*
* Interface class for all effects
*/
UCLASS(ClassGroup = (Custom), meta = (BlueprintSpawnableComponent))
class ROBOTREBELLION_API UEffect : public UActorComponent
{
GENERATED_BODY()
public:
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = Effect)
float m_zoneRadius;
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = Effect)
float m_duration;
//UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = Effect)
// ANIMATION m_animation;
public:
// Sets default values for this component's properties
UEffect();
// Called when the game starts
virtual void BeginPlay() override;
// Called every frame
virtual void TickComponent(float DeltaTime, ELevelTick TickType, FActorComponentTickFunction* ThisTickFunction) override;
// The behavior of the effect when it's a targeted effect
virtual void exec(class ARobotRebellionCharacter* caster, ARobotRebellionCharacter* target) PURE_VIRTUAL(UEffect::exec, );
// The behavior of the effect when it's point effect
virtual void exec(const FVector& impactPoint, ARobotRebellionCharacter* caster = nullptr) PURE_VIRTUAL(UEffect::exec, );
};
<file_sep>/Source/RobotRebellion/IA/BT/CheckEnnemyNearBTService.cpp
// Fill out your copyright notice in the Description page of Project Settings.
#include "RobotRebellion.h"
#include "CheckEnnemyNearBTService.h"
#include "../Controller/CustomAIControllerBase.h"
#include "../Character/RobotsCharacter.h"
UCheckEnnemyNearBTService::UCheckEnnemyNearBTService() : m_radiusRange{700}
{
NodeName = "CheckEnnemyNear";
// Interval update
Interval = 0.5f;
// Random update deviation for update
RandomDeviation = 0.1f;
}
void UCheckEnnemyNearBTService::TickNode(UBehaviorTreeComponent & OwnerComp, uint8 * NodeMemory, float DeltaSeconds)
{
Super::TickNode(OwnerComp, NodeMemory, DeltaSeconds);
ACustomAIControllerBase* AIController = Cast<ACustomAIControllerBase>(OwnerComp.GetOwner());
if(!AIController->hasALivingTarget())
{
AIController->CheckEnnemyNear(m_radiusRange);
}
else if(AIController->getTarget() && !AIController->getTarget()->isVisible()) //loose Track
{
AIController->setTarget(nullptr);
AIController->StopMovement();
}
}
<file_sep>/Source/RobotRebellion/IA/Controller/RobotShooterController.h
// Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "IA/Controller/EnnemiAIController.h"
#include "RobotShooterController.generated.h"
/**
*
*/
UCLASS()
class ROBOTREBELLION_API ARobotShooterController : public AEnnemiAIController
{
GENERATED_BODY()
private:
FVector m_shootLocation;
public:
// Debug use
float m_detectionRange;
public:
// specifie the distance to the target for the shoot position (percentage of weapon range)
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Shoot location", meta = (ClampMin = 0.f, ClampMax = 1.f))
float m_distanceToShoot;
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Eyes Height")
float m_crouchEyesHeight;
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Eyes Height")
float m_standingEyesHeight;
public:
void CheckEnnemyNear(float range) override;
void AttackTarget() const override;
/** Crouch the animation */
void crouch() const;
// Uncrouch the pawn
void uncrouch() const;
/** return true if the pawn is crouch*/
bool isCrouch() const;
// Update shootposition
void updateShootLocation();
// Same as moveToTartget function but use shootLocation instead of target to follow
EPathFollowingRequestResult::Type moveToShootLocation();
//Draw debug on screen
void drawDebug();
};
<file_sep>/Source/RobotRebellion/Character/Drone.cpp
// Fill out your copyright notice in the Description page of Project Settings.
#include "RobotRebellion.h"
#include "Drone.h"
#include "Gameplay/Weapon/Kaboom.h"
#include "Tool/UtilitaryFunctionLibrary.h"
#include "Components/SplineComponent.h"
ADrone::ADrone() : ANonPlayableCharacter()
{
PrimaryActorTick.bCanEverTick = true;
this->setImmortal(true);
this->GetCapsuleComponent()->BodyInstance.SetCollisionProfileName("Drone");
this->GetCharacterMovement()->GravityScale = 0.f;
m_debugTimer = 0.f;
}
void ADrone::BeginPlay()
{
Super::BeginPlay();
reload();
}
void ADrone::Tick(float deltaTime)
{
Super::Tick(deltaTime);
}
void ADrone::displayScore(float scores[5])
{
if (this->getBillboardComponent())
{
this->displayAnimatedText(FString::Printf(TEXT("Wait :%f \n Follow :%f \n Attack :%f \n Reload :%f \n"),
scores[0], scores[1], scores[2], scores[3]), FColor::Blue, ELivingTextAnimMode::TEXT_ANIM_NOT_MOVING);
}
}
bool ADrone::reload()
{
if (Role < ROLE_Authority)
{
return false;
}
//PRINT_MESSAGE_ON_SCREEN_UNCHECKED(FColor::Silver, "Loading Bomb");
UWorld* world = this->GetWorld();
if(!this->isLoaded() && world)
{
FActorSpawnParameters spawnParams;
spawnParams.Owner = this;
spawnParams.Instigator = this->Instigator;
m_currentBomb = world->SpawnActor<AKaboom>(
m_defaultKaboomBomb,
m_bombAccroch,
{ 0.f, 0.f, 0.f },
spawnParams
);
if(m_currentBomb)
{
m_currentBomb->attachToDrone(this);
//PRINT_MESSAGE_ON_SCREEN_UNCHECKED(FColor::Silver, "LOADED");
return true;
}
}
return false;
}
void ADrone::drop()
{
if (Role < ROLE_Authority)
{
return;
}
if(this->isLoaded())
{
m_currentBomb->activateBomb();
m_currentBomb->detachFromDrone();
//PRINT_MESSAGE_ON_SCREEN_UNCHECKED(FColor::Silver, "DROP");
m_currentBomb = nullptr;
}
}
void ADrone::autoDrop(float deltaTime)
{
m_debugTimer += deltaTime;
if(m_debugTimer > m_debugAutoDropTimer)
{
drop();
m_debugTimer = 0.f;
}
}
float ADrone::getBombBaseDamage() const USE_NOEXCEPT
{
return m_currentBomb->m_baseDamage;
}
float ADrone::getBombRadius() const USE_NOEXCEPT
{
return m_currentBomb->m_detonationRadius;
}
<file_sep>/Source/RobotRebellion/Character/Assassin.cpp
// Fill out your copyright notice in the Description page of Project Settings.
#include "RobotRebellion.h"
#include "Assassin.h"
AAssassin::AAssassin() :APlayableCharacter()
{}
//void AAssassin::BeginPlay()
//{
// Super::BeginPlay();
//}
<file_sep>/Source/RobotRebellion/Character/RobotRebellionCharacter.cpp
// Copyright 1998-2016 Epic Games, Inc. All Rights Reserved.
#include "RobotRebellion.h"
#include "RobotRebellionCharacter.h"
#include "PlayableCharacter.h"
#include "Gameplay/Weapon/WeaponBase.h"
#include "Gameplay/Weapon/WeaponInventory.h"
#include "Gameplay/Alteration/StunAlteration.h"
#include "Gameplay/Alteration/InvisibilityAlteration.h"
#include "Gameplay/Alteration/ShieldAlteration.h"
#include "UI/TextBillboardComponent.h"
#include "UI/LivingTextRenderComponent.h"
#include "Tool/UtilitaryMacros.h"
#include "Tool/UtilitaryFunctionLibrary.h"
#include "Global/GameInstaller.h"
#include "Kismet/HeadMountedDisplayFunctionLibrary.h"
#include "Global/WorldInstanceEntity.h"
#include "WidgetComponent.h"
#include "UI/LifeBarWidget.h"
#include "Global/EntityDataSingleton.h"
ARobotRebellionCharacter::ARobotRebellionCharacter()
{
PrimaryActorTick.bCanEverTick = true;
// Set size for collision capsule
GetCapsuleComponent()->InitCapsuleSize(42.f, 96.0f);
m_attribute = CreateDefaultSubobject<UAttributes>(TEXT("Attributes"));
m_alterationController = CreateDefaultSubobject<UAlterationController>(TEXT("AlterationController"));
m_isInCombat = false;
m_isShieldAnimated = true;
}
void ARobotRebellionCharacter::BeginPlay()
{
Super::BeginPlay();
this->m_timedDestroyDelegate = &ARobotRebellionCharacter::noDestroyForNow;
this->m_disableBeforeDestroyDelegate = &ARobotRebellionCharacter::disablingEverything;
m_isRestoreManaParticleSpawned = false;
m_isReviveParticleSpawned = false;
m_isShieldParticleSpawned = false;
m_tickCount = 0.f;
m_burningBonesCount = 0;
TArray<AActor*> entity;
UGameplayStatics::GetAllActorsOfClass(GetWorld(), AWorldInstanceEntity::StaticClass(), entity);
if(entity.Num() > 0)
{
m_worldEntity = Cast<AWorldInstanceEntity>(entity[0]);
}
m_bonesToUpdate = 0;
m_bonesSet = 5;
int32 bonesCount = GetMesh()->GetNumBones();
m_burningBones.Reserve(bonesCount);
m_fireEffects.Reserve(bonesCount);
m_effectTimer.Reserve(bonesCount);
m_decelerationCoeff = m_accelerationCoeff / 2.f;
m_maxVelocity = m_maxWalkVelocity;
m_healthBar = Cast<UWidgetComponent>(GetComponentByClass(UWidgetComponent::StaticClass()));
if(m_healthBar)
{
ULifeBarWidget* widget = Cast<ULifeBarWidget>(m_healthBar->GetUserWidgetObject());
if(widget)
{
widget->setOwner(this);
}
}
m_location = ELocation::OUTSIDE;
}
void ARobotRebellionCharacter::Tick(float deltaTime)
{
Super::Tick(deltaTime);
if(m_textBillboardInstance)
{
m_textBillboardInstance->update(deltaTime);
}
else
{
this->createTextBillboard();
}
(this->*m_timedDestroyDelegate)(deltaTime);
if(m_isRestoreManaParticleSpawned)
{
m_restoreManaEffectTimer += deltaTime;
if(m_restoreManaEffectTimer >= m_restoreManaEffectDuration)
{
unspawnManaParticle();
}
}
if(m_isReviveParticleSpawned)
{
m_reviveEffectTimer += deltaTime;
if(m_reviveEffectTimer >= m_reviveEffectDuration)
{
unspawnReviveParticle();
}
}
if(m_healthBar)
{
//Orient lifeBar for player camera
APlayableCharacter* charac = Cast<APlayableCharacter>(GetWorld()->GetFirstPlayerController()->GetPawn());
if(charac)
{
UCameraComponent* camera = charac->GetFollowCamera();
FRotator camRot = camera->GetComponentRotation();
m_healthBar->SetWorldRotation(FRotator(-camRot.Pitch, camRot.Yaw + 180.f, camRot.Roll));
m_healthBar->SetRelativeLocation(FVector(0.f, 0.f, charac->GetCapsuleComponent()->GetScaledCapsuleHalfHeight() + 50.f));
}
}
if(this->isBurning())
{
m_tickCount += deltaTime;
if(m_tickCount >= 1.33f)
{
//GEngine->AddOnScreenDebugMessage(0 + 1, 10, FColor::Blue, FString::Printf(TEXT("size: %i"), m_burningBones.Num()));
UpdateBurnEffect(m_tickCount);
m_tickCount = 0.f;
}
}
}
void ARobotRebellionCharacter::disablingEverything()
{
this->bHidden = true;
if(Controller)
{
Controller->UnPossess();
}
this->SetActorEnableCollision(false);
this->UnregisterAllComponents();
GetCapsuleComponent()->DestroyComponent();
this->m_disableBeforeDestroyDelegate = &ARobotRebellionCharacter::endDisabling;
}
void ARobotRebellionCharacter::startTimedDestroy() USE_NOEXCEPT
{
this->m_timedDestroyDelegate = &ARobotRebellionCharacter::destroyNow;
}
void ARobotRebellionCharacter::destroyNow(float deltaTime)
{
(this->*m_disableBeforeDestroyDelegate)();
//All conditions are met for destroying
//To add a condition for destroying, add it to this if.
//The destruction will occur when all conditions will be met
if(m_textBillboardInstance->nothingToRender())
{
//We have made everything important before destroying. Now we can destroy safely.
this->m_timedDestroyDelegate = &ARobotRebellionCharacter::noDestroyForNow;
if(Role >= ROLE_Authority)
{
netMultiKill();
}
else if(!this->IsPendingKillOrUnreachable())
{
this->Destroy();
}
}
}
void ARobotRebellionCharacter::netMultiKill_Implementation()
{
if(!this->IsPendingKillOrUnreachable())
{
this->ConditionalBeginDestroy();
}
}
bool ARobotRebellionCharacter::netMultiKill_Validate()
{
return true;
}
///// SERVER
void ARobotRebellionCharacter::GetLifetimeReplicatedProps(TArray< FLifetimeProperty > & OutLifetimeProps) const
{
Super::GetLifetimeReplicatedProps(OutLifetimeProps);
DOREPLIFETIME(ARobotRebellionCharacter, m_attribute);
DOREPLIFETIME(ARobotRebellionCharacter, m_isInCombat);
//DOREPLIFETIME(ARobotRebellionCharacter, m_burningBonesCount);
}
bool ARobotRebellionCharacter::hasDoubleWeapon() const USE_NOEXCEPT
{
return m_weaponInventory->m_hasDoubleWeapon;
}
UWeaponBase* ARobotRebellionCharacter::getCurrentEquippedWeapon() const USE_NOEXCEPT
{
return m_weaponInventory->getCurrentWeapon();
}
const UWeaponBase* ARobotRebellionCharacter::getMainWeapon() const USE_NOEXCEPT
{
return m_weaponInventory->getMainWeapon();
}
const UWeaponBase* ARobotRebellionCharacter::getSecondaryWeapon() const USE_NOEXCEPT
{
return m_weaponInventory->getSecondaryWeapon();
}
void ARobotRebellionCharacter::cppOnDeath()
{}
void ARobotRebellionCharacter::onDeath()
{
if(Role == ROLE_Authority)
{
clientOnDeath();
//return;
}
this->cppOnDeath();
}
void ARobotRebellionCharacter::clientOnDeath_Implementation()
{
this->cppOnDeath();
}
bool ARobotRebellionCharacter::clientOnDeath_Validate()
{
return true;
}
void ARobotRebellionCharacter::cppOnRevive()
{}
void ARobotRebellionCharacter::displayAnimatedIntegerValue(int32 valueToDisplay, const FColor& color, ELivingTextAnimMode mode)
{
m_textBillboardInstance->beginDisplayingInteger(this->GetActorLocation(), valueToDisplay, color, mode);
if(Role >= ROLE_Authority)
{
netMultidisplayAnimatedIntegerValue(valueToDisplay, color, mode);
}
}
void ARobotRebellionCharacter::displayAnimatedText(const FString& textToDisplay, const FColor& color, ELivingTextAnimMode mode)
{
m_textBillboardInstance->beginDisplayingText(this->GetActorLocation(), textToDisplay, color, mode);
if(Role >= ROLE_Authority)
{
netMultidisplayAnimatedText(textToDisplay, color, mode);
}
}
void ARobotRebellionCharacter::netMultidisplayAnimatedIntegerValue_Implementation(int32 valueToDisplay, const FColor& color, ELivingTextAnimMode mode)
{
if(m_textBillboardInstance)
{
m_textBillboardInstance->beginDisplayingInteger(this->GetActorLocation(), valueToDisplay, color, mode);
}
}
void ARobotRebellionCharacter::netMultidisplayAnimatedText_Implementation(const FString& textToDisplay, const FColor& color, ELivingTextAnimMode mode)
{
if(m_textBillboardInstance)
{
m_textBillboardInstance->beginDisplayingText(this->GetActorLocation(), textToDisplay, color, mode);
}
}
bool ARobotRebellionCharacter::netMultidisplayAnimatedIntegerValue_Validate(int32 valueToDisplay, const FColor& color, ELivingTextAnimMode mode)
{
return true;
}
bool ARobotRebellionCharacter::netMultidisplayAnimatedText_Validate(const FString& textToDisplay, const FColor& color, ELivingTextAnimMode mode)
{
return true;
}
void ARobotRebellionCharacter::createTextBillboard()
{
APlayableCharacter* charac = Cast<APlayableCharacter>(GetWorld()->GetFirstPlayerController()->GetPawn());
if(charac)
{
this->createTextBillboardWithThisCamera(charac->FollowCamera);
}
}
void ARobotRebellionCharacter::createTextBillboardWithThisCamera(UCameraComponent* camera)
{
if(UUtilitaryFunctionLibrary::createObjectFromDefault<UTextBillboardComponent>(&m_textBillboardInstance, m_textBillboardDefault, camera, RF_Dynamic))
{
setBillboardInstanceNewCamera(camera);
m_textBillboardInstance->Activate();
m_textBillboardInstance->RegisterComponent();
}
}
void ARobotRebellionCharacter::setBillboardInstanceNewCamera(UCameraComponent* camera)
{
if(NULL != m_textBillboardInstance)
{
m_textBillboardInstance->AttachToComponent(camera, FAttachmentTransformRules::KeepRelativeTransform);
m_textBillboardInstance->SetRelativeTransform({});
camera->UpdateChildTransforms();
}
}
void ARobotRebellionCharacter::inflictStun()
{
if(Role >= ROLE_Authority && !this->isImmortal())
{
this->internalInflictAlteration<UStunAlteration>(
[](UStunAlteration* stunAlteration) {});
}
}
void ARobotRebellionCharacter::inflictStun(float duration)
{
if(Role >= ROLE_Authority && !this->isImmortal())
{
this->internalInflictAlteration<UStunAlteration>(
[duration](UStunAlteration* stunAlteration) {
stunAlteration->m_lifeTime = duration;
});
}
}
void ARobotRebellionCharacter::inflictInvisibility()
{
if(Role >= ROLE_Authority)
{
this->internalInflictAlteration<UInvisibilityAlteration>([](UInvisibilityAlteration* invisibleAlteration) {});
}
}
void ARobotRebellionCharacter::addShield(float amount, float duration)
{
if(Role >= ROLE_Authority)
{
this->internalInflictAlteration<UShieldAlteration>(
[amount, duration](UShieldAlteration* shieldAlteration) {
shieldAlteration->m_lifeTime = duration;
shieldAlteration->m_amount = amount;
});
}
}
void ARobotRebellionCharacter::setInvisible(bool isInvisible)
{
updateInvisibilityMat(isInvisible);
m_isInvisible = isInvisible;
if(Role >= ROLE_Authority)
{
multiSetInvisible(isInvisible);
}
}
void ARobotRebellionCharacter::updateInvisibilityMat_Implementation(bool isVisible)
{
// does nothing
}
bool ARobotRebellionCharacter::isVisible() const
{
return this->m_alterationController->findByID(IdentifiableObject<UInvisibilityAlteration>::ID.m_value) == nullptr;
}
void ARobotRebellionCharacter::inflictDamage(float damage, ELivingTextAnimMode animType, const FColor& damageColor)
{
m_attribute->inflictDamage(damage);
displayAnimatedIntegerValue(damage, damageColor, animType);
if(isDead())
{
onDeath();
}
}
void ARobotRebellionCharacter::restoreHealth(float value, ELivingTextAnimMode animType)
{
m_attribute->restoreHealth(value);
displayAnimatedIntegerValue(value, FColor::Green, animType);
}
void ARobotRebellionCharacter::restoreMana(float value, ELivingTextAnimMode animType)
{
m_attribute->restoreMana(value);
displayAnimatedIntegerValue(value, FColor::Blue, animType);
}
////RESTORE MANA EFFECT
void ARobotRebellionCharacter::spawnManaParticle()
{
if(!m_restoreManaParticleSystem)
{
m_restoreManaParticleSystem = UGameplayStatics::SpawnEmitterAttached(m_restoreManaParticuleEffect, RootComponent, NAME_None,
GetActorLocation() - FVector(0, 0, GetCapsuleComponent()->GetScaledCapsuleHalfHeight()),
GetActorRotation(), EAttachLocation::KeepWorldPosition, false);
}
m_restoreManaParticleSystem->ActivateSystem(true);
m_isRestoreManaParticleSpawned = true;
if(Role >= ROLE_Authority)
{
multiSpawnManaParticle();
}
}
void ARobotRebellionCharacter::unspawnManaParticle()
{
m_restoreManaParticleSystem->DeactivateSystem();
m_isRestoreManaParticleSpawned = false;
if(Role >= ROLE_Authority)
{
m_restoreManaEffectTimer = 0.f;
multiUnspawnManaParticle();
}
}
void ARobotRebellionCharacter::multiSpawnManaParticle_Implementation()
{
if(!m_restoreManaParticleSystem)
{
m_restoreManaParticleSystem = UGameplayStatics::SpawnEmitterAttached(m_restoreManaParticuleEffect, RootComponent, NAME_None,
GetActorLocation() - FVector(0, 0, GetCapsuleComponent()->GetScaledCapsuleHalfHeight()),
GetActorRotation(), EAttachLocation::KeepWorldPosition, false);
}
m_restoreManaParticleSystem->ActivateSystem(true);
m_isRestoreManaParticleSpawned = true;
}
bool ARobotRebellionCharacter::multiSpawnManaParticle_Validate()
{
return true;
}
void ARobotRebellionCharacter::multiUnspawnManaParticle_Implementation()
{
m_restoreManaParticleSystem->DeactivateSystem();
m_isRestoreManaParticleSpawned = false;
m_restoreManaEffectTimer = 0.f;
}
bool ARobotRebellionCharacter::multiUnspawnManaParticle_Validate()
{
return true;
}
////REVIVE EFFECT
void ARobotRebellionCharacter::spawnReviveParticle()
{
if(!m_reviveParticleSystem)
{
m_reviveParticleSystem = UGameplayStatics::SpawnEmitterAttached(m_reviveParticuleEffect, RootComponent, NAME_None,
GetActorLocation() - FVector(0, 0, GetCapsuleComponent()->GetScaledCapsuleHalfHeight()),
GetActorRotation(), EAttachLocation::KeepWorldPosition, false);
}
m_reviveParticleSystem->ActivateSystem(true);
m_isReviveParticleSpawned = true;
if(Role >= ROLE_Authority)
{
multiSpawnReviveParticle();
}
}
void ARobotRebellionCharacter::unspawnReviveParticle()
{
m_reviveParticleSystem->DeactivateSystem();
m_isReviveParticleSpawned = false;
if(Role >= ROLE_Authority)
{
m_reviveEffectTimer = 0.f;
multiUnspawnReviveParticle();
}
}
void ARobotRebellionCharacter::multiSpawnReviveParticle_Implementation()
{
if(!m_reviveParticleSystem)
{
m_reviveParticleSystem = UGameplayStatics::SpawnEmitterAttached(m_reviveParticuleEffect, RootComponent, NAME_None,
GetActorLocation() - FVector(0, 0, GetCapsuleComponent()->GetScaledCapsuleHalfHeight()),
GetActorRotation(), EAttachLocation::KeepWorldPosition, false);
}
m_reviveParticleSystem->ActivateSystem(true);
m_isReviveParticleSpawned = true;
}
bool ARobotRebellionCharacter::multiSpawnReviveParticle_Validate()
{
return true;
}
void ARobotRebellionCharacter::multiUnspawnReviveParticle_Implementation()
{
m_reviveParticleSystem->DeactivateSystem();
m_isReviveParticleSpawned = false;
m_reviveEffectTimer = 0.f;
}
bool ARobotRebellionCharacter::multiUnspawnReviveParticle_Validate()
{
return true;
}
GENERATE_IMPLEMENTATION_METHOD_AND_DEFAULT_VALIDATION_METHOD(ARobotRebellionCharacter, multiSetInvisible, bool isInvisible)
{
updateInvisibilityMat(isInvisible);
m_isInvisible = isInvisible;
}
UTextBillboardComponent* ARobotRebellionCharacter::getBillboardComponent()
{
return m_textBillboardInstance;
}
////SHIELD EFFECT
void ARobotRebellionCharacter::spawnShieldParticle()
{
if(!m_isShieldParticleSpawned)
{
if(m_isShieldAnimated)
{
m_shieldParticleSystem =
UGameplayStatics::SpawnEmitterAttached(m_shieldParticuleEffect, RootComponent, NAME_None,
GetActorLocation() - FVector(0, 0, GetCapsuleComponent()->GetScaledCapsuleHalfHeight()),
GetActorRotation(), EAttachLocation::KeepWorldPosition, false);
}
else
{
m_shieldParticleSystem =
UGameplayStatics::SpawnEmitterAttached(m_shieldParticuleEffectUnanimated, RootComponent, NAME_None,
GetActorLocation() - FVector(0, 0, GetCapsuleComponent()->GetScaledCapsuleHalfHeight()),
GetActorRotation(), EAttachLocation::KeepWorldPosition, false);
}
}
// Test if shield animation has changed in option
if(m_isShieldAnimated != m_worldEntity->isShieldAnimated())
{
// Destroye old particle emitter and build a new one
m_shieldParticleSystem->DestroyComponent();
m_isShieldAnimated = m_worldEntity->isShieldAnimated();
if(m_isShieldAnimated)
{
m_shieldParticleSystem =
UGameplayStatics::SpawnEmitterAttached(m_shieldParticuleEffect, RootComponent, NAME_None,
GetActorLocation() - FVector(0, 0, GetCapsuleComponent()->GetScaledCapsuleHalfHeight()),
GetActorRotation(), EAttachLocation::KeepWorldPosition, false);
}
else
{
m_shieldParticleSystem =
UGameplayStatics::SpawnEmitterAttached(m_shieldParticuleEffectUnanimated, RootComponent, NAME_None,
GetActorLocation() - FVector(0, 0, GetCapsuleComponent()->GetScaledCapsuleHalfHeight()),
GetActorRotation(), EAttachLocation::KeepWorldPosition, false);
}
}
m_shieldParticleSystem->ActivateSystem(true);
m_isShieldParticleSpawned = true;
if(Role >= ROLE_Authority)
{
multiSpawnShieldParticle();
}
}
void ARobotRebellionCharacter::unspawnShieldParticle()
{
m_shieldParticleSystem->DeactivateSystem();
m_isShieldParticleSpawned = false;
if(Role >= ROLE_Authority)
{
multiUnspawnShieldParticle();
}
}
void ARobotRebellionCharacter::multiSpawnShieldParticle_Implementation()
{
if(!m_isShieldParticleSpawned)
{
if(m_isShieldAnimated)
{
m_shieldParticleSystem =
UGameplayStatics::SpawnEmitterAttached(m_shieldParticuleEffect, RootComponent, NAME_None,
GetActorLocation() - FVector(0, 0, GetCapsuleComponent()->GetScaledCapsuleHalfHeight()),
GetActorRotation(), EAttachLocation::KeepWorldPosition, false);
}
else
{
m_shieldParticleSystem =
UGameplayStatics::SpawnEmitterAttached(m_shieldParticuleEffectUnanimated, RootComponent, NAME_None,
GetActorLocation() - FVector(0, 0, GetCapsuleComponent()->GetScaledCapsuleHalfHeight()),
GetActorRotation(), EAttachLocation::KeepWorldPosition, false);
}
}
// Test if shield animation has changed in option
if( m_isShieldAnimated != m_worldEntity->isShieldAnimated())
{
// Destroye old particle emitter and build a new one
m_shieldParticleSystem->DestroyComponent();
m_isShieldAnimated = m_worldEntity->isShieldAnimated();
if(m_isShieldAnimated)
{
m_shieldParticleSystem =
UGameplayStatics::SpawnEmitterAttached(m_shieldParticuleEffect, RootComponent, NAME_None,
GetActorLocation() - FVector(0, 0, GetCapsuleComponent()->GetScaledCapsuleHalfHeight()),
GetActorRotation(), EAttachLocation::KeepWorldPosition, false);
}
else
{
m_shieldParticleSystem =
UGameplayStatics::SpawnEmitterAttached(m_shieldParticuleEffectUnanimated, RootComponent, NAME_None,
GetActorLocation() - FVector(0, 0, GetCapsuleComponent()->GetScaledCapsuleHalfHeight()),
GetActorRotation(), EAttachLocation::KeepWorldPosition, false);
}
}
m_shieldParticleSystem->ActivateSystem(true);
m_isShieldParticleSpawned = true;
}
bool ARobotRebellionCharacter::multiSpawnShieldParticle_Validate()
{
return true;
}
void ARobotRebellionCharacter::multiUnspawnShieldParticle_Implementation()
{
m_shieldParticleSystem->DeactivateSystem();
m_isShieldParticleSpawned = false;
}
bool ARobotRebellionCharacter::multiUnspawnShieldParticle_Validate()
{
return true;
}
////Burn Effect
void ARobotRebellionCharacter::UpdateBurnEffect(float DeltaTime)
{
int burningBonesNumber = m_burningBones.Num();
int nbBones = GetMesh()->GetNumBones();
TArray<FName> bonesToBurn;
for(int noCurrentBone = 0; noCurrentBone < burningBonesNumber; ++noCurrentBone)
{
int32 currentBoneId = m_burningBones[noCurrentBone];
FName currentBoneName = GetMesh()->GetBoneName(currentBoneId);
//compute if effect must be deactivated on this bone
m_effectTimer[m_fireEffects[noCurrentBone]] += DeltaTime;
if(m_effectTimer[m_fireEffects[noCurrentBone]] >= 3.f && (m_fireEffects[noCurrentBone])->IsActive())
{
//m_fireEffects[noCurrentBone]->DestroyComponent();
m_fireEffects[noCurrentBone]->Deactivate();
--m_burningBonesCount;
//GEngine->AddOnScreenDebugMessage(1, 10, FColor::Blue, FString::Printf(TEXT("number %i"), m_burningBonesCount));
m_effectTimer[m_fireEffects[noCurrentBone]] = 0.f;
continue;
}
// PARENT Bone
FName parentName = GetMesh()->GetParentBone(currentBoneName);
int32 parentid = GetMesh()->GetBoneIndex(parentName);
int32 intIsPresent = m_burningBones.Find(parentid);
if(intIsPresent == -1)
{
bonesToBurn.Emplace(parentName);
continue;
//CHILDRENBONE
// Not very good performances, no other ways found (dont update every bone each time for better performances)
for(int i = currentBoneId + 1 + m_bonesToUpdate; i < nbBones; i += m_bonesSet)
{
m_bonesToUpdate = (m_bonesToUpdate + 1) % m_bonesSet;
int32 isChildPresent = m_burningBones.Find(i); //Check if children already on fire
FName boneName = GetMesh()->GetBoneName(i);
if(GetMesh()->BoneIsChildOf(boneName, currentBoneName) && isChildPresent == -1)
{
bonesToBurn.Emplace(boneName);
}
}
}
}
displayFireOnBoneArray(bonesToBurn);
if(m_burningBonesCount <= 0)
{
cleanFireComp();
}
}
void ARobotRebellionCharacter::displayFireOnBone(const FName& bone)
{
internalDisplayFireOnBone(bone);
if(Role >= ROLE_Authority)
{
multiDisplayFireOnBone(bone);
}
}
void ARobotRebellionCharacter::multiDisplayFireOnBone_Implementation(const FName& bone)
{
if(m_worldEntity->IsBurnEffectEnabled())
{
internalDisplayFireOnBone(bone);
}
}
void ARobotRebellionCharacter::internalDisplayFireOnBone(const FName& bone)
{
FVector boneLocation = GetMesh()->GetBoneLocation(bone);
FTransform boneTransform = GetMesh()->GetBoneTransform(GetMesh()->GetBoneIndex(bone));
UParticleSystemComponent* fireEffect = UGameplayStatics::SpawnEmitterAttached(m_fireEffect, GetRootComponent(),
NAME_None, boneLocation,
FRotator::ZeroRotator, EAttachLocation::KeepWorldPosition, false);
if(fireEffect)
{
fireEffect->SetRelativeScale3D(FVector(0.4f, 0.4f, 0.4f));
m_burningBones.Emplace(GetMesh()->GetBoneIndex(bone));
m_fireEffects.Emplace(fireEffect);
m_effectTimer.Emplace(fireEffect, 0.f);
++m_burningBonesCount;
}
}
void ARobotRebellionCharacter::displayFireOnBoneArray(const TArray<FName>& bones)
{
internalDisplayFireOnBoneArray(bones);
if(Role >= ROLE_Authority)
{
multiDisplayFireOnBoneArray(bones);
}
}
void ARobotRebellionCharacter::internalDisplayFireOnBoneArray(const TArray<FName>& bones)
{
int size = bones.Num();
int max = (size >= 5 ? 5 : size); // limit size for performance
for(int i = 0; i < max; ++i)
{
FName bone = bones[i];
int32 boneLocationIndex = GetMesh()->GetBoneIndex(bone);
FVector boneLocation = GetMesh()->GetBoneLocation(bone);
UParticleSystemComponent* fireEffect = UGameplayStatics::SpawnEmitterAttached(m_fireEffect, GetRootComponent(),
NAME_None, boneLocation,
FRotator::ZeroRotator, EAttachLocation::KeepWorldPosition, false);
if(fireEffect)
{
fireEffect->SetRelativeScale3D({0.4f, 0.4f, 0.4f});
m_burningBones.Emplace(boneLocationIndex);
m_fireEffects.Emplace(fireEffect);
m_effectTimer.Emplace(fireEffect, 0.f);
++m_burningBonesCount;
}
}
}
void ARobotRebellionCharacter::multiDisplayFireOnBoneArray_Implementation(const TArray<FName>& bones)
{
if(m_worldEntity->IsBurnEffectEnabled())
{
internalDisplayFireOnBoneArray(bones);
}
}
void ARobotRebellionCharacter::internalSpawnFireEffect(FVector location)
{
if(m_worldEntity->IsBurnEffectEnabled())
{
FName bone = GetMesh()->FindClosestBone(location);
int32 boneIndex = GetMesh()->GetBoneIndex(bone);
int32 intIsPresent = (m_burningBones.Find(boneIndex));
if(intIsPresent == -1)
{
displayFireOnBone(bone);
}
}
}
void ARobotRebellionCharacter::spawnFireEffect(FVector location)
{
if(!isBurning())
{
internalSpawnFireEffect(location);
if(Role >= ROLE_Authority)
{
multiSpawnFireEffect(location);
}
}
}
void ARobotRebellionCharacter::multiSpawnFireEffect_Implementation(FVector location)
{
internalSpawnFireEffect(location);
}
void ARobotRebellionCharacter::internalCleanFireComp()
{
m_burningBones.Reset();
m_fireEffects.Reset();
m_effectTimer.Reset();
m_burningBonesCount = 0;
}
void ARobotRebellionCharacter::cleanFireComp()
{
internalCleanFireComp();
if(Role >= ROLE_Authority)
{
multiCleanFireComp();
}
else
{
serverCleanFireComp();
}
}
void ARobotRebellionCharacter::multiCleanFireComp_Implementation()
{
internalCleanFireComp();
}
void ARobotRebellionCharacter::serverCleanFireComp_Implementation()
{
cleanFireComp();
}
bool ARobotRebellionCharacter::serverCleanFireComp_Validate()
{
return true;
}<file_sep>/Source/RobotRebellion/Gameplay/Spell/DamageZone.cpp
// Fill out your copyright notice in the Description page of Project Settings.
#include "RobotRebellion.h"
#include "DamageZone.h"
#include "Character/RobotRebellionCharacter.h"
// Sets default values
ADamageZone::ADamageZone() : AActor()
{
// Set this actor to call Tick() every frame. You can turn this off to improve performance if you don't need it.
PrimaryActorTick.bCanEverTick = true;
}
// Called when the game starts or when spawned
void ADamageZone::BeginPlay()
{
Super::BeginPlay();
m_secondBetweenTick = 1.f / m_tickRate;
PRINT_MESSAGE_ON_SCREEN_UNCHECKED(FColor::Blue, "spawn molotov zone - tick" + FString::SanitizeFloat(m_secondBetweenTick));
m_burnedActors = 0;
}
// Called every frame
void ADamageZone::Tick(float DeltaTime)
{
Super::Tick(DeltaTime);
if(m_deltaSinceLastTick + DeltaTime > m_secondBetweenTick)// time to deal damage
{
m_deltaSinceLastTick = 0;// Reset delta
// proceed sphere cast
FVector MultiSphereStart = GetActorLocation();
TArray<AActor*> ActorsToIgnore;
ActorsToIgnore.Add(this);
TArray<FHitResult> hitActors;
bool Result = UKismetSystemLibrary::SphereTraceMultiForObjects(GetWorld(),
MultiSphereStart,
MultiSphereStart,
m_radius,
m_objectTypes,
false,
ActorsToIgnore,
SPHERECAST_DISPLAY_DURATION,
hitActors,
true);
// GEngine->AddOnScreenDebugMessage(-1, 2, FColor::Blue, "Tick after : "
// + FString::SanitizeFloat(m_deltaSinceLastTick)
// + " hit : " + FString::FromInt(hitActors.Num()));
// hitActors now countains all actor that should get damage
for(FHitResult& currentHit : hitActors)
{
ARobotRebellionCharacter* temp = Cast<ARobotRebellionCharacter>(currentHit.GetActor());
if(temp)
{
// this is brut damage
// TODO - use Damage class and more complexe damage calcul
if(m_isMolotov && m_burnedActors<=5)
{
++m_burnedActors;
FVector tempLocation = currentHit.Location;
tempLocation.Z = 0;
temp->spawnFireEffect(tempLocation);
}
temp->inflictDamage(m_damagePerTick);
}
}
}
else
{
m_deltaSinceLastTick += DeltaTime;
}
}
<file_sep>/Source/RobotRebellion/Gameplay/Alteration/StunAlteration.h
// Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "AlterationBase.h"
#include "../../Tool/IdentifiableObj.h"
#include "StunAlteration.generated.h"
/**
*
*/
UCLASS(Blueprintable)
class ROBOTREBELLION_API UStunAlteration : public UAlterationBase
{
GENERATED_BODY()
public:
bool m_isNPC;
class AController* m_alteredActorController;
public:
UStunAlteration();
void destroyItself() override;
void onCreate(class ARobotRebellionCharacter* alteredOwner) override;
virtual FString toDebugString() const USE_NOEXCEPT
{
return "Stun";
}
};
<file_sep>/Source/RobotRebellion/Gameplay/Weapon/LongRangeWeapon.h
// Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "WeaponBase.h"
#include "Sound/SoundCue.h"
#include "Components/AudioComponent.h"
#include "LongRangeWeapon.generated.h"
/**
*
*/
UCLASS()
class ROBOTREBELLION_API ULongRangeWeapon : public UWeaponBase
{
GENERATED_BODY()
public:
/************************************************************************/
/* CONSTANT */
/************************************************************************/
static constexpr const float LIFT_OFFSET = 10.f;
/************************************************************************/
/* UPROPERTY */
/************************************************************************/
/** Projectile class */
UPROPERTY(EditDefaultsOnly, Category = Projectile)
TSubclassOf<class AProjectile> m_projectileClass;
//Projectile position Offset
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = Gameplay)
FVector m_muzzleOffset;
// Weapon Fire Sound
UPROPERTY(EditDefaultsOnly, BlueprintReadWrite, Category = "Sounds")
USoundCue* m_longRangeWeaponOutsideFireSound;
UPROPERTY(EditDefaultsOnly, BlueprintReadWrite, Category = "Sounds")
USoundCue* m_longRangeWeaponBigRoomFireSound;
UPROPERTY(EditDefaultsOnly, BlueprintReadWrite, Category = "Sounds")
USoundCue* m_longRangeWeaponSmallRoomFireSound;
UPROPERTY(EditDefaultsOnly, BlueprintReadWrite, Category = "Sounds")
USoundCue* m_longRangeWeaponCorridorFireSound;
/************************************************************************/
/* PROPERTY */
/************************************************************************/
/************************************************************************/
/* UFUNCTION */
/************************************************************************/
UFUNCTION(BlueprintCallable, Category = "General")
virtual EWeaponRange getWeaponRange() const USE_NOEXCEPT override
{
return EWeaponRange::LONG_RANGE_WEAPON;
}
UFUNCTION(NetMulticast, Reliable)
virtual void playSound(USoundCue* sound, AActor* originator) override;
/************************************************************************/
/* METHODS */
/************************************************************************/
ULongRangeWeapon();
virtual void cppAttack(class ARobotRebellionCharacter* user) override;
virtual void cppAttack(ARobotRebellionCharacter* instigator, ARobotRebellionCharacter* ennemy) override;
virtual FString rangeToFString() const USE_NOEXCEPT;
void fireMethod(class AProjectile* projectile, const FVector& fireDirection);
};
<file_sep>/Source/RobotRebellion/Gameplay/Alteration/AlterationController.h
// Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "Components/ActorComponent.h"
#include "AlterationController.generated.h"
UCLASS(Blueprintable, ClassGroup=(Custom), meta=(BlueprintSpawnableComponent) )
class ROBOTREBELLION_API UAlterationController : public UActorComponent
{
GENERATED_BODY()
private:
/************************************************************************/
/* PROPERTY */
/************************************************************************/
UPROPERTY()
TArray<class UAlterationBase*> m_alterationsArray;
void (UAlterationController::* m_updateMethod)(float);
public:
/************************************************************************/
/* METHODS */
/************************************************************************/
// Sets default values for this component's properties
UAlterationController();
// Called when the game starts
virtual void BeginPlay() override;
// Called every frame
virtual void TickComponent( float DeltaTime, ELevelTick TickType, FActorComponentTickFunction* ThisTickFunction ) override;
class UAlterationBase* findByID(int32 id) const;
private:
void doesNothing(float) {}
void update(float deltaTime);
void internalRemoveAllAlteration();
public:
/************************************************************************/
/* UFUNCTION */
/************************************************************************/
UFUNCTION(BlueprintCallable, Category = "Alteration")
void removeAllAlteration();
UFUNCTION(Reliable, Server, WithValidation)
void serverRemoveAllAlteration();
UFUNCTION(BlueprintCallable, Category = "Alteration")
void addAlteration(class UAlterationBase* newAlteration);
UFUNCTION(Reliable, Server, WithValidation)
void serverAddAlteration(class UAlterationBase* newAlteration);
GENERATE_PROTOTYPE_SERVER_CLIENT_METHODS_BASED_VALIDATION_SERVER(m_inflictMethod, UAlterationController, addAlteration, class UAlterationBase*);
};
<file_sep>/Source/RobotRebellion/Tool/UtilitaryMacros.h
// Fill out your copyright notice in the Description page of Project Settings.
#pragma once
//#define ENABLE_PRINT_ON_SCREEN
//#define ENABLE_SPELL_DISPLAY_SHERECAST
//#define ENABLE_DRAW_DEBUG_LINE
//#define ENABLE_DRONE_DEBUG_DISPLAY
#if defined(UE_BUILD_DEBUG) || defined(UE_BUILD_TEST)
#define WE_RE_ON_DEBUG
#endif //UE_BUILD_DEBUG
#ifdef ENABLE_PRINT_ON_SCREEN /*&& defined(WE_RE_ON_DEBUG)*/
#define PRINT_MESSAGE_ON_SCREEN_UNCHECKED(color, message) GEngine->AddOnScreenDebugMessage(-1, 5.0f, color, message)
#define PRINT_MESSAGE_ON_SCREEN(color, message) if(GEngine) { PRINT_MESSAGE_ON_SCREEN_UNCHECKED(color, message); }
#define PRINT_MESSAGE_TO_TEST_OBJECT_NULLITY(object, color) PRINT_MESSAGE_ON_SCREEN(color, FString(#object) + ((object) ? TEXT(" is not Null") : TEXT(" is Null")))
#define PRINT_MESSAGE_TO_TEST_OBJECT_NULLITY_WITH_PREMESSAGE(message, object, color) PRINT_MESSAGE_TO_TEST_OBJECT_NULLITY(message## #object, color)
#else //!ENABLE_PRINT_ON_SCREEN
#define PRINT_MESSAGE_ON_SCREEN_UNCHECKED(color, message)
#define PRINT_MESSAGE_ON_SCREEN(color, message)
#define PRINT_MESSAGE_TO_TEST_OBJECT_NULLITY(object, color)
#define PRINT_MESSAGE_TO_TEST_OBJECT_NULLITY_WITH_PREMESSAGE(message, object, color)
#endif //ENABLE_PRINT_ON_SCREEN
#ifdef ENABLE_SPELL_DISPLAY_SHERECAST
#define SPHERECAST_DISPLAY_ONE_FRAME EDrawDebugTrace::ForOneFrame
#define SPHERECAST_DISPLAY_DURATION EDrawDebugTrace::ForDuration
#define SPHERECAST_DISPLAY_PERSISTENT EDrawDebugTrace::Persistent
#define SPHERECAST_DISPLAY_NONE EDrawDebugTrace::None
#else
#define SPHERECAST_DISPLAY_ONE_FRAME EDrawDebugTrace::None
#define SPHERECAST_DISPLAY_DURATION EDrawDebugTrace::None
#define SPHERECAST_DISPLAY_PERSISTENT EDrawDebugTrace::None
#define SPHERECAST_DISPLAY_NONE EDrawDebugTrace::None
#endif // ENABLE_SPELL_DISPLAY_SHERECAST
#ifdef ENABLE_DRAW_DEBUG_LINE
#define DRAW_DEBUG_LINE(world, startLocation, endLocation, color) DrawDebugLine(world, startLocation, endLocation, color, false, 5.f);
#else
#define DRAW_DEBUG_LINE(world, startLocation, endLocation, color)
#endif // ENABLE_DRAW_DEBUG_LINE
/************************************************************************/
/* NET */
/************************************************************************/
#define GENERATE_DEFAULT_VALIDATION_METHOD(className, funcName, ...) \
bool className::funcName##_Validate(__VA_ARGS__) \
{ \
return true; \
} \
#define GENERATE_IMPLEMENTATION_METHOD_AND_DEFAULT_VALIDATION_METHOD(className, funcName, ...) \
GENERATE_DEFAULT_VALIDATION_METHOD(className, funcName, __VA_ARGS__) \
void className::funcName##_Implementation(__VA_ARGS__)
/************************************************************************/
/* CLIENT */
/************************************************************************/
#define GENERATE_PROTOTYPE_SERVER_CLIENT_METHODS_BASED_VALIDATION_SERVER(MethodPtrName, className, funcName, argument) protected: \
void (className::* MethodPtrName)(argument); \
void funcName##ClientImp(argument); \
void funcName##ServerImp(argument);
#define GENERATE_DECLARATION_SERVER_CLIENT_METHODS_BASED_VALIDATION_SERVER_FROM_METHOD_PTR(methodPtrName, className, uPropFuncName, serverFuncName, argumentType, argumentName) \
GENERATE_DEFAULT_VALIDATION_METHOD(className, serverFuncName, argumentType) \
void className::serverFuncName##_Implementation(argumentType argumentName) \
{ \
(this->*methodPtrName)(argumentName); \
} \
void className::uPropFuncName(argumentType argumentName) \
{ \
(this->*methodPtrName)(argumentName); \
} \
#define GENERATE_DECLARATION_SERVER_CLIENT_METHODS_BASED_VALIDATION_SERVER_FROM_METHOD_PTR_WITH_CLIENT_IMPL_GEN(methodPtrName, className, uPropFuncName, serverFuncName, argumentType, argumentName) \
GENERATE_DECLARATION_SERVER_CLIENT_METHODS_BASED_VALIDATION_SERVER_FROM_METHOD_PTR(methodPtrName, className, uPropFuncName, serverFuncName, argumentType, argumentName) \
void className::uPropFuncName##ClientImp(argumentType argumentName) \
{ \
serverFuncName(argumentName); \
}
<file_sep>/Source/RobotRebellion/UI/LivingTextRenderComponent.h
// Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "Components/TextRenderComponent.h"
#include "ELivingTextAnimMode.h"
#include "LivingTextRenderComponent.generated.h"
/**
*
*/
UCLASS(Blueprintable)
class ROBOTREBELLION_API ULivingTextRenderComponent : public UTextRenderComponent
{
GENERATED_BODY()
public:
/************************************************************************/
/* PROPERTY */
/************************************************************************/
float m_currentTime;
//spatial translation speed along Z Axis
float m_zTranslationSpeed;
//to save the actor position
FVector m_savedBeginPosition;
protected:
//A delegate that specify the way the update method of this living text object component behaves.
void(ULivingTextRenderComponent::* m_updateMethod)(float deltaTime);
public:
/************************************************************************/
/* UPROPERTY */
/************************************************************************/
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "General")
float m_lifeTime;
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "General")
float m_heightBeginRelativeToDamagedActor;
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "General")
float m_heightEndRelativeToBeginHeight;
/************************************************************************/
/* METHODS */
/************************************************************************/
ULivingTextRenderComponent();
virtual void GetLifetimeReplicatedProps(TArray< FLifetimeProperty > & OutLifetimeProps) const override;
//copy the parameter. Warning : only the properties will be copied.
//It doesn't initialize the object => you must call initializeWith... to use the widget
void copyFrom(const ULivingTextRenderComponent& objectToCopyFrom);
void updateTextRotation();
protected:
void doesNothing(float deltaTime)
{}
void updateEverything(float deltaTime);
void updateWithoutMoving(float deltaTime);
void updateBoingBoing(float deltaTime);
void updateBoingBiggerText(float deltaTime);
void setDelegateAccordingToAnimMode(ELivingTextAnimMode mode);
public:
/************************************************************************/
/* UFUNCTION */
/************************************************************************/
//General method. Initialize this widget with a text. Must be called once for this component to be ready.
UFUNCTION(BlueprintCallable, Category = "General")
void initializeWithText(const FVector& actorPosition, const FString& textToDisplay, const FColor& colorToDisplay, ELivingTextAnimMode mode = ELivingTextAnimMode::TEXT_ANIM_MOVING);
//Specific method. Initialize this widget with an integer. Must be called once for this component to be ready.
UFUNCTION(BlueprintCallable, Category = "General")
void initializeWithInt(const FVector& actorPosition, int32 numberToDisplay, const FColor& colorToDisplay, ELivingTextAnimMode mode = ELivingTextAnimMode::TEXT_ANIM_MOVING);
/*
Main method. Must be called regularly to refresh the displaying animation of this object.
This object will be destroyed at the end of its live.
Does nothing until isReady return true.
*/
FORCEINLINE UFUNCTION(BlueprintCallable, Category = "General")
void update(float deltaTime)
{
(this->*m_updateMethod)(deltaTime);
}
UFUNCTION(BlueprintCallable, Category = "General")
void destroyLivingText();
FORCEINLINE UFUNCTION(BlueprintCallable, Category = "General")
bool isAtEndOfLife() const USE_NOEXCEPT
{
return m_currentTime > m_lifeTime;
}
//say if this instance is ready to be displayed and animated
UFUNCTION(BlueprintCallable, Category = "General")
FORCEINLINE bool isReady() const USE_NOEXCEPT
{
return this->m_updateMethod != &ULivingTextRenderComponent::doesNothing && this->IsRegistered();
}
};
<file_sep>/Source/RobotRebellion/Gameplay/Spell/ThrowSpell.cpp
// Fill out your copyright notice in the Description page of Project Settings.
#include "RobotRebellion.h"
#include "ThrowSpell.h"
#include "Gameplay/Spell/Effects/ProjectileEffect.h"
#include "Gameplay/Spell/Effects/Effect.h"
#include "Character/RobotRebellionCharacter.h"
UThrowSpell::UThrowSpell() : USpell()
{}
void UThrowSpell::BeginPlay()
{
Super::BeginPlay();
}
void UThrowSpell::cast()
{
if(!canCast())
{
PRINT_MESSAGE_ON_SCREEN(FColor::Emerald,
"Cooldown : " + FString::FromInt(m_nextAllowedCastTimer -FPlatformTime::Seconds()));
return;
}
ARobotRebellionCharacter* caster = Cast<ARobotRebellionCharacter>(GetOwner());
UWorld* const world = caster->GetWorld();
if(caster)
{
FVector cameraLocation;
FRotator muzzleRotation;
caster->GetActorEyesViewPoint(cameraLocation, muzzleRotation);
const FVector MuzzleLocation = cameraLocation + FTransform(muzzleRotation).TransformVector(m_muzzleOffset);
muzzleRotation.Pitch += m_liftOffset;
FActorSpawnParameters spawnParams;
spawnParams.Owner = caster;
spawnParams.Instigator = caster->Instigator;
// spawn the effect projectile
AProjectileEffect* const projectile = world->SpawnActor<AProjectileEffect>(
m_projectileClass,
MuzzleLocation,
muzzleRotation,
spawnParams
);
if(projectile)
{
const FVector fireDirection = muzzleRotation.Vector();
projectile->setOwner(caster);
projectile->setParent(this);
projectile->initMovement(fireDirection);
// the spell is successfully cast consumme mana and launch CD
caster->consumeMana(m_manaCost);
m_nextAllowedCastTimer = FPlatformTime::Seconds() + m_cooldown;
}
}
}
void UThrowSpell::onHit(UPrimitiveComponent*, AActor* target, UPrimitiveComponent*, FVector, const FHitResult& hitResult)
{
if(m_isTargetThrow && target != this->GetOwner())
{
ARobotRebellionCharacter* hitChar = Cast<ARobotRebellionCharacter>(target);
if(hitChar)
{
applyEffect(hitChar);
}
}
else
{
applyEffect(hitResult.ImpactPoint);
}
}
void UThrowSpell::applyEffect(ARobotRebellionCharacter* affectedTarget)
{
PRINT_MESSAGE_ON_SCREEN(FColor::Emerald, TEXT("ApplicateEffect on target"));
for(int i = 0; i < m_effects.Num(); ++i)
{
m_effects[i]->exec(Cast<ARobotRebellionCharacter>(GetOwner()), affectedTarget);
}
}
void UThrowSpell::applyEffect(FVector impactPoint)
{
PRINT_MESSAGE_ON_SCREEN(FColor::Emerald, TEXT("ApplicateEffect on point"));
for(int i = 0; i < m_effects.Num(); ++i)
{
m_effects[i]->exec(impactPoint, Cast<ARobotRebellionCharacter>(GetOwner()));
}
}<file_sep>/Source/RobotRebellion/Gameplay/Weapon/WeaponInventory.h
// Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "Components/ActorComponent.h"
#include "WeaponInventory.generated.h"
UCLASS(Blueprintable, ClassGroup = (Custom), meta = (BlueprintSpawnableComponent))
class ROBOTREBELLION_API UWeaponInventory : public UActorComponent
{
GENERATED_BODY()
public:
class UWeaponBase* m_currentWeapon;
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = Weapon)
bool m_hasDoubleWeapon;
private:
/************************************************************************/
/* UPROPERTY */
/************************************************************************/
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = Weapon, meta = (AllowPrivateAccess = "true"))
TSubclassOf<UWeaponBase> m_mainWeapon;
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = Weapon, meta = (AllowPrivateAccess = "true"))
TSubclassOf<UWeaponBase> m_secondaryWeapon;
UWeaponBase* m_mainWeaponInstance;
UWeaponBase* m_secondaryWeaponInstance;
/************************************************************************/
/* PROPERTY */
/************************************************************************/
public:
// Sets default values for this component's properties
UWeaponInventory();
public:
// Called when the game starts
virtual void BeginPlay() override;
// Called every frame
virtual void TickComponent(float DeltaTime, ELevelTick TickType, FActorComponentTickFunction* ThisTickFunction) override;
public:
//change the current equipped weapon to the main weapon
void changeToMainWeapon() USE_NOEXCEPT;
//change the current equipped weapon to the secondary weapon
void changeToSecondaryWeapon() USE_NOEXCEPT;
//equip the secondary weapon if the current weapon is the main one.
//equip the main weapon if the current weapon is the secondary one
void switchWeapon() USE_NOEXCEPT;
//get the current equipped weapon
UWeaponBase* getCurrentWeapon() USE_NOEXCEPT;
//return true if the current equipped weapon is the main weapon, false otherwise
bool isMainWeaponEquipped() const USE_NOEXCEPT;
//return true if the current equipped weapon is the secondary weapon, false otherwise
bool isSecondaryWeaponEquipped() const USE_NOEXCEPT;
FORCEINLINE const UWeaponBase* getMainWeapon() const USE_NOEXCEPT
{
return m_mainWeaponInstance;
}
FORCEINLINE const UWeaponBase* getSecondaryWeapon() const USE_NOEXCEPT
{
return m_secondaryWeaponInstance;
}
public:
//Debug string
FString toFString() const USE_NOEXCEPT;
};
<file_sep>/Source/RobotRebellion/Character/BossRobot.h
// Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "Character/NonPlayableCharacter.h"
#include "BossRobot.generated.h"
/**
*
*/
UCLASS()
class ROBOTREBELLION_API ABossRobot : public ANonPlayableCharacter
{
GENERATED_BODY()
public:
ABossRobot();
virtual void BeginPlay() override;
virtual void cppOnDeath() override;
};
<file_sep>/Source/RobotRebellion/Global/RobotRebellionGameMode.h
// Copyright 1998-2016 Epic Games, Inc. All Rights Reserved.
#pragma once
#include "GameFramework/GameModeBase.h"
#include "GameInstaller.h"
#include "RobotRebellionGameMode.generated.h"
UCLASS(minimalapi)
class ARobotRebellionGameMode : public AGameModeBase
{
GENERATED_BODY()
public:
ARobotRebellionGameMode();
virtual void BeginPlay() override;
virtual void Tick(float deltaTime) override;
};
<file_sep>/Source/RobotRebellion/IA/Character/SovecCharacter.h
// Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "Character/NonPlayableCharacter.h"
#include "SovecCharacter.generated.h"
/**
*
*/
UCLASS()
class ROBOTREBELLION_API ASovecCharacter : public ANonPlayableCharacter
{
GENERATED_BODY()
public:
ASovecCharacter();
};
<file_sep>/Source/RobotRebellion/IA/Character/RobotsCharacter.cpp
// Fill out your copyright notice in the Description page of Project Settings.
#include "RobotRebellion.h"
#include "RobotsCharacter.h"
#include "../../Gameplay/Weapon/WeaponInventory.h"
ARobotsCharacter::ARobotsCharacter() : ANonPlayableCharacter()
{
GetCapsuleComponent()->BodyInstance.SetCollisionProfileName("Robots");
m_weaponInventory = CreateDefaultSubobject<UWeaponInventory>(TEXT("WeaponInventory"));
}
<file_sep>/Source/RobotRebellion/IA/Controller/BossAIController.h
// Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "IA/Controller/CustomAIControllerBase.h"
#include "BossAIController.generated.h"
/**
*
*/
UCLASS()
class ROBOTREBELLION_API ABossAIController : public ACustomAIControllerBase
{
GENERATED_BODY()
public:
/************************************************************************/
/* UPROPERTY */
/************************************************************************/
/*The global ponderation coefficient for king*/
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "IA", meta = (ClampMin = 0.f, ClampMax = 1.f))
float m_baseKingCoefficient;
/*The global ponderation coefficient for players*/
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "IA", meta = (ClampMin = 0.f, ClampMax = 1.f))
float m_basePlayersCoefficient;
/*The malus applicated if the target is not in range*/
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "IA", meta = (ClampMin = 0.f, ClampMax = 1.f))
float m_overRangeMalusCoefficient;
/*The fall Off range when over range malus is applicated*/
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "IA", meta = (ClampMin = 1.f))
float m_fallOffRangeCoefficient;
/*Difficulty between 0 and 1. Higher value means higher difficulty*/
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "IA", meta = (ClampMin = 0.f, ClampMax = 1.f))
float m_difficulty;
/*Difficulty between 0 and 1. Higher value means higher difficulty*/
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "IA", meta = (ClampMin = 0.f))
float m_updateTargetCooldownTime;
/************************************************************************/
/* PROPERTY */
/************************************************************************/
float m_currentKingCoeff;
float m_currentPlayersCoeff;
float m_lifeThreshold;
float m_updateTargetTime;
/************************************************************************/
/* CONSTRUCTOR */
/************************************************************************/
ABossAIController();
/************************************************************************/
/* METHODS */
/************************************************************************/
virtual void BeginPlay() override;
virtual void Tick(float deltaTime) override;
virtual void CheckEnnemyNear(float range) override;
virtual void AttackTarget() const override;
private:
void computeTarget(float range);
float computeIndividualDistScoring(const FVector& bossPosition, const class ARobotRebellionCharacter* individual, float rangeSquared) const;
void initializeLifeThreshold();
void internalCheckEnnemy();
};
<file_sep>/Source/RobotRebellion/Character/NonPlayableCharacter.h
// Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "RobotRebellionCharacter.h"
#include "../Global/LootTable.h"
#include "NonPlayableCharacter.generated.h"
/**
* Mother class for every npc in RobotRebellion Game
*/
UCLASS()
class ROBOTREBELLION_API ANonPlayableCharacter : public ARobotRebellionCharacter
{
GENERATED_BODY()
public:
UPROPERTY(VisibleAnywhere, BlueprintReadWrite, Replicated)
bool m_isCrouch;
UPROPERTY(EditAnywhere, BlueprintReadWrite)
ULootTable* m_lootTable;
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Spawn Effect")
UParticleSystem* m_spawnParticleSystem;
public:
ANonPlayableCharacter();
////Server
void GetLifetimeReplicatedProps(TArray< FLifetimeProperty > & OutLifetimeProps) const override;
void spawnEffect();
virtual void cppOnDeath() override;
virtual FVector aim(const FVector& directionToShoot) const override;
void goAway(const FVector& fromWhere, float delta);
//Loot Probability
void dropLoot();
UFUNCTION(Server, Reliable, WithValidation)
void serverDropLoot();
UFUNCTION(Reliable, NetMulticast, WithValidation)
void multiSpawnEffect();
};
<file_sep>/Source/RobotRebellion/UI/TextBillboardComponent.cpp
// Fill out your copyright notice in the Description page of Project Settings.
#include "RobotRebellion.h"
#include "TextBillboardComponent.h"
#include "LivingTextRenderComponent.h"
#include "../Tool/UtilitaryFunctionLibrary.h"
UTextBillboardComponent::UTextBillboardComponent() : UBillboardComponent()
{
bAutoActivate = true;
bReplicates = true;
}
void UTextBillboardComponent::GetLifetimeReplicatedProps(TArray< FLifetimeProperty > & OutLifetimeProps) const
{
Super::GetLifetimeReplicatedProps(OutLifetimeProps);
}
void UTextBillboardComponent::beginDisplayingText(const FVector& actorPositionInWorld, const FString& text, const FColor& colorToDisplay, ELivingTextAnimMode mode)
{
ULivingTextRenderComponent* intermediary;
if (UUtilitaryFunctionLibrary::createObjectFromDefault<ULivingTextRenderComponent>(&intermediary, m_defaultRenderText, this, RF_Dynamic))
{
intermediary->AttachToComponent(this, FAttachmentTransformRules::KeepRelativeTransform);
intermediary->Activate();
m_damageRenderedTextArray.Add(intermediary);
m_damageRenderedTextArray.Top()->initializeWithText(actorPositionInWorld, text, colorToDisplay, mode);
}
}
void UTextBillboardComponent::beginDisplayingInteger(const FVector& actorPositionInWorld, int32 integerValue, const FColor& colorToDisplay, ELivingTextAnimMode mode)
{
this->beginDisplayingText(actorPositionInWorld, FString::FromInt(integerValue), colorToDisplay, mode);
}
void UTextBillboardComponent::update(float deltaTime)
{
if (this->nothingToRender())
{
return;
}
for (auto iter = 0; iter < m_damageRenderedTextArray.Num(); ++iter)
{
m_damageRenderedTextArray[iter]->update(deltaTime);
}
m_damageRenderedTextArray.RemoveAll(
[](ULivingTextRenderComponent* current) {
return
current == NULL ||
current->IsBeingDestroyed() ||
current->IsPendingKillOrUnreachable() ||
!current->isReady();
});
this->UpdateChildTransforms();
}
void UTextBillboardComponent::clearAllLivingTexts()
{
for (auto iter = 0; iter < m_damageRenderedTextArray.Num(); ++iter)
{
if (!m_damageRenderedTextArray[iter]->IsPendingKillOrUnreachable())
{
m_damageRenderedTextArray[iter]->destroyLivingText();
}
}
m_damageRenderedTextArray.Empty();
}
<file_sep>/Source/RobotRebellion/Gameplay/Weapon/WeaponInventory.cpp
// Fill out your copyright notice in the Description page of Project Settings.
#include "RobotRebellion.h"
#include "WeaponInventory.h"
#include "WeaponBase.h"
#include "LongRangeWeapon.h"
#include "ShortRangeWeapon.h"
#include "../../Tool/UtilitaryFunctionLibrary.h"
#include "../../Tool/UtilitaryMacros.h"
// Sets default values for this component's properties
UWeaponInventory::UWeaponInventory()
{
// Set this component to be initialized when the game starts, and to be ticked every frame. You can turn these features
// off to improve performance if you don't need them.
PrimaryComponentTick.bCanEverTick = false;
//m_mainWeapon = CreateDefaultSubobject<ULongRangeWeapon>(TEXT("mainWeapon"));
//m_secondaryWeapon = CreateDefaultSubobject<UShortRangeWeapon>(TEXT("secondaryWeapon"));
// ...
}
// Called when the game starts
void UWeaponInventory::BeginPlay()
{
Super::BeginPlay();
UWeaponBase* intermediary = Cast<UWeaponBase>(m_mainWeapon->GetDefaultObject());
if (intermediary->getWeaponRange() == EWeaponRange::LONG_RANGE_WEAPON)
{
UUtilitaryFunctionLibrary::createObjectFromDefault<ULongRangeWeapon>(
&m_mainWeaponInstance,
m_mainWeapon,
this,
TEXT("mainWeapon")
);
}
else if(intermediary->getWeaponRange() == EWeaponRange::SHORT_RANGE_WEAPON)
{
UUtilitaryFunctionLibrary::createObjectFromDefault<UShortRangeWeapon>(
&m_mainWeaponInstance,
m_mainWeapon,
this,
TEXT("mainWeapon")
);
}
else if(intermediary->getWeaponRange() == EWeaponRange::INVALID_RANGE_WEAPON)
{
PRINT_MESSAGE_ON_SCREEN(FColor::Red, TEXT("Main weapon class is invalid"));
}
if(m_hasDoubleWeapon)
{
intermediary = Cast<UWeaponBase>(m_secondaryWeapon->GetDefaultObject());
if(intermediary->getWeaponRange() == EWeaponRange::LONG_RANGE_WEAPON)
{
UUtilitaryFunctionLibrary::createObjectFromDefault<ULongRangeWeapon>(
&m_secondaryWeaponInstance,
m_secondaryWeapon,
this,
TEXT("secondaryWeapon")
);
}
else if(intermediary->getWeaponRange() == EWeaponRange::SHORT_RANGE_WEAPON)
{
UUtilitaryFunctionLibrary::createObjectFromDefault<UShortRangeWeapon>(
&m_secondaryWeaponInstance,
m_secondaryWeapon,
this,
TEXT("secondaryWeapon")
);
}
else if(intermediary->getWeaponRange() == EWeaponRange::INVALID_RANGE_WEAPON)
{
PRINT_MESSAGE_ON_SCREEN(FColor::Red, TEXT("Secondary weapon class is invalid"));
}
if(m_secondaryWeaponInstance)
{
m_secondaryWeaponInstance->m_owner = GetOwner();
}
}
changeToMainWeapon();
if(m_mainWeaponInstance)
{
m_mainWeaponInstance->m_owner = GetOwner();
}
}
// Called every frame
void UWeaponInventory::TickComponent( float DeltaTime, ELevelTick TickType, FActorComponentTickFunction* ThisTickFunction )
{
Super::TickComponent( DeltaTime, TickType, ThisTickFunction );
// ...
}
void UWeaponInventory::changeToMainWeapon() USE_NOEXCEPT
{
m_currentWeapon = m_mainWeaponInstance;
PRINT_MESSAGE_ON_SCREEN(FColor::Blue, TEXT("Main weapon equipped"));
}
void UWeaponInventory::changeToSecondaryWeapon() USE_NOEXCEPT
{
m_currentWeapon = m_secondaryWeaponInstance;
PRINT_MESSAGE_ON_SCREEN(FColor::Blue, TEXT("Secondary weapon equipped"));
}
UWeaponBase* UWeaponInventory::getCurrentWeapon() USE_NOEXCEPT
{
return m_currentWeapon;
}
bool UWeaponInventory::isMainWeaponEquipped() const USE_NOEXCEPT
{
return m_currentWeapon == m_mainWeaponInstance;
}
bool UWeaponInventory::isSecondaryWeaponEquipped() const USE_NOEXCEPT
{
return m_currentWeapon == m_secondaryWeaponInstance;
}
void UWeaponInventory::switchWeapon() USE_NOEXCEPT
{
if (isMainWeaponEquipped() && m_hasDoubleWeapon)
{
changeToSecondaryWeapon();
}
else
{
changeToMainWeapon();
}
}
FString UWeaponInventory::toFString() const USE_NOEXCEPT
{
FString message(TEXT("Current weapon : "));
if (isMainWeaponEquipped())
{
return message + TEXT("Main Weapon");
}
else
{
return message + TEXT("Secondary Weapon");
}
}
<file_sep>/Source/RobotRebellion/Character/Assassin.h
// Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "PlayableCharacter.h"
#include "Assassin.generated.h"
/**
*
*/
UCLASS()
class ROBOTREBELLION_API AAssassin : public APlayableCharacter
{
GENERATED_BODY()
public:
AAssassin();
//virtual void BeginPlay() override;
EClassType getClassType() const USE_NOEXCEPT override
{
return EClassType::ASSASSIN;
}
};
<file_sep>/Source/RobotRebellion/Gameplay/Item/ObjectTypes.h
#pragma once
//Object Type enum
UENUM(BlueprintType)
enum class EObjectType : uint8
{
NONE,
BOMB,
HEALTH_POTION,
MANA_POTION,
TYPE_COUNT
};<file_sep>/Source/RobotRebellion/Gameplay/TriggerBox/KingActivateTriggerBox.cpp
// Fill out your copyright notice in the Description page of Project Settings.
#include "RobotRebellion.h"
#include "KingActivateTriggerBox.h"
#include "Global/EntityDataSingleton.h"
#include "IA/Controller/KingAIController.h"
#include "Character/King.h"
AKingActivateTriggerBox::AKingActivateTriggerBox()
{
UShapeComponent* collisionComponent = GetCollisionComponent();
collisionComponent->SetCollisionResponseToAllChannels(ECR_Ignore);
collisionComponent->SetCollisionResponseToChannel(ECC_GameTraceChannel2, ECollisionResponse::ECR_Overlap);
collisionComponent->OnComponentBeginOverlap.AddUniqueDynamic(this, &AKingActivateTriggerBox::onEnter);
}
void AKingActivateTriggerBox::BeginPlay()
{
Super::BeginPlay();
}
void AKingActivateTriggerBox::onEnter(UPrimitiveComponent* var1, AActor* enteredActor, UPrimitiveComponent* var3, int32 var4, bool var5, const FHitResult& var6)
{
if(Role >= ROLE_Authority)
{
this->internal_signalToServer();
}
else
{
signalToServer();
}
this->killItself();
}
void AKingActivateTriggerBox::internal_signalToServer()
{
AKing* king = EntityDataSingleton::getInstance().getServerKing(this);
if(king)
{
AKingAIController* kingController = Cast<AKingAIController>(king->GetController());
check(kingController);
kingController->activate(true);
PRINT_MESSAGE_ON_SCREEN_UNCHECKED(FColor::Red, "COLLISION, KING ACTIVATED");
}
}
void AKingActivateTriggerBox::signalToServer_Implementation()
{
this->internal_signalToServer();
}
bool AKingActivateTriggerBox::signalToServer_Validate()
{
return true;
}
void AKingActivateTriggerBox::correctDestruction()
{
this->Destroy(true);
}
void AKingActivateTriggerBox::killItself()
{
if (Role < ROLE_Authority)
{
this->serverKills();
}
else
{
this->multiKills();
}
this->correctDestruction();
}
void AKingActivateTriggerBox::serverKills_Implementation()
{
this->multiKills();
this->correctDestruction();
}
bool AKingActivateTriggerBox::serverKills_Validate()
{
return true;
}
void AKingActivateTriggerBox::multiKills_Implementation()
{
this->correctDestruction();
}
<file_sep>/Source/RobotRebellion/Gameplay/Spell/RayCastSpell.cpp
// Fill out your copyright notice in the Description page of Project Settings.
#include "RobotRebellion.h"
#include "RayCastSpell.h"
#include "Gameplay/Spell/Effects/Effect.h"
#include "Character/RobotRebellionCharacter.h"
URayCastSpell::URayCastSpell() : USpell()
{}
void URayCastSpell::BeginPlay()
{
Super::BeginPlay();
}
void URayCastSpell::cast()
{
if(!canCast())
{
PRINT_MESSAGE_ON_SCREEN(FColor::Emerald,
"Cooldown : " + FString::FromInt(m_nextAllowedCastTimer - FPlatformTime::Seconds()));
return;
}
ARobotRebellionCharacter* caster = Cast<ARobotRebellionCharacter>(GetOwner());
UWorld* const world = caster->GetWorld();
if(caster)
{
// Get player location and where hes looking
FVector cameraLocation;
FRotator muzzleRotation;
caster->GetActorEyesViewPoint(cameraLocation, muzzleRotation);
FVector aimDir = getRealAimingVector(caster);
// Initialize Location
const FVector endLocation = caster->GetActorLocation() + (aimDir * m_range);
// offset the shoot to avoid collision with the capsule of the player
const FVector startLocation = caster->GetActorLocation() + (aimDir * 100.f) + FVector(0.f, 0.f, caster->BaseEyeHeight);
//Draw debug line
DRAW_DEBUG_LINE(world, startLocation, endLocation, FColor::Red);
// Cast the RAY!
FHitResult hitActors(ForceInit);
FCollisionQueryParams TraceParams(TEXT("WeaponTrace"), true, caster->Instigator);
TraceParams.bTraceAsyncScene = true;
TraceParams.bReturnPhysicalMaterial = true;
TraceParams.AddIgnoredActor(caster);
// atm only should only proc on static mesh
world->LineTraceSingleByChannel(hitActors, startLocation, endLocation, ECC_WorldStatic, TraceParams);
// hit Actors countains hit actors now
processHitActor(hitActors);
// the spell is successfully cast consumme mana and launch CD
caster->consumeMana(m_manaCost);
m_nextAllowedCastTimer = FPlatformTime::Seconds() + m_cooldown;
}
}
void URayCastSpell::applyEffect(ARobotRebellionCharacter* affectedTarget)
{
PRINT_MESSAGE_ON_SCREEN(FColor::Emerald, TEXT("ApplicateEffect on target"));
for(int i = 0; i < m_effects.Num(); ++i)
{
m_effects[i]->exec(Cast<ARobotRebellionCharacter>(GetOwner()), affectedTarget);
}
}
void URayCastSpell::applyEffect(FVector impactPoint)
{
ARobotRebellionCharacter* caster = Cast<ARobotRebellionCharacter>(GetOwner());
PRINT_MESSAGE_ON_SCREEN(FColor::Emerald, TEXT("ApplicateEffect on point"));
for(int i = 0; i < m_effects.Num(); ++i)
{
m_effects[i]->exec(impactPoint, caster);
}
}
void URayCastSpell::processHitActor(const FHitResult& hitResult)
{
if(hitResult.GetActor() != nullptr)
{
if(m_isTargetedSpell)
{
// apply effect on character hit
ARobotRebellionCharacter* hitCharacter = Cast<ARobotRebellionCharacter>(hitResult.GetActor());
if(hitCharacter)
{
PRINT_MESSAGE_ON_SCREEN_UNCHECKED(FColor::Red, "Ray cast spell done -> apply effect on target");
applyEffect(hitCharacter);
}
}
else
{
PRINT_MESSAGE_ON_SCREEN_UNCHECKED(FColor::Red, "Ray cast spell done -> apply effect on impactpoint");
applyEffect(hitResult.ImpactPoint);
}
}
}
// void processStartLocAndAimVector(const FVector &camLoc, const FVector &camDir, const FVector &playerLoc,
// FVector &startLoc, FVector &aimDirection)
// {
// FVector camToPlayer = playerLoc - camLoc;
// camToPlayer.Normalize();
// camDir.Normalize();
// }
FVector URayCastSpell::getRealAimingVector(const ARobotRebellionCharacter* caster)
{
APlayerController* playerController = Cast<APlayerController>(caster->Controller);
if(playerController)
{
FVector CamLoc;
FRotator CamRot;
playerController->GetPlayerViewPoint(CamLoc, CamRot);
return CamRot.Vector();
}
else if(caster->Instigator)
{
return caster->GetBaseAimRotation().Vector();
}
return FVector::ZeroVector;
}
<file_sep>/Source/RobotRebellion/Gameplay/Item/BombActor.cpp
// Fill out your copyright notice in the Description page of Project Settings.
#include "RobotRebellion.h"
#include "BombActor.h"
void ABombActor::OnPickup(APawn* InstigatorPawn)
{
//Nothing. To be derived.
PRINT_MESSAGE_ON_SCREEN(FColor::Purple, TEXT("Bomb PickedUp"));
Destroy();
}
<file_sep>/Source/RobotRebellion/Gameplay/Spell/Effects/ProjectileEffect.h
// Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "../../Weapon/Projectile.h"
#include "ProjectileEffect.generated.h"
/**
*
*/
UCLASS()
class ROBOTREBELLION_API AProjectileEffect : public AProjectile
{
GENERATED_BODY()
private:
class UThrowSpell* m_parentSpell;
public:
/** Emitter system launche on impact*/
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = Particule)
UParticleSystem* m_particleSystem;
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = Particule)
UParticleSystemComponent* m_particleSystemComp;
/** Specify if the projectil have to launche particule emitter on hit*/
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = Particule)
bool m_hasEffect;
/** Scale the particule emitter*/
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = Particule)
FVector m_effectScale;
/** offset particule emitter*/
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = Particule)
FVector m_effectOffset;
public:
AProjectileEffect();
void initMovement(const FVector& shootDirection);
void setParent(UThrowSpell *spell);
virtual void OnHit(UPrimitiveComponent* ThisComp, AActor* OtherActor, UPrimitiveComponent* OtherComp, FVector NormalImpulse, const FHitResult& Hit) override;
void GetLifetimeReplicatedProps(TArray< FLifetimeProperty > & OutLifetimeProps) const override;
void spawnEffect();
public:
UFUNCTION(Reliable, NetMulticast, WithValidation)
void multiSpawnEffect(FVector location);
};
<file_sep>/Source/RobotRebellion/Gameplay/Spell/RayCastSpell.h
// Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "Gameplay/Spell/Spell.h"
#include "RayCastSpell.generated.h"
/**
* Implemente logic for spell that doesnt have projectile
* That kin d of spell must hit something into his range
* It will just use rayCast to know how the spell is cast.
*/
UCLASS()
class ROBOTREBELLION_API URayCastSpell : public USpell
{
GENERATED_BODY()
public:
/** if true the spell need to land on a subclass of RobotRebellionCharacter if not it does nothing */
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Raycast Settings")
bool m_isTargetedSpell;
public:
URayCastSpell();
virtual void BeginPlay() override;
virtual void cast() override;
// Apply Effects on a target that have to be a RobotRebellion Character
void applyEffect(class ARobotRebellionCharacter* affectedTarget);
// Aplly Effects on a specific location
void applyEffect(FVector impactPoint);
private:
void processHitActor(const FHitResult& hitResult);
// from the camera position, rotation, and character position
// fill startLoc and aimDirection with the right location and unit vector
//void processStartLocAndAimVector(const FVector &camLoc, const FVector &camDir, const FVector &playerLoc,
// FVector &startLoc, FVector &aimDirection);
FVector getRealAimingVector(const ARobotRebellionCharacter* caster);
};
<file_sep>/Source/RobotRebellion/Tool/IdentifiableObj.cpp
// Fill out your copyright notice in the Description page of Project Settings.
#include "RobotRebellion.h"
#include "IdentifiableObj.h"
uint32 Identifiable::ID::accumulator = 0;
<file_sep>/Source/RobotRebellion/Gameplay/Alteration/InvisibilityAlteration.h
// Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "AlterationBase.h"
#include "../../Tool/IdentifiableObj.h"
#include "InvisibilityAlteration.generated.h"
/**
*
*/
UCLASS(Blueprintable)
class ROBOTREBELLION_API UInvisibilityAlteration : public UAlterationBase
{
GENERATED_BODY()
public:
UInvisibilityAlteration();
void destroyItself() override;
void onCreate(class ARobotRebellionCharacter* alteredOwner) override;
virtual FString toDebugString() const USE_NOEXCEPT
{
return "Invisibility";
}
};
<file_sep>/Source/RobotRebellion/Gameplay/TriggerBox/SpawnerTriggerBox.cpp
// Fill out your copyright notice in the Description page of Project Settings.
#include "RobotRebellion.h"
#include "SpawnerTriggerBox.h"
#include "Character/King.h"
#include "Character/NonPlayableCharacter.h"
#include "IA/Controller/CustomAIControllerBase.h"
#include "Global/EntityDataSingleton.h"
#include "Character/PlayableCharacter.h"
ASpawnerTriggerBox::ASpawnerTriggerBox()
{
UShapeComponent* collisionComponent = GetCollisionComponent();
collisionComponent->SetCollisionResponseToAllChannels(ECR_Ignore);
collisionComponent->SetCollisionResponseToChannel(ECC_Pawn, ECollisionResponse::ECR_Overlap);
collisionComponent->SetCollisionResponseToChannel(ECC_PhysicsBody, ECollisionResponse::ECR_Overlap);
collisionComponent->SetCollisionResponseToChannel(ECC_GameTraceChannel2, ECollisionResponse::ECR_Overlap);
collisionComponent->SetCollisionResponseToChannel(ECC_GameTraceChannel3, ECollisionResponse::ECR_Overlap);
collisionComponent->SetCollisionResponseToChannel(ECC_GameTraceChannel7, ECollisionResponse::ECR_Overlap);
collisionComponent->OnComponentBeginOverlap.AddUniqueDynamic(this, &ASpawnerTriggerBox::onHit);
m_spawnParams.SpawnCollisionHandlingOverride = ESpawnActorCollisionHandlingMethod::DontSpawnIfColliding;
}
void ASpawnerTriggerBox::BeginPlay()
{
Super::BeginPlay();
check(m_populationTransform.Num() == m_populationToSpawn.Num());
}
void ASpawnerTriggerBox::onHit(UPrimitiveComponent* var1, AActor* enteredActor, UPrimitiveComponent* var3, int32 var4, bool var5, const FHitResult& var6)
{
if(m_activeOnlyWhenKingHere && !Cast<AKing>(enteredActor))
{
return;
}
if(m_noSpawnWhenPopulated && m_spawned.Num() != 0)
{
return;
}
if(Role >= ROLE_Authority && m_autoActivateCombat)
{
this->checkCharactersOnBox();
}
this->spawnEnnemies();
if(m_destroyWhenPassed)
{
this->killItself();
}
}
void ASpawnerTriggerBox::checkCharactersOnBox()
{
FVector volumeCenter;
FVector extent;
this->GetActorBounds(false, volumeCenter, extent);
m_maxDist = volumeCenter.X + (extent.X + m_scope + 1000.f);
EntityDataSingleton& datas = EntityDataSingleton::getInstance();
auto containPredicate = [
minX = volumeCenter.X - (extent.X + m_scope),
maxX = volumeCenter.X + (extent.X + m_scope),
minY = volumeCenter.Y - (extent.Y + m_scope),
maxY = volumeCenter.Y + (extent.Y + m_scope),
minZ = volumeCenter.Z - (extent.Z + m_scope),
maxZ = volumeCenter.Z + (extent.Z + m_scope)
] (const FVector& position) {
return position.X > minX && position.X < maxX &&
position.Y > minY && position.Y < maxY &&
position.Z > minZ && position.Z < maxZ;
};
TArray<APlayableCharacter*>& characters = datas.m_playableCharacterArray;
m_characterOnBox.Empty(characters.Num() + 1);
for(APlayableCharacter* player : characters)
{
if(containPredicate(player->GetActorLocation()))
{
m_characterOnBox.Add(player);
}
}
AKing* m_king = Role >= ROLE_Authority ? datas.getServerKing(this) : datas.m_king;
if(containPredicate(m_king->GetActorLocation()))
{
m_characterOnBox.Add(m_king);
}
}
void ASpawnerTriggerBox::internalSpawn()
{
UWorld* world = this->GetWorld();
if(world)
{
if(m_random)
{
int32 ennemyCountToSpawn = FMath::RandRange(1, m_populationToSpawn.Num());
int32 lastIndex = m_populationToSpawn.Num() - 1;
m_spawned.Reserve(ennemyCountToSpawn);
for(int32 iter = 0; iter < ennemyCountToSpawn; ++iter)
{
this->internalSpawnCharacterAtIndex(FMath::RandRange(0, lastIndex), world);
}
}
else
{
m_spawned.Reserve(m_populationToSpawn.Num());
for(int32 iter = 0; iter < m_populationToSpawn.Num(); ++iter)
{
this->internalSpawnCharacterAtIndex(iter, world);
}
}
m_spawned.Shrink();
}
}
void ASpawnerTriggerBox::internalSpawnCharacterAtIndex(int32 index, UWorld* world)
{
ANonPlayableCharacter* spawned;
if(m_relativePosition)
{
FTransform intermediary = this->GetTransform().GetRelativeTransform(m_populationTransform[index]);
spawned = Cast<ANonPlayableCharacter>(world->SpawnActor(m_populationToSpawn[index], &intermediary, m_spawnParams));
}
else
{
spawned = Cast<ANonPlayableCharacter>(world->SpawnActor(m_populationToSpawn[index], &m_populationTransform[index], m_spawnParams));
}
if(spawned)
{
m_spawned.Add(spawned);
if (spawned->Controller && m_autoActivateCombat)
{
setNearTarget(spawned);
}
if (m_comeFromUpper)
{
FVector actorLocation = spawned->GetActorLocation();
actorLocation.Z += m_upperOffset;
spawned->SetActorLocation(actorLocation);
}
if (m_effectOnSpawn)
{
spawned->spawnEffect();
}
}
}
void ASpawnerTriggerBox::spawnEnnemies()
{
if(Role < ROLE_Authority)
{
this->serverSpawnEnnemies();
}
else
{
this->internalSpawn();
}
}
void ASpawnerTriggerBox::serverSpawnEnnemies_Implementation()
{
this->internalSpawn();
}
bool ASpawnerTriggerBox::serverSpawnEnnemies_Validate()
{
return true;
}
void ASpawnerTriggerBox::correctDestruction()
{
this->Destroy(true);
}
void ASpawnerTriggerBox::killItself()
{
if(Role < ROLE_Authority)
{
this->serverKills();
}
else
{
this->multiKills();
}
this->correctDestruction();
}
void ASpawnerTriggerBox::serverKills_Implementation()
{
this->multiKills();
this->correctDestruction();
}
bool ASpawnerTriggerBox::serverKills_Validate()
{
return true;
}
void ASpawnerTriggerBox::multiKills_Implementation()
{
this->correctDestruction();
}
void ASpawnerTriggerBox::setNearTarget(ANonPlayableCharacter* spawned)
{
FVector spawnedLocation = spawned->GetActorLocation();
float minDist = m_maxDist * m_maxDist;
ACustomAIControllerBase* controller = Cast<ACustomAIControllerBase>(spawned->Controller);
if(controller)
{
for(ARobotRebellionCharacter* charac : m_characterOnBox)
{
float toCheck = spawnedLocation.SizeSquared();
if(minDist < toCheck)
{
minDist = toCheck;
controller->setTarget(charac);
}
}
}
}<file_sep>/Source/RobotRebellion/Gameplay/Spell/SpellKit.h
// Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "Components/ActorComponent.h"
#include "SpellKit.generated.h"
/*
* Handle a skill set for a playable Character or maybe the boss
*/
UCLASS( ClassGroup=(Custom), meta=(BlueprintSpawnableComponent) )
class ROBOTREBELLION_API USpellKit : public UActorComponent
{
GENERATED_BODY()
public:
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = SpellKit)
TArray<TSubclassOf<class USpell>> m_spellsClass; // forward decl
private:
UPROPERTY(VisibleAnywhere, BlueprintReadWrite, Category = "Spells", meta = (AllowPrivateAccess = "true"), Replicated)
TArray<USpell *> m_spells;
public:
// Sets default values for this component's properties
USpellKit();
// Called when the game starts
virtual void BeginPlay() override;
// Called every frame
virtual void TickComponent( float DeltaTime, ELevelTick TickType, FActorComponentTickFunction* ThisTickFunction ) override;
// cast the spell matching the index if it exists
void cast(int32 index);
TArray<float> getCooldowns();
void GetLifetimeReplicatedProps(TArray< FLifetimeProperty > & OutLifetimeProps) const;
};
<file_sep>/Source/RobotRebellion/UI/GameMenu.cpp
// Fill out your copyright notice in the Description page of Project Settings.
#include "RobotRebellion.h"
#include "LobbyUIWidget.h"
#include "GameMenu.h"
#include "Character/PlayableCharacter.h"
AGameMenu::AGameMenu()
{
PrimaryActorTick.bCanEverTick = true;
}
void AGameMenu::firstCallHUD_Implementation()
{
// does nothing
}
void AGameMenu::BeginPlay()
{
Super::BeginPlay();
HUDCharacterImpl = CreateCustomWidget<UCustomRobotRebellionUserWidget>(HUDCharacterWidget.GetDefaultObject());
HUDCharacterImpl->SetVisibility(ESlateVisibility::Hidden);
LobbyImpl = CreateCustomWidget<ULobbyUIWidget>(Cast<ULobbyUIWidget>(LobbyWidget->GetDefaultObject()));
LobbyImpl->initialiseOnliSubsystem();
LobbyImpl->SetVisibility(ESlateVisibility::Hidden);
ReviveTimerWidgetImpl = CreateCustomWidget<UReviveTimerWidget>(ReviveWidget.GetDefaultObject());
ReviveTimerWidgetImpl->SetVisibility(ESlateVisibility::Hidden);
ClassSelectionWidgetImpl = CreateCustomWidget<URobotRebellionWidget>(ClassSelectionWidget.GetDefaultObject());
ClassSelectionWidgetImpl->SetVisibility(ESlateVisibility::Hidden);
OptionsWidgetImpl = CreateCustomWidget<UOptionsMenuWidget>(OptionsWidget.GetDefaultObject());
OptionsWidgetImpl->SetVisibility(ESlateVisibility::Hidden);
TopWidgetImpl = CreateCustomWidget<UTopWidget>(TopWidget.GetDefaultObject());
TopWidgetImpl->SetVisibility(ESlateVisibility::Hidden);
firstCallHUD();
}
void AGameMenu::Tick(float deltaTime)
{
Super::Tick(deltaTime);
APlayableCharacter* player = Cast<APlayableCharacter>(GetOwningPlayerController()->GetCharacter());
if(player)
{
if(player->isReviving())
{
ReviveTimerWidgetImpl->SetVisibility(ESlateVisibility::Visible);
}
else
{
ReviveTimerWidgetImpl->SetVisibility(ESlateVisibility::Hidden);
}
}
}
void AGameMenu::DisplayWidget(URobotRebellionWidget* WidgetRef)
{
WidgetRef->SetVisibility(ESlateVisibility::Visible);
WidgetRef->startSound();
}
void AGameMenu::HideWidget(URobotRebellionWidget* WidgetRef)
{
WidgetRef->SetVisibility(ESlateVisibility::Hidden);
WidgetRef->endSound();
}
<file_sep>/Source/RobotRebellion/Tool/IdentifiableObj.h
// Fill out your copyright notice in the Description page of Project Settings.
#pragma once
/**
*
*/
class ROBOTREBELLION_API Identifiable
{
public:
struct ID
{
private:
static uint32 accumulator;
public:
uint32 m_value;
public:
ID() USE_NOEXCEPT :
m_value{ accumulator++ }
{}
ID(uint32 newId) USE_NOEXCEPT :
m_value{ newId }
{}
};
public:
Identifiable::ID m_id;
Identifiable(const Identifiable::ID& id) USE_NOEXCEPT :
m_id{ id }
{}
virtual ~Identifiable()
{}
};
template<class ObjectType>
class ROBOTREBELLION_API IdentifiableObject : public Identifiable
{
public:
static Identifiable::ID ID;
public:
IdentifiableObject() USE_NOEXCEPT :
Identifiable{ IdentifiableObject<ObjectType>::ID }
{}
virtual ~IdentifiableObject() {}
};
template<class ObjectType> Identifiable::ID IdentifiableObject<ObjectType>::ID;
<file_sep>/Source/RobotRebellion/IA/Controller/KingAIController.cpp
// Fill out your copyright notice in the Description page of Project Settings.
#include "RobotRebellion.h"
#include "KingAIController.h"
#include "Global/EntityDataSingleton.h"
#include "DroneAIController.h"
#include "Tool/UtilitaryFunctionLibrary.h"
#include "Character/Drone.h"
void AKingAIController::BeginPlay()
{
Super::BeginPlay();
this->m_updateMethodPtr = &AKingAIController::doesNothing;
}
void AKingAIController::Tick(float deltaTime)
{
Super::Tick(deltaTime);
(this->*m_updateMethodPtr)();
}
void AKingAIController::updateKing()
{
this->computeTarget();
this->MoveToTarget();
}
EPathFollowingRequestResult::Type AKingAIController::MoveToTarget()
{
return MoveToLocation(m_destination, m_moveThreshold);
}
void AKingAIController::computeTarget()
{
ADrone* drone = EntityDataSingleton::getInstance().getServerDrone(this);
//always good. Never nullptr because AKingAIController only lives on server side.
if (drone)
{
ADroneAIController* droneController = Cast<ADroneAIController>(drone->GetController());
check(droneController);
if(FVector::DistSquared(m_destination, droneController->getAllyBarycenter()) > m_minimaleDistanceToMove)
{
m_destination = droneController->getAllyBarycenter();
}
}
}<file_sep>/Source/RobotRebellion/IA/Controller/GunTurretAIController.h
// Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "IA/Controller/CustomAIControllerBase.h"
#include "GunTurretAIController.generated.h"
/**
* AI controller for the soldiers Gun Turret. attack only ennemy : Beast, Robot
*/
UCLASS()
class ROBOTREBELLION_API AGunTurretAIController : public ACustomAIControllerBase
{
GENERATED_BODY()
public:
void CheckEnnemyNear(float range) override;
void AttackTarget() const override;
};
<file_sep>/Source/RobotRebellion/Gameplay/TriggerBox/BossActivateTriggerBox.h
// Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "Engine/TriggerBox.h"
#include "BossActivateTriggerBox.generated.h"
/**
*
*/
UCLASS()
class ROBOTREBELLION_API ABossActivateTriggerBox : public ATriggerBox
{
GENERATED_BODY()
public:
ABossActivateTriggerBox();
virtual void BeginPlay() override;
UFUNCTION()
void onHit(UPrimitiveComponent* var1, AActor* var2, UPrimitiveComponent* var3, FVector var4, const FHitResult& var5);
private:
void correctDestruction();
void killItself();
UFUNCTION(Reliable, Server, WithValidation)
void serverKills();
UFUNCTION(Reliable, NetMulticast)
void multiKills();
};
<file_sep>/Source/RobotRebellion/IA/BT/DebugBTService.h
// Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "BehaviorTree/BTService.h"
#include "DebugBTService.generated.h"
/**
* Debug service for AIcontroller
* TODO - make it usable by every AIController by adding drawDebug virtual methode in Custom Ai Controller.
* Now only used by RobotShooterController.
*/
UCLASS()
class ROBOTREBELLION_API UDebugBTService : public UBTService
{
GENERATED_BODY()
public:
UDebugBTService();
/** Will be called at each tick update */
virtual void TickNode(UBehaviorTreeComponent& OwnerComp, uint8* NodeMemory,
float DeltaSeconds) override;
};
<file_sep>/Source/RobotRebellion/IA/BT/CrouchBTTaskNode.h
// Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "BehaviorTree/BTTaskNode.h"
#include "CrouchBTTaskNode.generated.h"
/**
*
*/
UCLASS()
class ROBOTREBELLION_API UCrouchBTTaskNode : public UBTTaskNode
{
GENERATED_BODY()
public:
UCrouchBTTaskNode();
virtual EBTNodeResult::Type ExecuteTask(UBehaviorTreeComponent& OwnerComp,
uint8* NodeMemory) override;
virtual void TickTask(class UBehaviorTreeComponent& OwnerComp, uint8* NodeMemory,
float DeltaSeconds) override;
virtual FString GetStaticDescription() const override;
};
<file_sep>/Source/RobotRebellion/Character/ClassType.h
// Fill out your copyright notice in the Description page of Project Settings.
#pragma once
//CLASS FLAG
UENUM(BlueprintType)
enum class EClassType : uint8
{
NONE UMETA(DisplayName = "None"),
SOLDIER UMETA(DisplayName = "Soldier"),
ASSASSIN UMETA(DisplayName = "Assassin"),
HEALER UMETA(DisplayName = "Healer"),
WIZARD UMETA(DisplayName = "Wizard"),
};<file_sep>/Source/RobotRebellion/Gameplay/Weapon/FireProjectile.cpp
// Fill out your copyright notice in the Description page of Project Settings.
#include "RobotRebellion.h"
#include "FireProjectile.h"
#include "Character/RobotRebellionCharacter.h"
#include "Global/WorldInstanceEntity.h"
AFireProjectile::AFireProjectile()
{
}
void AFireProjectile::BeginPlay()
{
Super::BeginPlay();
}
void AFireProjectile::Tick(float DeltaTime)
{
Super::Tick(DeltaTime);
}
void AFireProjectile::OnHit(class UPrimitiveComponent* ThisComp, class AActor* OtherActor, class UPrimitiveComponent* OtherComp, FVector NormalImpulse, const FHitResult& Hit)
{
ARobotRebellionCharacter* receiver = Cast<ARobotRebellionCharacter>(OtherActor);
if(receiver && receiver !=m_owner)
{
receiver->spawnFireEffect(Hit.Location);
}
if(Role == ROLE_Authority)
{
if(receiver && m_owner != receiver && !receiver->isDead())
{
if(!receiver->isImmortal())
{
DamageCoefficientLogic coeff;
Damage damage{m_owner, receiver};
Damage::DamageValue currentDamage = damage(
&UGlobalDamageMethod::normalHitWithWeaponComputed,
coeff.getCoefficientValue()
);
setReceiverInCombat(receiver);
receiver->inflictDamage(m_baseDamage*currentDamage);
}
}
//TODO display burn effect on Mesh
//ASurvivalCharacter* hitActor = Cast<ASurvivalCharacter>(Impact.GetActor());
Destroy();
}
}<file_sep>/Source/RobotRebellion/Gameplay/Spell/Spell.cpp
// Fill out your copyright notice in the Description page of Project Settings.
#include "RobotRebellion.h"
#include "Spell.h"
#include "../../Tool/UtilitaryFunctionLibrary.h"
#include "Gameplay/Spell/Effects/Effect.h"
#include "Character/RobotRebellionCharacter.h"
USpell::USpell()
{
PrimaryComponentTick.bCanEverTick = true;
bReplicates = true;
}
void USpell::BeginPlay()
{
Super::BeginPlay();
}
void USpell::TickComponent(float DeltaTime, enum ELevelTick TickType, FActorComponentTickFunction *ThisTickFunction)
{
if(GetOwner()->Role == ROLE_Authority)
{
if(!canCast())
{
m_currentCooldown = m_nextAllowedCastTimer - FPlatformTime::Seconds();
}
else
{
m_currentCooldown = -1.f;
}
}
}
void USpell::GetLifetimeReplicatedProps(TArray< FLifetimeProperty > & OutLifetimeProps) const
{
Super::GetLifetimeReplicatedProps(OutLifetimeProps);
DOREPLIFETIME_CONDITION(USpell, m_currentCooldown, COND_OwnerOnly);
}
void USpell::cast()
{}
void USpell::initializeSpell()
{
for(int i = 0; i < m_effectsClass.Num(); ++i)
{
UEffect* tempEffect;
tempEffect = NewObject<UEffect>(this, m_effectsClass[i]);
if(tempEffect)
{
m_effects.Emplace(tempEffect);
}
}
this->RegisterComponent();
}
bool USpell::canCast() const
{
return (FPlatformTime::Seconds() > m_nextAllowedCastTimer)
&& Cast<ARobotRebellionCharacter>(GetOwner())->getMana() >= m_manaCost;
}
float USpell::getCurrentCooldown() const
{
return m_currentCooldown;
}<file_sep>/Source/RobotRebellion/Gameplay/Weapon/FireProjectile.h
// Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "Gameplay/Weapon/Projectile.h"
#include "FireProjectile.generated.h"
/**
*
*/
UCLASS(Blueprintable)
class ROBOTREBELLION_API AFireProjectile : public AProjectile
{
GENERATED_BODY()
public:
UPROPERTY(EditAnywhere, BlueprintReadWrite,Category="Projectile Settings")
float m_baseDamage;
AFireProjectile();
virtual void BeginPlay();
virtual void Tick(float DeltaTime);
UFUNCTION()
virtual void OnHit(class UPrimitiveComponent* ThisComp, class AActor* OtherActor, class UPrimitiveComponent*
OtherComp, FVector NormalImpulse, const FHitResult& Hit) override;
};
<file_sep>/Source/RobotRebellion/IA/Controller/DroneAIController.h
// Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "CustomAIControllerBase.h"
#include "DroneAIController.generated.h"
DECLARE_LOG_CATEGORY_EXTERN(DroneLog, Log, All);
UENUM(BlueprintType)
enum AIDroneState
{
DRONE_WAITING,
DRONE_MOVING,
DRONE_COMBAT,
DRONE_RECHARGE,
DRONE_ACTION_COUNT
};
typedef TPair<AIDroneState, float> ActionScore;
/**
*
*/
UCLASS()
class ROBOTREBELLION_API ADroneAIController : public ACustomAIControllerBase
{
GENERATED_BODY()
private:
/************************************************************************/
/* PROPERTY */
/************************************************************************/
int32 m_alliesAliveCount;
int32 m_alliesInScene;
FVector m_groupBarycenter;
int32 m_ennemyNear;
int32 m_ennemyInScene;
FVector m_ennemyNearBarycenter;
//the height the drone must be
float m_targetedHeight;
//the current time
float m_currentTime;
float m_debugCooldownDisplayTime;
bool m_isDebugEnabled;
//Position to follow
FVector m_destination;
//SafeZone
FVector m_safeZone;
class AKing* m_king;
float m_coeffKing;
void(ADroneAIController::* m_performAction)();
bool m_actionFinished;
AIDroneState m_state;
float m_idleTimer;
bool m_canDropBomb;
TArray<class ARobotRebellionCharacter*> m_sensedEnnemies;
TArray<class ARobotRebellionCharacter*> m_attackZoneCharacters;
FVector4 m_bestBombLocation;
public:
/************************************************************************/
/* UPROPERTY */
/************************************************************************/
//If problem arise (Controller spawns before drone), it will be at this position the drone will be spawned
//Please, update this according to the real drone position on the map.
UPROPERTY(EditDefaultsOnly, BlueprintReadWrite, Category = "AGeneral")
FVector m_defaultDroneSpawnPositionIfProblem;
//Deceleration Coefficient. Higher the value, faster the drone will arrive to its target and more rough the stop will be.
//Beware, a too high value will cause instability.
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "AGeneral")
float m_droneVelocity;
//Elevation relative to its target
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "AGeneral")
float m_stationaryElevation;
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "AGeneral")
float m_detectionDistance;
/** Max time for reload action*/
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Update Time")
float m_updateSafeZoneCooldownTime;
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "safeZone")
float m_safeZoneSize;
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "safeZone")
float m_reloadHeight;
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Utility Theory")
float m_waitingThreshold;
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Utility Theory")
float m_epsilonSquaredDistanceTolerance;
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Utility Theory")
float m_cooldown;
UPROPERTY(EditDefaultsOnly, BlueprintReadWrite, Category = "Move")
class USplineComponent* m_splinePath;
/** Specify if the path is showed on screen*/
UPROPERTY(EditDefaultsOnly, BlueprintReadWrite, Category = DebugParameter)
bool m_showOriginPath;
UPROPERTY(EditDefaultsOnly, BlueprintReadWrite, Category = DebugParameter)
bool m_showSmoothedPath;
UPROPERTY(EditDefaultsOnly, BlueprintReadWrite, Category = DebugParameter)
bool m_showFinalPath;
UPROPERTY(EditDefaultsOnly, BlueprintReadWrite, Category = DebugParameter)
bool m_showDestination;
UPROPERTY(EditDefaultsOnly, BlueprintReadWrite, Category = "Move", meta = (ClampMin = 0.f, ClampMax = 1.f))
float m_splineTension;
UPROPERTY(EditDefaultsOnly, BlueprintReadWrite, Category = "Move", meta = (ClampMin = 2))
int32 m_splinePointCountIntraSegment;
//Noisy travel random value used to modify travel point (to make it more drone like).
//0.f means no noisy travel method
UPROPERTY(EditDefaultsOnly, BlueprintReadWrite, Category = "Move", meta = (ClampMin = 0.f))
float m_noisyTravelRandom;
UPROPERTY(EditDefaultsOnly, BlueprintReadWrite, Category = "Move", meta = (ClampMin = 0.f, ClampMax = 3.14159f))
float m_idleAngle;
UPROPERTY(EditDefaultsOnly, BlueprintReadWrite, Category = "Move", meta = (ClampMin = 0.0001f, ClampMax = 1.f))
float m_idleAngleSpeed;
UPROPERTY(EditDefaultsOnly, BlueprintReadWrite, Category = "Move", meta = (ClampMin = 0.f))
float m_idleTranslationSpeed;
UPROPERTY(EditDefaultsOnly, BlueprintReadWrite, Category = "Move", meta = (ClampMin = 0.f))
float m_idleTranslationGain;
//acceleration between 0 percent and m_accelPercentPath. Beyond, the drone is at its travel speed.
//decceleration is the mirror of acceleration.
//Thus :
//- acceleration between 0% and m_accelPercentPath
//- travel speed between m_accelPercentPath and 1.f - m_accelPercentPath
//- decceleration between 1.f - m_accelPercentPath and 100%
UPROPERTY(EditDefaultsOnly, BlueprintReadWrite, Category = "Move", meta = (ClampMin = 0.f, ClampMax = 0.5f))
float m_accelPercentPath;
UPROPERTY(EditDefaultsOnly, BlueprintReadWrite, Category = "Move", meta = (ClampMin = 0.f))
float m_idleRotationResetTime;
private:
TArray<FVector> m_path;
TArray<FVector> m_smoothedPath;
TArray<FVector> m_finalPath;
float m_timeSinceLastUpdate;
int32 m_currentTripPoint;
float m_totalTripPoint;
float m_deccelPercentPath;
float m_deccelerationCoefficient;
FVector m_realDroneOrient;
FVector m_idleForwardGoal;
FVector m_idleTranslationDirection;
float m_timeIdleRotationMove;
private:
void internalNoisyTravelTransfertMethod(FVector& inOutPoint, const FVector& nextPoint);
void internalMakeIdleRotation();
void internalMakeIdleTranslation();
void resetTripPoint();
public:
/************************************************************************/
/* METHODS */
/************************************************************************/
ADroneAIController();
virtual void BeginPlay() override;
virtual void Tick(float deltaTime) override;
void updateFrameProperties(float deltaTime);
void updateEnnemiesCampInfo();
void updateAlliesCampInfo();
void resetIdleRotationGoal();
void resetIdleTranslationGoal();
void saveDroneLocalization();
EPathFollowingRequestResult::Type stopDroneMoves(class ADrone* drone);
virtual EPathFollowingRequestResult::Type MoveToTarget() override;
void makeIdleMove();
void findDropZone();
UFUNCTION(BlueprintCallable, Category = "Utility Theory Debug")
float getAttackScore();
UFUNCTION(BlueprintCallable, Category = "Utility Theory Debug")
float getFollowScore();
UFUNCTION(BlueprintCallable, Category = "Utility Theory Debug")
float getReloadScore();
UFUNCTION(BlueprintCallable, Category = "Utility Theory Debug")
float getWaitingScore();
UFUNCTION(BlueprintCallable, Category = "Utility Theory Debug")
float getDropScore();
bool HasABomb();
UFUNCTION()
void receiveBomb();
UFUNCTION(Reliable, Server, WithValidation)
void serverReceiveBomb();
/*Main IA methods*/
//update the properties of the drone
void IAUpdate(float deltaTime);
//The IA Loop
void IALoop(float deltaTime);
/*Intermediary IA Methods*/
void setDestination(const FVector& newDestinationPosition);
FORCEINLINE bool isArrivedAtDestination() const
{
return (m_destination - GetPawn()->GetActorLocation()).SizeSquared() < m_epsilonSquaredDistanceTolerance;
}
FORCEINLINE float getTravelCompletionPercentage() const
{
return static_cast<float>(m_currentTripPoint) / m_totalTripPoint;
}
//update the targeted height of the drone
void updateTargetedHeight() USE_NOEXCEPT;
void followKing();
void followGroup();
void followFireZone();
void followSafeZone();
void waiting();
void setFollowGroup();
void setFollowKing();
void setFollowFireZone();
void setFollowSafeZone();
void setWaiting();
void chooseNextAction();
void dropBomb();
virtual void CheckEnnemyNear(float range);
void CheckEnnemyNearPosition(const FVector& position, float range);
int getNbBombPlayers();
float getBombScore(const FVector& position);
bool isInCombat();
int getNbEnnemiesInZone(const FVector& zoneCenter);
FVector findSafeZone();
FORCEINLINE void enableDroneDisplay(bool enable)
{
m_isDebugEnabled = enable;
}
FORCEINLINE bool isDebugEnabled()
{
return m_isDebugEnabled;
}
FORCEINLINE const FVector& getAllyBarycenter() const USE_NOEXCEPT
{
return m_groupBarycenter;
}
FORCEINLINE const FVector& getEnnemyBarycenter() const USE_NOEXCEPT
{
return m_ennemyNearBarycenter;
}
void clearSplinePath();
/*
Update the spline path using the point array containing all passage point.
Tension must be between 0.f and 1.f and control the bending strength of the curve.
*/
void updateSplinePath(float tension);
// Draw the path on screen
void debugDrawPath() const;
void debugElementaryDrawPath(const TArray<FVector>& pathToDraw, const FColor& lineColor) const;
// Smooth the path, make it more optimal and more realistic
void smoothPath();
// See if the agent can go from one point to another
bool testFlyFromTo(const FVector& startPoint, const FVector& endPoint);
void processPath();
bool isLocationFree(const FVector& loc);
void splineForecast();
};
<file_sep>/Source/RobotRebellion/IA/Navigation/VolumeIdProvider.h
#pragma once
#include "../../Tool/IsSingleton.h"
/**
*
*/
class ROBOTREBELLION_API VolumeIdProvider : private IsSingleton<VolumeIdProvider>
{
GENERATED_USING_FROM_IsSingleton(VolumeIdProvider);
private:
int m_count;
VolumeIdProvider() : m_count{}
{}
public:
~VolumeIdProvider()
{
reset();
}
int getNextId()
{
// we need to start at 0
int returnValue = m_count++;
return returnValue;
}
void reset()
{
m_count = 0;
}
};<file_sep>/Source/RobotRebellion/Gameplay/Spell/Effects/InvisibilityEffect.cpp
// Fill out your copyright notice in the Description page of Project Settings.
#include "RobotRebellion.h"
#include "InvisibilityEffect.h"
#include "Character/RobotRebellionCharacter.h"
void UInvisibilityEffect::BeginPlay()
{
Super::BeginPlay();
}
void UInvisibilityEffect::TickComponent(float DeltaTime, ELevelTick TickType, FActorComponentTickFunction* ThisTickFunction)
{
Super::TickComponent(DeltaTime, TickType, ThisTickFunction);
}
void UInvisibilityEffect::exec(ARobotRebellionCharacter* caster, ARobotRebellionCharacter* target)
{
caster->inflictInvisibility();
}
void UInvisibilityEffect::exec(const FVector& impactPoint, ARobotRebellionCharacter* caster)
{
}
<file_sep>/Source/RobotRebellion/Gameplay/Weapon/Kaboom.h
// Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "GameFramework/Actor.h"
#include "Kaboom.generated.h"
/**
*
*/
UCLASS()
class ROBOTREBELLION_API AKaboom : public AActor
{
GENERATED_BODY()
public:
UPROPERTY(VisibleDefaultsOnly, Category = "Bomb Attribute")
USphereComponent* m_collisionComp;
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Charge")
class UStaticMeshComponent* m_kaboomMesh;
UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = Movement)
UProjectileMovementComponent* m_kaboomMovement;
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Effect")
class UParticleSystemComponent* m_explosionPCS;
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Effect")
FVector m_explosionEffectScale;
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Bomb Attribute", meta = (ClampMin = 0.f))
float m_baseDamage;
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Bomb Attribute", meta = (ClampMin = 0.f))
float m_detonationRadius;
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = Sound)
USoundCue* m_boomSound;
protected:
class ADrone* m_linkedDrone;
TArray<TEnumAsByte<EObjectTypeQuery>> m_objectTypesToConsider;
void (AKaboom::* m_activeBoomMethod)();
void (AKaboom::* m_destroyMethod)();
public:
AKaboom();
virtual ~AKaboom() = default;
virtual void BeginPlay() override;
virtual void Tick(float deltaTime) override;
FORCEINLINE UFUNCTION(BlueprintCallable, Category = "Action")
void activateBomb()
{
m_activeBoomMethod = &AKaboom::detonationImplementation;
}
FORCEINLINE UFUNCTION(BlueprintCallable, Category = "Action")
void deactivateBomb()
{
m_activeBoomMethod = &AKaboom::noMethod;
}
UFUNCTION(BlueprintCallable, Category = "Action")
FORCEINLINE bool isActivated() const USE_NOEXCEPT
{
return m_activeBoomMethod == &AKaboom::detonationImplementation;
}
UFUNCTION(BlueprintCallable, Category = "Action")
void attachToDrone(class ADrone* drone);
UFUNCTION(BlueprintCallable, Category = "Action")
void detachFromDrone();
UFUNCTION()
virtual void onHit(class UPrimitiveComponent* ThisComp, class AActor* OtherActor, class UPrimitiveComponent*
OtherComp, FVector NormalImpulse, const FHitResult& Hit)
{
(this->*m_activeBoomMethod)();
}
UFUNCTION(Reliable, NetMulticast)
void multiExplosionOnEveryone();
protected:
void noMethod() {}
void detonationImplementation();
void realDestroy();
void initializeDamagedObjectList();
void initializeKaboomMovementComponent();
void dropingPhysicSetting(bool reenablePhysic);
};
<file_sep>/README.md
# Robot-Rebellion
Projet fin session DDJV 12e cohorte- Equipe UniReverse
<file_sep>/Source/RobotRebellion/Global/GlobalDamageMethod.h
// Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "Tool/IsSingleton.h"
#include "Gameplay/Damage/Damage.h"
#include "Gameplay/Weapon/WeaponBase.h"
#include "Character/RobotRebellionCharacter.h"
/**
*
*/
class UGlobalDamageMethod
{
public:
static Damage::DamageValue normalHit(const ARobotRebellionCharacter* assailant, const ARobotRebellionCharacter* receiver);
static Damage::DamageValue normalHitWithWeaponComputed(const ARobotRebellionCharacter* assailant, const ARobotRebellionCharacter* receiver);
static Damage::DamageValue droneDamageComputed(const ARobotRebellionCharacter* assailant, const ARobotRebellionCharacter* receiver);
};
<file_sep>/Source/RobotRebellion/Tool/Algorithm.h
// Fill out your copyright notice in the Description page of Project Settings.
#pragma once
/**
* Base Algorithm class
*/
class ROBOTREBELLION_API Algorithm_Base
{
public:
Algorithm_Base() = default;
virtual ~Algorithm_Base() = default;
public:
template<class ReturnType, class ... Args>
ReturnType operator()(Args&& ... args);
};
template<class AlgoritmMethod>
class ROBOTREBELLION_API Algorithm final : public Algorithm_Base
{
private:
AlgoritmMethod m_func;
public:
Algorithm(const AlgoritmMethod& algorithm) :
m_func{ algorithm }
{}
public:
template<class ReturnType, class ... Args>
ReturnType operator()(Args&& ... args)
{
return m_func(std::forward<Args>(args)...);
}
};
<file_sep>/Source/RobotRebellion/IA/BT/DebugBTService.cpp
#include "RobotRebellion.h"
#include "DebugBTService.h"
#include "../Controller/RobotShooterController.h"
UDebugBTService::UDebugBTService()
{
NodeName = "Debug";
// Interval update
Interval = 2.0f;
// Random update deviation for update
RandomDeviation = 0.f;
}
void UDebugBTService::TickNode(UBehaviorTreeComponent & OwnerComp, uint8 * NodeMemory, float DeltaSeconds)
{
Super::TickNode(OwnerComp, NodeMemory, DeltaSeconds);
ARobotShooterController* AIController = Cast<ARobotShooterController>(OwnerComp.GetOwner());
AIController->drawDebug();
}// Fill out your copyright notice in the Description page of Project Settings.
<file_sep>/Source/RobotRebellion/Gameplay/Spell/DashSpell.h
// Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "Gameplay/Spell/Spell.h"
#include "DashSpell.generated.h"
/**
* Similar to the Ray cast spell
* This kind of spell doesnt need to hit object to apply effect
*/
UCLASS()
class ROBOTREBELLION_API UDashSpell : public USpell
{
GENERATED_BODY()
public:
UDashSpell();
virtual void BeginPlay() override;
virtual void cast() override;
// Apply Effects on a target that have to be a RobotRebellion Character
void applyEffect(class ARobotRebellionCharacter* affectedTarget);
// Aplly Effects on a specific location
void applyEffect(FVector impactPoint);
private:
// Return corrected aim direction
FVector getRealAimingVector(const ARobotRebellionCharacter* caster);
// Check if the caster can be placed at the end point may modify dashEndPoint to fill
// return false if its impossible to reach the end point for the caster.
bool computeDashHeight(FVector& dashEndPoint, const ARobotRebellionCharacter* caster);
};
<file_sep>/Source/RobotRebellion/UI/GameMenu.h
// Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "GameFramework/HUD.h"
#include "LobbyUIWidget.h"
#include "ReviveTimerWidget.h"
#include "CustomRobotRebellionUserWidget.h"
#include "RobotRebellionWidget.h"
#include "TopWidget.h"
#include "OptionsMenuWidget.h"
#include "GameMenu.generated.h"
/**
*
*/
UCLASS()
class ROBOTREBELLION_API AGameMenu : public AHUD
{
GENERATED_BODY()
public:
AGameMenu();
virtual void BeginPlay() override;
virtual void Tick(float deltaTime) override;
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Widget | Top Game Menu")
TSubclassOf<UTopWidget> TopWidget;
UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, Category = "Widget | Top Game Menu")
UTopWidget* TopWidgetImpl;
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Widget | UI Game Menu Lobby")
TSubclassOf<ULobbyUIWidget> LobbyWidget;
ULobbyUIWidget* LobbyImpl;
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Widget | HUD Character")
TSubclassOf<UCustomRobotRebellionUserWidget> HUDCharacterWidget;
UCustomRobotRebellionUserWidget* HUDCharacterImpl;
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Widget | Revive Timer")
TSubclassOf<UReviveTimerWidget> ReviveWidget;
UReviveTimerWidget* ReviveTimerWidgetImpl;
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Widget | Classes Selection")
TSubclassOf<URobotRebellionWidget> ClassSelectionWidget;
UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, Category = "Widget | Classes Selection")
URobotRebellionWidget* ClassSelectionWidgetImpl;
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Widget | Options Menu")
TSubclassOf<UOptionsMenuWidget> OptionsWidget;
UOptionsMenuWidget* OptionsWidgetImpl;
//TODO OPTIONS MENU
template <class T>
T* CreateCustomWidget(T *Widget)
{
if(Widget)
{
T* WidgetToImp = CreateWidget<T>(GetWorld(), Widget->GetClass());
/** Make sure widget was created */
if(WidgetToImp)
{
/** Add it to the viewport */
WidgetToImp->AddToViewport();
return WidgetToImp;
}
}
return nullptr;
}
template <class T>
void RemoveWidget(T *WidgetRef)
{
if(WidgetRef->IsInViewport())
{
WidgetRef->RemoveFromParent();
}
}
UFUNCTION(BlueprintCallable, Category = HUD)
void DisplayWidget(URobotRebellionWidget* WidgetRef);
UFUNCTION(BlueprintCallable, Category = HUD)
void HideWidget(URobotRebellionWidget* WidgetRef);
UFUNCTION(BlueprintNativeEvent, Category = "Methods")
void firstCallHUD();
};
<file_sep>/Source/RobotRebellion/Gameplay/TriggerBox/BossActivateTriggerBox.cpp
// Fill out your copyright notice in the Description page of Project Settings.
#include "RobotRebellion.h"
#include "BossActivateTriggerBox.h"
ABossActivateTriggerBox::ABossActivateTriggerBox()
{
GetCollisionComponent()->OnComponentHit.AddDynamic(this, &ABossActivateTriggerBox::onHit);
}
void ABossActivateTriggerBox::BeginPlay()
{
Super::BeginPlay();
}
void ABossActivateTriggerBox::onHit(UPrimitiveComponent* var1, AActor* var2, UPrimitiveComponent* var3, FVector var4, const FHitResult& var5)
{
PRINT_MESSAGE_ON_SCREEN_UNCHECKED(FColor::Red, "COLLISION, BOSS SOUND ACTIVATED");
UWorld* w = this->GetWorld();
TArray<AActor*> entity;
UGameplayStatics::GetAllActorsOfClass(w, AWorldInstanceEntity::StaticClass(), entity);
if(entity.Num() > 0)
{
Cast<AWorldInstanceEntity>(entity[0])->setBossGameMode();
}
this->killItself();
}
void ABossActivateTriggerBox::correctDestruction()
{
this->Destroy(true);
}
void ABossActivateTriggerBox::killItself()
{
if (Role < ROLE_Authority)
{
this->serverKills();
}
else
{
this->multiKills();
}
this->correctDestruction();
}
void ABossActivateTriggerBox::serverKills_Implementation()
{
this->multiKills();
this->correctDestruction();
}
bool ABossActivateTriggerBox::serverKills_Validate()
{
return true;
}
void ABossActivateTriggerBox::multiKills_Implementation()
{
this->correctDestruction();
}
<file_sep>/Source/RobotRebellion/Gameplay/Spell/SelfSpell.h
// Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "Gameplay/Spell/Spell.h"
#include "SelfSpell.generated.h"
/**
*
*/
UCLASS()
class ROBOTREBELLION_API USelfSpell : public USpell
{
GENERATED_BODY()
public:
USelfSpell();
virtual void BeginPlay() override;
virtual void cast() override;
// Call by the projectile once it hit smth
void onHit(class UPrimitiveComponent*, class AActor*, class UPrimitiveComponent*, FVector, const FHitResult&)
{}
// Apply Effects on a target that have to be a RobotRebellion Character
void applyEffect(class ARobotRebellionCharacter* affectedTarget);
// Aplly Effects on a specific location
void applyEffect(FVector impactPoint)
{}
};
<file_sep>/Source/RobotRebellion/Gameplay/Spell/Effects/Effect.cpp
// Fill out your copyright notice in the Description page of Project Settings.
#include "RobotRebellion.h"
#include "Effect.h"
// Sets default values for this component's properties
UEffect::UEffect()
{
// Set this component to be initialized when the game starts, and to be ticked every frame. You can turn these features
// off to improve performance if you don't need them.
PrimaryComponentTick.bCanEverTick = true;
}
// Called when the game starts
void UEffect::BeginPlay()
{
Super::BeginPlay();
}
// Called every frame
void UEffect::TickComponent( float DeltaTime, ELevelTick TickType, FActorComponentTickFunction* ThisTickFunction )
{
Super::TickComponent( DeltaTime, TickType, ThisTickFunction );
}<file_sep>/Source/RobotRebellion/Gameplay/Damage/Damage.h
// Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "../Tool/Algorithm.h"
#include <Runtime/Core/Public/Math/UnrealMathUtility.h>
/**
*
*/
class DamageHelperConstants
{
public:
static constexpr const float RANDOM_MIN_COEFFICIENT = 0.8f;
static constexpr const float RANDOM_MAX_COEFFICIENT = 1.2f;
};
class ARobotRebellionCharacter;
class ROBOTREBELLION_API Damage
{
public:
using CoefficientType = float;
using DamageValue = unsigned int;
private:
const ARobotRebellionCharacter* m_assailant;
const ARobotRebellionCharacter* m_receiver;
public:
Damage(const ARobotRebellionCharacter*const m_assailant, const ARobotRebellionCharacter*const m_receiver);
~Damage();
public:
template<class Func>
DamageValue operator()(const Func& algorithm, CoefficientType damageCoefficient) const
{
Algorithm<Func> alg{ algorithm };
return
damageCoefficient *
FMath::FRandRange(
DamageHelperConstants::RANDOM_MIN_COEFFICIENT,
DamageHelperConstants::RANDOM_MAX_COEFFICIENT
) * alg.operator()<DamageValue>(m_assailant, m_receiver);
}
};
<file_sep>/Source/RobotRebellion/Gameplay/Weapon/WeaponBase.cpp
// Fill out your copyright notice in the Description page of Project Settings.
#include "RobotRebellion.h"
#include "WeaponBase.h"
#include "Engine/World.h"
UWeaponBase::UWeaponBase() :
m_weaponDamageCoefficient{ 1.f },
m_weaponBaseDamage{ 0.f },
m_weaponBaseCadence{ 1.f },
m_nextAllowedAttackTimer{ 0.0 },
m_WeaponRadiusRange{ 700.0 }
{
bReplicates = true;
}
void UWeaponBase::GetLifetimeReplicatedProps(TArray<FLifetimeProperty>& OutLifetimeProps) const
{
Super::GetLifetimeReplicatedProps(OutLifetimeProps);
}
bool UWeaponBase::canAttack() const USE_NOEXCEPT
{
return FPlatformTime::Seconds() > m_nextAllowedAttackTimer;
}
void UWeaponBase::reload()
{
m_nextAllowedAttackTimer = FPlatformTime::Seconds() + m_weaponBaseCadence;
}
FString UWeaponBase::toDebugFString() const USE_NOEXCEPT
{
return TEXT("Damage coefficient multiplier : ") +
FString::FromInt(m_weaponDamageCoefficient) +
TEXT("weapon base damage : ") +
FString::FromInt(m_weaponBaseDamage);
}
FString UWeaponBase::rangeToFString() const USE_NOEXCEPT
{
return "Invalid weapon";
}<file_sep>/Source/RobotRebellion/Gameplay/Debug/RobotRobellionSpawnerClass.cpp
// Fill out your copyright notice in the Description page of Project Settings.
#include "RobotRebellion.h"
#include "RobotRobellionSpawnerClass.h"
#include "Character/PlayableCharacter.h"
#include "Character/Assassin.h"
#include "Character/Wizard.h"
#include "Character/Healer.h"
#include "Character/Soldier.h"
// Sets default values for this component's properties
URobotRobellionSpawnerClass::URobotRobellionSpawnerClass()
{
// Set this component to be initialized when the game starts, and to be ticked every frame. You can turn these features
// off to improve performance if you don't need them.
PrimaryComponentTick.bCanEverTick = false;
// ...
}
// Called when the game starts
void URobotRobellionSpawnerClass::BeginPlay()
{
Super::BeginPlay();
// ...
}
// Called every frame
void URobotRobellionSpawnerClass::TickComponent(float DeltaTime, ELevelTick TickType, FActorComponentTickFunction* ThisTickFunction)
{
Super::TickComponent(DeltaTime, TickType, ThisTickFunction);
// ...
}
void URobotRobellionSpawnerClass::spawnAndReplace(APlayableCharacter* owner, EClassType typeToChange)
{
// update HUD no matter the role
owner->updateHUD(typeToChange);
if(owner->Role < ROLE_Authority)
{
serverSpawnAndReplace(owner, typeToChange);
}
else if(typeToChange != owner->getType()) //already the same, does nothing
{
UWorld* const world = owner->GetWorld();
if(world)
{
FActorSpawnParameters spawnParams;
spawnParams.Owner = owner->GetOwner();
spawnParams.Instigator = owner->Instigator;
spawnParams.SpawnCollisionHandlingOverride = ESpawnActorCollisionHandlingMethod::AlwaysSpawn;
APlayableCharacter* intermediary;
FTransform spawnTransform{
FRotator{0.f,0.f,0.f},
owner->GetActorLocation(),
owner->GetActorScale3D()
};
switch(typeToChange)
{
case EClassType::ASSASSIN:
{
intermediary = world->SpawnActor<AAssassin>(m_assassinActor, spawnTransform, spawnParams);
}
break;
case EClassType::HEALER:
{
intermediary = world->SpawnActor<AHealer>(m_healerActor, spawnTransform, spawnParams);
}
break;
case EClassType::SOLDIER:
{
intermediary = world->SpawnActor<ASoldier>(m_soldierActor, spawnTransform, spawnParams);
}
break;
case EClassType::WIZARD:
{
intermediary = world->SpawnActor<AWizard>(m_wizardActor, spawnTransform, spawnParams);
}
break;
default:
return;
}
owner->Controller->Possess(intermediary);
owner->Destroy();
if(intermediary)
{
intermediary->createTextBillboardWithThisCamera(intermediary->FollowCamera);
intermediary->updateAllCharacterBillboard(intermediary->FollowCamera);
}
PRINT_MESSAGE_ON_SCREEN_UNCHECKED(FColor::Black, "Spawn");
}
}
}
void URobotRobellionSpawnerClass::serverSpawnAndReplace_Implementation(APlayableCharacter* owner, EClassType typeToChange)
{
spawnAndReplace(owner, typeToChange);
}
bool URobotRobellionSpawnerClass::serverSpawnAndReplace_Validate(APlayableCharacter* owner, EClassType typeToChange)
{
return true;
}<file_sep>/Source/RobotRebellion/Gameplay/Alteration/AlterationBase.cpp
// Fill out your copyright notice in the Description page of Project Settings.
#include "RobotRebellion.h"
#include "AlterationBase.h"
// Sets default values for this component's properties
UAlterationBase::UAlterationBase()
{
// Set this component to be initialized when the game starts, and to be ticked every frame. You can turn these features
// off to improve performance if you don't need them.
PrimaryComponentTick.bCanEverTick = false;
// ...
}
void UAlterationBase::update(float deltaTime)
{
m_currentTime += deltaTime;
if (m_currentTime > m_lifeTime)
{
destroyItself();
}
}
void UAlterationBase::destroyItself()
{
this->DestroyComponent();
}
<file_sep>/Source/RobotRebellion/Gameplay/Spell/Effects/RestoreManaEffect.cpp
// Fill out your copyright notice in the Description page of Project Settings.
#include "RobotRebellion.h"
#include "RestoreManaEffect.h"
#include "Character/RobotRebellionCharacter.h"
void URestoreManaEffect::BeginPlay()
{
Super::BeginPlay();
}
void URestoreManaEffect::TickComponent(float DeltaTime, ELevelTick TickType, FActorComponentTickFunction* ThisTickFunction)
{
Super::TickComponent(DeltaTime, TickType, ThisTickFunction);
}
void URestoreManaEffect::exec(ARobotRebellionCharacter* caster, ARobotRebellionCharacter* target)
{
target->restoreMana(m_manaGiven);
target->spawnManaParticle();
}
void URestoreManaEffect::exec(const FVector& impactPoint, ARobotRebellionCharacter* caster)
{
TArray<TEnumAsByte<EObjectTypeQuery>> ObjectTypes;
ObjectTypes.Add(UEngineTypes::ConvertToObjectType(ECC_GameTraceChannel2)); // Players
ObjectTypes.Add(UEngineTypes::ConvertToObjectType(ECC_GameTraceChannel3)); // Robots
ObjectTypes.Add(UEngineTypes::ConvertToObjectType(ECC_GameTraceChannel4)); // Sovec
ObjectTypes.Add(UEngineTypes::ConvertToObjectType(ECC_GameTraceChannel6)); // Beast
TArray<AActor*> ActorsToIgnore{};
TArray<FHitResult> hitActors;
bool Result = UKismetSystemLibrary::SphereTraceMultiForObjects(GetWorld(),
impactPoint,
impactPoint,
m_zoneRadius,
ObjectTypes,
false,
ActorsToIgnore,
SPHERECAST_DISPLAY_DURATION,
hitActors,
true);
PRINT_MESSAGE_ON_SCREEN_UNCHECKED(FColor::Blue, "Restore mana on : " + FString::FromInt(hitActors.Num()) + " actors");
for(FHitResult& currentHit : hitActors)
{
ARobotRebellionCharacter* temp = Cast<ARobotRebellionCharacter>(currentHit.GetActor());
if(temp)
{
temp->restoreMana(m_manaGiven);
}
}
}
<file_sep>/Source/RobotRebellion/Gameplay/Alteration/InvisibilityAlteration.cpp
// Fill out your copyright notice in the Description page of Project Settings.
#include "RobotRebellion.h"
#include "InvisibilityAlteration.h"
#include "Character/NonPlayableCharacter.h"
#include "Character/PlayableCharacter.h"
UInvisibilityAlteration::UInvisibilityAlteration() :
UAlterationBase()
{
m_id = IdentifiableObject<UInvisibilityAlteration>::ID;
}
void UInvisibilityAlteration::destroyItself()
{
m_alteredOwner->setInvisible(false);
this->DestroyComponent();
}
void UInvisibilityAlteration::onCreate(ARobotRebellionCharacter* alteredOwner)
{
m_alteredOwner = alteredOwner;
alteredOwner->setInvisible(true);
}
<file_sep>/Source/RobotRebellion/Gameplay/TriggerBox/KingActivateTriggerBox.h
// Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "Engine/TriggerBox.h"
#include "KingActivateTriggerBox.generated.h"
/**
*
*/
UCLASS()
class ROBOTREBELLION_API AKingActivateTriggerBox : public ATriggerBox
{
GENERATED_BODY()
public:
AKingActivateTriggerBox();
virtual void BeginPlay() override;
UFUNCTION()
void onEnter(UPrimitiveComponent* var1, AActor* enteredActor, UPrimitiveComponent* var3, int32 var4, bool var5, const FHitResult& var6);
private:
void internal_signalToServer();
void correctDestruction();
void killItself();
UFUNCTION(Reliable, Server, WithValidation)
void serverKills();
UFUNCTION(Reliable, NetMulticast)
void multiKills();
UFUNCTION(Reliable, Server, WithValidation)
void signalToServer();
};
<file_sep>/Source/RobotRebellion/Gameplay/Weapon/WizardMeteor.h
// Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "GameFramework/Actor.h"
#include "WizardMeteor.generated.h"
/*
* Actor invoke by wizard Ultimate, it must have lifespan
* once the end of lifespan is reach it destroye him self and deals damage to every character hit
*/
UCLASS()
class ROBOTREBELLION_API AWizardMeteor : public AActor
{
GENERATED_BODY()
private:
class ARobotRebellionCharacter* m_caster;
public:
/** Movement component */
UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = Movement)
UProjectileMovementComponent* m_projectileMovement;
/** How many damage will be made (won't be reduced) */
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Explosion Properties")
float m_unreducedDamage;
/** Explosion radius */
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Explosion Properties")
float m_explosionRadius;
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Explosion Effect")
UParticleSystem* m_explosionEffect;
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Explosion Effect")
UParticleSystemComponent* m_explosionEffectComp;
public:
// Sets default values for this actor's properties
AWizardMeteor();
// Called when the game starts or when spawned
virtual void BeginPlay() override;
// Called every frame
virtual void Tick( float DeltaSeconds ) override;
// Set the caster
void setCaster(ARobotRebellionCharacter* p);
// Replication method
// void GetLifetimeReplicatedProps(TArray< FLifetimeProperty > & OutLifetimeProps) const override;
private:
// Inflict damage then destroye it self
void explode();
void spawnEffect();
UFUNCTION(Reliable, NetMulticast, WithValidation)
void multiSpawnEffect(FVector location);
};
<file_sep>/Source/RobotRebellion/UI/SessionWidget.cpp
// Fill out your copyright notice in the Description page of Project Settings.
#include "RobotRebellion.h"
#include "LobbyUIWidget.h"
#include "SessionWidget.h"
void USessionWidget::initialiseWidget(int index, ULobbyUIWidget* parent)
{
m_index = index;
m_parentWidget = parent;
}
void USessionWidget::setSelected(bool selected)
{
UWidget *widgetButton = GetWidgetFromName("SessionButtonBackground");
widgetButton->SetIsEnabled(!selected);
}
void USessionWidget::OnClicked()
{
PRINT_MESSAGE_ON_SCREEN(FColor::Cyan, TEXT("Try selected session : " + FString::FromInt(m_index)));
m_parentWidget->setSelectedSession(m_index);
//this->SetIsEnabled(false);
}
<file_sep>/Source/RobotRebellion/Gameplay/Spell/SphereCastSpell.cpp
// Fill out your copyright notice in the Description page of Project Settings.
#include "RobotRebellion.h"
#include "SphereCastSpell.h"
#include "Character/RobotRebellionCharacter.h"
USphereCastSpell::USphereCastSpell() : USpell()
{}
void USphereCastSpell::BeginPlay()
{
Super::BeginPlay();
}
void USphereCastSpell::cast()
{
if(m_useEffect)
{
PRINT_MESSAGE_ON_SCREEN_UNCHECKED(FColor::Emerald, "use effect");
}
else
{
PRINT_MESSAGE_ON_SCREEN_UNCHECKED(FColor::Emerald, "dont use effect");
}
if(!canCast())
{
PRINT_MESSAGE_ON_SCREEN(FColor::Emerald,
"Cooldown : " + FString::FromInt(m_nextAllowedCastTimer - FPlatformTime::Seconds()));
return;
}
ARobotRebellionCharacter* caster = Cast<ARobotRebellionCharacter>(GetOwner());
if(caster)
{
// Get player location and where hes looking
FVector cameraLocation;
FRotator muzzleRotation;
caster->GetActorEyesViewPoint(cameraLocation, muzzleRotation);
// Initialize Location & aim direction
FVector aimDir = getRealAimingVector(caster);
FVector baseEyeHeight = FVector(0.f, 0.f, caster->BaseEyeHeight);
FVector endLocation = caster->GetActorLocation() + (aimDir * m_range) + baseEyeHeight;
FVector startLocation = caster->GetActorLocation() + baseEyeHeight;
// offset start location to fit with camera hight
startLocation.Z = cameraLocation.Z;
// proceed sphere cast
TArray<TEnumAsByte<EObjectTypeQuery>> ObjectTypes;
ObjectTypes.Add(UEngineTypes::ConvertToObjectType(ECC_GameTraceChannel2)); // Players
ObjectTypes.Add(UEngineTypes::ConvertToObjectType(ECC_GameTraceChannel3)); // Robots
ObjectTypes.Add(UEngineTypes::ConvertToObjectType(ECC_GameTraceChannel4)); // Sovec
ObjectTypes.Add(UEngineTypes::ConvertToObjectType(ECC_GameTraceChannel6)); // Beast
TArray<AActor*> ActorsToIgnore;
ActorsToIgnore.Add(caster);
TArray<FHitResult> hitActors;
bool Result = UKismetSystemLibrary::SphereTraceMultiForObjects(GetWorld(),
startLocation,
endLocation,
m_sphereRadius,
ObjectTypes,
false,
ActorsToIgnore,
EDrawDebugTrace::None,
hitActors,
true);
for(FHitResult& currentHit : hitActors)
{
ARobotRebellionCharacter* tempCharacter = Cast<ARobotRebellionCharacter>(currentHit.GetActor());
if(tempCharacter)
{
applyEffect(tempCharacter);
}
}
// the spell is successfully cast consumme mana and launch CD
if(m_useEffect)
{
AActor* temp = GetWorld()->SpawnActor<AActor>(m_effectActor, startLocation + m_offset * aimDir, aimDir.Rotation());
}
caster->consumeMana(m_manaCost);
m_nextAllowedCastTimer = FPlatformTime::Seconds() + m_cooldown;
}
}
void USphereCastSpell::applyEffect(ARobotRebellionCharacter* affectedTarget)
{
PRINT_MESSAGE_ON_SCREEN(FColor::Emerald, TEXT("ApplicateEffect on target"));
for(int i = 0; i < m_effects.Num(); ++i)
{
m_effects[i]->exec(Cast<ARobotRebellionCharacter>(GetOwner()), affectedTarget);
}
}
void USphereCastSpell::applyEffect(FVector impactPoint)
{
PRINT_MESSAGE_ON_SCREEN(FColor::Emerald, TEXT("ApplicateEffect on point"));
for(int i = 0; i < m_effects.Num(); ++i)
{
m_effects[i]->exec(impactPoint);
}
}
FVector USphereCastSpell::getRealAimingVector(const ARobotRebellionCharacter* caster)
{
APlayerController* playerController = Cast<APlayerController>(caster->Controller);
if(playerController)
{
FVector CamLoc;
FRotator CamRot;
playerController->GetPlayerViewPoint(CamLoc, CamRot);
return CamRot.Vector();
}
else if(caster->Instigator)
{
return caster->GetBaseAimRotation().Vector();
}
return FVector::ZeroVector;
}
<file_sep>/Source/RobotRebellion/Gameplay/Item/Focusable.cpp
// Fill out your copyright notice in the Description page of Project Settings.
#include "RobotRebellion.h"
#include "Focusable.h"
//Focusable::Focusable()
//{
//
//}
//
//Focusable::~Focusable()
//{
//}
void Focusable::OnBeginFocus()
{}
void Focusable::OnEndFocus()
{}
void Focusable::OnPickup(APawn* InstigatorPawn)
{
PRINT_MESSAGE_ON_SCREEN(FColor::Cyan,"FOCUSABLE");
}<file_sep>/Source/RobotRebellion/Gameplay/Spell/DashSpell.cpp
// Fill out your copyright notice in the Description page of Project Settings.
#include "RobotRebellion.h"
#include "DashSpell.h"
#include "Gameplay/Spell/Effects/Effect.h"
#include "Character/RobotRebellionCharacter.h"
UDashSpell::UDashSpell() : USpell()
{}
void UDashSpell::BeginPlay()
{
Super::BeginPlay();
}
void UDashSpell::cast()
{
if(!canCast())
{
PRINT_MESSAGE_ON_SCREEN(FColor::Emerald,
"Cooldown : " + FString::FromInt(m_nextAllowedCastTimer - FPlatformTime::Seconds()));
return;
}
ARobotRebellionCharacter* caster = Cast<ARobotRebellionCharacter>(GetOwner());
UWorld* const world = caster->GetWorld();
if(caster)
{
// Get player location and where hes looking
FVector cameraLocation;
FRotator muzzleRotation;
caster->GetActorEyesViewPoint(cameraLocation, muzzleRotation);
FVector aimDir = getRealAimingVector(caster);
// Initialize Location
FVector endLocation = caster->GetActorLocation() + (aimDir * m_range);
// offset the shoot to avoid collision with the capsule of the player
FVector startLocation = caster->GetActorLocation() + (aimDir * 100.f) + FVector(0.f, 0.f, caster->BaseEyeHeight);
//Draw debug line
DRAW_DEBUG_LINE(world, startLocation, endLocation, FColor::Red);
// Cast the RAY!
FHitResult hitActors(ForceInit);
FCollisionQueryParams TraceParams(TEXT("No hit raycast spell"), true, caster->Instigator);
TraceParams.bTraceAsyncScene = true;
TraceParams.bReturnPhysicalMaterial = true;
// atm only should only proc on static mesh
world->LineTraceSingleByChannel(hitActors, startLocation, endLocation, ECC_WorldStatic, TraceParams);
// hit Actors countains hit actors now
if(hitActors.GetActor() == nullptr)
{
// We've hit nothing
if(computeDashHeight(endLocation, caster))
{
applyEffect(endLocation);
}
else
{
return; // We cannot tp the caster at the position : cancel the spell
}
}
else
{
// is it a player?
ARobotRebellionCharacter* hitCharacter = Cast<ARobotRebellionCharacter>(hitActors.GetActor());
if(hitCharacter)
{
applyEffect(hitCharacter);
}
else
{
// have hit decors
FVector impactPoint = hitActors.ImpactPoint;
float capsuleRadius = caster->GetCapsuleComponent()->GetScaledCapsuleRadius();
// offset endpoint based on capsule radius
endLocation = impactPoint - (aimDir * capsuleRadius);
// check if endlocation has engouh height
if(computeDashHeight(endLocation, caster))
{
applyEffect(endLocation);
}
else
{
return; // We cannot tp the caster at the position : cancel the spell
}
}
}
// the spell is successfully cast consumme mana and launch CD
caster->consumeMana(m_manaCost);
m_nextAllowedCastTimer = FPlatformTime::Seconds() + m_cooldown;
}
}
void UDashSpell::applyEffect(ARobotRebellionCharacter* affectedTarget)
{
PRINT_MESSAGE_ON_SCREEN(FColor::Emerald, TEXT("ApplicateEffect on target"));
for(int i = 0; i < m_effects.Num(); ++i)
{
m_effects[i]->exec(Cast<ARobotRebellionCharacter>(GetOwner()), affectedTarget);
}
}
void UDashSpell::applyEffect(FVector impactPoint)
{
PRINT_MESSAGE_ON_SCREEN(FColor::Emerald, TEXT("ApplicateEffect on point"));
for(int i = 0; i < m_effects.Num(); ++i)
{
m_effects[i]->exec(impactPoint, Cast<ARobotRebellionCharacter>(GetOwner()));
}
}
FVector UDashSpell::getRealAimingVector(const ARobotRebellionCharacter* caster)
{
APlayerController* playerController = Cast<APlayerController>(caster->Controller);
if(playerController)
{
FVector CamLoc;
FRotator CamRot;
playerController->GetPlayerViewPoint(CamLoc, CamRot);
return CamRot.Vector();
}
else if(caster->Instigator)
{
return caster->GetBaseAimRotation().Vector();
}
return FVector::ZeroVector;
}
bool UDashSpell::computeDashHeight(FVector& dashEndPoint, const ARobotRebellionCharacter* caster)
{
UWorld* world = caster->GetWorld();
bool hasBeenMoved = false;
// test bottom colision
FHitResult hitActorsTop(ForceInit);
FCollisionQueryParams TraceParams(TEXT("No hit raycast spell"), true, caster->Instigator);
TraceParams.bTraceAsyncScene = true;
TraceParams.bReturnPhysicalMaterial = true;
float casterHalfHeight = caster->GetCapsuleComponent()->GetUnscaledCapsuleHalfHeight();
float offsetHeight = 2.f;
FVector endTestLocation = dashEndPoint - FVector{0.f, 0.f,casterHalfHeight + offsetHeight};
// check if endlocation has engouh height
world->LineTraceSingleByChannel(hitActorsTop, dashEndPoint, endTestLocation, ECC_WorldStatic, TraceParams);
if(hitActorsTop.GetActor() != nullptr)
{
// We've hit something
hasBeenMoved = true;
const FVector& impactPosition = hitActorsTop.ImpactPoint;
// let enough space below the character
dashEndPoint.Z = dashEndPoint.Z + (impactPosition.Z - endTestLocation.Z);
}
// test top colision
endTestLocation = dashEndPoint + FVector{0.f, 0.f,casterHalfHeight + offsetHeight};
FHitResult hitActorsBot(ForceInit);
world->LineTraceSingleByChannel(hitActorsBot, dashEndPoint, endTestLocation, ECC_WorldStatic, TraceParams);
if(hitActorsBot.GetActor() != nullptr)
{
if(hasBeenMoved)
{ // we cannot tp the caster here
return false;
}
// We've hit something
const FVector& impactPosition = hitActorsBot.ImpactPoint;
// let enough space below the character
dashEndPoint.Z = dashEndPoint.Z - (endTestLocation.Z - impactPosition.Z);
}
return true;
}<file_sep>/Source/RobotRebellion/Gameplay/Alteration/ShieldAlteration.h
// Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "Gameplay/Alteration/AlterationBase.h"
#include "ShieldAlteration.generated.h"
/**
* Class about the shield alteration
*/
UCLASS(Blueprintable)
class ROBOTREBELLION_API UShieldAlteration : public UAlterationBase
{
GENERATED_BODY()
public:
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "General")
float m_amount;
UShieldAlteration();
void destroyItself() override;
void onCreate(class ARobotRebellionCharacter* alteredOwner) override;
virtual FString toDebugString() const USE_NOEXCEPT
{
return "Shield";
}
};
<file_sep>/Source/RobotRebellion/Gameplay/Alteration/AlterationController.cpp
// Fill out your copyright notice in the Description page of Project Settings.
#include "RobotRebellion.h"
#include "AlterationController.h"
#include "AlterationBase.h"
#include "Character/RobotRebellionCharacter.h"
#include "../../Tool/UtilitaryFunctionLibrary.h"
// Sets default values for this component's properties
UAlterationController::UAlterationController()
{
// Set this component to be initialized when the game starts, and to be ticked every frame. You can turn these features
// off to improve performance if you don't need them.
PrimaryComponentTick.bCanEverTick = true;
// ...
}
// Called when the game starts
void UAlterationController::BeginPlay()
{
Super::BeginPlay();
// ...
UUtilitaryFunctionLibrary::bindServerClientMethodPtr(
GetOwner(),
m_updateMethod,
&UAlterationController::update,
&UAlterationController::doesNothing
);
UUtilitaryFunctionLibrary::bindServerClientMethodPtr(
GetOwner(),
m_inflictMethod,
&UAlterationController::addAlterationServerImp,
&UAlterationController::addAlterationClientImp
);
}
// Called every frame
void UAlterationController::TickComponent( float DeltaTime, ELevelTick TickType, FActorComponentTickFunction* ThisTickFunction )
{
Super::TickComponent( DeltaTime, TickType, ThisTickFunction );
(this->*m_updateMethod)(DeltaTime);
}
void UAlterationController::update(float deltaTime)
{
if(GetOwnerRole() < ROLE_Authority) //not sure
{
PRINT_MESSAGE_ON_SCREEN_UNCHECKED(FColor::Red, "Err. Problem... Must not go there");
return;
}
auto removePredicate = [](UAlterationBase* current) { return current && current->IsPendingKillOrUnreachable(); };
m_alterationsArray.RemoveAll(removePredicate);
for (int32 iter = 0; iter < m_alterationsArray.Num(); ++iter)
{
if (!removePredicate(m_alterationsArray[iter]))
{
m_alterationsArray[iter]->update(deltaTime);
}
else
{
m_alterationsArray.RemoveAt(iter);
--iter;
}
}
m_alterationsArray.RemoveAll(removePredicate);
}
UAlterationBase* UAlterationController::findByID(int32 id) const
{
for (auto iter = 0; iter < m_alterationsArray.Num(); ++iter)
{
if (m_alterationsArray[iter]->m_id.m_value == id)
{
return m_alterationsArray[iter];
}
}
return nullptr;
}
void UAlterationController::internalRemoveAllAlteration()
{
while(m_alterationsArray.Num() != 0)
{
UAlterationBase* alterationToDestroy = m_alterationsArray.Pop(false);
alterationToDestroy->destroyItself();
}
}
void UAlterationController::removeAllAlteration()
{
if (GetOwnerRole() < ROLE_Authority)
{
this->serverRemoveAllAlteration();
}
else
{
this->internalRemoveAllAlteration();
}
}
void UAlterationController::serverRemoveAllAlteration_Implementation()
{
this->internalRemoveAllAlteration();
}
bool UAlterationController::serverRemoveAllAlteration_Validate()
{
return true;
}
GENERATE_DECLARATION_SERVER_CLIENT_METHODS_BASED_VALIDATION_SERVER_FROM_METHOD_PTR_WITH_CLIENT_IMPL_GEN(m_inflictMethod, UAlterationController, addAlteration, serverAddAlteration, UAlterationBase*, alteredOwner);
void UAlterationController::addAlterationServerImp(UAlterationBase* newAlteration)
{
if (newAlteration)
{
if (!this->findByID(newAlteration->m_id.m_value))
{
auto character = Cast<ARobotRebellionCharacter>(GetOwner());
if (character)
{
m_alterationsArray.Add(newAlteration);
newAlteration->onCreate(character);
character->displayAnimatedText(newAlteration->toDebugString(), FColor::Silver, ELivingTextAnimMode::TEXT_ANIM_BOING_BOING);
}
}
}
}<file_sep>/Source/RobotRebellion/UI/LivingTextRenderComponent.cpp
// Fill out your copyright notice in the Description page of Project Settings.
#include "RobotRebellion.h"
#include "LivingTextRenderComponent.h"
#define PI_MUL_3 9.42477796077f
ULivingTextRenderComponent::ULivingTextRenderComponent() : UTextRenderComponent()
{
PrimaryComponentTick.bCanEverTick = true;
bReplicates = true;
bAutoActivate = true;
/*this->bCastCinematicShadow = false;
this->bCastDynamicShadow = false;
this->bCastFarShadow = false;
this->bCastHiddenShadow = false;
this->bCastInsetShadow = false;
this->bCastShadowAsTwoSided = false;
this->bCastStaticShadow = false;
this->bCastVolumetricTranslucentShadow = false;
this->bRenderCustomDepth = false;
*/
this->m_updateMethod = &ULivingTextRenderComponent::doesNothing;
}
void ULivingTextRenderComponent::GetLifetimeReplicatedProps(TArray< FLifetimeProperty > & OutLifetimeProps) const
{
Super::GetLifetimeReplicatedProps(OutLifetimeProps);
}
void ULivingTextRenderComponent::initializeWithText(const FVector& actorPosition, const FString& textToDisplay, const FColor& colorToDisplay, ELivingTextAnimMode mode)
{
//set the current time to 0
m_currentTime = 0.f;
//set the damage in the text
this->SetText(FText::FromString(textToDisplay));
this->SetTextRenderColor(colorToDisplay);
//put the component at the position to display the text
m_savedBeginPosition = actorPosition;
m_savedBeginPosition.Z += m_heightBeginRelativeToDamagedActor;
this->SetWorldLocation(actorPosition);
this->SetRelativeRotation(FRotator(0.f, 180.f, 0.f));
//Now speeds. For those in Unireverse that are not familiar with speed computation
// v = d / t
m_zTranslationSpeed = m_heightEndRelativeToBeginHeight / m_lifeTime;
//Now that everything is ready, we can begin to really update everything until this component dies...
this->setDelegateAccordingToAnimMode(mode);
//Registration. Important !!
this->RegisterComponent();
}
void ULivingTextRenderComponent::initializeWithInt(const FVector& actorPosition, int32 numberToDisplay, const FColor& colorToDisplay, ELivingTextAnimMode mode)
{
this->initializeWithText(actorPosition, FString::FromInt(numberToDisplay), colorToDisplay, mode);
}
void ULivingTextRenderComponent::updateTextRotation()
{
UWorld* world = GetWorld();
if(world)
{
APlayerController* pcControll = world->GetFirstPlayerController();
if (pcControll)
{
FVector dummy;
FRotator camViewPoint;
pcControll->GetPlayerViewPoint(dummy, camViewPoint);
camViewPoint.Yaw += 180.f;
camViewPoint.Pitch = -camViewPoint.Pitch;
this->SetWorldRotation(camViewPoint);
}
}
}
void ULivingTextRenderComponent::updateEverything(float deltaTime)
{
if (IsPendingKillOrUnreachable())
{
return;
}
m_currentTime += deltaTime;
if (!this->isAtEndOfLife())
{
m_savedBeginPosition.Z += m_zTranslationSpeed * deltaTime;
this->SetWorldLocation(m_savedBeginPosition);
this->updateTextRotation();
}
else
{
destroyLivingText();
}
}
void ULivingTextRenderComponent::updateWithoutMoving(float deltaTime)
{
if (IsPendingKillOrUnreachable())
{
return;
}
m_currentTime += deltaTime;
if (!this->isAtEndOfLife())
{
this->SetWorldLocation(m_savedBeginPosition);
this->updateTextRotation();
}
else
{
this->destroyLivingText();
}
}
void ULivingTextRenderComponent::updateBoingBoing(float deltaTime)
{
if (IsPendingKillOrUnreachable())
{
return;
}
m_currentTime += deltaTime;
if (!this->isAtEndOfLife())
{
float animationTransfertMethod = m_currentTime * PI_MUL_3 / m_lifeTime; //normalized time over 3pi
//sin(u)/u make it boing boing ^^
animationTransfertMethod = FMath::Sin(animationTransfertMethod) / animationTransfertMethod;
animationTransfertMethod /= 64.f; //vertical scaling
m_savedBeginPosition.Z += m_zTranslationSpeed * animationTransfertMethod;
this->SetWorldLocation(m_savedBeginPosition);
}
else
{
this->destroyLivingText();
}
}
void ULivingTextRenderComponent::updateBoingBiggerText(float deltaTime)
{
if(IsPendingKillOrUnreachable())
{
return;
}
m_currentTime += deltaTime;
if(!this->isAtEndOfLife())
{
m_savedBeginPosition.Z += m_zTranslationSpeed * deltaTime;
this->SetWorldLocation(m_savedBeginPosition);
float animationTransfertMethod = m_currentTime * PI_MUL_3 / m_lifeTime; //normalized time over 6 PI
animationTransfertMethod = FMath::Abs(FMath::Sin(animationTransfertMethod)) + 0.5f; //result will be between 0.3f and 1.3f
//this->SetRelativeScale3D({ this->RelativeScale3D.X, animationTransfertMethod, animationTransfertMethod });
this->SetXScale(animationTransfertMethod);
this->SetYScale(animationTransfertMethod);
this->updateTextRotation();
}
else
{
this->destroyLivingText();
}
}
void ULivingTextRenderComponent::copyFrom(const ULivingTextRenderComponent& objectToCopyFrom)
{
m_lifeTime = objectToCopyFrom.m_lifeTime;
m_heightBeginRelativeToDamagedActor = objectToCopyFrom.m_heightBeginRelativeToDamagedActor;
m_heightEndRelativeToBeginHeight = objectToCopyFrom.m_heightEndRelativeToBeginHeight;
setDelegateAccordingToAnimMode(ELivingTextAnimMode::TEXT_ANIM_NOT_READY);
}
void ULivingTextRenderComponent::setDelegateAccordingToAnimMode(ELivingTextAnimMode mode)
{
static void(ULivingTextRenderComponent::*const delegateArrayMapperLookUpTable[])(float) =
{
&ULivingTextRenderComponent::doesNothing,
&ULivingTextRenderComponent::updateEverything,
&ULivingTextRenderComponent::updateWithoutMoving,
&ULivingTextRenderComponent::updateBoingBoing,
&ULivingTextRenderComponent::updateBoingBiggerText
};
this->m_updateMethod = delegateArrayMapperLookUpTable[static_cast<uint8>(mode)];
}
void ULivingTextRenderComponent::destroyLivingText()
{
this->UnregisterComponent();
this->DestroyComponent();
}<file_sep>/Source/RobotRebellion/Gameplay/Spell/Effects/ShieldEffect.cpp
// Fill out your copyright notice in the Description page of Project Settings.
#include "RobotRebellion.h"
#include "ShieldEffect.h"
void UShieldEffect::BeginPlay()
{
Super::BeginPlay();
}
void UShieldEffect::TickComponent(float DeltaTime, ELevelTick TickType, FActorComponentTickFunction* ThisTickFunction)
{
Super::TickComponent(DeltaTime, TickType, ThisTickFunction);
}
void UShieldEffect::exec(ARobotRebellionCharacter* caster, ARobotRebellionCharacter* target)
{
// Inflict shield alteration on target
target->addShield(m_shieldAmount, m_duration);
PRINT_MESSAGE_ON_SCREEN(FColor::Magenta, "shielded for : " + FString::SanitizeFloat(m_shieldAmount)
+ "during : " + FString::SanitizeFloat(m_duration) + "s");
}
void UShieldEffect::exec(const FVector& impactPoint, ARobotRebellionCharacter* caster)
{
TArray<TEnumAsByte<EObjectTypeQuery>> ObjectTypes;
ObjectTypes.Add(UEngineTypes::ConvertToObjectType(ECC_GameTraceChannel2)); // Players
ObjectTypes.Add(UEngineTypes::ConvertToObjectType(ECC_GameTraceChannel3)); // Robots
ObjectTypes.Add(UEngineTypes::ConvertToObjectType(ECC_GameTraceChannel4)); // Sovec
ObjectTypes.Add(UEngineTypes::ConvertToObjectType(ECC_GameTraceChannel6)); // Beast
TArray<AActor*> ActorsToIgnore{};
TArray<FHitResult> hitActors;
bool Result = UKismetSystemLibrary::SphereTraceMultiForObjects(GetWorld(),
impactPoint,
impactPoint,
m_zoneRadius,
ObjectTypes,
false,
ActorsToIgnore,
SPHERECAST_DISPLAY_DURATION,
hitActors,
true);
PRINT_MESSAGE_ON_SCREEN(FColor::Magenta, "shielded for : " + FString::SanitizeFloat(m_shieldAmount)
+ "during : " + FString::SanitizeFloat(m_duration) + "s on :"
+ FString::FromInt(hitActors.Num()) + " target(s)");
for(FHitResult& currentHit : hitActors)
{
ARobotRebellionCharacter* temp = Cast<ARobotRebellionCharacter>(currentHit.GetActor());
if(temp)
{
// Apply shield effect
temp->addShield(m_shieldAmount, m_duration);
}
}
}
<file_sep>/Source/RobotRebellion/UI/TopWidget.h
// Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "UI/RobotRebellionWidget.h"
#include "TopWidget.generated.h"
/**
*
*/
UCLASS()
class ROBOTREBELLION_API UTopWidget : public URobotRebellionWidget
{
GENERATED_BODY()
public:
UFUNCTION(BlueprintCallable, Category = "Menu")
void SinglePlayerGame();
UFUNCTION(BlueprintCallable, Category = "Menu")
void CloseSinglePlayerGameWidget();
UFUNCTION(BlueprintCallable, Category = "Menu")
void NetworkPlayerGame();
UFUNCTION(BlueprintCallable, Category = "Menu")
void GameOptionsMenu();
UFUNCTION(BlueprintCallable, Category = "Menu")
void CloseGameOptionsMenu();
void setReturnInGameVisible(bool enable);
};
<file_sep>/Source/RobotRebellion/Global/LootTable.h
// Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "Components/ActorComponent.h"
#include "LootTable.generated.h"
UCLASS( ClassGroup=(Custom), meta=(BlueprintSpawnableComponent) )
class ROBOTREBELLION_API ULootTable : public UActorComponent
{
GENERATED_BODY()
public:
// Sets default values for this component's properties
ULootTable();
// Called when the game starts
virtual void BeginPlay() override;
// Called every frame
virtual void TickComponent( float DeltaTime, ELevelTick TickType, FActorComponentTickFunction* ThisTickFunction ) override;
// object array
UPROPERTY(EditAnywhere, BlueprintReadWrite)
TArray<TSubclassOf<AActor>> m_objects;
// probability array
UPROPERTY(EditAnywhere, BlueprintReadWrite)
TArray<int32> m_probs;
void dropItem(const FVector& pos);
};
<file_sep>/Source/RobotRebellion/CorridorTriggerBox.cpp
// Fill out your copyright notice in the Description page of Project Settings.
#include "RobotRebellion.h"
#include "CorridorTriggerBox.h"
#include "Character/RobotRebellionCharacter.h"
ACorridorTriggerBox::ACorridorTriggerBox()
{
//GetCollisionComponent()->OnComponentHit.AddDynamic(this, &ABigRoomTriggerBox::onOverlapBegin);
GetCollisionComponent()->OnComponentBeginOverlap.AddDynamic(this, &ACorridorTriggerBox::onOverlapBegin);
}
void ACorridorTriggerBox::BeginPlay()
{
Super::BeginPlay();
}
void ACorridorTriggerBox::onOverlapBegin(UPrimitiveComponent* var1, AActor* var2, UPrimitiveComponent* var3,
int32 OtherBodyIndex, bool bFromSweep, const FHitResult& SweepResult)
{
ARobotRebellionCharacter* player = Cast<ARobotRebellionCharacter>(var2);
if(player)
{
PRINT_MESSAGE_ON_SCREEN_UNCHECKED(FColor::Red, "TRIGGER CORRIDOR");
player->setLocation(ELocation::CORRIDOR);
}
}
<file_sep>/Source/RobotRebellion/Gameplay/TriggerBox/SpawnerTriggerBox.h
// Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "Engine/TriggerBox.h"
#include "SpawnerTriggerBox.generated.h"
/**
*
*/
UCLASS()
class ROBOTREBELLION_API ASpawnerTriggerBox : public ATriggerBox
{
GENERATED_BODY()
public:
/************************************************************************/
/* UPROPERTY */
/************************************************************************/
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Search")
float m_scope;
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "CONDITION")
uint8 m_destroyWhenPassed : 1;
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "CONDITION")
uint8 m_autoActivateCombat : 1;
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "CONDITION")
uint8 m_activeOnlyWhenKingHere : 1;
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "CONDITION")
uint8 m_random : 1;
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "CONDITION")
uint8 m_noSpawnWhenPopulated : 1;
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "CONDITION")
uint8 m_relativePosition : 1;
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "CONDITION")
uint8 m_effectOnSpawn : 1;
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "CONDITION")
uint8 m_comeFromUpper : 1;
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Population")
float m_upperOffset;
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Population")
TArray<FTransform> m_populationTransform;
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Population")
TArray<TSubclassOf<class ANonPlayableCharacter>> m_populationToSpawn;
/************************************************************************/
/* PROPERTY */
/************************************************************************/
TArray<class ARobotRebellionCharacter*> m_characterOnBox;
TArray<class APawn*> m_spawned;
float m_maxDist;
FActorSpawnParameters m_spawnParams;
public:
/************************************************************************/
/* CONSTRUCTOR */
/************************************************************************/
ASpawnerTriggerBox();
/************************************************************************/
/* METHODS */
/************************************************************************/
virtual void BeginPlay() override;
private:
void correctDestruction();
void killItself();
void internalSpawn();
void internalSpawnCharacterAtIndex(int32 index, UWorld* world);
void setNearTarget(class ANonPlayableCharacter* spawned);
void checkCharactersOnBox();
public:
/************************************************************************/
/* UFUNCTION */
/************************************************************************/
UFUNCTION()
void onHit(UPrimitiveComponent* var1, AActor* enteredActor, UPrimitiveComponent* var3, int32 var4, bool var5, const FHitResult& var6);
UFUNCTION()
void spawnEnnemies();
private:
UFUNCTION(Reliable, Server, WithValidation)
void serverKills();
UFUNCTION(Reliable, NetMulticast)
void multiKills();
UFUNCTION(Reliable, Server, WithValidation)
void serverSpawnEnnemies();
};
<file_sep>/Source/RobotRebellion/UI/RobotRebellionWidget.h
// Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "Blueprint/UserWidget.h"
#include "RobotRebellionWidget.generated.h"
/**
*
*/
UCLASS()
class ROBOTREBELLION_API URobotRebellionWidget : public UUserWidget
{
GENERATED_BODY()
private:
UPROPERTY(VisibleDefaultsOnly)
UAudioComponent* m_notifyAudioComp;
UPROPERTY(VisibleDefaultsOnly)
UAudioComponent* m_loopAudioComp;
public:
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "WidgetSound")
bool m_stopAmbiantSound;
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "WidgetSound")
USoundCue* m_widgetBeginSound;
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "WidgetSound")
USoundCue* m_widgetLoopSound;
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "WidgetSound")
USoundCue* m_widgetCloseSound;
UFUNCTION(BlueprintCallable, Category = "WidgetSound")
virtual void startSound();
UFUNCTION(BlueprintCallable, Category = "WidgetSound")
virtual void endSound();
void playSound(USoundCue* sound);
};
<file_sep>/Source/RobotRebellion/IA/BT/CrouchBTTaskNode.cpp
// Fill out your copyright notice in the Description page of Project Settings.
#include "RobotRebellion.h"
#include "CrouchBTTaskNode.h"
#include "RobotRebellion.h"
#include "MoveToShootLocBTTaskNode.h"
#include "../Controller/CustomAIControllerBase.h"
#include "../Controller/RobotShooterController.h"
UCrouchBTTaskNode::UCrouchBTTaskNode()
{
NodeName = "Crouch";
bNotifyTick = true;
}
EBTNodeResult::Type UCrouchBTTaskNode::ExecuteTask(UBehaviorTreeComponent& OwnerComp, uint8*
NodeMemory)
{
ARobotShooterController* AIController = Cast<ARobotShooterController>(OwnerComp.GetOwner());
if(AIController->isCrouch())
{
return EBTNodeResult::Succeeded;
}
AIController->crouch();
return EBTNodeResult::Succeeded;
}
void UCrouchBTTaskNode::TickTask(class UBehaviorTreeComponent& OwnerComp, uint8* NodeMemory,
float DeltaSeconds)
{
ARobotShooterController* AIController = Cast<ARobotShooterController>(OwnerComp.GetOwner());
if(AIController->isCrouch())
{
FinishLatentTask(OwnerComp, EBTNodeResult::Succeeded);
}
}
FString UCrouchBTTaskNode::GetStaticDescription() const
{
return TEXT("Action bloc that make owner crouch - only work with RobotShooterController atm");
}
<file_sep>/Source/RobotRebellion/Character/Soldier.cpp
// Fill out your copyright notice in the Description page of Project Settings.
#include "RobotRebellion.h"
#include "Soldier.h"
ASoldier::ASoldier() : APlayableCharacter()
{}
<file_sep>/Source/RobotRebellion/Character/RobotRebellionCharacter.h
// Copyright 1998-2016 Epic Games, Inc. All Rights Reserved.
#pragma once
#include "../Gameplay/Attributes/Attributes.h"
#include "../Gameplay/Alteration/AlterationController.h"
#include "../UI/ELivingTextAnimMode.h"
#include "GameFramework/Character.h"
#include "Location.h"
#include "RobotRebellionCharacter.generated.h"
/*
* Mother class for every character in RobotRebellion Game
*/
UCLASS(config = Game)
class ARobotRebellionCharacter : public ACharacter
{
GENERATED_BODY()
private:
bool m_isShieldAnimated;
public:
UPROPERTY(VisibleAnywhere, BlueprintReadWrite, Category = "Movement")
float m_moveForwardSpeed;
UPROPERTY(VisibleAnywhere, BlueprintReadWrite, Category = "Movement")
float m_moveStraphSpeed;
UPROPERTY(VisibleAnywhere, BlueprintReadWrite, Category = "Movement", meta = (ClampMin = 0.00001f))
float m_maxVelocity;
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Movement", meta = (ClampMin = 0.00001f))
float m_maxCrouchVelocity;
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Movement", meta = (ClampMin = 0.00001f))
float m_maxWalkVelocity;
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Movement", meta = (ClampMin = 0.00001f))
float m_maxRunVelocity;
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Movement", meta = (ClampMin = 0.00001f, ClampMax = 1.f))
float m_accelerationCoeff;
////Weapon Inventory/////
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Weapon")
class UWeaponInventory* m_weaponInventory;
////Billboard on character////
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "BillBoard")
TSubclassOf<class UTextBillboardComponent> m_textBillboardDefault;
UPROPERTY(VisibleAnywhere, BlueprintReadWrite, Category = "BillBoard")
class UTextBillboardComponent* m_textBillboardInstance;
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "IA")
bool m_canKillItsAllies;
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "IA")
bool m_canTransmitItsTarget;
UPROPERTY(Replicated)
bool m_isInCombat;
protected:
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = Attribute, meta = (AllowPrivateAccess = "true"), Replicated)
UAttributes* m_attribute;
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = Attribute, meta = (AllowPrivateAccess = "true"))
UAlterationController* m_alterationController;
bool m_isInvisible;
////RESTORE MANA EFFECT
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = RestoreMana)
UParticleSystem* m_restoreManaParticuleEffect;
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = RestoreMana)
float m_restoreManaEffectDuration;
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = RestoreMana)
UParticleSystemComponent* m_restoreManaParticleSystem;
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = RestoreMana)
bool m_isRestoreManaParticleSpawned;
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = RestoreMana)
float m_restoreManaEffectTimer;
////REVIVE EFFECT
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = Revive)
UParticleSystem* m_reviveParticuleEffect;
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = Revive)
float m_reviveEffectDuration;
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = Revive)
UParticleSystemComponent* m_reviveParticleSystem;
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = Revive)
bool m_isReviveParticleSpawned;
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = Revive)
float m_reviveEffectTimer;
////SHIELD EFFECT
/** Shield effect if animation shield animation is enabled*/
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = Shield)
UParticleSystem* m_shieldParticuleEffect;
/** Shield effect if animation shield animation is dsables*/
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = Shield)
UParticleSystem* m_shieldParticuleEffectUnanimated;
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = Shield)
UParticleSystemComponent* m_shieldParticleSystem;
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = Shield)
bool m_isShieldParticleSpawned;
UPROPERTY(BlueprintReadOnly, Replicated)
int m_burningBonesCount;
TArray<int32> m_burningBones;
TArray<UParticleSystemComponent*> m_fireEffects;
TMap<UParticleSystemComponent*, float> m_effectTimer;
float m_tickCount;
int m_bonesToUpdate;
int m_bonesSet;
class AWorldInstanceEntity* m_worldEntity;
float m_decelerationCoeff;
UPROPERTY(EditAnywhere, BlueprintReadWrite, Replicated)
ELocation m_location;
/************************************************************************/
/* PROPERTY */
/************************************************************************/
void(ARobotRebellionCharacter::* m_timedDestroyDelegate)(float deltaTime);
void(ARobotRebellionCharacter::* m_disableBeforeDestroyDelegate)();
public:
////HEALTH BAR
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = HealthBar)
class UWidgetComponent* m_healthBar;
public:
/************************************************************************/
/* METHODS */
/************************************************************************/
ARobotRebellionCharacter();
bool hasDoubleWeapon() const USE_NOEXCEPT;
class UWeaponBase* getCurrentEquippedWeapon() const USE_NOEXCEPT;
const class UWeaponBase* getMainWeapon() const USE_NOEXCEPT;
const class UWeaponBase* getSecondaryWeapon() const USE_NOEXCEPT;
virtual void BeginPlay() override;
virtual void Tick(float deltaTime) override;
////Server
virtual void GetLifetimeReplicatedProps(TArray< FLifetimeProperty > & OutLifetimeProps) const override;
virtual void cppOnRevive();
virtual void cppOnDeath();
void startTimedDestroy() USE_NOEXCEPT;
void inflictStun();
void inflictStun(float duration);
void inflictInvisibility();
void addShield(float amount, float duration);
void doesNothing()
{}
UTextBillboardComponent* getBillboardComponent();
void updateIfInCombat();
virtual FVector aim(const FVector& directionToShoot) const
{
return directionToShoot;
}
protected:
FORCEINLINE void noDestroyForNow(float deltaTime)
{}
void destroyNow(float deltaTime);
FORCEINLINE void endDisabling()
{}
void disablingEverything();
public:
/************************************************************************/
/* UFUNCTION */
/************************************************************************/
UFUNCTION(BlueprintNativeEvent, Category = "UpdateMethod")
void updateInvisibilityMat(bool isVisible);
UFUNCTION()
void onDeath();
UFUNCTION(Reliable, Client, WithValidation)
void clientOnDeath();
UFUNCTION(BlueprintCallable, Category = "Billboard - Living Text")
void createTextBillboard();
UFUNCTION(BlueprintCallable, Category = "Billboard - Living Text")
void createTextBillboardWithThisCamera(UCameraComponent* camera);
void setBillboardInstanceNewCamera(UCameraComponent* camera);
UFUNCTION(BlueprintCallable, Category = "Billboard - Living Text")
void displayAnimatedIntegerValue(int32 valueToDisplay, const FColor& color, ELivingTextAnimMode mode = ELivingTextAnimMode::TEXT_ANIM_MOVING);
UFUNCTION(BlueprintCallable, Category = "Billboard - Living Text")
void displayAnimatedText(const FString& textToDisplay, const FColor& color, ELivingTextAnimMode mode = ELivingTextAnimMode::TEXT_ANIM_MOVING);
UFUNCTION(Reliable, NetMulticast, WithValidation)
void netMultidisplayAnimatedIntegerValue(int32 valueToDisplay, const FColor& color, ELivingTextAnimMode mode);
UFUNCTION(Reliable, NetMulticast, WithValidation)
void netMultidisplayAnimatedText(const FString& textToDisplay, const FColor& color, ELivingTextAnimMode mode);
UFUNCTION(Reliable, NetMulticast, WithValidation)
void netMultiKill();
UFUNCTION()
void setInvisible(bool isInvisible);
UFUNCTION()
bool isVisible() const;
UFUNCTION(Reliable, NetMulticast, WithValidation)
void multiSetInvisible(bool isInvisible);
UFUNCTION()
UAttributes* getAttributes()
{
return m_attribute;
}
// Attributs relatives functions added by macro
public:
GENERATED_USING_AND_METHODS_FROM_Attributes(m_attribute, ->);
UFUNCTION()
void inflictDamage(float damage, ELivingTextAnimMode animType = ELivingTextAnimMode::TEXT_ANIM_MOVING, const FColor& damageColor = FColor::Red);
UFUNCTION()
void restoreHealth(float value, ELivingTextAnimMode animType = ELivingTextAnimMode::TEXT_ANIM_MOVING);
UFUNCTION()
void restoreMana(float value, ELivingTextAnimMode animType = ELivingTextAnimMode::TEXT_ANIM_MOVING);
////Restore Mana Effect
UFUNCTION()
void spawnManaParticle();
UFUNCTION(Reliable, NetMulticast, WithValidation)
void multiSpawnManaParticle();
UFUNCTION()
void unspawnManaParticle();
UFUNCTION(Reliable, NetMulticast, WithValidation)
void multiUnspawnManaParticle();
////Revive Effect
UFUNCTION()
void spawnReviveParticle();
UFUNCTION(Reliable, NetMulticast, WithValidation)
void multiSpawnReviveParticle();
UFUNCTION()
void unspawnReviveParticle();
UFUNCTION(Reliable, NetMulticast, WithValidation)
void multiUnspawnReviveParticle();
////Shield Effect
UFUNCTION()
void spawnShieldParticle();
UFUNCTION(Reliable, NetMulticast, WithValidation)
void multiSpawnShieldParticle();
UFUNCTION()
void unspawnShieldParticle();
UFUNCTION(Reliable, NetMulticast, WithValidation)
void multiUnspawnShieldParticle();
///////Burn Effects
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = Fire)
UParticleSystem* m_fireEffect;
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = Fire)
class UParticleSystemComponent* m_particuleComponent;
void UpdateBurnEffect(float DeltaTime);
void displayFireOnBone(const FName& bone);
UFUNCTION(Reliable, NetMulticast)
void multiDisplayFireOnBone(const FName& bone);
void internalDisplayFireOnBone(const FName& bone);
void displayFireOnBoneArray(const TArray<FName>& bone);
void spawnFireEffect(FVector location);
UFUNCTION(Reliable, NetMulticast)
void multiDisplayFireOnBoneArray(const TArray<FName>& bone);
void internalDisplayFireOnBoneArray(const TArray<FName>& bone);
bool isBurning() const USE_NOEXCEPT
{
return (m_burningBonesCount > 0);
}
UFUNCTION(Reliable, NetMulticast)
void multiSpawnFireEffect(FVector location);
void internalSpawnFireEffect(FVector location);
void cleanFireComp();
UFUNCTION(Reliable, NetMultiCast)
void multiCleanFireComp();
UFUNCTION(Reliable, Server, WithValidation)
void serverCleanFireComp();
void internalCleanFireComp();
UFUNCTION(BlueprintCallable, Category = "Reverberation")
ELocation GetLocation() const USE_NOEXCEPT
{
return m_location;
}
UFUNCTION(BlueprintCallable, Category = "Reverberation")
void setLocation(ELocation location)
{
m_location = location;
}
protected:
template<class Alteration, class AdditionalFunc, class ... AdditionalArgs>
void internalInflictAlteration(AdditionalFunc func, AdditionalArgs&& ... args)
{
Alteration* alteration;
if(UUtilitaryFunctionLibrary::createObjectFromDefaultWithoutAttach<Alteration>(
&alteration,
*GameAlterationInstaller::getInstance().getAlterationDefault<Alteration>()
))
{
func(alteration, std::forward<AdditionalArgs>(args)...);
m_alterationController->addAlteration(alteration);
}
}
};
<file_sep>/Source/RobotRebellion/Gameplay/Spell/Effects/ReviveEffect.cpp
// Fill out your copyright notice in the Description page of Project Settings.
#include "RobotRebellion.h"
#include "ReviveEffect.h"
#include "Character/RobotRebellionCharacter.h"
#include "Character/PlayableCharacter.h"
void UReviveEffect::BeginPlay()
{
Super::BeginPlay();
}
void UReviveEffect::TickComponent(float DeltaTime, ELevelTick TickType, FActorComponentTickFunction* ThisTickFunction)
{
Super::TickComponent(DeltaTime, TickType, ThisTickFunction);
}
void UReviveEffect::exec(ARobotRebellionCharacter* caster, ARobotRebellionCharacter* target)
{
APlayableCharacter* playableCaster = Cast<APlayableCharacter>(caster);
APlayableCharacter* playableTarget = Cast<APlayableCharacter>(target);
if(playableCaster && playableTarget)
{
playableCaster->cppPreRevive(playableTarget);
playableTarget->spawnReviveParticle();
}
}
void UReviveEffect::exec(const FVector& impactPoint, ARobotRebellionCharacter* caster)
{}<file_sep>/Config/DefaultGame.ini
[/Script/EngineSettings.GeneralProjectSettings]
ProjectID=9D254EC5496ADFB5A056F6B02F33953E
ProjectName=Robot Rebellion
CompanyName=Unireverse
ProjectVersion=0.0.0.1
ProjectDisplayedTitle=NSLOCTEXT("[/Script/EngineSettings]", "4326CFDE45B66EE77EC4408D877D9314", "Robot Rebellion")
bShouldWindowPreserveAspectRatio=True
[StartupActions]
bAddPacks=True
InsertPack=(PackSource="StarterContent.upack,PackName="StarterContent")
[/Script/UnrealEd.ProjectPackagingSettings]
StagingDirectory=(Path="C:/Workspace/Unreal Engine/UnrealPackages/RobotRebellion")
BuildConfiguration=PPBC_Development
<file_sep>/Source/RobotRebellion/UI/LifeBarWidget.h
// Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "UI/RobotRebellionWidget.h"
#include "Character/RobotRebellionCharacter.h"
#include "LifeBarWidget.generated.h"
/**
*
*/
UCLASS()
class ROBOTREBELLION_API ULifeBarWidget : public URobotRebellionWidget
{
GENERATED_BODY()
public:
ARobotRebellionCharacter* m_owner;
UFUNCTION(BlueprintCallable, Category = "UpdateMethod")
void getHealthRatio(float& ratio, float& ratioShield, float& health, float& shield, float& maxHealth);
void setOwner(ARobotRebellionCharacter* character)
{
m_owner = character;
}
};
<file_sep>/Source/RobotRebellion/Gameplay/Spell/Spell.h
// Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "Components/ActorComponent.h"
#include "Spell.generated.h"
/**
* Spell Base class implement shared methode like initializeSpell and canCast
*
*/
UCLASS(Blueprintable)
class ROBOTREBELLION_API USpell : public UActorComponent
{
GENERATED_BODY()
private:
float m_realeaseInputTimeAfterCasting;
public:
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Spell")
FString m_name;
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Spell")
float m_range;
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Spell")
float m_cooldown;
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Spell")
float m_manaCost;
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Spell")
bool m_hasMotionlessCastingTime;
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Spell")
float m_castingTime;
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Spell")
TArray<TSubclassOf<class UEffect>> m_effectsClass;
protected:
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = Attribute, meta = (AllowPrivateAccess = "true"))
float m_nextAllowedCastTimer;
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = Attribute, meta = (AllowPrivateAccess = "true"), Replicated)
float m_currentCooldown;
TArray<UEffect *> m_effects;
public:
USpell();
virtual void cast();
virtual void BeginPlay() override;
virtual void TickComponent(float DeltaTime, enum ELevelTick TickType, FActorComponentTickFunction *ThisTickFunction) override;
// Must be called to initialize effect list with Blueprint specified class
void initializeSpell();
bool canCast() const;
// return the actual time remaining before casting is possible if can cast return -1.f
float getCurrentCooldown() const;
void GetLifetimeReplicatedProps(TArray< FLifetimeProperty > & OutLifetimeProps) const;
};
<file_sep>/Source/RobotRebellion/IA/Controller/KingAIController.h
// Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "IA/Controller/CustomAIControllerBase.h"
#include "KingAIController.generated.h"
/**
*
*/
UCLASS()
class ROBOTREBELLION_API AKingAIController : public ACustomAIControllerBase
{
GENERATED_BODY()
public:
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "General")
float m_ennemyCoefficient;
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "General")
float m_moveThreshold;
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "General")
float m_minimaleDistanceToMove;
FVector m_destination;
void (AKingAIController::* m_updateMethodPtr)();
virtual void BeginPlay() override;
virtual void Tick(float deltaTime) override;
virtual EPathFollowingRequestResult::Type MoveToTarget() override;
FORCEINLINE UFUNCTION(BlueprintCallable, Category = "King")
void activate(bool isKingFree) USE_NOEXCEPT
{
this->m_updateMethodPtr = isKingFree ? &AKingAIController::updateKing : &AKingAIController::doesNothing;
}
FORCEINLINE UFUNCTION(BlueprintCallable, Category = "King")
bool isActivated() const USE_NOEXCEPT
{
return this->m_updateMethodPtr == &AKingAIController::updateKing;
}
private:
void doesNothing()
{}
void updateKing();
void computeTarget();
};
<file_sep>/Source/RobotRebellion/UI/LifeBarWidget.cpp
// Fill out your copyright notice in the Description page of Project Settings.
#include "RobotRebellion.h"
#include "LifeBarWidget.h"
void ULifeBarWidget::getHealthRatio(float& ratio, float& ratioShield, float& health, float& shield, float& maxHealth)
{
if(m_owner)
{
health = m_owner->getHealth();
shield = m_owner->getShield();
maxHealth = m_owner->getMaxHealth();
ratio = health / maxHealth;
ratioShield = (health + shield) / maxHealth;
}
else
{
health = 0.f;
maxHealth = 0.f;
ratio = 0.f;
}
}
<file_sep>/Source/RobotRebellion/Global/RobotRebellionGameMode.cpp
// Copyright 1998-2016 Epic Games, Inc. All Rights Reserved.
#include "RobotRebellion.h"
#include "RobotRebellionGameMode.h"
#include "AudioManager.h"
#include "Character/RobotRebellionCharacter.h"
#include "GameInstaller.h"
#include "Gameplay/Alteration/StunAlteration.h"
#include "Gameplay/Alteration/InvisibilityAlteration.h"
#include "EntityDataSingleton.h"
#include "IA/Navigation/NavigationVolumeGraph.h"
#include "Tool/UtilitaryMacros.h"
ARobotRebellionGameMode::ARobotRebellionGameMode()
{
// set default pawn class to our Blueprinted character
static ConstructorHelpers::FClassFinder<APawn> defaultPawn(TEXT("/Game/ThirdPersonCPP/Blueprints/DefaultSpawn_BP"));
DefaultPawnClass = defaultPawn.Class;
bUseSeamlessTravel = true;
PrimaryActorTick.bCanEverTick = true;
}
void ARobotRebellionGameMode::BeginPlay()
{
Super::BeginPlay();
}
void ARobotRebellionGameMode::Tick(float deltaTime)
{
Super::Tick(deltaTime);
}
<file_sep>/Source/RobotRebellion/Gameplay/Item/PickupActor.h
// Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "GameFramework/Actor.h"
#include "ObjectTypes.h"
#include "Focusable.h"
#include "PickupActor.generated.h"
UCLASS()
class ROBOTREBELLION_API APickupActor : public AActor, public Focusable
{
GENERATED_BODY()
public:
// Sets default values for this actor's properties
APickupActor();
// Called when the game starts or when spawned
virtual void BeginPlay() override;
// Called every frame
virtual void Tick( float DeltaSeconds ) override;
/* UFUNCTION(Reliable, Server, WithValidation)
void serverOnPickup(APawn* InstigatorPawn);*/
virtual EObjectType getObjectType() const USE_NOEXCEPT
{
return EObjectType::NONE;
}
UPROPERTY(EditDefaultsOnly, Category = "Mesh")
UStaticMeshComponent* MeshComp;
UPROPERTY(EditDefaultsOnly, Category = "Sound")
USoundCue* PickupSound;
virtual void OnBeginFocus() override;
virtual void OnEndFocus() override;
virtual void OnPickup(APawn * InstigatorPawn) override;
};
<file_sep>/Source/RobotRebellion/Gameplay/Weapon/WizardMeteor.cpp
// Fill out your copyright notice in the Description page of Project Settings.
#include "RobotRebellion.h"
#include "WizardMeteor.h"
#include "Character/RobotRebellionCharacter.h"
#include "Gameplay/Damage/Damage.h"
#include "Gameplay/Damage/DamageCoefficientLogic.h"
#include "Global/GlobalDamageMethod.h"
// Sets default values
AWizardMeteor::AWizardMeteor()
: AActor(),
m_unreducedDamage{},
m_explosionRadius{}
{
// Set this actor to call Tick() every frame. You can turn this off to improve performance if you don't need it.
PrimaryActorTick.bCanEverTick = true;
//Projectile Movement datas
m_projectileMovement = CreateDefaultSubobject<UProjectileMovementComponent>(TEXT("Movement Comp"));
m_projectileMovement->InitialSpeed = 3000.f;
m_projectileMovement->MaxSpeed = 3000.f;
m_projectileMovement->bRotationFollowsVelocity = true;
m_projectileMovement->bShouldBounce = false;
bReplicates = true;
}
// Called when the game starts or when spawned
void AWizardMeteor::BeginPlay()
{
Super::BeginPlay();
}
// Called every frame
void AWizardMeteor::Tick(float DeltaTime)
{
Super::Tick(DeltaTime);
//Use life Time
float delta = 0.5f;
// PRINT_MESSAGE_ON_SCREEN(FColor::Purple, "lifeSpan : " + FString::SanitizeFloat(GetLifeSpan())
// + " - delta : " + FString::SanitizeFloat(delta));
if(GetLifeSpan() <= delta)
{
explode();
}
}
// Call when actor reach it target location
void AWizardMeteor::explode()
{
//PRINT_MESSAGE_ON_SCREEN(FColor::Purple, "explode");
const FVector& actorLocation = GetActorLocation();
if(Role == ROLE_Authority)
{
//m_explosionEffectComp->SetIsReplicated(true);
// Can hit every character
TArray<TEnumAsByte<EObjectTypeQuery>> objectType = {
UEngineTypes::ConvertToObjectType(ECC_GameTraceChannel2), // Players
UEngineTypes::ConvertToObjectType(ECC_GameTraceChannel3), // Robots
UEngineTypes::ConvertToObjectType(ECC_GameTraceChannel4), // Sovec
UEngineTypes::ConvertToObjectType(ECC_GameTraceChannel6) // Beasts
};
TArray<FHitResult> OutHits;
UKismetSystemLibrary::SphereTraceMultiForObjects(
GetWorld(),
actorLocation,
actorLocation,
m_explosionRadius,
objectType,
false,
{this},
SPHERECAST_DISPLAY_DURATION,
OutHits,
true
);
{
for(int32 iter = 0; iter < OutHits.Num(); ++iter)
{
FHitResult Hit = OutHits[iter];
ARobotRebellionCharacter* target = Cast<ARobotRebellionCharacter>(Hit.GetActor());
if(target)
{
DamageCoefficientLogic coeff;
// This line could crash if owner is not RobotRebellion Charcater but it shouldn't
// happen...
Damage damage{Cast<ARobotRebellionCharacter>(GetOwner()), target};
float meteorDamage = m_unreducedDamage;
Damage::DamageValue currentDamage = damage(
[meteorDamage](const ARobotRebellionCharacter* caster, const ARobotRebellionCharacter* target)
{
// use strenght and shield cause it's fun to use shield
int32 ratio = (caster->getStrength() + (caster->getShield() * 2.f)) / (target->getDefense());
return static_cast<Damage::DamageValue>(ratio * meteorDamage);
}, 1.0f);
target->inflictDamage(currentDamage);
}
}
}
spawnEffect();
}
// now destroy the actor
this->Destroy();
}
void AWizardMeteor::spawnEffect()
{
m_explosionEffectComp = UGameplayStatics::SpawnEmitterAtLocation(GetWorld(), m_explosionEffect,
GetActorLocation(), GetActorRotation(), true);
if(Role >= ROLE_Authority)
{
multiSpawnEffect(GetActorLocation());
}
}
void AWizardMeteor::multiSpawnEffect_Implementation(FVector location)
{
m_explosionEffectComp = UGameplayStatics::SpawnEmitterAtLocation(GetWorld(), m_explosionEffect,
location, GetActorRotation(), true);
}
bool AWizardMeteor::multiSpawnEffect_Validate(FVector location)
{
return true;
}
void AWizardMeteor::setCaster(ARobotRebellionCharacter* p)
{
m_caster = p;
}
<file_sep>/Source/RobotRebellion/Gameplay/Damage/DamageCoefficientLogic.cpp
// Fill out your copyright notice in the Description page of Project Settings.
#include "RobotRebellion.h"
#include "DamageCoefficientLogic.h"
bool DamageCoefficientLogic::establishCritical(const FName& boneName) const USE_NOEXCEPT
{
static const TArray<FName> criticalBones{
TEXT("Head"),
TEXT("Neck_01"),
TEXT("Spine3")
};
return criticalBones.Contains(boneName);
}<file_sep>/Source/RobotRebellion/IA/Controller/GunTurretAIController.cpp
// Fill out your copyright notice in the Description page of Project Settings.
#include "RobotRebellion.h"
#include "GunTurretAIController.h"
#include "Character/NonPlayableCharacter.h"
#include "IA/Character/SovecCharacter.h"
#include "IA/Character/BeastCharacter.h"
#include "IA/Character/RobotsCharacter.h"
#include "Gameplay/Weapon/WeaponInventory.h"
#include "Gameplay/Weapon/WeaponBase.h"
#include "Global/EntityDataSingleton.h"
void AGunTurretAIController::CheckEnnemyNear(float range)
{
APawn *currentPawn = GetPawn();
FVector MultiSphereStart = currentPawn->GetActorLocation();
FVector MultiSphereEnd = MultiSphereStart + FVector(0, 0, 15.0f);
TArray<TEnumAsByte<EObjectTypeQuery>> ObjectTypes;
ObjectTypes.Add(UEngineTypes::ConvertToObjectType(ECC_GameTraceChannel6)); // Beast
ObjectTypes.Add(UEngineTypes::ConvertToObjectType(ECC_GameTraceChannel3)); // Robots
TArray<AActor*> ActorsToIgnore;
ActorsToIgnore.Add(currentPawn);
TArray<FHitResult> OutHits;
bool Result = UKismetSystemLibrary::SphereTraceMultiForObjects(GetWorld(),
MultiSphereStart,
MultiSphereEnd,
range,
ObjectTypes,
false,
ActorsToIgnore,
this->debugDrawTraceShowingMode(),
OutHits,
true);
if(Result == true)
{
for(int32 i = 0; i < OutHits.Num(); i++)
{
FHitResult Hit = OutHits[i];
ARobotRebellionCharacter* RRCharacter = Cast<ARobotRebellionCharacter>(Hit.GetActor());
if(NULL != RRCharacter)
{
if(RRCharacter->isDead() || !RRCharacter->isVisible())
{
continue;
}
setTarget(RRCharacter);
break;
}
}
}
else
{
setTarget(nullptr);
}
}
void AGunTurretAIController::AttackTarget() const
{
ANonPlayableCharacter* ennemiCharacter = Cast<ANonPlayableCharacter>(GetCharacter());
ennemiCharacter->m_weaponInventory->getCurrentWeapon()->cppAttack(ennemiCharacter);
}<file_sep>/Source/RobotRebellion/Gameplay/Spell/DamageZone.h
// Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "GameFramework/Actor.h"
#include "DamageZone.generated.h"
UCLASS()
class ROBOTREBELLION_API ADamageZone : public AActor
{
GENERATED_BODY()
public:
/** radius to define the damage zone*/
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = DamageZone)
float m_radius;
/** define how many damage will be deal to the actors (damage will be reduced)*/
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = DamageZone)
float m_damagePerTick;
/** how many time the zone should inflict damage in one second*/
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = DamageZone)
float m_tickRate;
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = DamageZone)
bool m_isMolotov;
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = DamageZone)
TArray<TEnumAsByte<EObjectTypeQuery>> m_objectTypes;
private:
// Private float to avoid doing the division every tick
float m_secondBetweenTick;
// Store how many long ago was the last tick
float m_deltaSinceLastTick;
int m_burnedActors;
public:
// Sets default values for this actor's properties
ADamageZone();
// Called when the game starts or when spawned
virtual void BeginPlay() override;
// Called every frame
virtual void Tick(float DeltaSeconds) override;
};
<file_sep>/Source/RobotRebellion/UI/OptionsMenuWidget.cpp
// Fill out your copyright notice in the Description page of Project Settings.
#include "RobotRebellion.h"
#include "Tool/UtilitaryMacros.h"
//#include "Engine/HairWorksAsset.h"
#include "OptionsMenuWidget.h"
#include "Global/EntityDataSingleton.h"
#include "Global/WorldInstanceEntity.h"
UOptionsMenuWidget::UOptionsMenuWidget()
{
//ConstructorHelpers::FObjectFinder<UObject> hairworkMaterialObject(TEXT("/Game/MixamoAnimPack/Mixamo_Maw/Materials/Maw_Hair"));
//UHairWorksAsset* hairworksAsset = Cast<UHairWorksAsset>(hairworkMaterialObject.Object);
//if(hairworksAsset)
//{
// m_hairworksMaterial = hairworksAsset->HairMaterial;
//}
}
void UOptionsMenuWidget::OptionsMenuCheckBox1(bool checkBoxStatus)
{
//if(m_hairworksMaterial)
//{
// m_hairworksMaterial->bEnable = checkBoxStatus;
//}
}
void UOptionsMenuWidget::OptionsMenuCheckBox2(bool checkBoxStatus)
{
TArray<AActor*> entity;
UGameplayStatics::GetAllActorsOfClass(GetWorld(), AWorldInstanceEntity::StaticClass(), entity);
if(entity.Num() > 0)
{
AWorldInstanceEntity* ent = Cast<AWorldInstanceEntity>(entity[0]);
ent->setShieldAnimation(checkBoxStatus);
}
}
void UOptionsMenuWidget::OptionsMenuCheckBox3(bool checkBoxStatus)
{
TArray<AActor*> outResult;
UGameplayStatics::GetAllActorsOfClass(GetWorld(), APostProcessVolume::StaticClass(), outResult);
for(AActor* postProcessActorVolume : outResult)
{
APostProcessVolume* postProcessVolume = Cast<APostProcessVolume>(postProcessActorVolume);
if(postProcessVolume && postProcessVolume->GetName() == "PostProcessVolume")
{
postProcessVolume->BlendWeight = checkBoxStatus ? 1.f : 0.f;
}
}
}
// Disable Burn Effect
void UOptionsMenuWidget::OptionsMenuCheckBox4(bool checkBoxStatus)
{
TArray<AActor*> entity;
UGameplayStatics::GetAllActorsOfClass(GetWorld(), AWorldInstanceEntity::StaticClass(), entity);
if(entity.Num() > 0)
{
AWorldInstanceEntity* ent = Cast<AWorldInstanceEntity>(entity[0]);
ent->setIsBurnEffectEnabled(checkBoxStatus);
}
}
void UOptionsMenuWidget::OptionsMenuCheckBox5(bool checkBoxStatus)
{
TArray<AActor*> outResult;
UGameplayStatics::GetAllActorsOfClass(GetWorld(), APostProcessVolume::StaticClass(), outResult);
for (AActor* postProcessActorVolume : outResult)
{
APostProcessVolume* postProcessVolume = Cast<APostProcessVolume>(postProcessActorVolume);
if(postProcessVolume && postProcessVolume->GetName().Contains("Fog"))
{
postProcessVolume->BlendWeight = checkBoxStatus ? 1.f : 0.f;
}
}
}<file_sep>/Source/RobotRebellion/IA/BT/IsTargetInRangeBTTaskNode.h
// Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "BehaviorTree/BTTaskNode.h"
#include "IsTargetInRangeBTTaskNode.generated.h"
/**
*
*/
UCLASS()
class ROBOTREBELLION_API UIsTargetInRangeBTTaskNode : public UBTTaskNode
{
GENERATED_BODY()
public:
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "AIBT | Settings")
float m_detectingRange;
UIsTargetInRangeBTTaskNode();
virtual EBTNodeResult::Type ExecuteTask(UBehaviorTreeComponent& OwnerComp,
uint8* NodeMemory) override;
virtual void TickTask(class UBehaviorTreeComponent& OwnerComp, uint8* NodeMemory,
float DeltaSeconds) override;
virtual FString GetStaticDescription() const override;
};
<file_sep>/Source/RobotRebellion/Global/EntityDataSingleton.cpp
// Fill out your copyright notice in the Description page of Project Settings.
#include "RobotRebellion.h"
#include "EntityDataSingleton.h"
#include "Character/RobotRebellionCharacter.h"
#include "Character/PlayableCharacter.h"
#include "Character/Drone.h"
#include "Character/King.h"
#include "IA/Character/SovecCharacter.h"
#include "IA/Character/RobotsCharacter.h"
void EntityDataSingleton::update(const UWorld* world)
{
m_playableCharacterArray.Reset();
m_robotArray.Reset();
if(world)
{
TArray<AActor*> foundActors;
UGameplayStatics::GetAllActorsOfClass(world, ARobotRebellionCharacter::StaticClass(), foundActors);
for(AActor* current : foundActors)
{
if(
updateType(current, m_robotArray) ||
updateType(current, m_playableCharacterArray)
)
{
continue;
}
if(updateType(current, m_king))
{
if(m_king->Role >= ROLE_Authority)
{
m_serverKing = m_king;
}
}
else if(updateType(current, m_drone))
{
if(m_drone->Role >= ROLE_Authority)
{
m_serverDrone = m_drone;
}
}
}
}
}
void EntityDataSingleton::clean()
{
m_playableCharacterArray.Reset();
m_robotArray.Reset();
m_king = nullptr;
m_drone = nullptr;
m_serverKing = nullptr;
m_serverDrone = nullptr;
}<file_sep>/Source/RobotRebellion/Character/CustomPlayerController.h
// Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "GameFramework/PlayerController.h"
#include "CustomPlayerController.generated.h"
/**
*
*/
UCLASS()
class ROBOTREBELLION_API ACustomPlayerController : public APlayerController
{
GENERATED_BODY()
public:
UFUNCTION(Reliable, Client)
void setInputMode(bool status);
void BeginPlay() override;
void Tick(float deltaTime) override;
void GetLifetimeReplicatedProps(TArray< FLifetimeProperty > & OutLifetimeProps) const override;
};
<file_sep>/Source/RobotRebellion/Gameplay/Weapon/RestoreHealthProjectile.cpp
// Fill out your copyright notice in the Description page of Project Settings.
#include "RobotRebellion.h"
#include "RestoreHealthProjectile.h"
ARestoreHealthProjectile::ARestoreHealthProjectile() : AProjectile()
{}
void ARestoreHealthProjectile::BeginPlay()
{
Super::BeginPlay();
}
void ARestoreHealthProjectile::Tick(float DeltaSeconds)
{
Super::Tick(DeltaSeconds);
}
void ARestoreHealthProjectile::inflictDamageLogic(class AActor* otherActor, const FHitResult& hit)
{
ARobotRebellionCharacter* receiver = Cast<ARobotRebellionCharacter>(otherActor);
if(receiver && m_owner != receiver && !receiver->isDead() && !receiver->isImmortal())
{
receiver->restoreHealth(m_restoredHealth);
}
}<file_sep>/Source/RobotRebellion/Character/CustomPlayerController.cpp
// Fill out your copyright notice in the Description page of Project Settings.
#include "RobotRebellion.h"
#include "CustomPlayerController.h"
void ACustomPlayerController::setInputMode_Implementation(bool status)
{
if(status)
{
FInputModeGameOnly Mode;
bShowMouseCursor = false;
SetInputMode(Mode);
}
else
{
FInputModeGameAndUI Mode;
Mode.SetLockMouseToViewportBehavior(EMouseLockMode::LockOnCapture);
Mode.SetHideCursorDuringCapture(false);
bShowMouseCursor = true;
SetInputMode(Mode);
}
}
void ACustomPlayerController::BeginPlay()
{
Super::BeginPlay();
}
void ACustomPlayerController::Tick(float deltaTime)
{
Super::Tick(deltaTime);
}
void ACustomPlayerController::GetLifetimeReplicatedProps(TArray< FLifetimeProperty > & OutLifetimeProps) const
{
Super::GetLifetimeReplicatedProps(OutLifetimeProps);
}
<file_sep>/Source/RobotRebellion/Global/LootTable.cpp
// Fill out your copyright notice in the Description page of Project Settings.
#include "RobotRebellion.h"
#include "LootTable.h"
// Sets default values for this component's properties
ULootTable::ULootTable()
{
// Set this component to be initialized when the game starts, and to be ticked every frame. You can turn these features
// off to improve performance if you don't need them.
PrimaryComponentTick.bCanEverTick = true;
// ...
}
// Called when the game starts
void ULootTable::BeginPlay()
{
Super::BeginPlay();
// ...
}
// Called every frame
void ULootTable::TickComponent(float DeltaTime, ELevelTick TickType, FActorComponentTickFunction* ThisTickFunction)
{
Super::TickComponent(DeltaTime, TickType, ThisTickFunction);
// ...
}
void ULootTable::dropItem(const FVector &pos)
{
TArray<int32> tempProb;
int indexCopy = 0;
int32 indexProbMax = m_probs.Num();
for(indexCopy; indexCopy < indexProbMax; ++indexCopy)
{
tempProb.Emplace(m_probs[indexCopy]);
}
for(indexCopy; indexCopy < m_objects.Num(); ++indexCopy)
{
tempProb.Emplace(m_probs[indexProbMax - 1]);
} // We can now work on tempProb
int32 currentMax = 0;
int32 lastProba = 0;
UWorld* const world = GetOwner()->GetWorld();
int32 randomNumber = FMath::RandRange(0, 100);
for(int i = 0; i < m_objects.Num(); ++i)
{
currentMax = lastProba + tempProb[i];
if(randomNumber < currentMax)
{
PRINT_MESSAGE_ON_SCREEN(FColor::Black, "Drop " + FString::FromInt(i));
world->SpawnActor<AActor>(m_objects[i], pos, FRotator());
break;
}
lastProba = currentMax;
}
}
<file_sep>/Source/RobotRebellion/Character/Wizard.cpp
// Fill out your copyright notice in the Description page of Project Settings.
#include "RobotRebellion.h"
#include "Wizard.h"
AWizard::AWizard() :APlayableCharacter()
{}
<file_sep>/Source/RobotRebellion/Global/AudioManager.cpp
#include "RobotRebellion.h"
#include "AudioManager.h"
#include "ActiveSound.h"
void AudioManager::stopBackgroundMusicWithException(UAudioComponent* soundToNotMute)
{
if (GEngine)
{
const TArray<FActiveSound*> sounds = GEngine->GetActiveAudioDevice()->GetActiveSounds();
for (auto sound : sounds)
{
UAudioComponent *audioComp = UAudioComponent::GetAudioComponentFromID(sound->GetAudioComponentID());
if (audioComp)
{
if (audioComp->GetAudioComponentID() != soundToNotMute->GetAudioComponentID())
{
audioComp->Stop();
}
}
}
}
}
void AudioManager::muteAllBackgroundSoundsWithException(UAudioComponent* soundToNotMute)
{
if(GEngine)
{
const TArray<FActiveSound*> sounds = GEngine->GetActiveAudioDevice()->GetActiveSounds();
for(auto sound : sounds)
{
UAudioComponent *audioComp = UAudioComponent::GetAudioComponentFromID(sound->GetAudioComponentID());
if(audioComp)
{
if(audioComp->GetAudioComponentID() != soundToNotMute->GetAudioComponentID())
{
audioComp->SetVolumeMultiplier(0.f);
}
}
}
}
}
void AudioManager::playBackgroundMusic(UAudioComponent * audioComponent)
{
if (audioComponent)
{
stopBackgroundMusicWithException(audioComponent);
if(!audioComponent->IsPlaying())
{
audioComponent->Play();
}
}
}
//
//void AudioManager::setGlobalVolume(float volume)
//{
//
//}
<file_sep>/Source/RobotRebellion/Gameplay/Weapon/RaycastProjectile.h
// Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "Gameplay/Weapon/Projectile.h"
#include "RaycastProjectile.generated.h"
/**
*
*/
UCLASS()
class ROBOTREBELLION_API ARaycastProjectile : public AProjectile
{
GENERATED_BODY()
public:
FORCEINLINE virtual bool isRaycast() const USE_NOEXCEPT override
{
return true;
}
};
| 371882f57f9936798e8a720f8ddfb6e989b88512 | [
"Markdown",
"C",
"C++",
"INI"
] | 190 | C++ | SunlayGGX/RobotRebellionWithoutAssets | d88f656f605fb2fcff05dc418e5fc0db973a7a4f | 09003bfa26a3bf1f5f38fdfc2d104bfb88bd6c6c |
refs/heads/master | <file_sep>export NPM_PACKAGES="${HOME}/.npm-packages"
export PATH=/usr/local/apache-maven-3.2.1/bin:/usr/local/bin:"$NPM_PACKAGES/bin":$PATH
export MAVEN_OPTS=-Xmx1024m
export M2_HOME=/usr/local/apache-maven-3.2.1
export JAVA_6_HOME=/System/Library/Frameworks/JavaVM.framework/Versions/CurrentJDK/Home
export JAVA_7_HOME=/Library/Java/JavaVirtualMachines/jdk1.7.0_45.jdk/Contents/Home
# Quickly switch between Java versions
alias java6='export JAVA_HOME=$JAVA_6_HOME;echo JAVA_HOME=$JAVA_6_HOME'
alias java7='export JAVA_HOME=$JAVA_7_HOME;echo JAVA_HOME=$JAVA_7_HOME'
# Show or hide hidden files in Finder
alias showFiles='defaults write com.apple.finder AppleShowAllFiles YES; killall Finder /System/Library/CoreServices/Finder.app'
alias hideFiles='defaults write com.apple.finder AppleShowAllFiles NO; killall Finder /System/Library/CoreServices/Finder.app'
# Modify hosts file
alias hosts='sudo nano /etc/hosts'
# List only directories
alias lsd='ls -l | grep "^d"'
# List IP addresses
alias ips="ifconfig -a | perl -nle'/(\d+\.\d+\.\d+\.\d+)/ && print $1'"
# Recursively delete .DS_Store files, handy before distributing packages
alias nods="find . -name '*.DS_Store' -type f -ls -delete"
| 5aa57bfd19f450cac72cd49d80e88fedab530df1 | [
"Shell"
] | 1 | Shell | stuartbennett/dotfiles | fd322013674c8897817a5321a4a5d0250f91270b | 59f464257f4de6a5ca53069bd3473d5ecef9b05e |
refs/heads/master | <repo_name>GINGMEE29/flask-pybo<file_sep>/migrations/versions/c0631c3cc09a_.py
"""empty message
Revision ID: c0631c3cc09a
Revises: c<PASSWORD>
Create Date: 2021-01-28 10:27:46.075460
"""
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import mysql
# revision identifiers, used by Alembic.
revision = 'c0631c3cc09a'
down_revision = 'c438d923bccd'
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.add_column('answer', sa.Column('user_id', sa.Integer(), server_default='1', nullable=True))
op.create_foreign_key(None, 'answer', 'user', ['user_id'], ['id'], ondelete='CASCADE')
op.alter_column('question', 'user_id',
existing_type=mysql.INTEGER(),
nullable=False)
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.alter_column('question', 'user_id',
existing_type=mysql.INTEGER(),
nullable=True)
op.drop_constraint(None, 'answer', type_='foreignkey')
op.drop_column('answer', 'user_id')
# ### end Alembic commands ###
<file_sep>/config.py
import os
BASE_DIR = os.path.dirname(__file__)
SQLALCHEMY_DATABASE_URI = f"mysql+mysqlconnector://admin:finman12@localhost:3306/samples?charset=utf8"
SQLALCHEMY_TRACK_MODIFICATIONS = False
SECRET_KEY = "dev"<file_sep>/migrations/versions/14449430ba53_.py
"""empty message
Revision ID: 14449430ba53
Revises: <PASSWORD>
Create Date: 2021-01-30 12:15:40.501321
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '14449430ba53'
down_revision = '<PASSWORD>'
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.create_foreign_key(None, 'answer', 'user', ['user_id'], ['id'], ondelete='CASCADE')
op.add_column('question', sa.Column('modify_date', sa.DateTime(), nullable=True))
op.create_foreign_key(None, 'question', 'user', ['user_id'], ['id'], ondelete='CASCADE')
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_constraint(None, 'question', type_='foreignkey')
op.drop_column('question', 'modify_date')
op.drop_constraint(None, 'answer', type_='foreignkey')
# ### end Alembic commands ###
<file_sep>/migrations/versions/a2967ac698e4_.py
"""empty message
Revision ID: a2967ac698e4
Revises: c0631c3cc09a
Create Date: 2021-01-28 10:30:56.323853
"""
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import mysql
# revision identifiers, used by Alembic.
revision = 'a2967ac698e4'
down_revision = 'c0631c3cc09a'
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.alter_column('answer', 'user_id',
existing_type=mysql.INTEGER(),
nullable=False,
existing_server_default=sa.text("'1'"))
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.alter_column('answer', 'user_id',
existing_type=mysql.INTEGER(),
nullable=True,
existing_server_default=sa.text("'1'"))
# ### end Alembic commands ###
| 1651f97dc342e6f5552ddc75c7e8f84a01321710 | [
"Python"
] | 4 | Python | GINGMEE29/flask-pybo | e32441edbf204c828b8cebc8eec6d925843ee9c3 | a106d823385f2e198ef61f749e1366903f03480a |
refs/heads/master | <file_sep>//
// ViewController.swift
// UCSD-CSSA-What-To-Eat
//
// Created by <NAME> on 10/17/15.
// Copyright © 2015 <NAME>. All rights reserved.
import UIKit
import GLKit
import AudioToolbox
var currentListName = "1"
class ViewController: UIViewController {
var def = UserDefaults.standard
var shaked = true
var cellDescriptors: NSMutableArray!
var ListNames = ["Dining Hall", "Campus", "Convoy", "My List"];
@IBOutlet weak var shakeMe: UIImageView!
@IBOutlet weak var filterButton: UIImageView!
@IBOutlet weak var filterName: UILabel!
@IBOutlet weak var dice: UIImageView!
@IBOutlet weak var selectedName: UILabel!
@IBOutlet weak var utf8Name: UILabel!
//Prevent user from rotating the view
override var shouldAutorotate : Bool {
return false
}
override var supportedInterfaceOrientations : UIInterfaceOrientationMask {
return UIInterfaceOrientationMask.portrait
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
icon.iconSize = 0.5*self.view.frame.width
initMyLayer(getPngSelected())
print("!!!");
print(getPngSelected());
self.filterButton.isUserInteractionEnabled = true
if(UserDefaults.standard.array(forKey: "ListNames") != nil)
{
ListNames = UserDefaults.standard.array(forKey: "ListNames")as! [String]
}
else
{
ListNames = ["Dining Hall", "Campus", "Convoy", "My List"];
}
if(UserDefaults.standard.string(forKey: "currentListName") != nil)
{
currentListName = UserDefaults.standard.string(forKey: "currentListName")!
print("HERE")
}
else
{
UserDefaults.standard.setValue("1", forKey: "currentListName")
}
if def.object(forKey: "EnableSound") == nil {
def.set(true, forKey: "EnableSound")
print("set")
}
filterName.text = ListNames[Int(currentListName)! - 1];
//print("viewdidiload")
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
UIApplication.shared.statusBarStyle = .lightContent
print("!!!");
print(getPngSelected());
self.iconview.alpha = 0
self.selectedName.alpha = 0
self.utf8Name.alpha = 0
self.shakeMe.alpha = 1
self.dice.alpha = 1
updatePool (getPngSelected())
if(UserDefaults.standard.array(forKey: "ListNames") != nil)
{
ListNames = UserDefaults.standard.array(forKey: "ListNames")as! [String]
}
else
{
ListNames = ["Dining Hall", "Campus", "Convoy", "My List"];
}
if(UserDefaults.standard.string(forKey: "currentListName") != nil)
{
print("HERE")
currentListName = UserDefaults.standard.string(forKey: "currentListName")!
}
else
{
UserDefaults.standard.setValue("1", forKey: "currentListName")
}
filterName.text = ListNames[Int(currentListName)! - 1];
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
UIApplication.shared.statusBarStyle = UIStatusBarStyle.default
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?){
let touch: UITouch? = touches.first
if touch?.view == filterButton{
let FilterViewController = self.storyboard!.instantiateViewController(withIdentifier: "FilterViewController")
self.present(FilterViewController, animated: true, completion: nil)
}
super.touchesEnded(touches, with: event)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override var canBecomeFirstResponder : Bool {
return true
}
//For detect motion start event
override func motionBegan(_ motion: UIEventSubtype, with event: UIEvent?) {
if motion == .motionShake{
}
}
//For detecting motion end evenet
override func motionEnded(_ motion: UIEventSubtype, with event: UIEvent?) {
if motion == .motionShake {
if(UserDefaults.standard.bool(forKey: "EnableSound") == true){
let musicSelected = UserDefaults.standard.string(forKey: "musicSelected")
if let soundURL = Bundle.main.url(forResource: musicSelected, withExtension: "mp3") {
var mySound: SystemSoundID = 0
AudioServicesCreateSystemSoundID(soundURL as CFURL, &mySound)
// Play
AudioServicesPlaySystemSound(mySound);
}
}
self.startAnimation()
}
}
var icons = [icon]()
var chosen0 = icon(superframe: CGRect())
var chosen1 = icon(superframe: CGRect())
var myLayer = CALayer()
var blurView = UIVisualEffectView()
var myview = UIView()
func initMyLayer(_ randomPool:Array<resinfo>) -> Void
{
icon.randomPool = randomPool
let blurEffect = UIBlurEffect(style: UIBlurEffectStyle.dark)
blurView = UIVisualEffectView(effect: blurEffect)
blurView.frame = CGRect(x: 0, y: 0, width: self.view.frame.width, height: self.view.frame.height)
self.view.insertSubview(blurView, at: 0)
myview = UIView(frame: CGRect(x: 0, y: 0, width: self.view.frame.width, height: self.view.frame.height/2.0))
myLayer.frame = myview.frame
myview.layer.addSublayer(myLayer)
self.view.insertSubview(myview, at: 0)
for x in -6...3
{
for y in -3...3
{
let i = icon(superframe: myview.frame)
i.shuffle()
i.x = x
i.y = y
icons.append(i)
myLayer.addSublayer(i.layer)
if (x==0 && y==0)
{
chosen0 = i
}
else if (x == -3 && y==0)
{
chosen1 = i
}
}
}
chosen0.layer.zPosition = 1
chosen1.layer.zPosition = 1
chosen0.layer.shadowColor = UIColor.black.cgColor
chosen0.layer.shadowOffset = CGSize(width: 5, height: 5)
chosen0.layer.shadowRadius = 5
chosen1.layer.shadowColor = UIColor.black.cgColor
chosen1.layer.shadowOffset = CGSize(width: 5, height: 5)
chosen1.layer.shadowRadius = 5
myview.layer.allowsEdgeAntialiasing = true
let model:GLKMatrix4! = GLKMatrix4Identity
myLayer.transform = getTransformWithModel(model)
//Icon view is the final big image displayed
iconview = UIView(frame: CGRect(x: 0, y: 0, width: self.view.frame.width, height: self.view.frame.height/2.0))
iconview.alpha = 0
iconviewObj = icon(superframe: iconview.frame)
iconview.layer.addSublayer(iconviewObj.layer)
iconviewObj.shuffle()
self.view.addSubview(iconview)
}
func getTransformWithModel(_ model:GLKMatrix4) -> CATransform3D
{
let ratio = Float(self.view.frame.width/500)
let view:GLKMatrix4! = GLKMatrix4MakeLookAt(-100.0*ratio, 300.0*ratio, 400.0*ratio, 0, 0, 0, 0, 0, -1)
let perspective:GLKMatrix4! = GLKMatrix4MakePerspective(Float(0.3 * M_PI), 1, 0.1, 10.0)
var ts:GLKMatrix4!
ts = GLKMatrix4MakeScale(2.0/Float(self.view.frame.width), 2.0/Float(self.view.frame.width), 2.0/Float(self.view.frame.width))
let tsi:GLKMatrix4! = GLKMatrix4Invert(ts, nil)
var mvp:GLKMatrix4! = GLKMatrix4Identity
mvp = GLKMatrix4Multiply(model, mvp)
mvp = GLKMatrix4Multiply(view, mvp)
mvp = GLKMatrix4Multiply(ts, mvp)
mvp = GLKMatrix4Multiply(perspective, mvp)
mvp = GLKMatrix4Multiply(tsi, mvp)
let cat = CATransform3D(m11: CGFloat(mvp.m00), m12: CGFloat(mvp.m01), m13: CGFloat(mvp.m02), m14: CGFloat(mvp.m03), m21: CGFloat(mvp.m10), m22: CGFloat(mvp.m11), m23: CGFloat(mvp.m12), m24: CGFloat(mvp.m13), m31: CGFloat(mvp.m20), m32: CGFloat(mvp.m21), m33: CGFloat(mvp.m22), m34: CGFloat(mvp.m23), m41: CGFloat(mvp.m30), m42: CGFloat(mvp.m31), m43: CGFloat(mvp.m32), m44: CGFloat(mvp.m33))
return cat
}
//#TODO call updatePool from filter view
func updatePool (_ randomPool:Array<resinfo>) -> Void
{
icon.randomPool = randomPool
for i in icons
{
i.shuffle()
}
}
var timer = Timer()
func startAnimation() -> Void
{
frameCount = 0
iconviewObj.layer.transform = self.getTransformWithModel(GLKMatrix4Identity)
UIView.animate(withDuration: 0.3, delay: 0.0, options: UIViewAnimationOptions.curveEaseOut, animations: {self.iconview.alpha = 0
self.shakeMe.alpha = 0
self.dice.alpha = 0
self.selectedName.alpha = 0
self.utf8Name.alpha = 0}, completion: nil)
UIView.animate(withDuration: 0.3, delay: 0.0, options: UIViewAnimationOptions.curveEaseOut, animations: {self.blurView.frame = CGRect(x: 0, y: self.view.frame.height * 0.75, width: self.view.frame.width, height: self.view.frame.height * 0.25)}, completion: nil)
timer.invalidate()
timer = Timer.scheduledTimer(timeInterval: 0.05, target: self, selector: #selector(ViewController.animationUpdate), userInfo: nil, repeats: true)
}
var iconview = UIView()
var iconviewObj = icon(superframe: CGRect())
func stopAnimation() -> Void
{
timer.invalidate()
timer = Timer()
chosen0.dx = 0.0
chosen0.dy = 0.0
chosen0.rotate = 0.0
chosen1.dx = 0.0
chosen1.dy = 0.0
chosen1.rotate = 0.0
if (isMoved)
{
iconviewObj.n = chosen1.n
self.selectedName.text = icon.randomPool[chosen1.n].englishName
self.utf8Name.text = icon.randomPool[chosen1.n].utf8Name
}
else
{
iconviewObj.n = chosen0.n
self.selectedName.text = icon.randomPool[chosen0.n].englishName
self.utf8Name.text = icon.randomPool[chosen0.n].utf8Name
}
let delay = 0.5 * Double(NSEC_PER_SEC)
let time = DispatchTime.now() + Double(Int64(delay)) / Double(NSEC_PER_SEC)
DispatchQueue.main.asyncAfter(deadline: time) {
self.iconview.alpha = 1
}
UIView.animate(withDuration: 0.3, delay: 0.5, options: UIViewAnimationOptions.curveEaseOut, animations: {self.blurView.frame = self.view.frame}, completion: chosenRotate)
}
func chosenRotate (_: Bool) -> Void
{
iconviewObj.layer.transform = CATransform3DMakeScale(1.04, 1.04, 1)
UIView.animate(withDuration: 0.5, animations: {self.selectedName.alpha = 1
self.utf8Name.alpha = 1})
}
func getResult() -> resinfo
{
if (isMoved)
{
return icon.randomPool[chosen1.n]
}
else
{
return icon.randomPool[chosen0.n]
}
}
var frameCount = 0
var isMoved = false
//Function that supports icon moving
func animationUpdate () -> Void
{
for i in icons{
let r = Int(arc4random_uniform(12))
let dx = Int(arc4random_uniform(400))
let dy = Int(arc4random_uniform(400))
i.rotate = CGFloat(r-6)/2
i.dx = CGFloat(dx)-200
i.dy = CGFloat(dy)-200
}
if (frameCount%4 == 0)
{
var model = GLKMatrix4Identity
if(!isMoved)
{
model = GLKMatrix4MakeTranslation(750, 0, 0)
}
myLayer.transform = getTransformWithModel(model)
chosen0.shuffle()
chosen1.shuffle()
isMoved = !isMoved
}
frameCount += 1
if frameCount>14{
stopAnimation()
}
}
func getPngSelected() -> Array<resinfo>
{
let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
let fileName = "CellDescriptor" + currentListName + ".plist"
let fileURL = documentsURL.appendingPathComponent(fileName)
let path = fileURL.path
let fileManager = FileManager.default
//check if file exists
if(!fileManager.fileExists(atPath: path))
{
// If it doesn't, copy it from the default file in the Bundle
if let bundlePath = Bundle.main.path(forResource: "CellDescriptor" + currentListName, ofType: "plist") {
let resultDictionary = NSMutableDictionary(contentsOfFile: bundlePath)
print("Bundle CellDescriptor.plist file is --> \(resultDictionary?.description)")
do {
try fileManager.copyItem(atPath: bundlePath, toPath: path)
} catch _ {
print("error")
}
//fileManager.copyItemAtPath(bundlePath, toPath: path)
print("copy")
} else {
print("CellDescriptor.plist not found. Please, make sure it is part of the bundle.")
}
}
cellDescriptors = NSMutableArray(contentsOfFile: path)
var returnArray = [resinfo]()
for currentSectionCells in cellDescriptors
{
for row in 0...((currentSectionCells as! [[String: AnyObject]]).count - 1)
{
if ((currentSectionCells as? NSArray)![row] as? NSDictionary)!["cellIdentifier"] as!
String == "idItemCell"
{
//print(((currentSectionCells as? NSArray)![row] as? NSDictionary)!["checked"])
if ((currentSectionCells as? NSArray)![row] as? NSDictionary)!["checked"] as! Bool == true
{
let png = ((currentSectionCells as? NSArray)![row] as? NSDictionary)!["png"] as! String
//var tmp = (currentSectionCells as! NSArray)[row]
var englishName = ((currentSectionCells as! NSArray)[row] as! NSDictionary)["label"]
if(englishName != nil){
}
else{
englishName = ""
}
var utf8Name = ((currentSectionCells as! NSArray)[row] as! NSDictionary)["utf8Name"]
if(utf8Name != nil){
print ("tmp1 is")
//print((currentSectionCells as! NSArray)[row]["a"])
}
else{
utf8Name = ""
}
let r = resinfo(png:png, englishName:englishName as! String, utf8Name:utf8Name as! String)
print(r.png)
returnArray.append(r)
}
}
}
}
return returnArray
}
}
| 30968bdcd753086f627a199dcdb0125606bd4196 | [
"Swift"
] | 1 | Swift | huangsuli/UCSD-CSSA-WHAT-TO-EAT | e9ae2e8efde0990c48a33e7cfa54335b66945c6a | 76c71dbcc9fdd80afb9e4968b797279cbe81bdd6 |
refs/heads/master | <file_sep># Bloc-Jams
Created by <NAME>
link: [Bloc-Jams]()
Bloc-Jams is the first web application I created for my front-end course at [Bloc](www.bloc.io). This application was made using HTML, CSS, and Javascript. Then it was refactored into jQuery for learning purposes. <file_sep>var createSongRow = function(songNumber, songName, songLength) {
var template =
'<tr class="album-view-song-item">' +
' <td class="song-item-number" data-song-number="' + songNumber + '">' + songNumber + '</td>' +
' <td class="song-item-title">' + songName + '</td>' +
' <td class="song-item-duration">' + songLength + '</td>' +
'</tr>';
var $row = $(template);
var clickHandler = function() {
var songNumber = parseInt($(this).attr('data-song-number'));
// If a song is currently playing, revert that song button to the song's number
if (currentlyPlayingSongNumber !== null) {
// Revert to song number for currently playing song because user started playing new song.
var currentlyPlayingCell = getSongNumberCell(currentlyPlayingSongNumber);
currentlyPlayingCell.html(currentlyPlayingSongNumber);
}
// If song clicked is not the currentlyPlayingSong, make it the currentlyPlayingSong and
// display a pause button
if (currentlyPlayingSongNumber !== songNumber) {
setSong(songNumber);
//Play the song that was clicked
currentSoundFile.play();
updateSeekBarWhileSongPlays();
//Store the currently playing song name and length object
currentSongFromAlbum = currentAlbum.songs[songNumber - 1];
var $volumeFill = $('.volume .fill');
var $volumeThumb = $('.volume .thumb');
$volumeFill.width(currentVolume + '%');
$volumeThumb.css({left: currentVolume + '%'});
$(this).html(pauseButtonTemplate);
updatePlayerBarSong();
// If clicking the currently playing song, revert the currentlyPlayingSong to null and
// display the play button
} else if (currentlyPlayingSongNumber === songNumber) {
// Conditional statement checks if the currentSoundFile is paused
// Use Buzz's isPaused() method on currentSoundFile to check if the song is paused or not.
if (currentSoundFile.isPaused()) {
// Update the song's button to pause
$(this).html(pauseButtonTemplate);
$('.main-controls .play-pause').html(playerBarPauseButton);
// If song is paused, start playing the song again and revert the icon
// in the song row and the player bar to the pause button.
currentSoundFile.play();
updateSeekBarWhileSongPlays();
} else {
//Update the songs button to play
$(this).html(playButtonTemplate);
$('.main-controls .play-pause').html(playerBarPlayButton);
//If the song is not paused, pause the song and set the content
// of the song number cell and players bar's pause button back to the play button
currentSoundFile.pause();
}
}
};
var onHover = function(event) {
var songNumberCell = $(this).find('.song-item-number');
var songNumber = parseInt($(songNumberCell).attr('data-song-number'));
if (songNumber !== currentlyPlayingSongNumber) {
songNumberCell.html(playButtonTemplate);
}
};
var offHover = function(event) {
var songNumberCell = $(this).find('.song-item-number');
var songNumber = parseInt($(songNumberCell).attr('data-song-number'));
if (songNumber !== currentlyPlayingSongNumber) {
songNumberCell.html(songNumber);
}
};
// Use find to find the element with .song-item-number class thats contained in whichever row is clicked
$row.find('.song-item-number').click(clickHandler);
//Combines the mouse and mouseleave functions we relied on previously
$row.hover(onHover, offHover);
// return row which is created w/ the event listener attached
return $row;
};
var setCurrentAlbum = function(album) {
console.log(album);
currentAlbum = album;
var $albumTitle = $('.album-view-title');
var $albumArtist = $('.album-view-artist');
var $albumReleaseInfo = $('.album-view-release-info');
var $albumImage = $('.album-cover-art');
var $albumSongList = $('.album-view-song-list');
$albumTitle.text(album.name);
$albumArtist.text(album.artist);
$albumReleaseInfo.text(album.year + ' ' + album.label);
$albumImage.attr('src', album.albumArtUrl);
$albumSongList.empty();
//Loop through each song in the album
for (i = 0; i < album.songs.length; i++) {
var $newRow = createSongRow(i + 1, album.songs[i].title, album.songs[i].duration);
$albumSongList.append($newRow);
console.log($newRow);
}
};
//Helper method to return the index of a song in the albums songs array
var trackIndex = function(album, song) {
return album.songs.indexOf(song);
};
var nextSong = function() {
// Function to help get the last song number so that we can
// update the HTML of the previous song's number
var getLastSongNumber = function(index) {
return index == 0 ? currentAlbum.songs.length : index;
};
// Use the trackIndex() helper function to get the index of the current song and
// then increment the value of the index.
var currentSongIndex = trackIndex(currentAlbum, currentSongFromAlbum);
// Note that we're _incrementing_ the song here
currentSongIndex++;
// If it's the last song, wrap it back around to the first song in the index
if (currentSongIndex >= currentAlbum.songs.length) {
currentSongIndex = 0;
}
// Set the new currently playing song number. Adding 1 to account for array starting at 0.
setSong(currentSongIndex + 1);
currentSoundFile.play();
updateSeekBarWhileSongPlays();
updatePlayerBarSong();
// Update the Player Bar information
$('.currently-playing .song-name').text(currentSongFromAlbum.title);
$('.currently-playing .artist-name').text(currentAlbum.artist);
$('.currently-playing .artist-song-mobile').text(currentSongFromAlbum.title + " - " + currentAlbum.title);
$('.main-controls .play-pause').html(playerBarPauseButton);
var lastSongNumber = getLastSongNumber(currentSongIndex);
var $nextSongNumberCell = getSongNumberCell(currentlyPlayingSongNumber);
var $lastSongNumberCell = getSongNumberCell(lastSongNumber);
$nextSongNumberCell.html(pauseButtonTemplate);
$lastSongNumberCell.html(lastSongNumber);
};
var previousSong = function() {
// Note the difference between this implementation and the one in
// nextSong()
var getLastSongNumber = function(index) {
return index == (currentAlbum.songs.length - 1) ? 1 : index + 2;
};
var currentSongIndex = trackIndex(currentAlbum, currentSongFromAlbum);
// Note that we're _decrementing_ the index here
currentSongIndex--;
if (currentSongIndex < 0) {
currentSongIndex = currentAlbum.songs.length - 1;
}
// Set a new current song
setSong(currentSongIndex + 1);
currentSoundFile.play();
updateSeekBarWhileSongPlays();
updatePlayerBarSong();
// Update the Player Bar information
$('.currently-playing .song-name').text(currentSongFromAlbum.title);
$('.currently-playing .artist-name').text(currentAlbum.artist);
$('.currently-playing .artist-song-mobile').text(currentSongFromAlbum.title + " - " + currentAlbum.title);
$('.main-controls .play-pause').html(playerBarPauseButton);
var lastSongNumber = getLastSongNumber(currentSongIndex);
var $previousSongNumberCell = getSongNumberCell(currentlyPlayingSongNumber);
var $lastSongNumberCell = getSongNumberCell(lastSongNumber);
$previousSongNumberCell.html(pauseButtonTemplate);
$lastSongNumberCell.html(lastSongNumber);
};
var updatePlayerBarSong = function() {
// Set the content of the current song playing in the player bar
$('.currently-playing .song-name').text(currentSongFromAlbum.title);
$('.currently-playing .artist-name').text(currentAlbum.artist);
$('.currently-playing .artist-song-mobile').text(currentSongFromAlbum.title + " - " + currentAlbum.artist);
// Change the play button to a pause button for the currently playing song
$('.main-controls .play-pause').html(playerBarPauseButton);
};
//Combines instances of repeating variables
var setSong = function(songNumber) {
//Prevents concurrent playback
if (currentSoundFile) {
currentSoundFile.stop();
}
currentlyPlayingSongNumber = songNumber;
currentSongFromAlbum = currentAlbum.songs[songNumber - 1];
//Create a new Buzz sound object and pass it the audio URL property of the currentSongFrom Album object
currentSoundFile = new buzz.sound(currentSongFromAlbum.audioUrl, {
formats: [ 'mp3' ],
preload: true
});
setVolume(currentVolume);
};
// Changes the current songs playback location(clicking a new location will seek to the corresponding position in the song)
var seek = function(time) {
if (currentSoundFile) {
// Uses the set time method to change the position in a song to a specified time
currentSoundFile.setTime(time);
}
}
var setVolume = function(volume) {
if (currentSoundFile) {
currentSoundFile.setVolume(volume);
}
};
var getSongNumberCell = function(number) {
return $('.song-item-number[data-song-number="' + number + '"]');
};
var updateSeekBarWhileSongPlays = function() {
if (currentSoundFile) {
// Use Buzz's timeupdate (event that fires repeatedly while time elapses during song playback) to currentSoundFile
currentSoundFile.bind('timeupdate', function(event) {
// Buzz's getTime(to get the current time of the song) and getDuration(to get the total length of the song)
// Calculate the seekBarFillRatio
var seekBarFillRatio = this.getTime() / this.getDuration();
var $seekBar = $('.seek-control .seek-bar');
updateSeekPercentage($seekBar, seekBarFillRatio);
});
}
};
// Method updates Seek bar. Two argurments:
// 1. Seekbar to alter (volumr or audio playback controls)
// 2. Ratio that will determine width and left values of .fill and .thumb classes(respectively)
var updateSeekPercentage = function($seekBar, seekBarFillRatio) {
// Multiply the fill ration by 100 to get percentage
var offsetXPercent = seekBarFillRatio * 100;
// Make sure our percentage is not < 0 && > 100
offsetXPercent = Math.max(0, offsetXPercent);
offsetXPercent = Math.min(100, offsetXPercent);
// Convert the percentage to a string and add % character
var percentageString = offsetXPercent + '%';
//Apply the percentage to the elements CSS
$seekBar.find('.fill').width(percentageString);
$seekBar.find('.thumb').css({left: percentageString});
};
// Determine the seekBarFillRatio in updateSeekPercentage
var setupSeekBars = function() {
// We are finding all the elements in the DOM with a class of seek bar in the player bar class
// this gives us an array containing both the song seek control and volume control
var $seekBars = $('.player-bar .seek-bar');
$seekBars.click(function(event) {
// Find the horizontal coordinate at which the event occured
var offsetX = event.pageX - $(this).offset().left;
// Width of the music bar
var barWidth = $(this).width();
var seekBarFillRatio = offsetX / barWidth;
if ($(this).parent().attr('class') == 'seek-control') {
//Skip to the seekbar percent bar position
seek(seekBarFillRatio * currentSoundFile.getDuration());
} else {
// Set the volume based on the seek bar position
setVolume(seekBarFillRatio * 100);
}
updateSeekPercentage($(this), seekBarFillRatio);
});
// Find elements within the class .thumb in the seekBar(array) and adding event listener for the mouse down event
// Click event fires when a mouse is pressed down and released quickly
$seekBars.find('.thumb').mousedown(function(event) {
//this === .thumb node that was clicked b/c attaching event to both song seek and volume control
var $seekBar = $(this).parent();
$(document).bind('mousemove.thumb', function(event){
var offsetX = event.pageX - $seekBar.offset().left;
var barWidth = $seekBar.width();
var seekBarFillRatio = offsetX / barWidth;
if ($seekBar.parent().attr('class') == 'seek-control') {
//Skip to the seekbar percent in the song
seek(seekBarFillRatio * currentSoundFile.getDuration());
} else {
// Set the volume based on the seek bar position
setVolume(seekBarFillRatio);
}
updateSeekPercentage($seekBar, seekBarFillRatio);
});
$(document).bind('mouseup.thumb', function() {
$(document).unbind('mousemove.thumb');
$(document).unbind('mouseup.thumb');
});
});
};
// Album button templates
var playButtonTemplate = '<a class="album-song-button"><span class="ion-play"></span></a>';
var pauseButtonTemplate = '<a class="album-song-button"><span class="ion-pause"></span></a>';
var playerBarPlayButton = '<span class="ion-play"></span>';
var playerBarPauseButton = '<span class="ion-pause"></span>';
// Store state of playing songs
var currentAlbum = null;
var currentlyPlayingSongNumber = null;
var currentSongFromAlbum = null;
var currentSoundFile = null;
var currentVolume = 80;
var $previousButton = $('.main-controls .previous');
var $nextButton = $('.main-controls .next');
$(document).ready(function() {
setCurrentAlbum(albumPicasso);
setupSeekBars();
$previousButton.click(previousSong);
$nextButton.click(nextSong);
}); | 449ed20a853f9aed3f9991eb413a6867e72e333e | [
"Markdown",
"JavaScript"
] | 2 | Markdown | hd719/Bloc-Jams | f9ecc70e71b2d52c2fa1c84fd1f127092231ea44 | 8b84a37d855e3c262ced43ec59eff5c2ec88587d |
refs/heads/master | <file_sep><!DOCTYPE html>
<html lang="en">
<head>
<title>Heart Disease Risk Predictor</title>
<meta name="viewport" content="width=device-width, initial-scale=1"><!-- defining responsivnes in mobile devices -->
<meta charset="utf-8"><!-- defining the character set for encoding -->
<link href="css/bootstrap.css" rel="stylesheet">
<link href="css/bootstrap.min.css" rel="stylesheet">
<link href="css/bootstrap-theme.css" rel="stylesheet">
<link href="css/bootstrap-theme.min.css" rel="stylesheet">
<link href="css/style.css" rel="stylesheet"> <!-- styling link -->
<link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons"> <!-- google glyphicons -->
<link rel="stylesheet" href="http://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.4.0/css/font-awesome.min.css"> <!--For Awsome Icons -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script> <!-- jQuery library -->
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script> <!-- Latest compiled JavaScript -->
</head>
<body>
<div id="index">
<?php include_once 'navbar.php'; ?>
<div class="container-fluid">
<div id="ttl" class="bs-docs-header" tabindex="-1">
<h1 id="overview">HDRP <small>Heart Disease Risk Predictor</small></h1>
</div>
<div class="col-md-6">
<form action= "process_generalPopulation.php" method= "POST" >
<h2 id="physicianForm" class="page-header">Form</h2>
<a href="#" data-toggle="popover" title="Exercise Induced Angina" data-content="INSERT INFO">
<h4>Exercise Induced Angina* </a><small>Select if the patient has exercise induces angina</small></h4>
<input type="radio" name="exang" id="yes" value="yes" label="yes" required> Yes
<br>
<input type="radio" name="exang" id="no" value="no" label="no" required> No
<br>
<br>
<a href="#" data-toggle="popover" title="Age" data-content="INSERT INFO">
<h4>Age* </a><small>Input the age of the patient in years </small></h4>
<input type="number" class="form-control" name="age" id="age" placeholder="Age" required>
<br>
<br>
<a href="#" data-toggle="popover" title="Gender" data-content="INSERT INFO">
<h4>Gender* </a><small>Select the gender of the patient</small></h4>
<input type="radio" name="sex" id="male" value="male" label="male" required> Male
<br>
<input type="radio" name="sex" id="female" value="female" label="female" required> Female
<br>
<br>
<a href="#" data-toggle="popover" title="Cholestarol" data-content="INSERT INFO">
<h4>Cholestarol* </a><small>Input the cholestarol in ???. If you do non know it select Unknown </small></h4>
<input type="radio" name="chol" id="chol" value="small" label="small" required> <247
<br>
<input type="radio" name="chol" id="chol" value="big" label="big" required> >247
<br>
<input type="radio" name="chol" id="chol" value="unknown" label="unknown" required> Unknown
<br>
<br>
<input type="Submit" class="btn btn-primary btn-lg" value="Submit" />
</form>
</div>
<div class="col-md-6">
<h2 id="physicianDescription" class="page-header">Form Description </h2>
<p>
Please fill out this form. The different types of pain on the chest are described in the question.
Choose one option and fill in your age and gender. If you submit, your risk on a heart disease will be predicted.
</p>
<p>
This risk calculation is based on very few factors, you should always visit a physician to get more accurate results.
</p>
</div>
</div>
<?php include_once 'footer.php'; ?>
<script>
$(document).ready(function(){
$('[data-toggle="popover"]').popover();
});
</script>
</body>
</html>
<file_sep><!DOCTYPE html>
<html lang="en">
<head>
<title>Heart Disease Risk Predictor</title>
<meta name="viewport" content="width=device-width, initial-scale=1"><!-- defining responsivnes in mobile devices -->
<meta charset="utf-8"><!-- defining the character set for encoding -->
<link href="css/bootstrap.css" rel="stylesheet">
<link href="css/bootstrap.min.css" rel="stylesheet">
<link href="css/bootstrap-theme.css" rel="stylesheet">
<link href="css/bootstrap-theme.min.css" rel="stylesheet">
<link href="css/style.css" rel="stylesheet"> <!-- styling link -->
<link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons"> <!-- google glyphicons -->
<link rel="stylesheet" href="http://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.4.0/css/font-awesome.min.css"> <!--For Awsome Icons -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script> <!-- jQuery library -->
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script> <!-- Latest compiled JavaScript -->
</head>
<body>
<div id="index">
<?php include_once 'navbar.php'; ?>
<div class="container-fluid">
<div id="ttl" class="bs-docs-header" tabindex="-1">
<h1 id="overview">HDRP <small>Heart Disease Risk Predictor</small></h1>
</div>
<div class="col-md-6">
<form action= "process_physician.php" method= "POST" >
<h2 id="physicianForm" class="page-header">Form</h2>
<a href="#" data-toggle="popover" title="Age" data-content="INSERT INFO">
<h4>Age*
</a><small>Input the age of the patient in years </small></h4>
<input type="number" class="form-control" name="age" id="age" placeholder="Age" required>
<br>
<br>
<a href="#" data-toggle="popover" title="Chest Pain Type" data-content="
Typical angina: All of the three criteria should be fulfilled if you choose this option.
Pain or sense of intense pressure in the middle of the chest, that can radiate towards arm (most commonly the left arm), towards the neck, back and/or lower jaws.
The above describes discomfort is experienced with increased physical or emotional stress.
The above described discomforts is relieved when allowed to rest and/or by usage of nitroglycerine medications.
Atypical angina: If you experience two of the three points described above you select this option.
Non-anginal pain: If you experience one of the three points described above you select this option, or if you suffer from other symtoms from the chest, but not like the ones described above.
Asymptomatic: If you do not experience any problems with pain or discomfort in the chest, please select this option.">
<h4>Chest Pain Type* </a><small>Select one of the chest pain type</small></h4>
<input type="radio" name="cp" id="typicalAngina" value="typicalAngina" label="typicalAngina" required> Typical Angina
<br>
<input type="radio" name="cp" id="atypicalAngina" value="atypicalAngina" label="atypicalAngina" required> Atypical Angina
<br>
<input type="radio" name="cp" id="nonAnginalPain" value="nonAnginalPain" label="nonAnginalPain" required> Non-Anginal Pain
<br>
<input type="radio" name="cp" id="asymptomatic" value="asymptomatic" label="asymptomatic" required> Asymptomatic
<br>
<br>
<a href="#" data-toggle="popover" title="Exercise Induced Angina" data-content="INSERT INFO">
<h4>Exercise Induced Angina* </a><small>Select if the patient has exercise induces angina</small></h4>
<input type="radio" name="exang" id="yes" value="1" label="yes" required> Yes
<br>
<input type="radio" name="exang" id="no" value="0" label="no" required> No
<br>
<br>
<a href="#" data-toggle="popover" title="The Slope of the Peak Exercise ST Segment" data-content="INSERT INFO">
<h4>The Slope of the Peak Exercise ST Segment* </a><small>Select how the patient's slope of the peak exercise ST segment looks like</small></h4>
<input type="radio" name="slope" id="upsloping" value="upsloping" label="upsloping" required> Upsloping
<br>
<input type="radio" name="slope" id="flat" value="flat" label="flat" required> Flat
<br>
<input type="radio" name="slope" id="downsloping" value="downsloping" label="downsloping" required> Downsloping
<br>
<input type="radio" name="slope" id="unknown" value="unknown" label="unknown" required> Unknown
<br>
<br>
<a href="#" data-toggle="popover" title="Gender" data-content="INSERT INFO">
<h4>Gender* </a><small>Select the gender of the patient</small></h4>
<input type="radio" name="sex" id="male" value="male" label="male" required> Male
<br>
<input type="radio" name="sex" id="female" value="female" label="female" required> Female
<br>
<br>
<a href="#" data-toggle="popover" title="Fasting Blood Sugar" data-content="INSERT INFO">
<h4>Fasting Blood Sugar* </a><small>Select YES if the patient has > 120 mg/dl and NO otherwise.</small></h4>
<input type="radio" name="fbs" id="yes" value="yes" label="yes" required> Yes
<br>
<input type="radio" name="fbs" id="no" value="no" label="no" required> No
<br>
<br>
<a href="#" data-toggle="popover" title="Thallium Scintigraphy Result" data-content="INSERT INFO">
<h4>Thallium Scintigraphy Result* </a><small>Select the Thallium Scintigraphy Result of the patient.</small></h4>
<input type="radio" name="thal" id="3" value="3" label="3" required> Normal
<br>
<input type="radio" name="thal" id="6" value="6" label="6" required> Fixed Defect
<br>
<input type="radio" name="thal" id="7" value="7" label="7" required> Reversable Defect
<br>
<input type="radio" name="thal" id="0" value="0" label="0" required> Unknown
<br>
<br>
<input type="Submit" class="btn btn-primary btn-lg" value="Submit" />
</form>
</div>
<div class="col-md-6">
<h2 id="Description" class="page-header">Form Description </h2>
<p>
In this form, you can fill out the data for a specific patient.
If there is unknown data, you can use the patient form as well. However, the patient form is less accurate.
</p>
</div>
</div>
</div>
<?php include_once 'footer.php'; ?>
<script>
$(document).ready(function(){
$('[data-toggle="popover"]').popover();
container: 'body'
});
</script>
</body>
</html>
<file_sep><!DOCTYPE html>
<html lang="en">
<head>
<title>Heart Disease Risk Predictor</title>
<meta name="viewport" content="width=device-width, initial-scale=1"><!-- defining responsivnes in mobile devices -->
<meta charset="utf-8"><!-- defining the character set for encoding -->
<link href="css/bootstrap.css" rel="stylesheet">
<link href="css/bootstrap.min.css" rel="stylesheet">
<link href="css/bootstrap-theme.css" rel="stylesheet">
<link href="css/bootstrap-theme.min.css" rel="stylesheet">
<link href="css/style.css" rel="stylesheet"> <!-- styling link -->
<link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons"> <!-- google glyphicons -->
<link rel="stylesheet" href="http://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.4.0/css/font-awesome.min.css"> <!--For Awsome Icons -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script> <!-- jQuery library -->
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script> <!-- Latest compiled JavaScript -->
</head>
<body>
<div id="index">
<?php include_once 'navbar.php'; ?>
<div class="container-fluid">
<div class="col-md-1"> </div>
<div class="col-md-10">
<div id="ttl" class="bs-docs-header" tabindex="-1">
<h1 id="overview">HDRP <small>Heart Disease Risk Predictor</small></h1>
</div>
<div class="bs-docs-section">
<h2 id="" class="page-header">Your results are: </h2>
<?php
$result = 0;
if(isset($_POST['age'], $_POST['cp'], $_POST['exang'], $_POST['slope'], $_POST['sex'], $_POST['fbs'], $_POST['thal']))
{
$age = $_POST['age'];
$cp = $_POST['cp'];
$exang = $_POST['exang'];
$slope = $_POST['slope'];
$sex = $_POST['sex'];
$fbs = $_POST['fbs'];
$thal = $_POST['thal'];
// echo $age;
// echo $cp;
// echo $exang;
// echo $slope;
// echo $sex;
// echo $fbs;
// echo $thal;
if (($cp == 'typicalAngina') || ($cp == 'atypicalAngina') || ($cp == 'nonAnginalPain'))
{
if ($age < 54.5)
{
if (($slope =='upsloping') || ($slope == 'unknown'))
{
$result = 0;
}
elseif (($slope == 'flat') || ($slope == 'downsloping'))
{
if (($thal == '3') || ($thal == '6'))
{
$result = 0;
}
elseif (($thal == '7') || ($thal == '0'))
{
echo "sdfbh ".$thal;
$result = 1;
}
}
}
elseif ($age >= 54.5)
{
if ($sex == 'female')
{
$result = 0;
}
elseif ($sex == 'male')
{
$result = 1;
}
}
}
elseif ($cp = 'asymptomatic')
{
if ($exang == 'no')
{
if ($fbs == 'no')
{
if (($thal == '3') || ($thal == '0'))
{
$result == 0;
}
elseif (($thal == '6') || ($thal == '7'))
{
$result = 1;
}
}
elseif ($fbs == 'yes')
{
$result = 1;
}
}
elseif ($exang == 'yes')
{
echo "gh ";
echo "exang ".$exang;
$result = 1;
}
}
// echo "res ".$result. "<br>";
// echo "age ".$age. "<br>";
// echo "cp ".$cp. "<br>";
// echo "exang ".$exang. "<br>";
// echo "slope ".$slope. "<br>";
// echo "sex ".$sex. "<br>";
// echo "fbs ".$fbs. "<br>";
// echo "thal ".$thal. "<br>";
// echo "result ".$result. "<br>";
if($result == 0){
echo "no";
}
elseif ($result == 1) {
echo "yes";
}
}
else{
// echo "res ".$result. "<br>";
// echo "age ".$age. "<br>";
// echo "cp ".$cp. "<br>";
// echo "exang ".$exang. "<br>";
// echo "slope ".$slope. "<br>";
// echo "sex ".$sex. "<br>";
// echo "fbs ".$fbs. "<br>";
// echo "thal ".$thal. "<br>";
// echo "result ".$result. "<br>";
echo "There are missing fields in your form. Please fill in all the required filds (filds with an asterisk (*)). If you do not have all the information concider using the General Population form";
}
?>
</div>
<div class="bs-docs-section">
<h2 id="form_link" class="page-header">Check again </h2>
<p class="lead">
Would you like to test for another patient? <a href="PHYSICIAN.php">Start by clicking here</a>
</p>
</div>
</div>
</div>
</div>
<?php include_once 'footer.php'; ?>
</body>
</html>
<file_sep><!DOCTYPE html>
<html lang="en">
<head>
<title>Heart Disease Risk Predictor</title>
<meta name="viewport" content="width=device-width, initial-scale=1"><!-- defining responsivnes in mobile devices -->
<meta charset="utf-8"><!-- defining the character set for encoding -->
<link href="css/bootstrap.css" rel="stylesheet">
<link href="css/bootstrap.min.css" rel="stylesheet">
<link href="css/bootstrap-theme.css" rel="stylesheet">
<link href="css/bootstrap-theme.min.css" rel="stylesheet">
<link href="css/style.css" rel="stylesheet"> <!-- styling link -->
<link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons"> <!-- google glyphicons -->
<link rel="stylesheet" href="http://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.4.0/css/font-awesome.min.css"> <!--For Awsome Icons -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script> <!-- jQuery library -->
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script> <!-- Latest compiled JavaScript -->
</head>
<body>
<div id="index">
<?php include_once 'navbar.php'; ?>
<div class="container-fluid">
<div class="col-md-1"> </div>
<div class="col-md-10">
<div id="ttl" class="bs-docs-header" tabindex="-1">
<h1 id="overview">HDRP <small>Heart Disease Risk Predictor</small></h1>
</div>
<div class="bs-docs-section">
<h2 id="" class="page-header">Your results are: </h2>
<?php
$result = 0;
if(isset($_POST['exang'], $_POST['age'], $_POST['sex'], $_POST['chol']))
{
$exang = $_POST['exang'];
$age = $_POST['age'];
$sex = $_POST['sex'];
$chol = $_POST['chol'];
if ($exang == 'no')
{
if ($age < 56.5)
{
if ($sex == 'female')
{
$result = 0;
}
elseif ($sex == 'male')
{
if (($chol == 'big') || ($chol == 'unknown'))
{
$result = 1;
}
}
}
elseif ($age >= 56.5)
{
if ($sex == 'female')
{
$result = 0;
}
elseif ($sex == 'male')
{
$result = 1;
}
}
}
elseif ($exang == 'yes')
{
$result = 1;
}
// echo "exang ".$exang. "<br>";
// echo "res ".$result. "<br>";
// echo "age ".$age. "<br>";
// echo "sex ".$sex. "<br>";
// echo "chol ".$chol. "<br>";
if($result == 0)
{
echo "no";
}
elseif ($result == 1)
{
echo "yes";
}
}
else
{
// echo "res ".$result. "<br>";
// echo "age ".$age. "<br>";
// echo "sex ".$sex. "<br>";
// echo "chol ".$chol. "<br>";
echo "There are missing fields in your form. Please fill in all the required filds (filds with an asterisk (*)). If you do not have all the information concider using the General Population form";
}
?>
</div>
<div class="bs-docs-section">
<h2 id="form_link" class="page-header">Check again </h2>
<p class="lead">
Would you like to take the test again? <a href="generalPopulation.php">Start by clicking here</a>
</p>
</div>
</div>
</div>
</div>
<?php include_once 'footer.php'; ?>
</body>
</html>
<file_sep><!DOCTYPE html>
<html lang="en">
<head>
<title>Heart Disease Risk Predictor</title>
<meta name="viewport" content="width=device-width, initial-scale=1"><!-- defining responsivnes in mobile devices -->
<meta charset="utf-8"><!-- defining the character set for encoding -->
<link href="css/bootstrap.css" rel="stylesheet">
<link href="css/bootstrap.min.css" rel="stylesheet">
<link href="css/bootstrap-theme.css" rel="stylesheet">
<link href="css/bootstrap-theme.min.css" rel="stylesheet">
<link href="css/style.css" rel="stylesheet"> <!-- styling link -->
<link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons"> <!-- google glyphicons -->
<link rel="stylesheet" href="http://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.4.0/css/font-awesome.min.css"> <!--For Awsome Icons -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script> <!-- jQuery library -->
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script> <!-- Latest compiled JavaScript -->
</head>
<body>
<div id="index">
<?php include_once 'navbar.php'; ?>
<div class="container-fluid">
<div class="col-md-1"> </div>
<div class="col-md-10">
<div id="ttl" class="bs-docs-header" tabindex="-1">
<h1 id="overview">HDRP <small>Heart Disease Risk Predictor</small></h1>
</div>
<div class="bs-docs-section">
<h2 id="overview" class="page-header">Overview </h2>
<p>
This application can be used to predict the risk on a heart disease. On the homepage, you can choose between the physician
page and the patient page. The physician page contains more questions, which are usually not known by patients or the general
population.
</p>
</div>
</div>
</div>
<?php include_once 'footer.php'; ?>
</body>
</html>
</body>
</html>
<file_sep># Heart Disease Risk Predictor
Project for Projects in Halth Informatics: From Idea to Specification course
Health Informatics Master Program
Karolinska Insititutet
Group Members
<NAME>
<NAME>
<NAME>
<NAME>
<NAME>
<NAME>
Prototype of a platform predicting the degree of stenosis in a patient.
<file_sep><!DOCTYPE html>
<html lang="en">
<head>
<title>Heart Disease Risk Predictor</title>
<meta name="viewport" content="width=device-width, initial-scale=1"><!-- defining responsivnes in mobile devices -->
<meta charset="utf-8"><!-- defining the character set for encoding -->
<link href="css/bootstrap.css" rel="stylesheet">
<link href="css/bootstrap.min.css" rel="stylesheet">
<link href="css/bootstrap-theme.css" rel="stylesheet">
<link href="css/bootstrap-theme.min.css" rel="stylesheet">
<link href="css/style.css" rel="stylesheet"> <!-- styling link -->
<link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons"> <!-- google glyphicons -->
<link rel="stylesheet" href="http://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.4.0/css/font-awesome.min.css"> <!--For Awsome Icons -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script> <!-- jQuery library -->
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script> <!-- Latest compiled JavaScript -->
</head>
<body>
<div id="index">
<?php include_once 'navbar.php'; ?>
<div class="container-fluid">
<div class="col-md-1"> </div>
<div class="col-md-10">
<div id="ttl" class="bs-docs-header" tabindex="-1">
<h1 id="overview">HDRP <small>Heart Disease Risk Predictor</small></h1>
</div>
<div class="bs-docs-section">
<h2 id="overview" class="page-header">Overview </h2>
<p>
The Heart Disease Risk Predictor (HDRP) web application will help you to predict the risk for a heart disease.
The application can be used by both physicians and patients. If you are a physician, you can predict the risk for a specific patient.
If you are a patient, you can predict the risk for yourself.
</p>
<p>
The Heart Disease Risk Predictor (HDRP) is a prediction tool of your risk of suffering from a certain kind of heart disease.
There are several kinds of heart disease and by entering information into a form, a prediction will be made to determine if you suffer
from ischemic heart disease. Ischemic heart disease means that the heart muscle itself does not get sufficient amount of oxygen and
nutrients, especially under certain circumstances, such as emotional stress or physical activity when the demands of these are higher.
Usually as a result of buildup of plaque inside the blood vessels. You can read more about this disease in our “about” section.
</p>
<div class="btn-group" role="group" aria-label="FormSelect">
<a class="btn btn-default" href="physician.php" role="button">Physician</a>
<a class="btn btn-default" href="generalPopulation.php" role="button">General Population</a>
</div>
</div>
</div>
</div>
<?php include_once 'footer.php'; ?>
</body>
</html>
| 9323fe7a2db65e4c84c7b4983fd29c389d196ca7 | [
"Markdown",
"PHP"
] | 7 | PHP | mnikolop/HDRP | f63fdd22e055d02df1b7ecd680ab4c2044b74c00 | ba7a976527ae710e161c347e2b90e28b270b6c60 |
refs/heads/master | <file_sep>import random
def jogar():
imprime_abertura()
palavra_secreta = carrega_palavra()
letras_acertadas = ["_" for letra in palavra_secreta]
erros = 0
qtd_letras(letras_acertadas)
while(True):
chute = pede_chute()
if(chute in palavra_secreta):
chute_correto(palavra_secreta, chute, letras_acertadas)
else:
erros +=1
chute_errado(erros)
if(erros == 7):
break
if("_" not in letras_acertadas):
break
print(letras_acertadas)
if("_" not in letras_acertadas):
voce_ganhou(palavra_secreta)
else:
voce_errou(palavra_secreta)
print("Fim do Jogo!!")
def imprime_abertura():
print("*********************************")
print("***Bem vindo ao jogo de Forca!***")
print("*********************************")
def carrega_palavra(nome_arquivo = "palavras.txt"):
arquivo = open(nome_arquivo, "r")
palavras = []
for linha in arquivo:
linha = linha.strip()
palavras.append(linha)
arquivo.close()
numero = random.randrange(0, len(palavras))
palavra_secreta = palavras[numero].upper()
return palavra_secreta
def pede_chute():
chute = str.strip(input("Digite uma letra para adivinhar a palavra:\n"))
chute = chute.upper()
return chute
def chute_correto(palavra_secreta, chute, letras_acertadas):
index = 0
for letra in palavra_secreta:
if(chute == letra):
letras_acertadas[index] = letra
index += 1
def chute_errado(erros):
print("Ops, você errou! Faltam {} tentativas.".format(7-erros))
print(" _______ ")
print(" |/ | ")
if(erros == 1):
print(" | (_) ")
print(" | ")
print(" | ")
print(" | ")
if(erros == 2):
print(" | (_) ")
print(" | \ ")
print(" | ")
print(" | ")
if(erros == 3):
print(" | (_) ")
print(" | \| ")
print(" | ")
print(" | ")
if(erros == 4):
print(" | (_) ")
print(" | \|/ ")
print(" | ")
print(" | ")
if(erros == 5):
print(" | (_) ")
print(" | \|/ ")
print(" | | ")
print(" | ")
if(erros == 6):
print(" | (_) ")
print(" | \|/ ")
print(" | | ")
print(" | / ")
if (erros == 7):
print(" | (_) ")
print(" | \|/ ")
print(" | | ")
print(" | / \ ")
print(" | ")
print("_|___ ")
print()
def voce_ganhou(palavra_secreta):
print("Você ganhou, parabéns!! A palavra é {}".format(palavra_secreta))
print(" ___________ ")
print(" '._==_==_=_.' ")
print(" .-\\: /-. ")
print(" | (|:. |) | ")
print(" '-|:. |-' ")
print(" \\::. / ")
print(" '::. .' ")
print(" ) ( ")
print(" _.' '._ ")
print(" '-------' ")
def voce_errou(palavra_secreta):
print("Puxa, você foi enforcado!")
print("A palavra é {}".format(palavra_secreta))
print(" _______________ ")
print(" / \ ")
print(" / \ ")
print("// \/\ ")
print("\| XXXX XXXX | / ")
print(" | XXXX XXXX |/ ")
print(" | XXX XXX | ")
print(" | | ")
print(" \__ XXX __/ ")
print(" |\ XXX /| ")
print(" | | | | ")
print(" | I I I I I I I | ")
print(" | I I I I I I | ")
print(" \_ _/ ")
print(" \_ _/ ")
print(" \_______/ ")
def qtd_letras(letras_acertadas):
print("A palavra a ser adivinhada contém o número de letras abaixo: ")
print(letras_acertadas)
if(__name__ == "__main__"):
jogar()
<file_sep>
def jogar():
imprime_abertura()
esplic_jogo()
um_pergunta = pergunta_um()
while um_pergunta <1 or um_pergunta >3:
print("ESSA OPÇÃO NÃO EXISTE!!")
um_pergunta = pergunta_um()
if(um_pergunta == 1):
print("Você é um festeiro então e gosta da bagunça!!")
dois_um = pergunta_um_dois()
if(dois_um == 1):
print("******PARABÉNS PAPAI ou Mamãe!!!!******")
tres_um = pergunta_um_tres()
if(tres_um == 1):
print("Ainda vejo futuro em você!! Talvez você ainda se salve!!")
else:
print("FDP você vai para o inferno!!! HAHAHAHAHAHA")
if(dois_um == 2):
print("Se deu mau Parça você foi para o hospital!!!!")
dois_dois = pergunta_dois_um()
if(dois_dois == 1):
print("Que MENTIROSO Parça!! Sabemos que você vai continuar na zueira gastando o dinheiro")
print("Só pra você saber, passou uns dias e você MORREU!!")
else:
print("ISSO MESMO PARÇA!!! TEM QUE SER HONESTO COM VOCÊ MESMO E CURTIR A VIDA!!!")
if(dois_um == 3):
print("Que Fita Parça!! Se perdeu?? HAHAHAHAHA")
tres_tres = pergunta_tres_um()
if(tres_tres == 1):
print("Que pena parça, você ficou loco e passou sua grana toda para uma instituição de caridade pela net!! Pelo lado bom você tem salvação!!")
else:
print("É parça!! Era melhor não ter ido porque agora você sabe que se casou e não vai poder curtir mais a vida!!")
elif(um_pergunta == 2):
print("Você é um cara de bom coração!!! Mais será que esta falando a verdade mesmo??")
um_dois = pergunta_dois()
if(um_dois == 1):
print("BOM <NAME> VC ESTÁ TENTANDO SER HONESTO")
um_dois_dois = pergunta_dois_dois()
if(um_dois_dois == 1):
print("Boa!!! Está sendo hosnesto e irá ajudar pessoas! VC ESTÁ SALVO NO REINO DE DEUS! HAHAHAHA")
elif(um_dois_dois == 2):
print("HUMMMMM! SERÁ QUE PODEMOS ACREDITAR NESTES 50% NÃO ESTAMOS MUITO CERTOS QUE VOCÊ IRÁ FAZER ISSO!! TÁ MENTIDO? DESUS CASTIGA! HAHAHAHA")
else:
print("HAHAHAHAHAHAH BOA TENTATIVA DE NOS ENGANAR PENSANDO QUE VAI PRO SEU!! COMEÇA O JOGO NOVAMENTE E ESCOLHE OUTRA OPÇÃO!!!!")
else:
print("NÃO MINTA PARA MENTIROSO SABEMOS QUE NÃO VAI FAZER ISSO!! HAHAHAHAHHA")
else:
print("VOCÊ É FERA BIXO!!! Isso é ser honesto")
print("***********************************************")
print("***************FIM DE JOGO*********************")
print("***********************************************")
def imprime_abertura():
print("*********************************")
print("***Bem vindo ao jogo de Aventura!")
print("*********************************")
def esplic_jogo():
print("Vamos Começar a Aventura!")
print("O Jogo de Aventura será baseado em cima de suas escolhas.")
print("Conforme as respostas escolhidas nos chegaremos no seu final!!")
def pergunta_um():
print("###################################")
print("O que você faria se ganhasse $ 1.00000,00?")
print("Escolha as opções abaixo:")
resp = int(input("(1) Gastaria tudo em Festas! (2) Ajudaria Pessoas em Dificuldades (3) Gastaria e também ajudaria:\n"))
return resp
def pergunta_um_dois():
print("#############################################")
print("#############################################")
print("Vamos continuar a aventura!")
print("Já que você escolheu a opção (1) sabermos que temos um festeiro e que pode passar pelas seguintes situações:\n")
print("(1) Engravidar umas desconhecidas nestas festas e ter que começar a dividir o seu $$$ ou ficar grávida de um cara desconhecido!!")
print("(2) Passar mau em uma destas festas por estar aproveitando demais se é que você me entende!!")
print("(3) Acordar com pessoas que você nunca viu e em um lugar que você desconhece")
resp = int(input("Então nos diga digitando uma das opções acima e que poderia acontecer ou talvez perdo disso:\n"))
return resp
def pergunta_um_tres():
print("#############################################")
print("#############################################")
print("Já que você é o Papai ou Mamãe do ano você tem duas opções para continuar nesta aventura que são:\n")
resp = int(input("(1) Virar um Papai/Mamãe 'responsa' e cuidar dos filhos ou (2) Que se FODA!! EU QUERO FESTA!!!!\n"))
return resp
def pergunta_dois_um():
print("#############################################")
print("#############################################")
print("No hospital você está pensando na vida! E temos algumas opções que poderiam surgir:")
print("(1) Se eu sair dessa prometo parar com tudo e viver uma vida calma e construir uma familia!!")
print("(2) Quase fui nessa!! Poxa se eu sair daqui vou aproveitar mais minha vida como se não tivesse amanhã!!")
resp = int(input("Queremos saber qual dessas vocês decidiria seguir, conte para nos!!!\n"))
return resp
def pergunta_tres_um():
print("#############################################")
print("#############################################")
print("Já que você acordou e não lembra de nada do que você fez qual seria o seu pensamento:")
resp = int(input("(1) FODA-SE!! BORA CURTIR SOU RICO MESMO! ou (2) Vou saber o que aconteceu e o que eu fiz!!\n"))
return resp
def pergunta_dois():
print("#############################################")
print("#############################################")
print("Então borá verificar isso!! Vejamos o que você poderia fazer!!")
resp = int(input("(1) Administraria o dinheiro ajudando conforme suas pesquisas ou (2) Transferia o dinheiro para um instituição confiavél\n"))
return resp
def pergunta_dois_dois():
print("#############################################")
print("#############################################")
print("Quanto estaria disposto a doar deste dinheiro:")
resp = int(input("(1) 30% ou (2) 50% ou (3) 80%\n"))
return resp
if (__name__ == "__main__"):
jogar()<file_sep>import random
def jogar():
imprime_abertura()
fim = 5
cont = 0
while cont < fim:
pergunta()
loop_resp(fim, cont, [carrega_respostas()])
cont = cont + 1
else:
print("Decidido e boa sorte!")
def imprime_abertura():
print("*********************************")
print("Bem vindo ao jogo Decida por MIM!")
print("*********************************")
def pergunta():
questoes = str(input("Digite sua pergunta:\n"))
return questoes
def loop_resp(fim, cont, resp_loop):
for resp in resp_loop:
print(resp)
def carrega_respostas(nome_arquivo = "respostas.txt"):
arquivo = open(nome_arquivo, "r")
respostas = []
for linha in arquivo:
linha = linha.strip()
respostas.append(linha)
arquivo.close()
numero = random.randrange(0, len(respostas))
resp_loop = respostas[numero]
return resp_loop
if (__name__ == "__main__"):
jogar()<file_sep>import jogoforca
import jogoadivinhacao
import jogodados
import jogodecisao
import jogoaventura
def escolhe_jogo():
print("*********************************")
print("*******Escolha o seu Jogo!*******")
print("*********************************")
print("(1) Forca (2) Adivinhação (3) Dados (4) Decide por MIM (5) Aventuras da Vida")
jogo = int(input("Qual Jogo?\n"))
while jogo <1 or jogo >5:
jogo = int(input("Opção de jogo não existe. Escolha o seu jogo com as opções (1) Forca (2) Adivinhação (3) Dados (4) Decide por MIM (5) Aventuras da Vida:\n"))
if(jogo == 1):
print("Sua Escolha foi o Jogo Forca")
jogoforca.jogar()
elif(jogo == 2):
print("Sua Escolha foi o Jogo Adivinhação")
jogoadivinhacao.jogar()
elif(jogo == 3):
print("Sua Escolha foi o Jogo Dados")
jogodados.jogar()
elif (jogo == 4):
print("Sua Escolha foi o Jogo Dados")
jogodecisao.jogar()
else:
print("Sua Escolha foi o jogo Decida por MIM")
jogoaventura.jogar()
if(__name__ == "__main__"):
escolhe_jogo()<file_sep>import random
def jogar():
imprime_abertura()
numero_secreto = random.randrange(1,7)
nivel = escolha_nivel()
while nivel < 1 or nivel > 2:
nivel = nivel_errado()
if (nivel == 1):
print("Numero do dado é {} :".format(numero_secreto))
else:
print("Ok!! Obrigado")
def imprime_abertura():
print("*********************************")
print("Bem vindo ao jogo de Dados!")
print("*********************************")
def escolha_nivel():
print("Você quer Jogar dados?")
print("(1) sim (2) não ")
nivel = int(input(""))
return nivel
def nivel_errado():
nivel = int(input("Esta opção não existe. Você quer jogar dados (1) sim (2) não : "))
return nivel
if (__name__ == "__main__"):
jogar() | a1353267bcd044d90945ac83377488644d4ec298 | [
"Python"
] | 5 | Python | robertorreis/jogos-python | bb283c176c567c238045adc308b1ce13e1824003 | c2447df3d69bad9b19043aab20f54317d01b9f23 |
refs/heads/master | <repo_name>qdef/team<file_sep>/team/blog/models.py
from django.db import models
from django.core.urlresolvers import reverse
from django.contrib.auth.models import User
class BlogArticles(models.Model):
FOOTBALL = 'Football'
RUGBY = 'Rugby'
AMERICAN = 'American Football'
SPORTS_CHOICES = (
(FOOTBALL, 'Football'),
(RUGBY, 'Rugby'),
(AMERICAN, 'American Football'),
)
title = models.CharField(max_length=200)
sport = models.CharField(choices=SPORTS_CHOICES, max_length=20)
body = models.TextField()
image = models.FileField(null=True, blank=True)
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
author = models.ForeignKey(User, models.CASCADE, default=None)
def __str__(self):
return self.title
def get_pk(self):
return self.pk
<file_sep>/team/blog/views.py
from django.shortcuts import render, get_object_or_404, redirect
from .models import BlogArticles
from django.contrib import messages
from django.http import HttpResponse, HttpResponseRedirect
from blog.forms import PostForm
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from rest_framework import viewsets
from .serializers import BlogSerializer, USerSerializer
class BlogViewSet(viewsets.ModelViewSet):
""" ViewSet for viewing and editing Chain objects """
queryset = BlogArticles.objects.all()
serializer_class = BlogSerializer
class USerViewSet(viewsets.ModelViewSet):
""" ViewSet for viewing and editing Chain objects """
queryset = User.objects.all()
serializer_class = USerSerializer
def liste(request):
articles_list = BlogArticles.objects.all().order_by("-created")[:10]
context = { 'blog_articles': articles_list}
return render(request, 'blog/list.html', context)
def football(request):
football_list = BlogArticles.objects.filter(sport='Football').order_by("-created")
context = { 'blog_articles': football_list}
return render(request, 'blog/football.html', context)
def rugby(request):
rugby_list = BlogArticles.objects.filter(sport='Rugby').order_by("-created")
context = { 'blog_articles': rugby_list}
return render(request, 'blog/rugby.html', context)
def american(request):
american_list = BlogArticles.objects.filter(sport='American Football').order_by("-created")
context = { 'blog_articles': american_list}
return render(request, 'blog/american.html', context)
def detail(request, pk):
articles = BlogArticles.objects.get(pk=pk)
articles_list = BlogArticles.objects.filter(sport=articles.sport).order_by("-created")[:10]
context = { 'full_article': articles, 'blog_articles': articles_list}
return render(request, 'blog/detail.html', context)
@login_required
def create(request):
form=PostForm(request.POST or None, request.FILES or None)
if form.is_valid():
instance = form.save(commit=False)
instance.author=request.user
instance.save()
#messages.success(request, "Post was successfully created!")
return redirect('detail', pk=instance.get_pk())
else:
#messages.success(request, "Post creation failed.")
context={"form":form}
return render(request, "blog/post_form.html",context)
@login_required
def edit(request, pk=None):
instance = get_object_or_404(BlogArticles, pk=pk)
form=PostForm(request.POST or None, request.FILES or None, instance=instance)
if request.user==instance.author:
if form.is_valid():
instance=form.save(commit=False)
instance.save()
#messages.success(request, "Post was successfully updated!")
return redirect('detail', pk=pk)
else:
pass
else:
return redirect('user_error')
#messages.success(request, "Post modification failed.")
context={"title":instance.title, "instance":instance, "form":form}
return render(request, "blog/edit_form.html", context)
def delete(request, pk=None):
instance=get_object_or_404(BlogArticles, pk=pk)
if request.user==instance.author:
instance.delete()
#messages.success(request, "Post was successfully deleted.")
return redirect('blog')
else:
return redirect('user_error')
def user_error(request):
return render(request, "blog/user_error.html")
<file_sep>/team/blog/forms.py
from django import forms
from .models import BlogArticles
class PostForm(forms.ModelForm):
class Meta:
model=BlogArticles
fields = [
"title",
"sport",
"image",
"body",
#"author",
]<file_sep>/team/blog/serializers.py
from rest_framework import serializers
from .models import BlogArticles
from django.contrib.auth.models import User
class BlogSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = BlogArticles
fields = ('title', 'body', 'sport', 'created', 'updated', 'image')
class USerSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = User
fields = ('id', 'username', 'is_superuser', 'date_joined', 'last_login')
<file_sep>/requirements.txt
certifi==2018.1.18
chardet==3.0.4
Django==1.9
django-extensions==1.9.9
djangorestframework==3.3.0
idna==2.6
lxml==4.1.1
requests==2.18.4
six==1.11.0
typing==3.6.2
urllib3==1.22
<file_sep>/team/team/views.py
from django.shortcuts import render, redirect
from django.http import HttpResponse
from blog.models import BlogArticles
from django.contrib.auth import login, authenticate
from django.contrib.auth.forms import UserCreationForm
# Create your views here.
def contact(request):
return render(request, 'home/contact.html')
def liste_index(request):
articles_list = BlogArticles.objects.all().order_by("-created")[:10]
context = { 'blog_articles': articles_list}
return render(request, 'home/index.html', context)
def signup(request):
if request.method == 'POST':
form = UserCreationForm(request.POST)
if form.is_valid():
form.save()
username = form.cleaned_data.get('username')
raw_password = <PASSWORD>.cleaned_data.get('<PASSWORD>')
user = authenticate(username=username, password=<PASSWORD>)
login(request, user)
return redirect('blog')
else:
form = UserCreationForm()
return render(request, 'registration/signup.html', {'form': form})
<file_sep>/team/templates/home/scrap.py
import sys
import requests
import time
from lxml import html
website = requests.get('https://twitter.com/onedirection?lang=fr')
tree=html.fromstring(website.content)
followers=tree.xpath("//a[@data-nav='followers']/span/@data-count")[0]
date = time.strftime("%d/%m/%Y")
heure = time.strftime("%H:%M:%S")
print(str(followers) + ' ' + date + ' ' + heure)<file_sep>/team/scores/webscrap.py
import requests
import time
from lxml import html
class Scores:
def __init__(self):
self.followers=followers
def followers(self):
website = requests.get('https://twitter.com/onedirection?lang=fr')
tree=html.fromstring(website.content)
self.followers=tree.xpath("//a[@data-nav='followers']/span/@data-count")[0]
return self.followers<file_sep>/team/blog/admin.py
from django.contrib import admin
from .models import BlogArticles
# Register your models here.
class BlogAdmin(admin.ModelAdmin):
list_display = ["id", "title", "created", "sport"]
list_display_links = ["title"]
list_filter = ["sport"]
search_fields = ["title", "body"]
class Meta:
model = BlogArticles
admin.site.register(BlogArticles, BlogAdmin)<file_sep>/team/blog/urls.py
"""team URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.9/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Add an import: from blog import urls as blog_urls
2. Import the include() function: from django.conf.urls import url, include
3. Add a URL to urlpatterns: url(r'^blog/', include(blog_urls))
"""
from django.conf.urls import url, include
from django.contrib import admin
from . import views
urlpatterns = [
url(r'^$', views.liste, name='blog'),
url(r'^football/$', views.football, name='football'),
url(r'^rugby/$', views.rugby, name='rugby'),
url(r'^american/$', views.american, name='american'),
url(r'create/$', views.create, name='create'),
url(r'^detail/(?P<pk>\d+)/$', views.detail, name='detail'),
url(r'^edit/(?P<pk>\d+)/$', views.edit , name='edit'),
url(r'^careful_when_clicking_this_link!!!/(?P<pk>\d+)/$', views.delete , name='delete'),
url(r'^user_error/$', views.user_error, name='user_error'),
]
<file_sep>/team/scores/views.py
from django.shortcuts import render
from .webscrap import Scores
# Create your views here.
def scores(request):
#score = Scores.followers(self)
context={'scores': scores}
return render(request, 'scores/scores.html', context)<file_sep>/team/blog/templates/blog/user_error.html
{% extends "blog/blog.html" %}
{% block content %}
<div class="container">
<div class="content">
<div class="single-page">
<div class="print-main">
<br><br>
<div class="alert alert-danger">
<h4><strong>Error:</strong> You must be the author of this post to perform this action.</h4>
</div>
<br>
<a href= {% url 'blog' %}> <h3>→ Back to Team.Blog </h3> </a>
<br><br>
</div>
</div>
</div>
</div>
<h1></h1>
{% endblock content %}<file_sep>/team/templates/home/Untitled-1.py
list=[12,24,35,70]
l=[12,24,35,70,88,120,155]
li=[l[x] for x in range(len(l)) if x!= 0] | 521318d6011d351a347f22e71a10d4e85392ccde | [
"Python",
"Text",
"HTML"
] | 13 | Python | qdef/team | 058fda4fa781307e2df3f1c80755cc9f216d6e6a | 6c49b930db442cbaffb5956f5a34d399b4ba5006 |
refs/heads/master | <repo_name>pynchia/tdj<file_sep>/tdj/urls.py
from django.conf.urls import patterns, include, url
from django.conf.urls.defaults import *
from django.contrib.auth.views import login, logout
from tdj import views #, settings
import vgenerate
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'tdj.views.home', name='home'),
# url(r'^tdj/', include('tdj.foo.urls')),
# Uncomment the admin/doc line below to enable admin documentation:
# url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
# Uncomment the next line to enable the admin:
(r'^admin/', include(admin.site.urls)),
(r'^indirizzario/', include('indirizzario.urls')),
(r'^prodotti/', include('prodotti.urls')),
(r'^eventi/', include('eventi.urls')),
(r'^$', views.inethome),
(r'^accounts/login/$', login,{'template_name':'login.html'}),
(r'^accounts/logout/$', logout),
(r'^genihome/$', vgenerate.gen_ihome),
# (r'^static/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.STATIC_ROOT, 'show_indexes':True}),
# (r'^media/(?P<path>.*)$', 'django.views.static.serve', { 'document_root': settings.MEDIA_ROOT }),
)
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
# .... your url patterns are here ...
urlpatterns += staticfiles_urlpatterns()
from django.conf import settings
if settings.DEBUG:
urlpatterns += patterns('',
url(r'^media/(?P<path>.*)$', 'django.views.static.serve', {
'document_root': settings.MEDIA_ROOT,
}),
)
<file_sep>/eventi/forms.py
# coding=utf-8
# forms.py
from django import forms
from eventi.models import TipoEvento
import datetime
class SearchEvForm(forms.Form):
codiceev = forms.ChoiceField(required=False,
choices=[('', 'Qualsiasi')]+[(s.codicetipoev, s.descrtipoev) for s in TipoEvento.objects.all()],
label='Evento')
daldate = forms.DateField(input_formats=['%d/%m/%Y'],
# widget=forms.DateInput(format = '%d/%m/%Y'),
required=False,
label=u'dal')
aldate = forms.DateField(input_formats=['%d/%m/%Y'],
# widget=forms.DateInput(format = '%d/%m/%Y'),
required=False,
label=u'al')
def clean(self):
super(SearchEvForm,self).clean()
ds = self.cleaned_data.get('daldate')
if ds:
self.cleaned_data['daldate'] = datetime.datetime.combine(ds, datetime.time.min)
else:
self.cleaned_data['daldate'] = datetime.datetime(2012,01,01)
ds = self.cleaned_data.get('aldate')
if ds:
self.cleaned_data['aldate'] = datetime.datetime.combine(ds, datetime.time.max)
else:
self.cleaned_data['aldate'] = datetime.datetime.now()
return self.cleaned_data
<file_sep>/eventi/views.py
# Create your views here.
from django.http import HttpResponse
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.views.generic import list_detail
from django.contrib.auth.decorators import login_required
from eventi.forms import SearchEvForm
from eventi.models import Evento
import datetime
import tdj
@login_required
def evhome(request):
today=datetime.date.today()
evform = SearchEvForm(initial={'daldate': today, 'aldate': today})
return render_to_response('evhome.html',
{'evform': evform},
context_instance=RequestContext(request))
@login_required
def search_ev(request):
codiceev=request.GET.get('codiceev', None)
dal=request.GET.get('daldate', None)
al=request.GET.get('aldate', None)
if None in (codiceev, dal, al,):
return HttpResponse('Not enough params given!')
try:
curpage = int(request.GET.get('page', '1'))
except ValueError:
curpage = 1
#format dates to YYYY-MM-DD for the filter query
daldate = "%s-%s-%s" % (dal[6:],dal[3:5],dal[:2])
aldate = "%s-%s-%s" % (al[6:],al[3:5],al[:2])
return list_detail.object_list(request,
queryset = Evento.objects.filter(codiceev__icontains=codiceev,
timestampev__range=(daldate, aldate)),
template_name = 'listevento.html',
template_object_name = "evento",
extra_context = {'codiceev':codiceev,
'daldate':dal,
'aldate':al},
page=curpage,
paginate_by=tdj.PAGELEN
)
<file_sep>/tdj/views.py
# Create your views here.
from django.http import HttpResponse
from django.shortcuts import render_to_response, get_object_or_404
from django.template import RequestContext
from django.contrib.auth.decorators import login_required
from django.views.generic import list_detail
import datetime
import tdj
@login_required
def inethome(request):
userazfile = "generated/"+request.user.username+".txt"
return render_to_response('intranethome.html',
{'userazfile':userazfile, 'today':datetime.date.today()},
context_instance=RequestContext(request))
@login_required
def search_entity(request, model, fieldname):
if 'key' in request.GET:
fieldval=request.GET['key']
else:
return HttpResponse('No key param given!')
try:
curpage = int(request.GET.get('page', '1'))
except ValueError:
curpage = 1
modname=model.__name__.lower()
# entitylist=model.objects.filter(**{'%s__icontains' % fieldname: fieldval})
# return render_to_response('list%s.html' % modname,
# {'fieldval':fieldval, modname+'_list': entitylist})
return list_detail.object_list(
request,
queryset = model.objects.filter(**{'%s__icontains' % fieldname: fieldval}),
template_name = 'list%s.html' % modname,
template_object_name = modname,
extra_context = {'fieldval':fieldval},
page=curpage,
paginate_by=tdj.PAGELEN
)
@login_required
def list_entity(request, parid, parmodel, entmodel, tipoentev=False):
parent = get_object_or_404(parmodel, pk=parid)
entmodname = entmodel.__name__.lower()
parmodname = parmodel.__name__.lower()
try:
curpage = int(request.GET.get('page', '1'))
except ValueError:
curpage = 1
if tipoentev: # we are listing events
return list_detail.object_list(
request,
queryset = entmodel.objects.filter(fkev=parid,
tipoentev=tipoentev),
template_name = 'listevento.html',
template_object_name = entmodname,
extra_context = {'parent': parent, 'parmodname': parmodname, 'tipoentev': tipoentev},
page=curpage,
paginate_by=tdj.PAGELEN
)
else: # we are listing any other entity belonging to parent
return list_detail.object_list(
request,
queryset = entmodel.objects.filter(**{parmodname: parid}),
template_name = 'list%s.html' % entmodname,
template_object_name = entmodname,
extra_context = {'parent': parent, 'parmodname': parmodname},
page=curpage,
paginate_by=tdj.PAGELEN
)
@login_required
def view_entity(request, entid, model):
modname=model.__name__.lower()
return list_detail.object_detail(
request,
queryset = model.objects.all(),
object_id = entid,
template_name = 'view%s.html' % modname,
template_object_name = modname
)
<file_sep>/tdj/__init__.py
# coding=utf-8
# constants
SZ_SCODICE = 4 # maxfieldsize codice (small)
SZ_MCODICE = 8 # maxfieldsize codice (medium)
SZ_CODICE = 16 # maxfieldsize codice (normale)
SZ_NOME = 32 # maxfieldsize nome/small descr
SZ_LNOME = 64 # maxfieldsize bigger nome
SZ_XLNOME = 80 # maxfieldsize large nome
IMGMAXSIDE = 128 # max num of pixels width and height
IMGUPL_FAM = 'fam/' # where to upload file for Famiglia
IMGUPL_LINEA = 'linea/' # where to upload file for Linea
IMGUPL_PROD = 'prod/' # where to upload file for Prodotto
IMGNOPIC = 'nopic.png' # empty image file
PAGELEN = 100 # number of items per page
CURRENCY = '€'
<file_sep>/README.rst
A sophisticated system to track and manage product life-cycle. It offers CRM of contacts/clients/agents. Useful to OEMs and distributors
Useful to manufacturers, shops, etc.
The system provides standard Django user authentication and admin.
Built with Python 2.6 and Django 1.4
AT THE MOMENT THE WHOLE PROJECT IS IN ITALIAN.
If you want it translated to another language, please go ahead.
There are three main sections:
1) PRODUCT Management section:
The system allows to create, edit, search and manage product entities like:
Families, Lines (Series), Products and Options.
Families have Lines
Lines have Options and Products.
Products can have multiple versions.
Products can be associated to one another (i.e. can have accessories).
The system can generate a pricelist.
2) CRM section:
The system allows to create, edit, search and manage entities like:
Companies
Contacts (people)
Actions (interaction with the subject)
3) Events section:
The system tracks most relevant actions (creation, editing, status) on all entities
allowing users to keep an eye on the evolution of the data modeled.
<file_sep>/eventi/admin.py
from eventi import models
from django.contrib import admin
class TipoEvAdmin(admin.ModelAdmin):
list_display = ('codicetipoev', 'descrtipoev')
search_fields = ('codicetipoev',)
class EvAdmin(admin.ModelAdmin):
list_display = ('codiceev',)
search_fields = ('codiceev',)
admin.site.register(models.TipoEvento, TipoEvAdmin)
admin.site.register(models.Evento, EvAdmin)
<file_sep>/tdj/widgets.py
from django import forms
from django.utils.safestring import mark_safe
class CheckboxSelectMultipleP(forms.CheckboxSelectMultiple):
def render(self, *args, **kwargs):
output = super(CheckboxSelectMultipleP, self).render(*args,**kwargs)
return mark_safe(output.replace(u'<ul>', u'').replace(u'</ul>', u'').replace(u'<li>', u'<p><strong>').replace(u'</li>', u'</strong></p>'))
class RadioSelectP(forms.RadioSelect):
def render(self, *args, **kwargs):
output = super(RadioSelectP, self).render(*args,**kwargs)
return mark_safe(output.replace(u'<ul>', u'').replace(u'</ul>', u'').replace(u'<li>', u'<p><strong>').replace(u'</li>', u'</strong></p>'))
<file_sep>/eventi/models.py
# coding=utf-8
from django.db import models
import tdj
# Create your models here.
class TipoEvento(models.Model):
codicetipoev = models.CharField(max_length=tdj.SZ_MCODICE, verbose_name='codice')
descrtipoev = models.CharField(max_length=tdj.SZ_NOME, verbose_name='descr')
class Meta:
db_table = u'tipoevento'
class Evento(models.Model):
fkev = models.IntegerField(blank=True)
codiceev = models.CharField(max_length=tdj.SZ_MCODICE,
# choices=((s.codicetipoev, s.descrtipoev) for s in TipoEvento.objects.all()),
verbose_name='codice')
tipoentev = models.CharField(max_length=tdj.SZ_SCODICE,
choices=(('FAM', 'Famiglia'),
('LIN', 'Linea'),
('PRD', 'Prodotto'),
('OPZ', 'Opzione'),
('ANG', 'Anagrafica'),
('CNT', 'Contatto')),
verbose_name='tipoentita')
entitaev = models.CharField(max_length=tdj.SZ_CODICE, verbose_name='entita')
c1ev = models.CharField(max_length=tdj.SZ_NOME, verbose_name='campo1', blank=True)
c2ev = models.CharField(max_length=tdj.SZ_NOME, verbose_name='campo2', blank=True)
c3ev = models.CharField(max_length=tdj.SZ_NOME, verbose_name='campo3', blank=True)
noteev = models.CharField(max_length=tdj.SZ_NOME, verbose_name='note', blank=True)
utenteev = models.CharField(max_length=tdj.SZ_SCODICE, verbose_name='utente')
timestampev = models.DateTimeField(auto_now_add=True, verbose_name='dataora')
class Meta:
db_table = u'evento'
ordering = ['-timestampev']
<file_sep>/indirizzario/views.py
# Create your views here.
#from django.views.decorators.csrf import csrf_protect
from django.http import HttpResponse
from django.shortcuts import render_to_response, get_object_or_404, redirect
from django.template import RequestContext
from django.views.generic import list_detail
import datetime
from django.contrib.auth.decorators import login_required
#from django.contrib.admin.views.decorators import staff_member_required
#from django.core.urlresolvers import reverse
from indirizzario.models import Anagrafica, Contatto, Azione
from indirizzario import forms
import tdj
#from django.conf import settings
#from django.utils.translation import activate
#activate('it')
@login_required
def indhome(request):
agnform = forms.SearchAgByNameForm()
contform = forms.SearchContForm()
today=datetime.date.today()
azform = forms.SearchAzForm(initial={'daldate': today, 'aldate': today})
return render_to_response('indhome.html',
{'agnform':agnform, 'contform':contform, 'azform':azform},
context_instance=RequestContext(request))
@login_required
def ext_search_ag(request):
if request.method == 'POST':
extform = forms.ExtSearchAgForm(request.POST)
if extform.is_valid():
sort1 = extform.cleaned_data.pop('sort1')
sort2 = extform.cleaned_data.pop('sort2')
criteria={}
for f,v in extform.cleaned_data.items():
if v!=u'':
criteria[f] = v
qs = Anagrafica.objects.filter(**criteria).order_by(sort1,sort2)
#print qs.query
return list_detail.object_list(request,
queryset = qs,
template_name = 'listanagrafica.html',
template_object_name = "anagrafica",
extra_context = {'criteria': dict(criteria,sort1=sort1,sort2=sort2)})
else:
extform = forms.ExtSearchAgForm(initial={'sort1': 'nomeag', 'sort2': 'catag'})
return render_to_response('extsearchag.html',
{'form':extform},
context_instance=RequestContext(request))
@login_required
def search_azione(request):
titoloaz=request.GET.get('titoloaz', None)
dal=request.GET.get('daldate', None)
al=request.GET.get('aldate', None)
if None in (titoloaz, dal, al,):
return HttpResponse('Not enough params given!')
try:
curpage = int(request.GET.get('page', '1'))
except ValueError:
curpage = 1
#format dates to YYYY-MM-DD for the filter query
daldate = "%s-%s-%s" % (dal[6:],dal[3:5],dal[:2])
aldate = "%s-%s-%s" % (al[6:],al[3:5],al[:2])
return list_detail.object_list(request,
queryset = Azione.objects.filter(titoloaz__icontains=titoloaz,
dataaz__range=(daldate, aldate)),
template_name = 'listazione.html',
template_object_name = "azione",
extra_context = {'titoloaz':titoloaz,
'daldate':dal,
'aldate':al},
page=curpage,
paginate_by=tdj.PAGELEN
)
@login_required
def create_ag(request):
if request.method == 'POST':
form = forms.AnagraficaForm(request.POST)
if form.is_valid():
ag = form.save(user=request.user)
return redirect('viewag', ag.id)
else:
form = forms.AnagraficaForm(initial={'tiposcontag': 'NUL'})
return render_to_response('editanagrafica.html',
{'form': form, 'create': True},
context_instance=RequestContext(request))
@login_required
def edit_ag(request, agid):
ag = get_object_or_404(Anagrafica, pk=agid)
if request.method == 'POST':
form = forms.AnagraficaForm(request.POST, instance=ag)
if form.is_valid():
ag=form.save(user=request.user)
return redirect('viewag', ag.id)
else:
form = forms.AnagraficaForm(instance=ag)
return render_to_response('editanagrafica.html',
{'form': form, 'ag': ag},
context_instance=RequestContext(request))
@login_required
def view_ag(request, agid):
ag = get_object_or_404(Anagrafica, pk=agid)
contatti = ag.contatto_set.all() # all ag's contacts
azioni = ag.azione_set.all()[:5] # latest 5 azioni
return render_to_response('viewanagrafica.html',
{'anagrafica': ag,
'cont_list': contatti,
'az_list': azioni,
'today': datetime.date.today()
},
context_instance=RequestContext(request))
@login_required
def list_client(request, promoid):
promo = get_object_or_404(Anagrafica, pk=promoid)
return list_detail.object_list(request,
queryset = promo.client_set.all(),
template_name = 'listanagrafica.html',
template_object_name = 'ag',
extra_context = {'promo': promo})
@login_required
def stat_ag(request, agid):
ag = get_object_or_404(Anagrafica, pk=agid)
ordini = ag.ordini_set.all() # all ag's orders/sale
return render_to_response('statanagrafica.html',
{'anagrafica': ag, 'ordini': ordini},
context_instance=RequestContext(request))
@login_required
def create_cont(request, agid):
if request.method == 'POST':
form = forms.ContattoForm(request.POST)
if form.is_valid():
cont = form.save(agid=agid, user=request.user)
return redirect('viewcont', cont.id)
else:
form = forms.ContattoForm()
ag = get_object_or_404(Anagrafica, pk=agid)
return render_to_response('editcontatto.html',
{'form': form, 'ag': ag, 'create': True},
context_instance=RequestContext(request))
@login_required
def edit_cont(request, contid):
cont = get_object_or_404(Contatto, pk=contid)
if request.method == 'POST':
form = forms.ContattoForm(request.POST, instance=cont)
if form.is_valid():
cont = form.save(user=request.user)
return redirect('viewcont', cont.id)
else:
form = forms.ContattoForm(instance=cont)
return render_to_response('editcontatto.html',
{'form': form, 'cont': cont},
context_instance=RequestContext(request))
@login_required
def create_az(request, agid):
if request.method == 'POST':
form = forms.AzioneForm(request.POST)
if form.is_valid():
form.save(agid=agid, user=request.user)
return redirect('viewag', agid)
else:
form = forms.AzioneForm(initial={'dataaz': datetime.date.today()})
ag = get_object_or_404(Anagrafica, pk=agid)
return render_to_response('editazione.html',
{'form': form, 'ag': ag, 'create': True},
context_instance=RequestContext(request))
@login_required
def edit_az(request, azid):
az = get_object_or_404(Azione, pk=azid)
if request.method == 'POST':
form = forms.AzioneForm(request.POST, instance=az)
if form.is_valid():
az = form.save(user=request.user)
return redirect('viewag', az.anagrafica_id)
else:
form = forms.AzioneForm(instance=az)
return render_to_response('editazione.html',
{'form': form, 'az': az},
context_instance=RequestContext(request))
@login_required
def followup_az(request, azid):
az = get_object_or_404(Azione, pk=azid)
if request.method == 'POST':
form = forms.FollowAzioneform(request.POST)
if form.is_valid():
form.save(agid=az.anagrafica_id, user=request.user)
az.promemaz = not form.cleaned_data['evadiaz']
az.save()
return redirect('viewag', az.anagrafica_id)
else:
form = forms.FollowAzioneform(initial={'dataaz': datetime.date.today(),
'evadiaz': True})
ag = get_object_or_404(Anagrafica, pk=az.anagrafica_id)
return render_to_response('editazione.html',
{'form': form, 'ag': ag, 'create': True},
context_instance=RequestContext(request))
@login_required
def stats_ind(request):
agbycat = Anagrafica.objects.raw('SELECT id, catag, COUNT(catag) AS ncat FROM anagrafica GROUP BY catag')
agbyrapp = Anagrafica.objects.raw('SELECT id, rappag, COUNT(rappag) AS nrapp FROM anagrafica GROUP BY rappag')
promos = Anagrafica.objects.filter(rappag='PRO')
nclients = [(i.codiceproag, i.client_set.count()) for i in promos]
return render_to_response('statsind.html',
{'agbycatval': [i.ncat for i in agbycat], 'agbycatlab': ["%s (%d)" % (i.catag,i.ncat) for i in agbycat],
'agbyrappval': [i.nrapp for i in agbyrapp], 'agbyrapplab': ["%s (%d)" % (i.rappag, i.nrapp) for i in agbyrapp],
'agbyproval': [numcl for codepro,numcl in nclients], 'agbyprolab': ["%s (%d)" % (codepro,numcl) for codepro,numcl in nclients]
},
context_instance=RequestContext(request))
<file_sep>/eventi/urls.py
from django.conf.urls import patterns, include, url
from django.conf.urls.defaults import *
from eventi import models, views
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'tdj.views.home', name='home'),
# url(r'^tdj/', include('tdj.foo.urls')),
# Uncomment the admin/doc line below to enable admin documentation:
# url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
url(r'^evhome/$', views.evhome, name="evhome"),
url(r'^searchev/$', views.search_ev, name="searchev"),
)
<file_sep>/prodotti/forms.py
# coding=utf-8
# forms.py
import os, datetime
from django.conf import settings
from django import forms
from PIL import Image
from prodotti import models
from eventi.models import Evento
import tdj.widgets
class SearchFamForm(forms.Form):
key = forms.CharField(required=False, label=u'Famiglia (nome)')
def clean_nomefam(self):
return " ".join(self.cleaned_data['nomefam'].upper().split())
class SearchLineaForm(forms.Form):
key = forms.CharField(required=False, label=u'Linea (nome)')
def clean_nomelinea(self):
return " ".join(self.cleaned_data['nomelinea'].upper().split())
class SearchProdForm(forms.Form):
key = forms.CharField(required=False, label=u'Prodotto (codice)')
class SearchOpzForm(forms.Form):
key = forms.CharField(required=False, label=u'Opzione (codice)')
class AlterPriceForm(forms.Form):
DELTATYPE = (('1', 'percentuale',),
('0', 'assoluto'),
)
pricedelta = forms.FloatField(required=True, label=u'delta Prezzo')
valmindelta = forms.FloatField(required=True, label=u'delta Val min')
perc = forms.ChoiceField(widget=tdj.widgets.RadioSelectP, choices=DELTATYPE, label=u'Tipo delta')
real = forms.BooleanField(required=False, label=u'alteraz. Reale')
def clean(self):
super(AlterPriceForm,self).clean()
self.cleaned_data['pricedelta'] = round(self.cleaned_data['pricedelta'],2)
self.cleaned_data['valmindelta'] = round(self.cleaned_data['valmindelta'],2)
perc=self.cleaned_data.get('perc')
msgperc = "il delta deve essere espresso in percentuale"
if perc:
if self.cleaned_data['pricedelta'] > 100.0:
self._errors["pricedelta"] = self.error_class([msgperc])
del self.cleaned_data["pricedelta"]
if self.cleaned_data['valmindelta'] > 100.0:
self._errors["valmindelta"] = self.error_class([msgperc])
del self.cleaned_data["valmindelta"]
return self.cleaned_data
class FamigliaForm(forms.ModelForm):
class Meta:
model = models.Famiglia
def __init__(self, *args, **kwargs):
super(FamigliaForm, self).__init__(*args, **kwargs)
if self.instance.id: # obj in db already
self.prev_codicefam = self.instance.codicefam
self.prev_nomefam = self.instance.nomefam
self.prev_statofam = self.instance.statofam
self.prev_pubfam = self.instance.pubfam
self.prev_fotoname = self.instance.fotofam.name
self.objedit = True # obj in db already
else:
self.objedit = False # obj being created now
self.prev_fotoname = tdj.IMGNOPIC
def clean_codicefam(self):
return "".join(self.cleaned_data['codicefam'].upper().split())
def clean_nomefam(self):
return " ".join(self.cleaned_data['nomefam'].upper().split())
# def clean(self):
# super(FamigliaForm,self).clean()
# return self.cleaned_data
def save(self, *args, **kwargs):
user = kwargs.pop('user', None)
if not self.instance.fotofam.name: #if name is empty because cleared
self.instance.fotofam.name = tdj.IMGNOPIC
fam = super(FamigliaForm, self).save(*args, **kwargs)
fotochanged = 'fotofam' in self.changed_data
if fotochanged: # a different file was specified
if (fam.fotofam.name != tdj.IMGNOPIC): #but field not cleared
im = Image.open(fam.fotofam.path)
im.thumbnail((tdj.IMGMAXSIDE,tdj.IMGMAXSIDE,), Image.ANTIALIAS)
im.save(fam.fotofam.path)
if self.prev_fotoname != tdj.IMGNOPIC: # prev is not empty img placeholder
os.remove(settings.MEDIA_ROOT+self.prev_fotoname)
# Now let's add the appropriate events
enttype = 'FAM'
entname = fam.__str__()
if self.objedit: # obj in db already
newev = Evento(fkev=fam.id,
codiceev='EDIT',
tipoentev=enttype,
entitaev=entname,
c2ev=fam.statofam,
utenteev=user)
newev.save()
if fam.codicefam != self.prev_codicefam:
newev = Evento(fkev=fam.id,
codiceev='CODICE',
tipoentev=enttype,
entitaev=entname,
c1ev=self.prev_codicefam,
c2ev=fam.codicefam,
utenteev=user)
newev.save()
if fam.nomefam != self.prev_nomefam:
newev = Evento(fkev=fam.id,
codiceev='NOME',
tipoentev=enttype,
entitaev=entname,
c1ev=self.prev_nomefam,
c2ev=fam.nomefam,
utenteev=user)
newev.save()
if fam.statofam != self.prev_statofam:
newev = Evento(fkev=fam.id,
codiceev='STATO',
tipoentev=enttype,
entitaev=entname,
c1ev=self.prev_statofam,
c2ev=fam.statofam,
utenteev=user)
newev.save()
if fam.pubfam != self.prev_pubfam:
newev = Evento(fkev=fam.id,
codiceev='PUBB',
tipoentev=enttype,
entitaev=entname,
c1ev=self.prev_pubfam,
c2ev=fam.pubfam,
utenteev=user)
newev.save()
if fotochanged: # a different file was specified
newev = Evento(fkev=fam.id,
codiceev='FOTO',
tipoentev=enttype,
entitaev=entname,
c1ev=self.prev_fotoname,
c2ev=fam.fotofam.name,
utenteev=user)
newev.save()
else: # obj being created now
newev = Evento(fkev=fam.id,
codiceev='CREAZ',
tipoentev=enttype,
entitaev=entname,
c2ev=fam.statofam,
utenteev=user)
newev.save()
return fam
class LineaForm(forms.ModelForm):
class Meta:
model = models.Linea
def __init__(self, *args, **kwargs):
super(LineaForm, self).__init__(*args, **kwargs)
if self.instance.id: # obj in db already
self.prev_famiglia = self.instance.famiglia
self.prev_famiglia_name = self.instance.famiglia.nomefam
self.prev_codicelinea = self.instance.codicelinea
self.prev_nomelinea = self.instance.nomelinea
self.prev_faselinea = self.instance.faselinea
self.prev_statolinea = self.instance.statolinea
self.prev_displinea = self.instance.displinea
self.prev_publinea = self.instance.publinea
self.prev_fotoname = self.instance.fotolinea.name
self.objedit = True # obj in db already
else:
self.objedit = False # obj being created now
self.prev_fotoname = tdj.IMGNOPIC
def clean_codicelinea(self):
return "".join(self.cleaned_data['codicelinea'].upper().split())
def clean_nomelinea(self):
return " ".join(self.cleaned_data['nomelinea'].upper().split())
# def clean(self):
# super(LineaForm,self).clean()
# return self.cleaned_data
def save(self, *args, **kwargs):
user = kwargs.pop('user', None)
if not self.instance.fotolinea.name: #if name is empty because cleared
self.instance.fotolinea.name = tdj.IMGNOPIC
linea = super(LineaForm, self).save(*args, **kwargs)
fotochanged = 'fotolinea' in self.changed_data
if fotochanged: # a different file was specified
if (linea.fotolinea.name != tdj.IMGNOPIC): #but field not cleared
im = Image.open(linea.fotolinea.path)
im.thumbnail((tdj.IMGMAXSIDE,tdj.IMGMAXSIDE,), Image.ANTIALIAS)
im.save(linea.fotolinea.path)
if self.prev_fotoname != 'nopic.png': # prev is not empty img placeholder
os.remove(settings.MEDIA_ROOT+self.prev_fotoname)
# Now let's add the appropriate events
ts = datetime.datetime.today()
enttype='LIN'
entname = linea.__str__()
if self.objedit: # obj in db already
newev = Evento(fkev=linea.id,
codiceev='EDIT',
tipoentev=enttype,
entitaev=entname,
c1ev=linea.faselinea,
c2ev=linea.statolinea,
c3ev=linea.displinea,
utenteev=user)
newev.save()
if linea.famiglia != self.prev_famiglia:
newev = Evento(fkev=linea.id,
codiceev='MIGRFAM',
tipoentev=enttype,
entitaev=entname,
c1ev=self.prev_famiglia_name,
c2ev=linea.famiglia.nomefam,
utenteev=user)
newev.save()
if linea.codicelinea != self.prev_codicelinea:
newev = Evento(fkev=linea.id,
codiceev='CODICE',
tipoentev=enttype,
entitaev=entname,
c1ev=self.prev_codicelinea,
c2ev=linea.codicelinea,
utenteev=user)
newev.save()
if linea.nomelinea != self.prev_nomelinea:
newev = Evento(fkev=linea.id,
codiceev='NOME',
tipoentev=enttype,
entitaev=entname,
c1ev=self.prev_nomelinea,
c2ev=linea.nomelinea,
utenteev=user)
newev.save()
if linea.faselinea != self.prev_faselinea:
newev = Evento(fkev=linea.id,
codiceev='FASE',
tipoentev=enttype,
entitaev=entname,
c1ev=self.prev_faselinea,
c2ev=linea.faselinea,
utenteev=user)
newev.save()
if linea.statolinea != self.prev_statolinea:
newev = Evento(fkev=linea.id,
codiceev='STATO',
tipoentev=enttype,
entitaev=entname,
c1ev=self.prev_statolinea,
c2ev=linea.statolinea,
utenteev=user)
newev.save()
if linea.displinea != self.prev_displinea:
newev = Evento(fkev=linea.id,
codiceev='DISP',
tipoentev=enttype,
entitaev=entname,
c1ev=self.prev_displinea,
c2ev=linea.displinea,
utenteev=user)
newev.save()
if linea.publinea != self.prev_publinea:
newev = Evento(fkev=linea.id,
codiceev='PUBB',
tipoentev=enttype,
entitaev=entname,
c1ev=self.prev_publinea,
c2ev=linea.publinea,
utenteev=user)
newev.save()
if fotochanged: # a different file was specified
newev = Evento(fkev=linea.id,
codiceev='FOTO',
tipoentev=enttype,
entitaev=entname,
c1ev=self.prev_fotoname,
c2ev=linea.fotolinea.name,
utenteev=user)
newev.save()
else: # obj being created now
newev = Evento(fkev=linea.id,
codiceev='CREAZ',
tipoentev=enttype,
entitaev=entname,
c1ev=linea.faselinea,
c2ev=linea.statolinea,
c3ev=linea.displinea,
utenteev=user)
newev.save()
return linea
class OpzioneForm(forms.ModelForm):
class Meta:
model = models.Opzione
def __init__(self, *args, **kwargs):
super(OpzioneForm, self).__init__(*args, **kwargs)
if self.instance.id: # obj in db already
self.prev_linea = self.instance.linea
self.prev_linea_name = self.instance.linea.nomelinea
self.prev_codiceopz = self.instance.codiceopz
self.prev_faseopz = self.instance.faseopz
self.prev_statoopz = self.instance.statoopz
self.prev_dispopz = self.instance.dispopz
self.prev_prezzoopz = self.instance.prezzoopz
self.prev_minprezzoopz = self.instance.minprezzoopz
self.prev_pubprezzoopz = self.instance.pubprezzoopz
self.prev_minqtaopz = self.instance.minqtaopz
self.prev_pesoopz = self.instance.pesoopz
self.prev_pubopz = self.instance.pubopz
self.objedit = True # obj in db already
else:
self.objedit = False # obj being created now
def clean_codiceopz(self):
return "".join(self.cleaned_data['codiceopz'].upper().split())
def clean(self):
super(OpzioneForm,self).clean()
codiceopz=self.cleaned_data.get('codiceopz')
linea=self.cleaned_data.get('linea')
if codiceopz:
if self.objedit:
num_indb=models.Opzione.objects.filter(codiceopz=codiceopz,
linea=linea).exclude(pk=self.instance.id).count()
else:
num_indb=models.Opzione.objects.filter(codiceopz=codiceopz, linea=linea).count()
if num_indb: # opz with this code for this line is in db already
msg = "Un'opzione con questo Codice esiste gia' nella stessa Linea"
self._errors["codiceopz"] = self.error_class([msg])
self._errors["linea"] = self.error_class([msg])
del self.cleaned_data["codiceopz"]
del self.cleaned_data["linea"]
self.cleaned_data['prezzoopz'] = round(self.cleaned_data['prezzoopz'],2)
self.cleaned_data['minprezzoopz'] = round(self.cleaned_data['minprezzoopz'],2)
return self.cleaned_data
def save(self, *args, **kwargs):
user = kwargs.pop('user', None)
opz = super(OpzioneForm, self).save(*args, **kwargs)
# Now let's add the appropriate events
ts = datetime.datetime.today()
enttype='OPZ'
entname = opz.__str__()
if self.objedit: # obj in db already
newev = Evento(fkev=opz.id,
codiceev='EDIT',
tipoentev=enttype,
entitaev=entname,
c1ev=opz.faseopz,
c2ev=opz.statoopz,
c3ev=opz.dispopz,
utenteev=user)
newev.save()
if opz.linea != self.prev_linea:
newev = Evento(fkev=opz.id,
codiceev='MIGRLIN',
tipoentev=enttype,
entitaev=entname,
c1ev=self.prev_linea_name,
c2ev=opz.linea.nomelinea,
utenteev=user)
newev.save()
if opz.codiceopz != self.prev_codiceopz:
newev = Evento(fkev=opz.id,
codiceev='CODICE',
tipoentev=enttype,
entitaev=entname,
c1ev=self.prev_codiceopz,
c2ev=opz.codiceopz,
utenteev=user)
newev.save()
if opz.faseopz != self.prev_faseopz:
newev = Evento(fkev=opz.id,
codiceev='FASE',
tipoentev=enttype,
entitaev=entname,
c1ev=self.prev_faseopz,
c2ev=opz.faseopz,
utenteev=user)
newev.save()
if opz.statoopz != self.prev_statoopz:
newev = Evento(fkev=opz.id,
codiceev='STATO',
tipoentev=enttype,
entitaev=entname,
c1ev=self.prev_statoopz,
c2ev=opz.statoopz,
utenteev=user)
newev.save()
if opz.dispopz != self.prev_dispopz:
newev = Evento(fkev=opz.id,
codiceev='DISP',
tipoentev=enttype,
entitaev=entname,
c1ev=self.prev_dispopz,
c2ev=opz.dispopz,
utenteev=user)
newev.save()
if opz.prezzoopz != self.prev_prezzoopz:
newev = Evento(fkev=opz.id,
codiceev='PREZZO',
tipoentev=enttype,
entitaev=entname,
c1ev=self.prev_prezzoopz,
c2ev=opz.prezzoopz,
utenteev=user)
newev.save()
if opz.minprezzoopz != self.prev_minprezzoopz:
newev = Evento(fkev=opz.id,
codiceev='VALMIN',
tipoentev=enttype,
entitaev=entname,
c1ev=self.prev_minprezzoopz,
c2ev=opz.minprezzoopz,
utenteev=user)
newev.save()
if opz.pubprezzoopz != self.prev_pubprezzoopz:
newev = Evento(fkev=opz.id,
codiceev='PUBPREZ',
tipoentev=enttype,
entitaev=entname,
c1ev=self.prev_pubprezzoopz,
c2ev=opz.pubprezzoopz,
utenteev=user)
newev.save()
if opz.minqtaopz != self.prev_minqtaopz:
newev = Evento(fkev=opz.id,
codiceev='QTAMIN',
tipoentev=enttype,
entitaev=entname,
c1ev=self.prev_minqtaopz,
c2ev=opz.minqtaopz,
utenteev=user)
newev.save()
if opz.pesoopz != self.prev_pesoopz:
newev = Evento(fkev=opz.id,
codiceev='PESO',
tipoentev=enttype,
entitaev=entname,
c1ev=self.prev_pesoopz,
c2ev=opz.pesoopz,
utenteev=user)
newev.save()
if opz.pubopz != self.prev_pubopz:
newev = Evento(fkev=opz.id,
codiceev='PUBB',
tipoentev=enttype,
entitaev=entname,
c1ev=self.prev_pubopz,
c2ev=opz.pubopz,
utenteev=user)
newev.save()
else: # obj being created now
newev = Evento(fkev=opz.id,
codiceev='CREAZ',
tipoentev=enttype,
entitaev=entname,
c1ev=opz.faseopz,
c2ev=opz.statoopz,
c3ev=opz.dispopz,
utenteev=user)
newev.save()
return opz
class ProdottoForm(forms.ModelForm):
class Meta:
model = models.Prodotto
def __init__(self, *args, **kwargs):
super(ProdottoForm, self).__init__(*args, **kwargs)
if self.instance.id: # obj in db already
#now populate the accessprod field excluding the current product!
self.fields['accessprod'].queryset = models.Prodotto.objects.exclude(pk=self.instance.id)
self.prev_linea = self.instance.linea
self.prev_linea_name = self.instance.linea.nomelinea
self.prev_codiceprod = self.instance.codiceprod
self.prev_versprod = self.instance.versprod
self.prev_faseprod = self.instance.faseprod
self.prev_statoprod = self.instance.statoprod
self.prev_dispprod = self.instance.dispprod
self.prev_prezzoprod = self.instance.prezzoprod
self.prev_minprezzoprod = self.instance.minprezzoprod
self.prev_pubprezzoprod = self.instance.pubprezzoprod
self.prev_minqtaprod = self.instance.minqtaprod
self.prev_pesoprod = self.instance.pesoprod
self.prev_scortaprod = self.instance.scortaprod
self.prev_scortaminprod = self.instance.scortaminprod
self.prev_pubprod = self.instance.pubprod
self.prev_fotoname = self.instance.fotoprod.name
self.objedit = True # obj in db already
else:
self.objedit = False # obj being created now
self.prev_fotoname = tdj.IMGNOPIC
def clean_codiceprod(self):
return "".join(self.cleaned_data['codiceprod'].upper().split())
def clean_versprod(self):
return "".join(self.cleaned_data['versprod'].upper().split())
def clean(self):
super(ProdottoForm,self).clean()
codiceprod=self.cleaned_data.get('codiceprod')
versprod=self.cleaned_data.get('versprod')
if codiceprod and versprod:
if self.objedit: # in db already
num_indb=models.Prodotto.objects.filter(codiceprod=codiceprod,
versprod=versprod).exclude(pk=self.instance.id).count()
else: # not in db yet
num_indb=models.Prodotto.objects.filter(codiceprod=codiceprod, versprod=versprod).count()
if num_indb: # prod with same code and version is in db already
msg = "Un prodotto con questo Codice e Versione esiste gia'"
self._errors["codiceprod"] = self.error_class([msg])
self._errors["versprod"] = self.error_class([msg])
del self.cleaned_data["codiceprod"]
del self.cleaned_data["versprod"]
self.cleaned_data['prezzoprod'] = round(self.cleaned_data['prezzoprod'],2)
self.cleaned_data['minprezzoprod'] = round(self.cleaned_data['minprezzoprod'],2)
return self.cleaned_data
def save(self, *args, **kwargs):
user = kwargs.pop('user', None)
if not self.instance.fotoprod.name: #if name is empty because cleared
self.instance.fotoprod.name = tdj.IMGNOPIC
prod = super(ProdottoForm, self).save(*args, **kwargs)
fotochanged = 'fotoprod' in self.changed_data
if fotochanged: # a different file was specified
if (prod.fotoprod.name != tdj.IMGNOPIC): #but field not cleared
im = Image.open(prod.fotoprod.path)
im.thumbnail((tdj.IMGMAXSIDE,tdj.IMGMAXSIDE,), Image.ANTIALIAS)
im.save(prod.fotoprod.path)
if self.prev_fotoname != 'nopic.png': # prev is not empty img placeholder
os.remove(settings.MEDIA_ROOT+self.prev_fotoname)
# Now let's add the appropriate events
ts = datetime.datetime.today()
enttype='PRD'
entname = prod.__str__()
if self.objedit: # obj in db already
newev = Evento(fkev=prod.id,
codiceev='EDIT',
tipoentev=enttype,
entitaev=entname,
c1ev=prod.faseprod,
c2ev=prod.statoprod,
c3ev=prod.dispprod,
utenteev=user)
newev.save()
if prod.linea != self.prev_linea:
newev = Evento(fkev=prod.id,
codiceev='MIGRLIN',
tipoentev=enttype,
entitaev=entname,
c1ev=self.prev_linea_name,
c2ev=prod.linea.nomelinea,
utenteev=user)
newev.save()
if prod.codiceprod != self.prev_codiceprod:
newev = Evento(fkev=prod.id,
codiceev='CODICE',
tipoentev=enttype,
entitaev=entname,
c1ev=self.prev_codiceprod,
c2ev=prod.codiceprod,
utenteev=user)
newev.save()
if prod.versprod != self.prev_versprod:
newev = Evento(fkev=prod.id,
codiceev='VERS',
tipoentev=enttype,
entitaev=entname,
c1ev=self.prev_versprod,
c2ev=prod.versprod,
utenteev=user)
newev.save()
if prod.faseprod != self.prev_faseprod:
newev = Evento(fkev=prod.id,
codiceev='FASE',
tipoentev=enttype,
entitaev=entname,
c1ev=self.prev_faseprod,
c2ev=prod.faseprod,
utenteev=user)
newev.save()
if prod.statoprod != self.prev_statoprod:
newev = Evento(fkev=prod.id,
codiceev='STATO',
tipoentev=enttype,
entitaev=entname,
c1ev=self.prev_statoprod,
c2ev=prod.statoprod,
utenteev=user)
newev.save()
if prod.dispprod != self.prev_dispprod:
newev = Evento(fkev=prod.id,
codiceev='DISP',
tipoentev=enttype,
entitaev=entname,
c1ev=self.prev_dispprod,
c2ev=prod.dispprod,
utenteev=user)
newev.save()
if prod.prezzoprod != self.prev_prezzoprod:
newev = Evento(fkev=prod.id,
codiceev='PREZZO',
tipoentev=enttype,
entitaev=entname,
c1ev=self.prev_prezzoprod,
c2ev=prod.prezzoprod,
utenteev=user)
newev.save()
if prod.minprezzoprod != self.prev_minprezzoprod:
newev = Evento(fkev=prod.id,
codiceev='VALMIN',
tipoentev=enttype,
entitaev=entname,
c1ev=self.prev_minprezzoprod,
c2ev=prod.minprezzoprod,
utenteev=user)
newev.save()
if prod.pubprezzoprod != self.prev_pubprezzoprod:
newev = Evento(fkev=prod.id,
codiceev='PUBPREZ',
tipoentev=enttype,
entitaev=entname,
c1ev=self.prev_pubprezzoprod,
c2ev=prod.pubprezzoprod,
utenteev=user)
newev.save()
if prod.minqtaprod != self.prev_minqtaprod:
newev = Evento(fkev=prod.id,
codiceev='QTAMIN',
tipoentev=enttype,
entitaev=entname,
c1ev=self.prev_minqtaprod,
c2ev=prod.minqtaprod,
utenteev=user)
newev.save()
if prod.pesoprod != self.prev_pesoprod:
newev = Evento(fkev=prod.id,
codiceev='PESO',
tipoentev=enttype,
entitaev=entname,
c1ev=self.prev_pesoprod,
c2ev=prod.pesoprod,
utenteev=user)
newev.save()
if prod.scortaprod != self.prev_scortaprod:
newev = Evento(fkev=prod.id,
codiceev='SCORTA',
tipoentev=enttype,
entitaev=entname,
c1ev=self.prev_scortaprod,
c2ev=prod.scortaprod,
utenteev=user)
newev.save()
if prod.scortaminprod != self.prev_scortaminprod:
newev = Evento(fkev=prod.id,
codiceev='SCORTMIN',
tipoentev=enttype,
entitaev=entname,
c1ev=self.prev_scortaminprod,
c2ev=prod.scortaminprod,
utenteev=user)
newev.save()
if prod.pubprod != self.prev_pubprod:
newev = Evento(fkev=prod.id,
codiceev='PUBB',
tipoentev=enttype,
entitaev=entname,
c1ev=self.prev_pubprod,
c2ev=prod.pubprod,
utenteev=user)
newev.save()
if fotochanged: # a different file was specified
newev = Evento(fkev=prod.id,
codiceev='FOTO',
tipoentev=enttype,
entitaev=entname,
c1ev=self.prev_fotoname,
c2ev=prod.fotoprod.name,
utenteev=user)
newev.save()
else: # obj being created now
newev = Evento(fkev=prod.id,
codiceev='CREAZ',
tipoentev=enttype,
entitaev=entname,
c1ev=prod.faseprod,
c2ev=prod.statoprod,
c3ev=prod.dispprod,
utenteev=user)
newev.save()
return prod
class NewProdVersForm(forms.Form):
newvers = forms.CharField(required=True, initial='1',
max_length=tdj.SZ_SCODICE, label=u'nuova Vers.')
samefoto = forms.BooleanField(required=False, label=u'stessa Foto')
def __init__(self, *args, **kwargs):
self.prod = kwargs.pop('prod', None)
super(NewProdVersForm, self).__init__(*args, **kwargs)
if self.prod:
prodacc = self.prod.accessprod.all() # my accessories
whoseacc = self.prod.prodotto_set.all() # prods I'm an access. of
self.fields['newvers'].initial = self.prod.versprod
self.fields['prodacc'] = forms.MultipleChoiceField(required=False, widget=tdj.widgets.CheckboxSelectMultipleP,
choices=((p.id, p.__str__()+" "+p.descrprod) for p in prodacc)
)
self.fields['whoseacc'] = forms.MultipleChoiceField(required=False, widget=tdj.widgets.CheckboxSelectMultipleP,
choices=((p.id, p) for p in whoseacc)
)
def clean_newvers(self):
newvers="".join(self.cleaned_data['newvers'].upper().split())
num_indb=models.Prodotto.objects.filter(codiceprod=self.prod.codiceprod,
versprod=newvers).count()
if num_indb: # prod with same code and version is in db already
raise forms.ValidationError("questa Versione esiste gia'")
return newvers
<file_sep>/tdj/vgenerate.py
'''
Created on 16/gen/2013
@author: mbb
'''
from django.http import HttpResponse
from django.contrib.auth.models import User
from django.template.loader import render_to_string
from django.template import RequestContext
import datetime
from indirizzario.models import Anagrafica, Azione
import settings
def gen_ihome(request):
user_list = User.objects.exclude(username='admin')
for user in user_list:
az_list = Azione.objects.filter(promemaz=True, autoreaz=user.username).order_by('scadaz')
az_list_html = render_to_string('azioni_rows.html',
dictionary={'azione_list': az_list,
'today':datetime.date.today(),
'STATIC_URL':settings.STATIC_URL})
f = open('template/generated/'+request.user.username+'.txt', "w")
f.write(az_list_html.encode('UTF-8'))
f.close()
return HttpResponse(status=201)
<file_sep>/indirizzario/urls.py
from django.conf.urls import patterns, url
#from django.conf.urls.defaults import *
from indirizzario import models, views
from tdj.views import view_entity, list_entity, search_entity
from eventi.models import Evento
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'tdj.views.home', name='home'),
# url(r'^tdj/', include('tdj.foo.urls')),
# Uncomment the admin/doc line below to enable admin documentation:
# url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
url(r'^indhome/$', views.indhome, name="indhome"),
url(r'^searchag/$', search_entity,{'model':models.Anagrafica, 'fieldname':'nomeag'}, name="searchag"),
url(r'^extsearchag/$', views.ext_search_ag, name="extsearchag"),
url(r'^searchcont/$', search_entity,{'model':models.Contatto, 'fieldname':'cognomecont'}, name="searchcont"),
url(r'^searchaz/$', views.search_azione, name="searchaz"),
url(r'^listclient/(\d+)/$', views.list_client, name="listclient"),
url(r'^listcont/(?P<parid>\d+)/$', list_entity, {'parmodel':models.Anagrafica, 'entmodel':models.Contatto}, name="listcont"),
url(r'^listaz/(?P<parid>\d+)/$', list_entity, {'parmodel':models.Anagrafica, 'entmodel':models.Azione}, name="listaz"),
url(r'^listevag/(?P<parid>\d+)/$', list_entity, {'parmodel':models.Anagrafica, 'entmodel':Evento, 'tipoentev':'ANG'}, name="listevag"),
url(r'^listevcont/(?P<parid>\d+)/$', list_entity, {'parmodel':models.Contatto, 'entmodel':Evento, 'tipoentev':'CNT'}, name="listevcont"),
url(r'^viewag/(\d+)/$', views.view_ag, name="viewag"),
url(r'^viewcont/(?P<entid>\d+)/$', view_entity, {'model':models.Contatto}, name="viewcont"),
url(r'^createag/$', views.create_ag, name="createag"),
url(r'^createcont/(?P<agid>\d+)/$', views.create_cont, name="createcont"),
url(r'^createaz/(?P<agid>\d+)/$', views.create_az, name="createaz"),
url(r'^followupaz/(\d+)/$', views.followup_az, name="followupaz"),
url(r'^editag/(\d+)/$', views.edit_ag, name="editag"),
url(r'^editcont/(\d+)/$', views.edit_cont, name="editcont"),
url(r'^editaz/(\d+)/$', views.edit_az, name="editaz"),
url(r'^statag/(\d+)/$', views.stat_ag, name="statag"),
url(r'^statsind/$', views.stats_ind, name="statsind"),
)
<file_sep>/template/login.html
{% extends "baseonecol.html" %}
{% block title %}Intranet{% endblock %}
{% block headmenu %}{% endblock %}
{% block h1 %}LOGIN{% endblock %}
{% block content %}
{% if form.errors %}
<p class="error">Sorry, that's not a valid username or password</p>
{% endif %}
<form action="" method="post">
{% csrf_token %}
<h3>
<label for="username">Username:</label>
<input type="text" name="username" value="" id="username">
</h3>
<h3>
<label for="password">Password:</label>
<input type="password" name="password" value="" id="password"><br /><br />
</h3>
<input type="submit" value=" login " />
<input type="hidden" name="next" value="{{ next|escape }}" />
</form>
<p> </p>
<p>N.B: per la corretta visualizzazione di questo sito si consigliano i browser</p>
<p><a href="http://www.google.com/chrome/" target="_blank">Google chrome<img src="{{ STATIC_URL }}img/chrome_logo.png" alt="Chrome" width="35" height="35" /></a></p>
<p><a href="http://en.www.mozilla.com/en/firefox/all.html" target="_blank">Mozilla Firefox <img src="{{ STATIC_URL }}img/firefox-ico.png" alt="Firefox" width="34" height="34" /></a></p>
<p> </p>
{% endblock %}
<file_sep>/prodotti/admin.py
from prodotti import models
from django.contrib import admin
class FaseAdmin(admin.ModelAdmin):
search_fields = ('codicefase',)
class StatoAdmin(admin.ModelAdmin):
search_fields = ('codicestato',)
class DispAdmin(admin.ModelAdmin):
search_fields = ('codicedisp',)
class FamigliaAdmin(admin.ModelAdmin):
search_fields = ('nomefam',)
class LineaAdmin(admin.ModelAdmin):
search_fields = ('nomelinea',)
list_filter = ('famiglia',)
class ProdAdmin(admin.ModelAdmin):
search_fields = ('codiceprod',)
list_filter = ('linea',)
filter_horizontal = ('accessprod',)
class OpzAdmin(admin.ModelAdmin):
search_fields = ('codiceopz',)
list_filter = ('linea',)
admin.site.register(models.Fase, FaseAdmin)
admin.site.register(models.Stato, StatoAdmin)
admin.site.register(models.Disponib, DispAdmin)
admin.site.register(models.Famiglia, FamigliaAdmin)
admin.site.register(models.Linea, LineaAdmin)
admin.site.register(models.Prodotto, ProdAdmin)
admin.site.register(models.Opzione, OpzAdmin)
<file_sep>/prodotti/urls.py
from django.conf.urls import patterns, url
#from django.conf.urls.defaults import *
from prodotti import models, views
from tdj.views import view_entity, list_entity, search_entity
from eventi.models import Evento
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'tdj.views.home', name='home'),
# url(r'^tdj/', include('tdj.foo.urls')),
# Uncomment the admin/doc line below to enable admin documentation:
# url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
url(r'^prodhome/$', views.prodhome, name="prodhome"),
url(r'^searchfam/$', search_entity,{'model':models.Famiglia, 'fieldname':'nomefam'}, name="searchfam"),
url(r'^searchlinea/$', search_entity,{'model':models.Linea, 'fieldname':'nomelinea'}, name="searchlinea"),
url(r'^searchopz/$', search_entity,{'model':models.Opzione, 'fieldname':'codiceopz'}, name="searchopz"),
url(r'^searchprod/$', search_entity,{'model':models.Prodotto, 'fieldname':'codiceprod'}, name="searchprod"),
url(r'^listlinea/(?P<parid>\d+)/$', list_entity, {'parmodel':models.Famiglia, 'entmodel':models.Linea}, name="listlinea"),
url(r'^listopz/(?P<parid>\d+)/$', list_entity, {'parmodel':models.Linea, 'entmodel':models.Opzione}, name="listopz"),
url(r'^listprod/(?P<parid>\d+)/$', list_entity, {'parmodel':models.Linea, 'entmodel':models.Prodotto}, name="listprod"),
url(r'^listevfam/(?P<parid>\d+)/$', list_entity, {'parmodel':models.Famiglia, 'entmodel':Evento, 'tipoentev':'FAM'}, name="listevfam"),
url(r'^listevlinea/(?P<parid>\d+)/$', list_entity, {'parmodel':models.Linea, 'entmodel':Evento, 'tipoentev':'LIN'}, name="listevlinea"),
url(r'^listevopz/(?P<parid>\d+)/$', list_entity, {'parmodel':models.Opzione, 'entmodel':Evento, 'tipoentev':'OPZ'}, name="listevopz"),
url(r'^listevprod/(?P<parid>\d+)/$', list_entity, {'parmodel':models.Prodotto, 'entmodel':Evento, 'tipoentev':'PRD'}, name="listevprod"),
url(r'^listaccprod/(\d+)/$', views.list_acc_prod, name="listaccprod"),
url(r'^viewfam/(?P<entid>\d+)/$', view_entity, {'model':models.Famiglia}, name="viewfam"),
url(r'^viewlinea/(?P<entid>\d+)/$', view_entity, {'model':models.Linea}, name="viewlinea"),
url(r'^viewopz/(?P<entid>\d+)/$', view_entity, {'model':models.Opzione}, name="viewopz"),
url(r'^viewprod/(?P<entid>\d+)/$', view_entity, {'model':models.Prodotto}, name="viewprod"),
url(r'^createfam/$', views.create_fam, name="createfam"),
url(r'^createlinea/$', views.create_linea, name="createlinea"),
url(r'^createopz/$', views.create_opz, name="createopz"),
url(r'^createprod/$', views.create_prod, name="createprod"),
url(r'^editfam/(\d+)/$', views.edit_fam, name="editfam"),
url(r'^editlinea/(\d+)/$', views.edit_linea, name="editlinea"),
url(r'^editopz/(\d+)/$', views.edit_opz, name="editopz"),
url(r'^editprod/(\d+)/$', views.edit_prod, name="editprod"),
url(r'^newprodvers/(\d+)/$', views.new_prod_vers, name="newprodvers"),
url(r'^genlp/$', views.gen_lp, name="genlp"),
url(r'^alterprice/$', views.alter_price, name="alterprice"),
url(r'^statprod/$', views.stats_prod, name="statprod"),
)
<file_sep>/indirizzario/forms.py
# coding=utf-8
# forms.py
from django import forms
from django.contrib.auth.models import User
from indirizzario import models
from eventi.models import Evento
import datetime
import string
#from django.core.exceptions import ObjectDoesNotExist
import tdj.widgets
class SearchAgByNameForm(forms.Form):
key = forms.CharField(label=u'Anagrafica (rag.soc.)')
def clean_nomeag(self):
return " ".join(self.cleaned_data['nomeag'].upper().split())
class SearchContForm(forms.Form):
key = forms.CharField(label=u'Contatto (cognome)')
def clean_cognomecont(self):
return string.capwords(self.cleaned_data['cognomecont'])
class SearchAzForm(forms.Form):
titoloaz = forms.CharField(max_length=tdj.SZ_NOME, required=False, label=u'Azione (titolo)')
daldate = forms.DateField(input_formats=['%d/%m/%Y', '%d-%m-%Y'],
# widget=forms.DateInput(format = '%d/%m/%Y'),
required=False,
label=u'dal')
aldate = forms.DateField(input_formats=['%d/%m/%Y', '%d-%m-%Y'],
# widget=forms.DateInput(format = '%d/%m/%Y'),
required=False,
label=u'al')
def clean_titoloaz(self):
return " ".join(self.cleaned_data['titoloaz'].upper().split())
def clean_daldate(self):
ds = self.cleaned_data.get('daldate')
if not ds:
ds = datetime.date(2012,01,01)
return ds
def clean_aldate(self):
ds = self.cleaned_data.get('aldate')
if not ds:
ds = datetime.date.today()
return ds
class AnagraficaForm(forms.ModelForm):
class Meta:
model = models.Anagrafica
def __init__(self, *args, **kwargs):
super(AnagraficaForm, self).__init__(*args, **kwargs)
if self.instance.id: # obj in db already
#self.prev_pubfam = self.instance.pubfam
self.objedit = True # obj in db already
else:
self.objedit = False # obj being created now
def clean_nomeag(self):
return " ".join(self.cleaned_data['nomeag'].upper().split())
def clean(self):
cleaned_data = super(AnagraficaForm, self).clean()
rappag = cleaned_data.get("rappag")
codiceproag = cleaned_data.get("codiceproag")
if rappag=="PRO":
if not codiceproag:
msg = "Se il rapporto=PROmotore specificarne il codice"
self._errors["codiceproag"] = self.error_class([msg])
del cleaned_data["codiceproag"]
else:
agswithcodpro = models.Anagrafica.objects.filter(codiceproag=codiceproag)
if self.objedit: # obj in db already
agswithcodpro = agswithcodpro.exclude(id=self.instance.id)
if agswithcodpro: # the code is taken already
msg = "Codice promotore gia' usato da %s" % agswithcodpro[0].nomeag
self._errors["codiceproag"] = self.error_class([msg])
del cleaned_data["codiceproag"]
else: # not a promoter then clear the promoter code
cleaned_data["codiceproag"] = ''
return cleaned_data
def save(self, *args, **kwargs):
user = kwargs.pop('user', None)
ag = super(AnagraficaForm, self).save(*args, **kwargs)
if self.objedit: # obj in db already
codiceev='EDIT'
else: # obj being created now
codiceev='CREAZ'
newev = Evento(fkev=ag.id,
codiceev=codiceev,
tipoentev='ANG',
entitaev=ag.__str__(),
c1ev=ag.validag,
c2ev=ag.catag,
utenteev=user)
newev.save()
return ag
class ExtSearchAgForm(forms.Form):
SORTFIELDS = (('nomeag', '',),
('validag', '',),
('rappag', ''),
('catag', ''),
('referag', ''),
('provag', ''),
('regag', ''),
('nazag', ''),
)
sort1 = forms.ChoiceField(widget=tdj.widgets.RadioSelectP, choices=SORTFIELDS)
sort2 = forms.ChoiceField(widget=tdj.widgets.RadioSelectP, choices=SORTFIELDS)
validag = forms.ChoiceField(required=False,
choices=(('', 'Qualsiasi'), ('1', 'Valida'), ('0', 'Invalida')),
label='Validità')
rappag = forms.ChoiceField(required=False,
choices=[('', 'Qualsiasi')]+[(s.codice, s.nome) for s in models.Rapporto.objects.all()],
label='Rapporto')
catag = forms.ChoiceField(required=False,
choices=[('', 'Qualsiasi')]+[(s.codice, s.nome) for s in models.Categoria.objects.all()],
label='Categoria')
referag = forms.ChoiceField(required=False,
choices=[('', 'Qualsiasi')]+[(s.username, s.username) for s in User.objects.exclude(username='admin')],
label='Referente')
provag = forms.ChoiceField(required=False,
choices=[('', 'Qualsiasi')]+[(s.codice, s.nome) for s in models.Provincia.objects.all()],
label='Provincia')
regag = forms.ChoiceField(required=False,
choices=[('', 'Qualsiasi')]+[(s.nome, s.nome) for s in models.Regione.objects.all()],
label='Regione')
nazag = forms.ChoiceField(required=False,
choices=[('', 'Qualsiasi')]+[(s.nome, s.nome) for s in models.Nazione.objects.all()],
label='Nazione')
class ContattoForm(forms.ModelForm):
class Meta:
model = models.Contatto
def __init__(self, *args, **kwargs):
super(ContattoForm, self).__init__(*args, **kwargs)
if self.instance.id: # obj in db already
self.objedit = True
else: # obj being created now
self.objedit = False
def clean_nomecont(self):
return string.capwords(self.cleaned_data['nomecont'])
def clean_cognomecont(self):
return string.capwords(self.cleaned_data['cognomecont'])
# def clean(self):
# cleaned_data = super(ContattoForm, self).clean()
# return cleaned_data
def save(self, *args, **kwargs):
agid = kwargs.pop('agid', None)
user = kwargs.pop('user', None)
if self.objedit: # obj in db already
codiceev='EDIT'
else: # obj being created now
self.instance.anagrafica_id = agid # link the new contatto to the ag it belongs
codiceev='CREAZ'
cont = super(ContattoForm, self).save(*args, **kwargs)
newev = Evento(fkev=cont.id,
codiceev=codiceev,
tipoentev='CNT',
entitaev=cont.__str__(),
c1ev=cont.validcont,
c2ev=cont.prefcont,
utenteev=user)
newev.save()
return cont
class AzioneForm(forms.ModelForm):
class Meta:
model = models.Azione
def clean_titoloaz(self):
return " ".join(self.cleaned_data['titoloaz'].upper().split())
def clean(self):
cleaned_data = super(AzioneForm, self).clean()
promemaz = cleaned_data.get("promemaz")
scadaz = cleaned_data.get("scadaz")
if promemaz and not scadaz:
msg = "Per ottenere un promemoria specificare la scadenza"
self._errors["scadaz"] = self.error_class([msg])
del cleaned_data["scadaz"]
return cleaned_data
def save(self, *args, **kwargs):
agid = kwargs.pop('agid', None)
user = kwargs.pop('user', None)
if not self.instance.id: # obj not in db yet
self.instance.anagrafica_id = agid # link the new azione to the ag it belongs
self.instance.autoreaz = user
az = super(AzioneForm, self).save(*args, **kwargs)
return az
class FollowAzioneform(AzioneForm):
evadiaz = forms.BooleanField(required=False, label=u'Evadi azione orig.')
<file_sep>/prodotti/views.py
# Create your views here.
#from django.db import connection
from django.shortcuts import render_to_response, get_object_or_404, redirect
from django.template import RequestContext
#from django.views.generic import list_detail
from django.db.models import F
import shutil, os
from django.contrib.auth.decorators import login_required
#from django.contrib.admin.views.decorators import staff_member_required
#from django.core.urlresolvers import reverse
from prodotti.models import Famiglia, Linea, Opzione, Prodotto
from eventi.models import Evento
from prodotti import forms
from django.conf import settings
import tdj
#from django.utils.translation import activate
#activate('it')
@login_required
def prodhome(request):
famform = forms.SearchFamForm()
lineaform = forms.SearchLineaForm()
prodform = forms.SearchProdForm()
opzform = forms.SearchOpzForm()
return render_to_response('prodhome.html',
{'famform':famform, 'lineaform':lineaform, 'prodform':prodform, 'opzform':opzform},
context_instance=RequestContext(request))
@login_required
def list_acc_prod(request, prodid):
prod = get_object_or_404(Prodotto, pk=prodid)
prodacc = prod.accessprod.all() # my accessories
whoseacc = prod.prodotto_set.all() # prods I'm an access. of
return render_to_response('listaccess.html',
{'prodotto':prod, 'prodacc':prodacc, 'whoseacc':whoseacc},
context_instance=RequestContext(request))
@login_required
#@staff_member_required
def create_fam(request):
if request.method == 'POST':
form = forms.FamigliaForm(request.POST, request.FILES)
if form.is_valid():
fam = form.save(user=request.user)
return redirect('viewfam', fam.id)
# return HttpResponseRedirect(reverse('viewfam', args=(fam.id,)))
else:
form = forms.FamigliaForm()
return render_to_response('editfamiglia.html',
{'form': form, 'create': True},
context_instance=RequestContext(request))
@login_required
def edit_fam(request, famid):
fam = get_object_or_404(Famiglia, pk=famid)
if request.method == 'POST':
form = forms.FamigliaForm(request.POST, request.FILES, instance=fam)
if form.is_valid():
fam=form.save(user=request.user)
return redirect('viewfam', fam.id)
else:
form = forms.FamigliaForm(instance=fam)
return render_to_response('editfamiglia.html',
{'form': form},
context_instance=RequestContext(request))
@login_required
def create_linea(request):
if request.method == 'POST':
form = forms.LineaForm(request.POST, request.FILES)
if form.is_valid():
linea = form.save(user=request.user)
return redirect('viewlinea', linea.id)
# return HttpResponseRedirect(reverse('viewlinea', args=(linea.id,)))
else:
form = forms.LineaForm()
return render_to_response('editlinea.html',
{'form': form, 'create': True},
context_instance=RequestContext(request))
@login_required
def edit_linea(request, lineaid):
linea = get_object_or_404(Linea, pk=lineaid)
if request.method == 'POST':
form = forms.LineaForm(request.POST, request.FILES, instance=linea)
if form.is_valid():
linea=form.save(user=request.user)
return redirect('viewlinea', linea.id)
# return HttpResponseRedirect(reverse('viewlinea', args=(linea.id,)))
else:
form = forms.LineaForm(instance=linea)
return render_to_response('editlinea.html',
{'form': form},
context_instance=RequestContext(request))
@login_required
def create_opz(request):
if request.method == 'POST':
form = forms.OpzioneForm(request.POST)
if form.is_valid():
opz = form.save(user=request.user)
return redirect('viewopz', opz.id)
# return HttpResponseRedirect(reverse('viewopz', args=(opz.id,)))
else:
form = forms.OpzioneForm()
return render_to_response('editopzione.html',
{'form': form, 'create': True},
context_instance=RequestContext(request))
@login_required
def edit_opz(request, opzid):
opz = get_object_or_404(Opzione, pk=opzid)
if request.method == 'POST':
form = forms.OpzioneForm(request.POST, instance=opz)
if form.is_valid():
opz=form.save(user=request.user)
return redirect('viewopz', opz.id)
# return HttpResponseRedirect(reverse('viewopz', args=(opz.id,)))
else:
form = forms.OpzioneForm(instance=opz)
return render_to_response('editopzione.html',
{'form': form},
context_instance=RequestContext(request))
@login_required
def create_prod(request):
if request.method == 'POST':
form = forms.ProdottoForm(request.POST, request.FILES)
if form.is_valid():
prod = form.save(user=request.user)
return redirect('viewprod', prod.id)
# return HttpResponseRedirect(reverse('viewprod', args=(prod.id,)))
else:
form = forms.ProdottoForm()
return render_to_response('editprodotto.html',
{'form': form, 'create': True},
context_instance=RequestContext(request))
@login_required
def edit_prod(request, prodid):
prod = get_object_or_404(Prodotto, pk=prodid)
if request.method == 'POST':
form = forms.ProdottoForm(request.POST, request.FILES, instance=prod)
if form.is_valid():
prod=form.save(user=request.user)
return redirect('viewprod', prod.id)
# return HttpResponseRedirect(reverse('viewprod', args=(prod.id,)))
else:
form = forms.ProdottoForm(instance=prod)
return render_to_response('editprodotto.html',
{'form': form},
context_instance=RequestContext(request))
@login_required
def new_prod_vers(request, prodid):
prod = get_object_or_404(Prodotto, pk=prodid)
oricodevers = prod.__str__()
orivers= prod.versprod
if request.method == 'POST':
form = forms.NewProdVersForm(request.POST, prod=prod)
if form.is_valid():
prodacc = request.POST.getlist('prodacc')
whoseacc = request.POST.getlist('whoseacc')
#remove this prod as an accessory of whoseacc prods
prod.prodotto_set.remove(*whoseacc)
#duplicate prod and save it to db
prod.id = None
prod.versprod = form.cleaned_data['newvers']
orifotoname=prod.fotoprod.name
if form.cleaned_data.get('samefoto') and orifotoname!=tdj.IMGNOPIC:
prodpath, imgfname = os.path.split(orifotoname)
prod.fotoprod.name= prodpath+"/V"+prod.versprod+imgfname
prod.save()
shutil.copyfile(settings.MEDIA_ROOT+orifotoname,
settings.MEDIA_ROOT+prod.fotoprod.name)
else:
prod.fotoprod.name = tdj.IMGNOPIC
prod.save()
#now add all selected accessories
prod.accessprod.add(*prodacc)
#now make all whoseacc prod point to this new prod id
prod.prodotto_set.add(*whoseacc)
#now add the events
newev = Evento(fkev=prodid,
codiceev='NUOVAVER',
tipoentev='PRD',
entitaev=oricodevers,
c1ev=orivers,
c2ev=prod.versprod,
utenteev=request.user)
# timestampev=datetime.datetime.today())
newev.save() # create the event for the ori prod
newev.id = None
newev.fkev = prod.id
newev.entitaev = prod.__str__()
newev.save() # create the event for the new prod
response = redirect('searchprod')
response['Location'] += '?codiceprod=%s' % prod.codiceprod
return response # show all versions
else:
form = forms.NewProdVersForm(prod=prod)
return render_to_response('newversprod.html',
{'form': form},
context_instance=RequestContext(request))
@login_required
def stats_prod(request):
fambystato = Famiglia.objects.raw('SELECT id, statofam, COUNT(statofam) AS nstato FROM famiglia GROUP BY statofam')
lineabystato = Linea.objects.raw('SELECT id, statolinea, COUNT(statolinea) AS nstato FROM linea GROUP BY statolinea')
opzbystato = Opzione.objects.raw('SELECT id, statoopz, COUNT(statoopz) AS nstato FROM opzione GROUP BY statoopz')
prodbystato = Prodotto.objects.raw('SELECT id, statoprod, COUNT(statoprod) AS nstato FROM prodotto GROUP BY statoprod')
famstatoval = []
famstatotag = []
totfam = 0
for i in fambystato:
famstatoval.append(i.nstato)
famstatotag.append("%s (%d)" % (i.statofam, i.nstato))
totfam += i.nstato
lineastatoval = []
lineastatotag = []
totlinea = 0
for i in lineabystato:
lineastatoval.append(i.nstato)
lineastatotag.append("%s (%d)" % (i.statolinea, i.nstato))
totlinea += i.nstato
opzstatoval = []
opzstatotag = []
totopz = 0
for i in opzbystato:
opzstatoval.append(i.nstato)
opzstatotag.append("%s (%d)" % (i.statoopz, i.nstato))
totopz += i.nstato
prodstatoval = []
prodstatotag = []
totprod = 0
for i in prodbystato:
prodstatoval.append(i.nstato)
prodstatotag.append("%s (%d)" % (i.statoprod, i.nstato))
totprod += i.nstato
return render_to_response('statsprod.html',
{'totfam':totfam, 'totlinea':totlinea, 'totopz':totopz, 'totprod':totprod,
'famstatoval': famstatoval, 'famstatotag': famstatotag,
'lineastatoval': lineastatoval, 'lineastatotag': lineastatotag,
'opzstatoval': opzstatoval, 'opzstatotag': opzstatotag,
'prodstatoval': prodstatoval, 'prodstatotag': prodstatotag,
},
context_instance=RequestContext(request))
@login_required
def alter_price(request):
if request.method == 'POST':
apform = forms.AlterPriceForm(request.POST)
if apform.is_valid():
perc = int(apform.cleaned_data['perc'])
oripricedelta = apform.cleaned_data['pricedelta']
orivalmindelta = apform.cleaned_data['valmindelta']
if perc:
pricedelta = oripricedelta/100.0 + 1.0
valmindelta = orivalmindelta/100.0 + 1.0
oripricedelta = str(oripricedelta)+'%'
orivalmindelta = str(orivalmindelta)+'%'
else:
pricedelta = oripricedelta
valmindelta = orivalmindelta
oripricedelta = str(oripricedelta)+tdj.CURRENCY
orivalmindelta = str(orivalmindelta)+tdj.CURRENCY
real = apform.cleaned_data.get('real',False)
prodqs = Prodotto.objects.filter(statoprod=u'VAL').order_by('linea')
opzqs = Opzione.objects.filter(statoopz=u'VAL').order_by('linea')
#print prodqs.query, opzqs.query
if real:
for prod in prodqs:
oriprezzo = prod.prezzoprod
oriminprezzo = prod.minprezzoprod
if perc: #percentage
#print "perc", pricedelta, valmindelta
prod.prezzoprod = round(prod.prezzoprod*pricedelta, 2)
prod.minprezzoprod = round(prod.minprezzoprod*valmindelta, 2)
else: #absolute value
#print "abs", pricedelta, valmindelta
prod.prezzoprod = round(prod.prezzoprod+pricedelta, 2)
prod.minprezzoprod = round(prod.minprezzoprod+valmindelta, 2)
prod.save()
newev = Evento(fkev=prod.id,
codiceev='PREZZO',
tipoentev='PRD',
entitaev=prod.__str__(),
c1ev=oriprezzo,
c2ev=prod.prezzoprod,
c3ev=oripricedelta,
utenteev=request.user)
newev.save()
newev = Evento(fkev=prod.id,
codiceev='VALMIN',
tipoentev='PRD',
entitaev=prod.__str__(),
c1ev=oriminprezzo,
c2ev=prod.minprezzoprod,
c3ev=orivalmindelta,
utenteev=request.user)
newev.save()
for opz in opzqs:
oriprezzo = opz.prezzoopz
oriminprezzo = opz.minprezzoopz
if perc: #percentage
#print "perc", pricedelta, valmindelta
opz.prezzoopz = round(opz.prezzoopz*pricedelta, 2)
opz.minprezzoopz = round(opz.minprezzoopz*valmindelta, 2)
else: #absolute value
#print "abs", pricedelta, valmindelta
opz.prezzoopz = round(opz.prezzoopz+pricedelta, 2)
opz.minprezzoopz = round(opz.minprezzoopz+valmindelta, 2)
opz.save()
newev = Evento(fkev=opz.id,
codiceev='PREZZO',
tipoentev='OPZ',
entitaev=opz.__str__(),
c1ev=oriprezzo,
c2ev=opz.prezzoopz,
c3ev=oripricedelta,
utenteev=request.user)
newev.save()
newev = Evento(fkev=opz.id,
codiceev='VALMIN',
tipoentev='OPZ',
entitaev=opz.__str__(),
c1ev=oriminprezzo,
c2ev=opz.minprezzoopz,
c3ev=orivalmindelta,
utenteev=request.user)
newev.save()
numprod = prodqs.count()
numopz = opzqs.count()
return render_to_response('alterprice.html',
{'prod_list':prodqs, 'opz_list':opzqs,
'pricedelta': oripricedelta,
'valmindelta': orivalmindelta,
'real': real,
'numprod':numprod, 'numopz':numopz},
context_instance=RequestContext(request))
else: # HTTP GET
apform = forms.AlterPriceForm(initial={'perc':'1',
'pricedelta':0.0, 'valmindelta':0.0})
return render_to_response('alterform.html',
{'form':apform},
context_instance=RequestContext(request))
@login_required
def gen_lp(request):
linee = Linea.objects.filter(statolinea='VAL', publinea=True).order_by('famiglia')
fullist = []
for linea in linee:
prods= linea.prodotto_set.filter(statoprod='VAL', pubprod=True)
obj = (linea, prods,)
fullist.append(obj)
print fullist
return render_to_response('pricelist.html',
{'fullist':fullist},
context_instance=RequestContext(request))
<file_sep>/indirizzario/admin.py
from indirizzario import models
from django.contrib import admin
class ProvinciaAdmin(admin.ModelAdmin):
search_fields = ('codiceprov',)
class RegioneAdmin(admin.ModelAdmin):
search_fields = ('nomereg',)
class NazioneAdmin(admin.ModelAdmin):
search_fields = ('nomenaz',)
class RapportoAdmin(admin.ModelAdmin):
search_fields = ('codicerap',)
class PagamentoAdmin(admin.ModelAdmin):
search_fields = ('codicepag',)
class ScontoAdmin(admin.ModelAdmin):
search_fields = ('codicesconto',)
class SpedizioneAdmin(admin.ModelAdmin):
search_fields = ('codicesped',)
class SettoreAdmin(admin.ModelAdmin):
search_fields = ('codicesett',)
class CategoriaAdmin(admin.ModelAdmin):
search_fields = ('codicecat',)
class AnagraficaAdmin(admin.ModelAdmin):
search_fields = ('nomeag',)
class TipoazioneAdmin(admin.ModelAdmin):
search_fields = ('codicetipoaz',)
class AzioneAdmin(admin.ModelAdmin):
search_fields = ('titoloaz',)
class ContattoAdmin(admin.ModelAdmin):
search_fields = ('cognomecont',)
admin.site.register(models.Provincia, ProvinciaAdmin)
admin.site.register(models.Regione, RegioneAdmin)
admin.site.register(models.Nazione, NazioneAdmin)
admin.site.register(models.Rapporto, RapportoAdmin)
admin.site.register(models.Pagamento, PagamentoAdmin)
admin.site.register(models.Sconto, ScontoAdmin)
admin.site.register(models.Spedizione, SpedizioneAdmin)
admin.site.register(models.Settore, SettoreAdmin)
admin.site.register(models.Categoria, CategoriaAdmin)
admin.site.register(models.Anagrafica, AnagraficaAdmin)
admin.site.register(models.Tipoazione, TipoazioneAdmin)
admin.site.register(models.Azione, AzioneAdmin)
admin.site.register(models.Contatto, ContattoAdmin)
| 1769ce6e7dafdffad987d037fc14134f41b608cd | [
"Python",
"HTML",
"reStructuredText"
] | 20 | Python | pynchia/tdj | 02730ef255ba074a8a9bb07f7aa4b1ea2628b086 | a7254936889ae48aff39260bfbd6b94cd998cdfa |
refs/heads/master | <file_sep>from flask import Flask, request
app = Flask(__name__)
@app.route('/he/<string:name>/<string:id>')
def hello_world(name, id):
return 'hello world' + name + id
if __name__ == '__main__':
app.run(port=8888, debug=True)
| ddca530b3cd95859893b0a768eb1b46a172586cc | [
"Python"
] | 1 | Python | SZSTIwang/Wi-FiProbe | f29a61d4cb799d839fc4cefbeae0848034e046e5 | f94bb5faea8d3c9abaeb1f82a4c308a0a22131db |
refs/heads/master | <file_sep>autobg
======
Automated wallpaper switching daemon written in C.
TODO
----
- Print command specific help
- Get daemon working
- Get interval working
- Implement safe file path checking
op
==
This program uses the op library. The source for op can be found at
<https://github.com/matthiasbeyer/op.git>
<file_sep>/*
Copyright (c) 2013 <NAME>
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* 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.
* Neither the name of the copyright owners 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.
*/
#include <autobg.h>
#include <stdarg.h>
#define FAIL "[\e[01;31mFAIL\e[00m]"
#define PASS "[\e[01;32mPASS\e[00m]"
#define MIN(a, b) \
({ __typeof__ (a) _a = (a); \
__typeof__ (b) _b = (b); \
_a > _b ? _b : _a; })
/************************ Function Prototypes *************************/
// Setup functions
static int test_count_bgs ();
static int test_get_next_bg ();
static int test_get_relpath ();
static int test_join_path ();
static int test_populate_bgs ();
// Print functions
void print_test_result (const char *, ...);
void print_test_status (int, const char *);
/******************************** Main ********************************/
int main (int argc, const char **argv)
{
printf("[\e[01;32mPASS\e[00m/\e[01;31mFAIL\e[00m]\tTest Name\t\t");
printf("Expected:\t\tGot:\n\n");
test_count_bgs();
test_get_relpath();
test_join_path();
test_get_next_bg();
return EXIT_SUCCESS;
}
/******************************** Print ********************************/
void print_test_result (const char *format, ...)
{
va_list args;
va_start(args, format);
vprintf(format, args);
}
void print_test_status(int status, const char *test)
{
if (status)
printf("%s\t\t", FAIL);
else
printf("%s\t\t", PASS);
printf("%s:\t", test);
if (strlen(test) < 16)
printf("\t");
}
/******************************** Tests ********************************/
static int test_count_bgs ()
{
const int expected = 2;
int got = 0;
count_bgs("/home/ryan/Pictures/Wallpapers", &got);
int status = (got == expected ? 0 : 1);
print_test_status(status, "test_count_bgs");
print_test_result("%d\t\t\t%d\n", expected, got);
return status;
}
static int test_get_next_bg ()
{
char *bg0 = "/home/ryan/Picture00.jpg";
char *bg1 = "/home/ryan/Picture01.jpg";
char *bg2 = "/home/ryan/Picture02.jpg";
char **bg_list = malloc(4 * sizeof(char*));
bg_list[0] = bg0;
bg_list[1] = bg1;
bg_list[2] = bg2;
bg_list[3] = NULL;
char *result1 = get_next_bg(bg_list, bg0);
char *result2 = get_next_bg(bg_list, bg2);
print_test_status(strcmp(bg1, result1), "test_count_bgs");
print_test_result("%s\t%s\n", bg1, result1);
print_test_status(strcmp(bg0, result2), "test_count_bgs");
print_test_result("%s\t%s\n", bg0, result2);
free(bg_list);
return EXIT_SUCCESS;
}
static int test_get_relpath ()
{
const char *expected = "/home/ryan/colors";
const char *got = get_relpath("colors");
int status = strcmp(expected, got);
print_test_status(status, "test_get_relpath");
print_test_result("%s\t%s\n", expected, got);
return status;
}
static int test_join_path ()
{
const char *expected = "/usr/bin/autobg";
const char *got = join_path("/usr/bin", "autobg");
int status = strcmp(expected, got);
print_test_status(status, "test_join_path");
print_test_result("%s\t\t%s\n", expected, got);
return status;
}
static int test_populate_bgs ()
{
}
<file_sep>/*
Copyright (c) 2013 <NAME>
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* 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.
* Neither the name of the copyright owners 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.
*/
#include <autobg.h>
struct program_options {
int delay;
const char *path;
//const char * (*sort)(const char **);
};
/*********************** Command line arguments ***********************/
const char *D[] = { "-D", "--daemon" };
const char *d[] = { "-d", "--directory" };
const char *h[] = { "-h", "--help" };
const char *i[] = { "-i", "--interval" };
const char *v[] = { "-v", "--version" };
/************************** Setup Functions ***************************/
char *get_directory (const int ops)
{
if (not (ops & ABG_DIRECTORY_BIT)) {
return get_relpath(ABG_WALLPAPER);
}
int i = op_arg_cnt(d[0]);
char **args;
if (i) {
args = (char **) op_args(d[0]);
} else {
fprintf(stderr, "ERROR: Must specify a directory\n");
print_help(ops);
exit(EXIT_FAILURE);
}
return args[0];
}
char *get_relpath (const char *relpath)
{
char *home = getenv("HOME");
char *path = join_path(home, relpath);
return path;
}
void init_args ()
{
op_init(5);
op_add_option(d, 2);
op_add_option(D, 2);
op_add_option(h, 2);
op_add_option(i, 2);
op_add_option(v, 2);
}
char *join_path (const char *root, const char *rel)
{
int root_len = strlen(root);
int rel_len = strlen(rel);
char *full = malloc(root_len + rel_len + 1);
strcpy(full, root);
strcat(full, "/");
strcat(full, rel);
return full;
}
int parse_ops (int argc, const char **argv)
{
op_parse(argv, argc);
int flags = 0;
if (op_is_set(h[0]))
flags = flags | ABG_HELP_BIT;
if (op_is_set(v[0]))
flags = flags | ABG_VERSION_BIT;
if (op_is_set(D[0]))
flags = flags | ABG_DAEMON_BIT;
if (op_is_set(d[0]))
flags = flags | ABG_DIRECTORY_BIT;
if (op_is_set(i[0]))
flags = flags | ABG_INTERVAL_BIT;
return flags;
}
void free_bg_strs (char **bgs)
{
for (int i = 0; bgs[i] not_eq NULL; i++)
free(bgs[i]);
free(bgs);
}
/************************ Daemonize Functions *************************/
/**
* Closes the connection to stdin, stdout, and stderr so we don't dump
* anything to the console.
*/
void close_io ()
{
close(STDIN_FILENO); // Close stdin
close(STDOUT_FILENO); // Close stdout
close(STDERR_FILENO); // Close stderr
}
/**
* Daemonizes the program.
*
* Delegation method that handles forking, and other things necessary
* to safely and properly run as a daemon.
*
* @return 0 If this is the child process, >0 if successfully
* daemonized, or <0 if unsuccessfully daemonized.
*/
int daemonize ()
{
open_log();
int p = spawn_child();
if (p not_eq 0)
return p;
umask(0); // Change file mask
close_io();
return 0;
}
/**
* Handles the opening of the logger and setting the log mask.
*
* @returns 0 If successful. (Always successful, can this fail?)
*/
void open_log ()
{
setlogmask(LOG_UPTO(LOG_NOTICE));
openlog(ABG_DAEMON_NAME, LOG_CONS | LOG_NDELAY | LOG_PERROR, LOG_USER);
syslog(LOG_INFO, "Starting Daemon");
}
void process (const char *dir)
{
}
/**
* Forks the parent process.
*
* @return 0 If this is the child process, >0 if successfully
* daemonized, or <0 if unsuccessfullly daemonized.
*/
pid_t spawn_child ()
{
pid_t pid;
pid = fork(); // Fork the parent process
if (pid not_eq 0)
return pid;
pid_t sid;
sid = setsid(); // Create new Signature ID for child
if (sid < 0) // Bad sid
return -1;
return 0;
}
/************************* Program Functions **************************/
/*
*
*/
int change_bg (const char *path)
{
const int exec_len = strlen(ABG_EXEC);
const int opts_len = strlen(ABG_OPTS);
const int path_len = strlen(path);
char *command = malloc(exec_len + opts_len + path_len + 2);
strcpy(command, ABG_EXEC);
strcat(command, " ");
strcat(command, ABG_OPTS);
strcat(command, " ");
strcat(command, path);
printf("command: %s\n", command);
int status = system(command);
free(command);
return status;
}
/*
*
*/
int count_bgs (const char *path, int *count)
{
DIR *dir = opendir(path);
if (dir == NULL) {
fprintf(stderr, "ERROR: Cannot open wallpaper directory.\n");
return EXIT_FAILURE;
}
struct dirent *ent;
// Get dir count
int lcount = 0;
while ((ent = readdir(dir)) not_eq NULL) {
char *f = ent->d_name;
if (f[0] == '.' && (f[1] == 0 or f[1] == '.'))
continue;
++lcount;
}
closedir(dir);
*count = lcount;
return EXIT_SUCCESS;
}
/*
*
*/
int count_current_len (const char *path, int *count, long *offset)
{
FILE *feh = fopen(path, "r");
if (feh == NULL)
return EXIT_FAILURE;
int lcount = 0, do_count = 0;
for (char c = 33; c not_eq EOF; c = fgetc(feh)) {
if (do_count and c == '\'') {
break;
}
if (do_count) {
++lcount;
continue;
}
if (c == '\'') {
do_count = 1;
*offset = ftell(feh);
++lcount;
}
}
fclose(feh);
*count = lcount;
return EXIT_SUCCESS;
}
/*
*
*/
char *get_next_bg (char **bg_list, char *current)
{
assert(bg_list != NULL);
assert(current != NULL);
char *next = bg_list[0];
for (int i = 0; bg_list[i] not_eq NULL; i++) {
if (strcmp(current, bg_list[i]))
continue;
int try = i + 1;
if (bg_list[try] not_eq NULL)
next = bg_list[try];
break;
}
return next;
}
/**
* Opens the directory specified, gets the next wallpaper, and changes
* the wallpaper.
*/
int next_bg (const char *path)
{
char *fehpath = get_relpath(".fehbg");
int count = 0;
if (count_bgs(path, &count))
return EXIT_FAILURE;
char **bg_list = malloc((count + 1) * sizeof(char*));
bg_list[count] = NULL;
if (populate_bgs(path, bg_list)) {
printf("Populating failed");
free(fehpath);
free_bg_strs(bg_list);
return EXIT_FAILURE;
}
count = 0;
long offset = 0;
if (count_current_len(fehpath, &count, &offset)) {
printf("Counting failed");
return EXIT_FAILURE;
}
char *current = malloc(count);
if (parse_current_bg(fehpath, current, offset)) {
printf("Parsing failed");
free(fehpath);
free_bg_strs(bg_list);
free(current);
return EXIT_SUCCESS;
}
char *bg = get_next_bg(bg_list, current);
free(fehpath);
free(current);
change_bg(bg);
free_bg_strs(bg_list);
return EXIT_SUCCESS;
}
/*
*
*/
int parse_current_bg (const char *path, char *current, long offset)
{
FILE *feh = fopen(path, "r");
if (feh == NULL) {
fprintf(stderr, "ERROR: Cannot open %s\n", path);
return EXIT_FAILURE;
}
fseek(feh, offset, SEEK_SET);
fscanf(feh, "%s", current);
fclose(feh);
size_t len = strlen(current);
current[len - 1] = 0; // trim off an excess ' that feh puts in
return EXIT_SUCCESS;
}
/*
*
*/
int populate_bgs (const char *path, char **bg_list)
{
DIR *dir = opendir(path);
if (dir == NULL) {
fprintf(stderr, "ERROR: Cannot open wallpaper directory.\n");
return EXIT_FAILURE;
}
struct dirent *ent;
int i = 0;
while ((ent = readdir(dir)) not_eq NULL) {
char *f = ent->d_name;
if (f[0] == '.' && (f[1] == 0 or f[1] == '.'))
continue;
char *abs = join_path(path, f);
bg_list[i] = abs;
++i;
}
closedir(dir);
return EXIT_SUCCESS;
}
/************************** Print Functions ***************************/
void print_help (const int flags)
{
print_version();
printf("Usage:\n%s [-Dhv] [-d <directory>] [-i <interval>]",
ABG_PROGRAM_NAME);
printf("\n\nOPTIONS\n");
print_opt("-h", "--help", "Print this message");
print_opt("-v", "--version", "Print the current version");
print_opt("-D", "--daemon", "Run as a daemon");
print_opt("-d", "--directory", "Specify the directory to search in");
print_opt("-i", "--interval",
"Value in minutes to wait between each wallpaper. Only works\
\twith the -D option");
}
void print_opt(const char *s, const char *l, const char *m)
{
printf("%s, %s\n", s, l);
printf("\t\t%s\n\n", m);
}
void print_version ()
{
printf("%s version %s - Compiled on %s\n\n", ABG_PROGRAM_NAME, ABG_VERSION,
ABG_DATE);
}
// EOF
<file_sep>INC=./include
LIB=./lib
SRC=./src
BIN=./bin
DOC=./doc
TEST=./test
EXEC_NAME=autobg
SOURCES=$(wildcard $(SRC)/*.c)
TEST_SOURCES=$(wildcard $(TEST)/*.c)
TARGET=$(BIN)/$(EXEC_NAME)
CFLAGS+=-std=c99 -Wall -Werror -I$(INC) -L$(LIB) -lop -O2
LD=/usr/bin/gcc
LDFLAGS+= -lc
all: prepare
$(CC) $(CFLAGS) $(SOURCES) -o $(TARGET)
doc:
@mkdir -p $(DOC)
@$(shell doxygen)
prepare:
@mkdir -p $(BIN)
<file_sep>/*
* @brief op header
*
* @author <NAME>
*
* @license Have a look at the LICENSE file, shipped with the code repository
*/
#ifndef __OP_H__
#define __OP_H__
#define OP_LONG_OPTION_PREF "--"
#define OP_SHORT_OPTION_PREF "-"
void op_init (unsigned int opt_count);
void op_add_option (const char **keys, const unsigned int key_count);
int op_is_set (const char *key);
unsigned int op_arg_cnt (const char *key);
const char ** op_args (const char *key);
void op_shutdown (void);
void op_parse (const char **argv, const int argc);
#endif //__OP_H__
<file_sep>/*
Copyright (c) 2013 <NAME>
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* 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.
* Neither the name of the copyright owners 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 AUTOBG_H
#define AUTOBG_H
#include <assert.h>
#include <dirent.h>
#include <errno.h>
#include <fcntl.h>
#include <iso646.h>
#include <op.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <syslog.h>
#include <unistd.h>
#include <sys/stat.h>
#include <sys/types.h>
/************************* User Configuration *************************/
// External dependency which handles background switching for us
#define ABG_EXEC "feh"
// Command line arguments passed to ABG_EXEC
#define ABG_OPTS "--bg-scale"
/***************************** Constants ******************************/
#define ABG_DAEMON_NAME "autobgd"
#define ABG_PROGRAM_NAME "autobg"
#define ABG_VERSION "0.1.7"
#define ABG_DATE "2013-07-26"
#define ABG_WALLPAPER "Pictures/Wallpapers"
#define ABG_HELP_BIT (1 << 0) // 0b00000001
#define ABG_VERSION_BIT (1 << 1) // 0b00000010
#define ABG_DAEMON_BIT (1 << 2) // 0b00000100
#define ABG_DIRECTORY_BIT (1 << 3) // 0b00001000
#define ABG_INTERVAL_BIT (1 << 4) // 0b00010000
/************************ Function-like Macros ************************/
#define OVERFLOW(a, b)\
({ __typeof__ (a) _a = (a);\
__typeof__ (b) _b = (b);\
_a > _b ? 0 : _a })
/************************ Function Prototypes *************************/
// Setup functions
char * get_directory (const int);
char * get_relpath (const char*);
void init_args ();
char * join_path (const char *, const char *);
int parse_ops ();
void free_bg_strs (char **);
// Daeamonize functions
void close_io ();
int daemonize ();
void open_log ();
void process ();
pid_t spawn_child ();
// Program functions
int change_bg (const char *);
int count_bgs (const char *, int *);
int count_current_len (const char *, int *, long *);
char * get_next_bg (char **, char *);
int next_bg (const char *);
int parse_current_bg (const char *, char *, long);
int populate_bgs (const char *, char **);
// Print functions
void print_help (const int);
void print_opt (const char *, const char *, const char *);
void print_version ();
#endif // AUTOBG_H
| c4e78dc8b8e104213415b0e52c8e1fe3e463eb87 | [
"Markdown",
"C",
"Makefile"
] | 6 | Markdown | ShadowHawk54/autobg | fc8b0cb95f4ccb34349a3e0126cf3dd533f2cc8f | bdbec546b40badcdf0738189b8b3107e8f577187 |
refs/heads/master | <file_sep># javascrip_3
Description: The java script written for passwordgenerator is very userfriendly. This applicatioin allows user to choose various condition and generate password accordingly. User can choose the number of character in the password along with upper case, lowercase and special characters. This application is ideal for any employer who needs a secure and different password for security reasons.
link to the deployed application: https://github.com/bishank10/javascrip_3.git , https://bishank10.github.io/javascrip_3/<file_sep>// Assignment Code
var generateBtn = document.querySelector("#generate");
var length;
var uppCase;
var lowCase;
var specChar;
var character;
var password;
// function here generates random password and logs it
function generatePassword() {
length = parseInt(prompt("Choose a number from 8 to 28 for your password?"));
uppCase = confirm("Would you like uppercase?");
lowCase = confirm("Would you like lowercase?");
specChar = confirm("Would you like special characters?");
if (uppCase && lowCase && specChar ) {
firstCase();
} else if (uppCase === false && lowCase === true && specChar === true) {
secondCase();
} else if (lowCase === false && uppCase === true && specChar === true ) {
thirdCase();
} else if (specChar === false && lowCase === true && uppChar === true ) {
fourthCase();
} else {
alert("invalid entry");
generatePassword();
}
}
// the function listed here are called upon satisfied condition up above
function firstCase() { // this satifies cas
password ="";
var character = "abcdefghijklmnopqrstuvwxyz!@#$%^&*()-+<>ABCDEFGHIJKLMNOP1234567890";
for ( i=0; i <= length; i++) {
password += character.charAt(Math.floor(Math.random() * (character.length) +1));
var passwordText = document.querySelector("#password");
passwordText.value = password;
}
}
function secondCase() {
password = "";
var character = "abcdefghijklmnopqrstuvwxyz!@#$%^&*()-+<>1234567890";
for (i=0; i <= length; i++) {
var password = password + character.charAt(Math.floor(Math.random() * character.length +1));
var passwordText = document.querySelector("#password");
passwordText.value = password;
}
}
function thirdCase() {
password = "";
var character = "!@#$%^&*()-+<>ABCDEFGHIJKLMNOP1234567890";
for (i=0; i<=length; i++) {
var password = <PASSWORD> + character.charAt(Math.floor(Math.random() * character.length +1));
var passwordText = document.querySelector("#password");
passwordText.value = password;
}
}
function fourthCase() {
password = "";
var character = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOP1234567890";
for (i=0; i<length; i++) {
var password = password + character.charAt(Math.floor(Math.random() * character.length +1));
var passwordText = document.querySelector("#password");
passwordText.value = password;
}
}
document.getElementById("generate").addEventListener("click", generatePassword); | 8c3f73d0b061580857dbbf4b07b27e0acdb864cb | [
"Markdown",
"JavaScript"
] | 2 | Markdown | bishank10/javascrip_3 | 4ac8599d99a1125ab499585659ee80d87346969e | a8f4b5626291eb866af657369dca94183d907962 |
refs/heads/master | <repo_name>danbrauer/react-breakout<file_sep>/src/components/game.js
import React, { Component } from "react";
import {Layer, Group} from "react-konva";
import { Field } from "./field";
import { Ball, updateBallLocation } from "./ball";
import { Paddle, updatePaddleLocation } from "./paddle";
import Konva from "konva";
import { Brick, bricksInitialize } from "./brick";
import { Status } from "./gameStatus";
export default class Game extends Component {
FIELD_WIDTH = 400;
FIELD_HEIGHT = 400;
FIELD_BORDER_WIDTH = 4;
FIELD_MIN_X = this.FIELD_BORDER_WIDTH;
FIELD_MIN_Y = this.FIELD_BORDER_WIDTH;
FIELD_MAX_X = this.FIELD_WIDTH - this.FIELD_BORDER_WIDTH;
FIELD_MAX_Y = this.FIELD_HEIGHT - this.FIELD_BORDER_WIDTH;
PADDLE_WIDTH = 60;
PADDLE_HEIGHT = 10;
PADDLE_OFFSET = 50;
PADDLE_COLOR = Konva.Util.getRandomColor();
PADDLE_MIN_X = this.FIELD_MIN_X;
PADDLE_MAX_X = this.FIELD_MAX_X - this.PADDLE_WIDTH;
BALL_COLOR = Konva.Util.getRandomColor();
BALL_SPEED = 10;
BALL_RADIUS = 8;
BALL_MIN_X = this.FIELD_MIN_X + this.BALL_RADIUS;
BALL_MIN_Y = this.FIELD_MIN_Y + this.BALL_RADIUS;
BALL_MAX_X = this.FIELD_MAX_X - this.BALL_RADIUS;
BALL_MAX_Y = this.FIELD_MAX_Y - this.BALL_RADIUS;
INITIAL_STATE = () => {
const bricks = bricksInitialize();
return {
paddleX: this.FIELD_MIN_X + 100,
paddleY: this.FIELD_MAX_Y - this.PADDLE_OFFSET,
ballXCoord: 0,
ballYCoord: 0,
ballDirection: {
x: 0,
y: 0
},
bricks,
bricksBroken: 0,
gameRestarts: 0
}
};
componentDidMount() {
const x = this.FIELD_MIN_X + this.BALL_RADIUS;
const y = this.FIELD_MAX_Y - this.PADDLE_OFFSET;
const dirX = Math.floor(Math.random() * this.BALL_SPEED) + 1;
const dirY = -this.BALL_SPEED;
this.setState({
...this.state,
ballDirection: {
x: dirX,
y: dirY
},
ballXCoord: x,
ballYCoord: y,
});
this.ballAnimate();
}
componentWillUnmount() {
clearTimeout(this.animationTimeout);
}
gameEnd = (ballY) => {
if (ballY >= this.BALL_MAX_Y) {
this.componentWillUnmount();
// I am guessing react has a better way to do this...
// window.alert("OH NO YOU LOST! CLICK TO START AGAIN!");
this.setState({...this.INITIAL_STATE(), gameRestarts: this.state.gameRestarts + 1});
this.componentDidMount();
}
};
constructor(props) {
super(props);
this.state = this.INITIAL_STATE();
};
_onMouseMove = ({ evt }) => {
this.setState({
...this.state,
paddleX: updatePaddleLocation(evt.clientX, this.PADDLE_MIN_X, this.PADDLE_MAX_X)
});
};
_onTouchMove = ({ evt }) => {
// i'm guessing there are a lot of touch edge-cases I'm missing here but...
// this works, and I added it in under ten minutes, and I'm impressed that
// browser tech allowed me to add this in so easily. wow.
if (evt.touches && evt.touches.length > 0) {
this.setState({
...this.state,
paddleX: updatePaddleLocation(evt.touches[0].clientX, this.PADDLE_MIN_X, this.PADDLE_MAX_X)
});
}
};
// the ball-brick collisions aren't very precise but they work for my purposes thus far...
ballAnimate = () => {
if (this.state.ballDirection.x !== 0 || this.state.ballDirection.y !== 0) {
const newState = updateBallLocation(this.state, this.BALL_RADIUS, this.PADDLE_WIDTH, this.PADDLE_HEIGHT, this.BALL_MAX_X, this.BALL_MIN_X, this.BALL_MAX_Y, this.BALL_MIN_Y);
this.setState({
...this.state,
...newState
});
this.gameEnd(this.state.ballYCoord);
this.ballBrickAnimate();
}
this.animationTimeout = setTimeout(this.ballAnimate, 50);
};
// returns one brick, if collision occured; null otherwise
determineBallBrickCollision = (bricks, ballX, ballY) => {
for (let i=0; i < bricks.length; i++) {
const brick = bricks[i];
const brickLeft = brick.x;
const brickRight = brick.x + brick.width;
const brickTop = brick.y + brick.height;
const brickBottom = brick.y;
if (ballX >= brickLeft && ballX <= brickRight && ballY >= brickBottom && ballY <= brickTop) {
// if found, break loop, return early
return brick;
}
}
return null;
};
ballBrickAnimate = () => {
const collidedBrick = this.determineBallBrickCollision(this.state.bricks, this.state.ballXCoord, this.state.ballYCoord);
if (collidedBrick) {
// update ball direction
const ballDirection = {
x: this.state.ballDirection.x,
y: -this.state.ballDirection.y
};
// remove brick from list (note filter creates a copy of the array, so state is not mutated here
const bricks = this.state.bricks.filter( (val) => val.key !== collidedBrick.key);
const bricksBroken = this.state.bricksBroken + 1;
this.setState({
...this.state,
bricks,
ballDirection,
bricksBroken
})
}
};
render() {
const bricks = this.state.bricks.map(b => {
return <Brick
key={b.key}
width={b.width}
height={b.height}
x={b.x}
y={b.y}
color={b.color}
/>
});
return (
<Layer
onMouseMove={(e) => this._onMouseMove(e)}
onTouchMove={(e) => this._onTouchMove(e)}
>
<Field
width={this.FIELD_WIDTH}
height={this.FIELD_HEIGHT}
borderWidth={this.FIELD_BORDER_WIDTH}
/>
<Ball
color={this.BALL_COLOR}
radius={this.BALL_RADIUS}
x={this.state.ballXCoord}
y={this.state.ballYCoord}
/>
<Paddle
color={this.PADDLE_COLOR}
x={this.state.paddleX}
y={this.state.paddleY}
width={this.PADDLE_WIDTH}
height={this.PADDLE_HEIGHT}
/>
<Group>{bricks}</Group>
<Status bricksBroken={this.state.bricksBroken} gameRestarts={this.state.gameRestarts} />
</Layer>
);
}
}
<file_sep>/src/components/gameStatus.js
import React from "react";
import Portal from './portal';
// I acknowledge that the layout and "styling" here
// might cause pain to people who actually know how to
// work on the front-end.
const Status = (props) => {
return (
<Portal>
<table style={{
position: 'absolute',
top: 410,
left: 5,
width: '395px'
}}>
<tr>
<td >game restarts</td>
<td >{props.gameRestarts}</td>
<td >bricks broken</td>
<td >{props.bricksBroken}</td>
</tr>
<tr />
<tr>
<th colSpan='4'><i>about this page</i></th>
</tr>
<tr>
<td colSpan='4'>
As a small, personal challenge, I wanted to build a web app in <a href="https://reactjs.org/" target="_blank" rel="noopener noreferrer"> React</a>. I spend most of my time on back-end work, and what front-end experience I do have is old and mostly not browser-based, so I was starting almost from scratch.
<br/><br/>
The source code, plus some background and technical details, are on <a href="https://github.com/danbrauer/react-breakout" target="_blank" rel="noopener noreferrer">Github</a>.
</td>
</tr>
</table>
</Portal>
);
};
export {
Status
}<file_sep>/src/components/paddle.js
import React from "react";
import { Rect } from "react-konva";
const updatePaddleLocation = (mouseXCoord, paddleMinX, paddleMaxX) => {
let xCoord = mouseXCoord;
if (mouseXCoord > paddleMaxX) {
xCoord = paddleMaxX;
} else if (mouseXCoord < paddleMinX) {
xCoord = paddleMinX
}
return xCoord;
};
const Paddle = (props) => {
return (
<Rect
x={props.x}
y={props.y}
width={props.width}
height={props.height}
fill={props.color}
/>
);
};
export {
Paddle,
updatePaddleLocation
};
<file_sep>/README.md
# Breakout in React
As a small, personal challenge, I wanted to build a web app in [React](https://reactjs.org/).
I spend most of my time on back-end work, and what front-end experience I do have is old and mostly not browser-based, so I was starting almost from scratch.
The end result here is not remotely polished, because I gave myself a limited time for this exercise. But I did learn about React components and their state management, which was the point.
You can play the end result at [thedanielbrauer.com/breakout](https://thedanielbrauer.com/breakout)
### What it looks like

### Potential next steps
If I gave myself more time, I would consider doing the following:
* **Testing**. React is [testable](https://reactjs.org/docs/testing.html), and the only reason I didn't include tests was because I was focused on gaining some rudimentary understanding of components and state management. Testing would, I think, be the most important next step.
* **Converting to Typescript**. I'd initially intended to do this in Typescript, and in prep had converted [React's tic-tac-toe tutorial](https://github.com/danbrauer/react-tic-tac-toe) from JS to TS. The burden of getting React to work with Typescript, however, ended up distracting me from learning React, so I reverted to plain JS. I miss Typescript and would prefer to work in it.
* **Cleaning up the code**. Lots of my methods here take lots of parameters, which is bad style, error-prone, and confusing.
### How this was deployed
This exercise was about trying new things, even if for their own sake, and I'd heard that Heroku makes deploying apps easy, so I did their [getting started](https://devcenter.heroku.com/start) tutorial and then followed the steps [here](https://create-react-app.dev/docs/deployment/#heroku).
(If I had to rely on things I already knew, I could have deployed this from an AWS Lambda fronted by an API Gateway. It would involve wrapping the React app in Express, then using [aws-serverless-express](https://github.com/awslabs/aws-serverless-express).)
### Why this
I hazily remembered building a version of [Breakout](https://en.wikipedia.org/wiki/Breakout_(video_game)) in Java Swing, a long long time ago, and it seemed like a good exercise.
### Starting point
I used [this code](https://codesandbox.io/s/5qvyyyjrx) as reference on how to get draw shapes and get ball bouncing inside a square.
But then I had to rewrite most of it to allow my components to interact.
The ball and square components initially kept their own states, which seems like a React anti-pattern. [I'd read](https://reactjs.org/tutorial/tutorial.html#lifting-state-up) that state should travel only one way, from parent components to children. If two children need to share state (for example to determine whether a ball hits a paddle or a brick) then that should be coordinated by some parent component.
| e4ecf12f226207c7d25e8fd0602fd0e497a18d77 | [
"JavaScript",
"Markdown"
] | 4 | JavaScript | danbrauer/react-breakout | 14c9a240e0a515fc7463011a17434c182e786c05 | 637b1f5fb57cf5fecf00a74cf8eb9695a4e1bff7 |
refs/heads/master | <repo_name>KnickFocks/pipVideo<file_sep>/js/pipVideo.js
// <NAME>
var VideoPiP = function(opt){
var self = this;
self.prefix, self.prefixEnd, self.pip, self.pipm, self.vid, self.vidc, self.pipBtn, self.vidcbg, self.soundBarShell, self.soundShell, self.soundBar, self.progressTimeModal, self.progressShellBg, self.playpauseBtn, self.rewindBtn, self.fastforwardBtn, self.startClientX, self.startClientY, self.mouseDown, self.endClientX, self.endClientY, self.diffX, self.diffY;
self.userInit = false;
self.prevVolume;
self.options = opt;
self.options.pip = false;
self.options.uid = Math.floor(Math.random() * 100000000) + 1;
self.options.modalBorderRadius = 5;
self.options.initialModalPadding = 20;
self.options.initialModalWidth = 300;
self.init = function(){
self.getPrefix();
// create pip shell
pip = document.createElement('div');
pip.id = 'pip' + self.options.uid;
pip.style.width = self.options.width;
pip.style.height = self.options.height;
pip.style.backgroundImage = 'url(img/pip.png)';
pip.style.backgroundSize = '100px 100px';
pip.style.backgroundRepeat = 'no-repeat';
pip.style.backgroundPosition = '50% 50%';
pip.style.backgroundColor = '#000';
pip.style.position = 'absolute';
document.getElementById(self.options.id).appendChild(pip);
// create video modal
pipm = document.createElement('div');
pipm.id = 'pipm' + self.options.uid;
pipm.style.width = '100%';
pipm.style.height = '100%';
pipm.style.position = 'relative';
pip.appendChild(pipm);
// create video element
vid = document.createElement('video');
vid.id = 'vid' + self.options.uid;
vid.src = self.options.videoPath[0];
vid.style.width = '100%';
vid.style.height = '100%';
vid.style.position = 'absolute';
vid.autoplay = self.options.autoplay;
vid.loop = self.options.loop;
vid.volume = 0.65;
self.prevVolume = vid.volume;
pipm.appendChild(vid);
// create controls
vidc = document.createElement('div');
vidc.id = 'vidc' + self.options.uid;
vidc.style.width = '100%';
vidc.style.height = '100%';
vidc.style.position = 'absolute';
vidc.style.cursor = 'pointer';
vidc.style.opacity = 1;
vidc.style.setProperty(self.prefix + 'transition', 'opacity 300ms ease-out');
pipm.appendChild(vidc);
// create video background
vidcbg = document.createElement('div');
vidcbg.id = 'vidcbg' + self.options.uid;
vidcbg.style.width = '100%';
vidcbg.style.height = '100%';
vidcbg.style.position = 'absolute';
vidcbg.style.backgroundColor = 'black';
vidcbg.style.opacity = 0.6;
vidc.appendChild(vidcbg);
// create pip button
pipBtn = document.createElement('div');
pipBtn.id = 'pipbtn' + self.options.uid;
pipBtn.style.width = '50px';
pipBtn.style.height = '50px';
pipBtn.style.top = '0px';
pipBtn.style.right = '0px';
pipBtn.style.position = 'absolute';
pipBtn.style.backgroundImage = 'url(img/pipIconLarge.png)';
pipBtn.style.backgroundSize = 'cover';
pipBtn.style.opacity = 0.9;
pipBtn.style.setProperty(self.prefix + 'transition', 'opacity 300ms ease-out');
vidc.appendChild(pipBtn);
// create play/pause button
playpauseBtn = document.createElement('div');
playpauseBtn.id = 'playpausebtn' + self.options.uid;
playpauseBtn.style.width = '100px';
playpauseBtn.style.height = '100px';
playpauseBtn.style.top = '50%';
playpauseBtn.style.left = '50%';
playpauseBtn.style.marginTop = '-50px';
playpauseBtn.style.marginLeft = '-50px';
playpauseBtn.style.position = 'absolute';
playpauseBtn.style.backgroundImage = 'url(img/play.png)';
playpauseBtn.style.backgroundSize = 'cover';
playpauseBtn.style.opacity = 0.9;
playpauseBtn.style.setProperty(self.prefix + 'transition', 'opacity 300ms ease-out');
vidc.appendChild(playpauseBtn);
// create rewind 15 button
rewindBtn = document.createElement('div');
rewindBtn.id = 'rewindbtn' + self.options.uid;
rewindBtn.style.width = '50px';
rewindBtn.style.height = '50px';
rewindBtn.style.top = '50%';
rewindBtn.style.left = '50%';
rewindBtn.style.marginTop = '-25px';
rewindBtn.style.marginLeft = '-125px';
rewindBtn.style.position = 'absolute';
rewindBtn.style.backgroundImage = 'url(img/rewind.png)';
rewindBtn.style.backgroundSize = 'cover';
rewindBtn.style.opacity = 0.6;
rewindBtn.style.setProperty(self.prefix + 'transition', 'opacity 300ms ease-out');
rewindBtn.style.visibility = 'hidden';
vidc.appendChild(rewindBtn);
// create fastforward 15 button
fastforwardBtn = document.createElement('div');
fastforwardBtn.id = 'fastforwardbtn' + self.options.uid;
fastforwardBtn.style.width = '50px';
fastforwardBtn.style.height = '50px';
fastforwardBtn.style.top = '50%';
fastforwardBtn.style.right = '50%';
fastforwardBtn.style.marginTop = '-25px';
fastforwardBtn.style.marginRight = '-125px';
fastforwardBtn.style.position = 'absolute';
fastforwardBtn.style.backgroundImage = 'url(img/fastforward.png)';
fastforwardBtn.style.backgroundSize = 'cover';
fastforwardBtn.style.opacity = 0.6;
fastforwardBtn.style.setProperty(self.prefix + 'transition', 'opacity 300ms ease-out');
fastforwardBtn.style.visibility = 'hidden';
vidc.appendChild(fastforwardBtn);
// create progressShell
progressShell = document.createElement('div');
progressShell.id = 'progShell' + self.options.uid;
progressShell.style.position = 'absolute';
progressShell.style.visibility = 'hidden';
vidc.appendChild(progressShell);
// create progressShell Background
progressShellBg = document.createElement('div');
progressShellBg.id = 'progShellBg' + self.options.uid;
progressShellBg.style.width = '100%';
progressShellBg.style.height = '5px';
progressShellBg.style.top = '50%';
progressShellBg.style.marginTop = '-3px';
progressShellBg.style.left = '0px';
progressShellBg.style.position = 'absolute';
progressShellBg.style.backgroundColor = '#fff';
progressShellBg.style.opacity = 0.2;
progressShell.appendChild(progressShellBg);
// create progress bar
progressBar = document.createElement('div');
progressBar.id = 'progBar' + self.options.uid;
progressBar.style.width = '0px';
progressBar.style.height = '5px';
progressBar.style.top = '50%';
progressBar.style.marginTop = '-3px';
progressBar.style.left = '0px';
progressBar.style.position = 'absolute';
progressBar.style.backgroundColor = 'white';
progressShell.appendChild(progressBar);
// create progress time modal
progressTimeModal = document.createElement('div');
progressTimeModal.id = 'progTimeModal' + self.options.uid;
progressTimeModal.style.width = 'auto';
progressTimeModal.style.height = '14px';
progressTimeModal.style.bottom = '40px';
progressTimeModal.style.padding = '5px';
progressTimeModal.style.left = '0px';
progressTimeModal.style.position = 'absolute';
progressTimeModal.style.border = 'solid 2px white';
progressTimeModal.style.borderRadius = '3px';
progressTimeModal.style.backgroundColor = 'white';
progressTimeModal.style.fontFamily = 'Antenna, Arial, Helvetica, sans-serif';
progressTimeModal.style.fontSize = '14px';
progressTimeModal.style.lineHeight = '14px';
progressTimeModal.style.textAlign = 'center';
progressTimeModal.style.color = 'black';
progressTimeModal.style.pointerEvents = 'none';
progressTimeModal.style.opacity = 0;
progressTimeModal.style.setProperty(self.prefix + 'transition', 'opacity 300ms ease-out');
progressShell.appendChild(progressTimeModal);
// create progress time modal
progressArrow = document.createElement('div');
progressArrow.id = 'progArrow' + self.options.uid;
progressArrow.style.width = '0';
progressArrow.style.height = '0';
progressArrow.style.bottom = '32px';
progressArrow.style.position = 'absolute';
progressArrow.style.borderLeft = '8px solid transparent';
progressArrow.style.borderRight = '8px solid transparent';
progressArrow.style.borderTop = '8px solid white';
progressArrow.style.pointerEvents = 'none';
progressArrow.style.opacity = 0;
progressArrow.style.setProperty(self.prefix + 'transition', 'opacity 300ms ease-out');
progressShell.appendChild(progressArrow);
controls = document.createElement('div');
controls.id = 'controls' + self.options.uid;
controls.style.width = '90%';
controls.style.height = '20px';
controls.style.bottom = '20px';
controls.style.left = '5%';
controls.style.position = 'absolute';
controls.style.visibility = 'hidden';
vidc.appendChild(controls);
soundShell = document.createElement('div');
soundShell.id = 'soundShell' + self.options.uid;
soundShell.style.width = '20px';
soundShell.style.height = '20px';
soundShell.style.overflow = 'hidden';
soundShell.style.marginRight = '10px';
soundShell.style.position = 'relative';
soundShell.style.float = 'left';
soundShell.style.opacity = 0.6;
soundShell.style.setProperty(self.prefix + 'transition', 'opacity 300ms ease-out, width 300ms ease-out');
controls.appendChild(soundShell);
soundBtn = document.createElement('div');
soundBtn.id = 'soundBtn' + self.options.uid;
soundBtn.style.width = '20px';
soundBtn.style.height = '20px';
soundBtn.style.position = 'absolute';
soundBtn.style.backgroundImage = 'url(img/unmuted.png)';
soundBtn.style.backgroundSize = 'cover';
soundBtn.style.setProperty(self.prefix + 'transition', 'opacity 300ms ease-out');
soundShell.appendChild(soundBtn);
soundBarShell = document.createElement('div');
soundBarShell.id = 'soundBarShell' + self.options.uid;
soundBarShell.style.top = '50%';
soundBarShell.style.left = '30px';
soundBarShell.style.marginTop = '-2px';
soundBarShell.style.width = '65px';
soundBarShell.style.height = '5px';
soundBarShell.style.position = 'absolute';
soundShell.appendChild(soundBarShell);
soundBarBg = document.createElement('div');
soundBarBg.id = 'soundBarBg' + self.options.uid;
soundBarBg.style.top = '0px';
soundBarBg.style.left = '0px';
soundBarBg.style.width = '100%';
soundBarBg.style.height = '100%';
soundBarBg.style.position = 'absolute';
soundBarBg.style.backgroundColor = 'white';
soundBarBg.style.opacity = 0.2;
soundBarShell.appendChild(soundBarBg);
soundBar = document.createElement('div');
soundBar.id = 'soundBar' + self.options.uid;
soundBar.style.top = '0px';
soundBar.style.left = '0px';
soundBar.style.width = '50px';
soundBar.style.height = '100%';
soundBar.style.position = 'absolute';
soundBar.style.backgroundColor = 'white';
soundBar.style.opacity = 0.6;
soundBarShell.appendChild(soundBar);
soundBarDrag = document.createElement('div');
soundBarDrag.id = 'soundBarDrag' + self.options.uid;
soundBarDrag.style.top = '50%';
soundBarDrag.style.left = '0px';
soundBarDrag.style.marginTop = '-6px';
soundBarDrag.style.marginLeft = '-6px';
soundBarDrag.style.width = '12px';
soundBarDrag.style.height = '12px';
soundBarDrag.style.borderRadius = '50px';
soundBarDrag.style.position = 'absolute';
soundBarDrag.style.backgroundColor = 'white';
soundBarDrag.style.setProperty(self.prefix + 'transition', self.prefix + 'transform 300ms ease-out');
soundBarShell.appendChild(soundBarDrag);
self.setVolume();
counter = document.createElement('div');
counter.id = 'progCounter' + self.options.uid;
counter.style.width = 'auto';
counter.style.height = 'auto';
counter.style.position = 'relative';
counter.style.float = 'left';
counter.style.pointerEvents = 'none';
counter.style.fontFamily = 'Antenna, Arial, Helvetica, sans-serif';
controls.appendChild(counter);
pipSmallBtn = document.createElement('div');
pipSmallBtn.id = 'pips' + self.options.uid;
pipSmallBtn.style.width = '20px';
pipSmallBtn.style.height = '20px';
pipSmallBtn.style.position = 'relative';
pipSmallBtn.style.float = 'right';
pipSmallBtn.style.opacity = 0.6;
pipSmallBtn.style.backgroundImage = 'url(img/pipIcon.png)';
pipSmallBtn.style.backgroundSize = 'cover';
pipSmallBtn.style.setProperty(self.prefix + 'transition', 'opacity 300ms ease-out');
controls.appendChild(pipSmallBtn);
fullscreenBtn = document.createElement('div');
fullscreenBtn.id = 'fullscreenBtn' + self.options.uid;
fullscreenBtn.style.width = '20px';
fullscreenBtn.style.height = '20px';
fullscreenBtn.style.position = 'relative';
fullscreenBtn.style.float = 'right';
fullscreenBtn.style.opacity = 0.6;
fullscreenBtn.style.backgroundColor = 'blue';
fullscreenBtn.style.setProperty(self.prefix + 'transition', 'opacity 300ms ease-out');
controls.appendChild(fullscreenBtn);
fullscreenBtn.style.display = 'none';
var work = document.createElement('style');
work.innerHTML = '#pipm' + self.options.uid + ':-webkit-full-screen { width: 100%; height: 100%; position:relative;}';
document.getElementsByTagName('body')[0].appendChild(work);
self.updateVideoSize();
if(!self.isFullscreenEndabled()){
fullscreenBtn.style.display = 'none';
}
self.options.aspectRatio = self.getAspectRatio();
if(!self.isTouchDevice()){
vidc.addEventListener('mouseenter', self.vidcEnterBtnEvent);
vidc.addEventListener('mouseleave', self.vidcLeaveBtnEvent);
pipBtn.addEventListener('mouseenter', self.vidcontrolsEnterEvent);
pipBtn.addEventListener('mouseleave', self.vidcontrolsLeaveEvent);
playpauseBtn.addEventListener('mouseenter', self.vidcontrolsEnterEvent);
playpauseBtn.addEventListener('mouseleave', self.vidcontrolsLeaveEvent);
rewindBtn.addEventListener('mouseenter', self.vidcontrolsEnterEvent);
rewindBtn.addEventListener('mouseleave', self.vidcontrolsLeaveEvent);
fastforwardBtn.addEventListener('mouseenter', self.vidcontrolsEnterEvent);
fastforwardBtn.addEventListener('mouseleave', self.vidcontrolsLeaveEvent);
progressShell.addEventListener('mouseenter', self.vidcontrolsEnterEvent);
progressShell.addEventListener('mouseleave', self.vidcontrolsLeaveEvent);
soundShell.addEventListener('mouseenter', self.vidcontrolsEnterEvent);
soundShell.addEventListener('mouseleave', self.vidcontrolsLeaveEvent);
pipSmallBtn.addEventListener('mouseenter', self.vidcontrolsEnterEvent);
pipSmallBtn.addEventListener('mouseleave', self.vidcontrolsLeaveEvent);
fullscreenBtn.addEventListener('mouseenter', self.vidcontrolsEnterEvent);
fullscreenBtn.addEventListener('mouseleave', self.vidcontrolsLeaveEvent);
soundBarDrag.addEventListener('mouseenter', self.vidcontrolsEnterEvent);
soundBarDrag.addEventListener('mouseleave', self.vidcontrolsLeaveEvent);
soundBarDrag.addEventListener('mousedown',self.handleMouseDownVolume);
window.addEventListener('mousemove', self.handleMouseMoveVolume);
soundBarDrag.addEventListener('mouseup', self.handleMouseUpVolume);
window.addEventListener('mouseup', self.handleMouseUpVolume);
}else{
vidc.addEventListener('touchend', self.vidcTouchBtnEvent);
soundBarDrag.addEventListener('touchstart',self.handleMouseDownVolume);
window.addEventListener('touchmove', self.handleMouseMoveVolume);
soundBarDrag.addEventListener('touchend', self.handleMouseUpVolume);
}
playpauseBtn.addEventListener(self.options.event, self.playpauseBtnEvent);
pipBtn.addEventListener(self.options.event, self.pipBtnEvent);
pipSmallBtn.addEventListener(self.options.event, self.pipBtnEvent);
fullscreenBtn.addEventListener(self.options.event, self.fullscreenBtnEvent);
rewindBtn.addEventListener(self.options.event, self.rewindBtnEvent);
fastforwardBtn.addEventListener(self.options.event, self.fastforwardBtnEvent);
progressShell.addEventListener(self.options.event, self.seekBtnEvent);
soundBar.addEventListener(self.options.event, self.soundBarEvent);
soundBarBg.addEventListener(self.options.event, self.soundBarEvent);
soundBtn.addEventListener(self.options.event, self.soundBtnEvent);
vid.addEventListener('play', self.vidPlay);
vid.addEventListener('pause', self.vidPause);
vid.addEventListener('timeupdate', self.vidTimeUpdate);
vid.addEventListener('volumechange', self.vidVolumeChange);
vid.addEventListener('seeked', self.vidSeeked);
vid.addEventListener('ended', self.vidEnded);
vid.addEventListener('error', self.vidError);
console.log(self.options);
}
self.remove = function(){
document.getElementById(self.options.vId).remove();
}
self.updateVideoSize = function(){
progressShell.style.width = '90%';
progressShell.style.height = '50px';
progressShell.style.bottom = '20px';
progressShell.style.left = '5%';
controls.style.bottom = '20px';
progressTimeModal.style.visibility = 'visible';
progressArrow.style.visibility = 'visible';
counter.style.fontSize = '18px';
counter.style.lineHeight = '24px';
}
self.updateModalVideoSize = function(){
progressShell.style.width = '100%';
progressShell.style.height = '5px';
progressShell.style.left = '0%';
progressShell.style.bottom = '0px';
controls.style.bottom = '10px';
progressTimeModal.style.visibility = 'hidden';
progressArrow.style.visibility = 'hidden';
counter.style.fontSize = '14px';
counter.style.lineHeight = '24px';
}
self.setVolume = function(){
if(!self.userInit){
var per = vid.volume;
soundBarDrag.style.left = soundBarShell.offsetWidth * per + 'px';
soundBar.style.width = soundBarShell.offsetWidth * per + 'px';
}
console.log(vid.volume);
}
self.getAspectRatio = function(){
return vid.offsetWidth / (vid.offsetWidth - vid.offsetHeight) + ':' + vid.offsetHeight / (vid.offsetWidth - vid.offsetHeight);
}
self.vidPlay = function(){
console.log('VIDEO PLAY')
self.options.videoPlaying = true;
rewindBtn.style.visibility = 'visible';
fastforwardBtn.style.visibility = 'visible';
}
self.isFullscreenEndabled = function(){
if(document.fullscreenEnabled || document.webkitFullscreenEnabled || document.mozFullScreenEnabled || document.msFullscreenEnabled){
return true
}else{
return false
}
}
self.vidPause = function(){
console.log('VIDEO PAUSE')
self.options.videoPlaying = false;
}
self.vidTimeUpdate = function(){
console.log('VIDEO TIME UPDATE')
self.options.videoCurrentTime = vid.currentTime;
self.options.videoPercentComplate = vid.currentTime / vid.duration * 100;
progressBar.style.width = self.options.videoPercentComplate + '%';
self.updateCounterTimer();
}
self.vidVolumeChange = function(){
console.log('VIDEO VOLUME CHANGE')
self.options.videoVolume = vid.volume;
}
self.vidEnded = function(){
console.log('VIDEO ENDED')
playpauseBtn.style.backgroundImage = 'url(img/restart.png)';
rewindBtn.style.visibility = 'hidden';
fastforwardBtn.style.visibility = 'hidden';
}
self.vidSeeked = function(){
console.log('VIDEO SEEKED')
}
self.vidError = function(){
console.log('VIDEO ERROR')
}
self.playpauseBtnEvent = function(){
if(!self.userInit){
self.userInit = true;
pipBtn.style.display = 'none';
rewindBtn.style.visibility = 'visible';
fastforwardBtn.style.visibility = 'visible';
progressShell.style.visibility = 'visible';
controls.style.visibility = 'visible';
}
if(self.options.videoPlaying){
vid.pause();
playpauseBtn.style.backgroundImage = 'url(img/play.png)';
}else{
vid.play();
playpauseBtn.style.backgroundImage = 'url(img/pause.png)';
}
}
self.seekBtnEvent = function(event){
vid.currentTime = event.offsetX / progressShell.offsetWidth * vid.duration;
}
self.rewindBtnEvent = function(){
vid.currentTime = vid.currentTime < 15 ? 0 : vid.currentTime - 15;
}
self.fastforwardBtnEvent = function(){
vid.currentTime = vid.currentTime + 15 >= vid.duration ? vid.duration - 0.1 : vid.currentTime + 15;
}
self.fullscreenBtnEvent = function(){
var element = pipm;
if(element.requestFullscreen) {
element.requestFullscreen();
} else if(element.mozRequestFullScreen) {
element.mozRequestFullScreen();
} else if(element.webkitRequestFullscreen) {
element.webkitRequestFullscreen();
} else if(element.msRequestFullscreen) {
element.msRequestFullscreen();
}
}
self.pipBtnEvent = function(){
if(self.options.pip){
window.removeEventListener('resize', self.resize);
self.updateVideoSize()
self.removeModalEvents();
self.options.pip = false;
pipm.style.position = 'absolute';
pipm.style.width = '100%';
pipm.style.height = '100%';
pipm.style.left = '0px';
pipm.style.top = '0px';
pipm.style.boxShadow = '';
}else{
window.addEventListener('resize', self.resize);
self.updateModalVideoSize();
self.options.pip = true;
pipm.style.position = 'fixed';
pipm.style.width = pip.offsetWidth + 'px';
pipm.style.height = pip.offsetHeight + 'px';
pipm.style.left = self.offsetX(pip) - window.pageXOffset + 'px';
pipm.style.top = self.offsetY(pip) - window.pageYOffset + 'px';
window.setTimeout(function(){
pipm.style.setProperty(self.prefix + 'transition', 'all 300ms ease-out');
pipm.addEventListener(self.prefixEnd, self.transitionEnd);
pipm.style.top = window.innerHeight - (self.aspectRatio(self.options.aspectRatio) + self.options.initialModalPadding) + 'px';
pipm.style.left = window.innerWidth - (self.options.initialModalWidth + self.options.initialModalPadding) + 'px';
pipm.style.width = self.options.initialModalWidth + 'px';
pipm.style.boxShadow = '0px 0px 5px 0px rgba(0,0,0,0.65)';
pipm.style.height = self.aspectRatio(self.options.aspectRatio) + 'px';
pipm.style.borderRadius = self.options.modalBorderRadius + 'px';
pipm.style.overflow = 'hidden';
},10);
self.addModalEvents();
}
}
self.vidcTouchBtnEvent = function(){
// if(vidc.style.opacity == 0){
// vidc.style.opacity = 1;
// }else{
// vidc.style.opacity = 0;
// }
}
self.vidcEnterBtnEvent = function(){
vidc.style.opacity = 1;
}
self.vidcLeaveBtnEvent = function(){
if(self.userInit){
vidc.style.opacity = 0;
}
}
self.vidcontrolsEnterEvent = function(event){
if(self.userInit){
document.getElementById(event.target.id).style.opacity = 0.9;
}
if(event.target.id == progressShell.id){
progressTimeModal.style.opacity = 0.9;
progressArrow.style.opacity = 0.9;
progressShell.addEventListener('mousemove', self.videoTimeStampDisplay);
}
if(event.target.id == soundShell.id && !self.options.pip){
soundShell.style.width = '103px';
}
if(event.target.id == soundBarDrag.id){
soundBarDrag.style.webkitTransform = 'scale(1.2)';
soundBarDrag.style.opacity = 1;
}
}
self.vidcontrolsLeaveEvent = function(event){
if(self.userInit){
document.getElementById(event.target.id).style.opacity = 0.6;
}
if(event.target.id == progressShell.id){
progressTimeModal.style.opacity = 0;
progressArrow.style.opacity = 0;
progressShell.removeEventListener('mousemove', self.videoTimeStampDisplay);
}
if(event.target.id == soundShell.id){
soundShell.style.width = '20px';
}
if(event.target.id == soundBarDrag.id){
soundBarDrag.style.webkitTransform = 'scale(1)';
soundBarDrag.style.opacity = 1;
}
}
self.videoTimeStampDisplay = function(event){
var sec = event.offsetX / progressShell.offsetWidth * vid.duration;
progressTimeModal.innerHTML = self.getSecondsConversion(sec);
progressArrow.style.left = event.offsetX - (progressArrow.offsetWidth / 2) + 'px';
var borderLeftWidth = parseInt(progressArrow.style.borderLeftWidth.split('px')[0]) / 2;
var offset = event.offsetX - (progressTimeModal.offsetWidth / 2) < -progressShell.offsetLeft / 2 - borderLeftWidth ? -progressShell.offsetLeft / 2 - borderLeftWidth : event.offsetX + (progressTimeModal.offsetWidth / 2) > progressShell.offsetWidth + progressShell.offsetLeft / 2 + borderLeftWidth ? progressShell.offsetWidth - progressTimeModal.offsetWidth + progressShell.offsetLeft / 2 + borderLeftWidth : event.offsetX - (progressTimeModal.offsetWidth / 2);
progressTimeModal.style.left = offset + 'px';
}
self.updateCounterTimer = function(){
counter.innerHTML = '<span style="color:white;">' + self.getSecondsConversion(vid.currentTime) + '</span><span style="color:white; opacity:0.6;"> / ' + self.getSecondsConversion(vid.duration) + '</span>';
}
self.getSecondsConversion = function(sec){
var h = Math.floor(sec / 3600);
var m = Math.floor(sec % 3600 / 60);
var s = Math.floor(sec % 3600 % 60);
return ((h > 0 ? h + ":" + (m < 10 ? "0" : "") : "") + m + ":" + (s < 10 ? "0" : "") + s);
}
self.transitionEnd = function(){
pipm.removeEventListener(self.prefixEnd, self.transitionEnd);
pipm.style.setProperty(self.prefix + 'transition', '');
}
self.resize = function(){
pipm.style.top = window.innerHeight - (self.aspectRatio(self.options.aspectRatio) + self.options.initialModalPadding) + 'px';
pipm.style.left = window.innerWidth - (self.options.initialModalWidth + self.options.initialModalPadding) + 'px';
}
self.addModalEvents = function(){
if(self.isTouchDevice()){
vidc.addEventListener('touchstart',self.handleMouseDown);
window.addEventListener('touchmove', self.handleMouseMove);
vidc.addEventListener('touchend', self.handleMouseUp);
}else{
vidc.addEventListener('mousedown',self.handleMouseDown);
window.addEventListener('mousemove', self.handleMouseMove);
vidc.addEventListener('mouseup', self.handleMouseUp);
}
}
self.removeModalEvents = function(){
if(self.isTouchDevice()){
vidc.removeEventListener('touchstart',self.handleMouseDown);
window.removeEventListener('touchmove', self.handleMouseMove);
vidc.removeEventListener('touchend', self.handleMouseUp);
}else{
vidc.removeEventListener('mousedown',self.handleMouseDown);
window.removeEventListener('mousemove', self.handleMouseMove);
vidc.removeEventListener('mouseup', self.handleMouseUp);
}
}
self.handleMouseDown = function(event){
event.preventDefault();
self.mouseDown = true;
self.startClientX = event.clientX || event.touches[0].screenX;
self.startClientY = event.clientY || event.touches[0].screenY;
var offsetX = pipm.offsetLeft;
var offsetY = pipm.offsetTop;
self.diffX = self.startClientX - offsetX;
self.diffY = self.startClientY - offsetY;
pipm.style.left = self.startClientX - self.diffX + 'px';
pipm.style.top = self.startClientY - self.diffY + 'px';
}
self.handleMouseMove = function(event){
if(self.mouseDown){
event.preventDefault();
self.endClientX = event.clientX || event.touches[0].screenX;
self.endClientY = event.clientY || event.touches[0].screenY;
pipm.style.left = self.endClientX - self.diffX + 'px';
pipm.style.top = self.endClientY - self.diffY + 'px';
pipm.setAttribute();
}
}
self.handleMouseUp = function(event){
self.mouseDown = false;
self.endClientX = event.clientX || self.endClientX;
self.endClientY = event.clientY || self.endClientY;
// console.log(event.target.id)
// if(self.startClientY == self.endClientY && self.startClientX == self.endClientX && event.target.id == 'vidcbg' + self.options.uid){
// if(vidc.style.opacity == 1){
// self.vidcLeaveBtnEvent();
// }else{
// self.vidcEnterBtnEvent();
// }
// }
}
self.handleMouseDownVolume = function(event){
event.preventDefault();
self.mouseDown = true;
self.startClientX = event.clientX || event.touches[0].screenX;
}
self.handleMouseMoveVolume = function(event){
if(self.mouseDown){
vid.muted = false;
event.preventDefault();
self.endClientX = event.clientX || event.touches[0].screenX;
var dif = (self.endClientX - self.offsetX(soundBarShell)) / soundBarShell.offsetWidth;
dif = dif > 1 ? 1 : dif < 0 ? 0 : dif;
self.updateVolume(dif);
}
}
self.handleMouseUpVolume = function(event){
self.mouseDown = false;
self.endClientX = event.offsetX || self.offsetX;
}
self.updateVolume = function(dif){
soundBarDrag.style.left = dif * 100 + '%';
soundBar.style.width = dif * 100 + '%';
if(dif == 0){
soundBtn.style.backgroundImage = 'url(img/muted.png)';
}else{
soundBtn.style.backgroundImage = 'url(img/unmuted.png)';
}
vid.volume = dif;
}
self.soundBarEvent = function(event){
var dif = event.offsetX / soundBarShell.offsetWidth;
self.updateVolume(dif);
}
self.soundBtnEvent = function(){
if(vid.muted){
vid.muted = false;
if(self.options.pip){
vid.volume = 1;
self.prevVolume = vid.volume;
self.updateVolume(1);
}else{
vid.volume = self.prevVolume;
self.updateVolume(self.prevVolume);
}
}else{
vid.muted = true;
self.prevVolume = vid.volume;
self.updateVolume(0);
}
}
self.aspectRatio = function(ratio){
var w1 = ratio.split(':')[0];
var h1 = ratio.split(':')[1];
return h1 / w1 * self.options.initialModalWidth
}
self.getPrefix = function(){
if(/mozilla/.test(navigator.userAgent.toLowerCase()) && !/webkit/.test(navigator.userAgent.toLowerCase())){
self.prefix = '-moz-';
self.prefixEnd = 'transitionend';
}else if(/webkit/.test(navigator.userAgent.toLowerCase())){
self.prefix = '-webkit-';
self.prefixEnd = 'webkitTransitionEnd';
}else if(/msie/.test(navigator.userAgent.toLowerCase())){
self.prefix = '-ms-';
self.prefixEnd = 'MSTransitionEnd';
}else if(/opera/.test(navigator.userAgent.toLowerCase())){
self.prefix = '-o-';
self.prefixEnd = 'oTransitionEnd';
}else{
self.prefix = '';
self.prefixEnd = '';
}
}
self.offsetX = function(e){
var x = 0,
n = e;
while (n.offsetParent) {
x += n.offsetLeft;
n = n.offsetParent;
}
return x;
}
self.offsetY = function(e){
var y = 0,
n = e;
while (n.offsetParent) {
y += n.offsetTop;
n = n.offsetParent;
}
return y;
}
self.isTouchDevice = function(){
try{
document.createEvent('TouchEvent');
self.options.event = 'touchend';
return true;
}catch(e){
self.options.event = 'click';
return false;
}
}
}
<file_sep>/readme.md
# PipVideo
'PipVideo' allows you to easily create a video with a picture in picture option.
<file_sep>/js/script.js
// <NAME>
var videopip;
var options = {
id:'videoContainer',
width:'640px',
height:'360px',
poster:'',
videoPath:[
'video/toyStory3.mp4',
'',
'',
],
autoplay:false,
loop: false
}
window.addEventListener("load", function(event) {
videopip = new VideoPiP(options);
videopip.init();
})
| 284bead485127508553674eb5ad0248198324a38 | [
"JavaScript",
"Markdown"
] | 3 | JavaScript | KnickFocks/pipVideo | 13ae6ce980381b180f1c894113b1d9f8f3e7ac79 | 526c02480f965f632519d271c2604f959e8165d8 |
refs/heads/master | <file_sep>#ifndef CREATCACHE_H
#define CREATCACHE_H
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define byteOffset 2
typedef struct cacheInfo_t{
unsigned int lineSize; /* block size */
unsigned int associat; /* cache assocativity */
unsigned int dataSize; /* total cache size */
unsigned int replacePolicy; /* replacement policy */
unsigned int missPenalty; /* miss penalty */
unsigned int writeAlloc; /* write allocate */
unsigned int writeBack; /* 1 = wirte back, 0 = write through */
}cacheInfo_t;
typedef struct cache_t{
unsigned int lruBit;
unsigned int valid; /* valid bit */
unsigned int dirty; /* dirty bit */
unsigned int tag;
}cache_t;
extern cacheInfo_t cacheInfo;
extern cache_t *cacheD;
extern cache_t **cacheN;
extern unsigned int numOfBlock;
extern unsigned int blockOffset;
void initCache(char*);
unsigned int _log2(unsigned int);
#endif
<file_sep>#include "creatCache.h"
#include "traceInput.h"
int main(int argc, char **argv)
{
if (argc != 3){
printf("Please input 2 arguments\n");
printf("========================\n");
printf(" First : Config file \n");
printf(" Second: Trace file \n");
printf("========================\n");
return 0;
}
char *confPath = argv[1];
char *tracePath = argv[2];
initCache(confPath);
traceInput(tracePath);
return 0;
}
<file_sep>#ifndef TRACEINPUT_H
#define TRACEINPUT_H
typedef struct trace_t{
char accessType; /* l = load, s = store */
unsigned int address; /* 32 bit address */
}trace_t;
void traceInput(char*);
unsigned int _strHexToIntDec(unsigned char*);
unsigned int _hexToDec(unsigned char);
#endif
<file_sep>This is a cache simulator
<file_sep>#include "traceInput.h"
#include "creatCache.h"
void traceInput(char *tracePath)
{
FILE *tracefp;
struct trace_t trace;
char buf[16];
int i;
char addrBuf[9];
tracefp = fopen(tracePath, "r");
memset(buf, 0, sizeof(buf));
while (fgets(buf, sizeof(buf), tracefp) != NULL){
trace.accessType = buf[0];
for (i = 4; i < 12; i++){
addrBuf[i - 4] = buf[i];
}
addrBuf[9] = '\0';
trace.address = _strHexToIntDec(addrBuf);
}
fclose(tracefp);
}
unsigned int _strHexToIntDec(unsigned char *hex)
{
unsigned int total = 0;
unsigned int dec;
int i;
int j = 7; /* MSB to LSB weight */
for (i = 0; i < 8; i++){
dec = _hexToDec(hex[i]);
dec = (dec << (j * 4));
total += dec;
j--;
}
return total;
}
unsigned int _hexToDec(unsigned char hex)
{
switch (hex){
case '1':
return 1;
case '2':
return 2;
case '3':
return 3;
case '4':
return 4;
case '5':
return 5;
case '6':
return 6;
case '7':
return 7;
case '8':
return 8;
case '9':
return 9;
case 'a':
return 10;
case 'b':
return 11;
case 'c':
return 12;
case 'd':
return 13;
case 'e':
return 14;
case 'f':
return 15;
default:
printf("traceInput _hexToDec: hex error\n");
exit(1);
}
}
<file_sep>#include "creatCache.h"
struct cacheInfo_t cacheInfo;
struct cache_t *cacheD = NULL;
struct cache_t **cacheN = NULL;
unsigned int numOfBlock;
unsigned int blockOffset;
void initCache(char *configPath)
{
FILE *configFp;
int i = 0;
unsigned int configVal[7];
char buf[8];
configFp = fopen(configPath, "r");
memset(buf, 0, sizeof(buf));
while (fgets(buf, sizeof(buf), configFp) != NULL){
configVal[i] = atoi(buf);
memset(buf, 0, sizeof(buf));
i++;
}
cacheInfo.lineSize = configVal[0];
cacheInfo.associat = configVal[1];
cacheInfo.dataSize = configVal[2];
cacheInfo.replacePolicy = configVal[3];
cacheInfo.missPenalty = configVal[4];
cacheInfo.writeAlloc = configVal[5];
cacheInfo.writeBack = configVal[6];
numOfBlock = cacheInfo.dataSize / cacheInfo.lineSize;
blockOffset = _log2(numOfBlock);
if (cacheInfo.associat < 2){
cacheD = (cache_t*)malloc(sizeof(cache_t) * numOfBlock);
memset(cacheD, 0, sizeof(cache_t) * numOfBlock);
}else{
cacheN = (cache_t**)malloc(sizeof(cache_t*) * numOfBlock);
for (i = 0; i < numOfBlock; i++)
cacheN[i] = (cache_t*)malloc(sizeof(cache_t) * cacheInfo.associat);
memset(cacheN, 0, sizeof(cache_t) * cacheInfo.associat * numOfBlock);
}
fclose(configFp);
}
unsigned int _log2(unsigned int numBlock)
{
unsigned int bit = 0;
while ((numBlock >> 1) != 0){
bit++;
}
return bit;
}
| 78fd90782f24a4faf58ad7ecb504578e6cf8948a | [
"Markdown",
"C"
] | 6 | C | s9001055/cacheSim | df9efba5565cb8f29e6170005f0e89cda90a12ca | dda9f01c9ef57849b96841393389fb8d09d83f6c |
refs/heads/master | <file_sep>import easygui
import numpy as np
from PIL import Image
from tensorflow import keras
from keras import layers
from keras.models import model_from_json, Sequential
from keras.optimizers import SGD, RMSprop, Adam, Adagrad, Adadelta
from keras.utils.np_utils import to_categorical
import matplotlib.pylab as plt
import cv2
import numpy as np
import sklearn
import os
from sklearn import model_selection
from sklearn.model_selection import train_test_split, KFold, cross_val_score, StratifiedKFold, learning_curve, GridSearchCV
from sklearn.metrics import confusion_matrix, make_scorer, accuracy_score
from sklearn.linear_model import LogisticRegression
from sklearn.tree import DecisionTreeClassifier
from sklearn.neighbors import KNeighborsClassifier
from sklearn.discriminant_analysis import LinearDiscriminantAnalysis
from sklearn.naive_bayes import GaussianNB
from sklearn.svm import SVC, LinearSVC
from sklearn.ensemble import RandomForestClassifier, GradientBoostingClassifier
import keras
from keras import backend as K
from keras.callbacks import Callback, EarlyStopping, ReduceLROnPlateau, ModelCheckpoint
from keras.preprocessing.image import ImageDataGenerator
from keras.utils.np_utils import to_categorical
from keras.models import Sequential, model_from_json, load_model
from keras.optimizers import SGD, RMSprop, Adam, Adagrad, Adadelta
from keras.layers import Dense, Dropout, Activation, Flatten, BatchNormalization, Conv2D, MaxPool2D, MaxPooling2D
path = "/home/stefy/cpp/ProiectIP/"
thresholds = [0.5,0.8]
MAX_SUM = 1800000
def split_image_aky(img, size = (50,50)):
maxX, maxY = img.width, img.height
cols = (maxX+size[0]-1)//size[0]
rows = (maxY+size[1]-1)//size[1]
patches = [[0 for x in range(rows)] for y in range(cols)]
new_im = Image.new('RGB',(cols*size[0],rows*size[1]),color=(255,255,255))
new_im.paste(img)
print(len(patches),len(patches[0]))
patches_list = []
for x in range(1,maxX,50):
for y in range(1,maxY,50):
patch = new_im.crop((x,y,x+50,y+50))
patches_list.append(patch)
return patches_list
def split_image(img, size = (50,50)):
maxX, maxY = img.width, img.height
cols = (maxX+size[0]-1)//size[0]
rows = (maxY+size[1]-1)//size[1]
patches = [[0 for x in range(rows)] for y in range(cols)]
new_im = Image.new('RGB',(cols*size[0],rows*size[1]),color=(255,255,255))
new_im.paste(img)
#print(len(patches),len(patches[0]))
for x in range(1,maxX,50):
for y in range(1,maxY,50):
patch = new_im.crop((x,y,x+50,y+50))
patches[x//50][y//50] = patch
return patches
def split_file(filename,size = (50,50)):
img = Image.open(filename)
return split_image(img)
def getPatches(image_patches):
x = len(image_patches)
y = len(image_patches[0])
print(x,y)
print()
patches = []
index = 0
path = "/home/stefy/cpp/ProiectIP/webserver/temporary/"
for patch_list in image_patches:
for patch in patch_list:
new_image = Image.new('RGB', (50, 50), color=(255,255,255))
new_image.paste(patch)
temporary_file_path = path + "temporary" + str(index) + ".jpg"
new_image.save(temporary_file_path)
patches.append(cv2.imread(temporary_file_path))
os.remove(temporary_file_path)
index += 1
return patches, x, y
def analize_patches(patches,x,y, model):
y_pred = model.predict(patches/255.0)
y = np.reshape(y_pred,(x,y,2))
return y[:,:,1]
def get_model(name):
with open(path + "models/" + name + "/" + name + ".json", "r") as json_file:
_model = model_from_json(json_file.read())
_model.load_weights(path + "models/" + name + "/" + name + ".h5")
_model.compile(loss=keras.losses.categorical_crossentropy,
optimizer=keras.optimizers.Adadelta(),
metrics=['accuracy'])
return _model
def merge_images(img1,img2,x=0.5):
arr1 = np.array(img1)
arr2 = np.array(img2)
arr = arr1//4*3 + arr2//4
img = Image.fromarray(arr,'RGB')
return img
def generate_image(image_patches,grid,path = 'result.png'):
x,y = grid.shape
img = Image.new('RGB',(x*50,y*50),color=(255,255,255))
for i in range(x):
for j in range(y):
if grid[i][j] > thresholds[1]:
img.paste(merge_images(
image_patches[i][j],
Image.new('RGB',(50,50),color=(200,0,0))
)
,(i*50+1,j*50+1))
elif grid[i][j] < thresholds[0]:
img.paste(merge_images(image_patches[i][j],Image.new('RGB',(50,50),color=(0,200,0))),(i*50+1,j*50+1))
else:
img.paste(merge_images(image_patches[i][j],Image.new('RGB',(50,50),color=(200,200,0))),(i*50+1,j*50+1))
img.save(path)
def count_blanks(patches):
count = 0
sums = []
for patch in patches:
sum = patch.sum()
if sum > MAX_SUM: count += 1
return count
def count_poz(grid):
x,y = grid.shape
count = 0
for i in range(x):
for j in range(y):
if grid[i][j] > thresholds[1]:
count += 1
return count
def analyse(source_path, destination_path, rn_model):
image_patches = split_file(source_path)
patches, xx, yy = getPatches(image_patches)
#RESHAPE THE PHOTOS FOR TESTING
width, height, channels = 50, 50, 3
patches_reshaped = np.reshape(patches, (len(patches),height,width,channels))
rez = analize_patches(patches_reshaped,xx,yy, rn_model)
generate_image(image_patches,rez,destination_path)
blanks = count_blanks(patches)
total = len(patches)
poz = count_poz(rez)
percent = str(round(poz/(total-blanks)*100,2))
return total, blanks, poz, percent
def analyse_by_name(source_path, destination_path, rn_name):
return analyse(source_path,destination_path,get_model(rn_name))
"""
rn_model = get_model("the_one")
analyse("../8863.png","../8863_r.png",rn_model)
analyse("../8863_free.png","../8863_0_r.png",rn_model)
"""<file_sep>using System;
using System.Collections.Generic;
using System.Text;
namespace IP_Framework
{
class IContext
{
public byte[] context;
public int sizeOfContext;
public String json;
public string user_id;
public byte[] answer;
public int sizeOfAnswer;
public IContext(byte[] initContext, int initSizeOfContext)
{
context = initContext;
sizeOfContext = initSizeOfContext;
string raspuns = "Not implemented yet, but here should stay the answer for the query";
sizeOfAnswer = raspuns.Length;
answer = Encoding.ASCII.GetBytes(raspuns);
}
public IContext()
{
context = null;
sizeOfContext = 0;
string raspuns = "Not implemented yet, but here should stay the answer for the query";
sizeOfAnswer = raspuns.Length;
answer = Encoding.ASCII.GetBytes(raspuns);
}
public static implicit operator IContext(Dictionary<string, string> v)
{
throw new NotImplementedException();
}
public IContext(String json)
{
this.json = json;
}
}
class ImageContext : IContext
{
// to be discussed and implemented
}
class EpidemyContext : IContext
{
public double x;
public double y;
public string specificSearch;
public Dictionary<string, string> AnswerDictionary;
public EpidemyContext(String json)
{
this.json = json;
}
public EpidemyContext()
{
}
}
class SymptomLearningContext : IContext
{
// to be discussed and implemented
}
class SymptomContext : IContext
{
public int id;
public float status;
public String response;
public SymptomContext(int id, float status)
{
this.id = id;
this.status = status;
}
}
class FormContext : IContext
{
// to be discussed and implemented
}
class DataBaseContext : IContext
{
public DataBaseDefines databaseId;
public DataBaseDefines databaseFunctionId;
public Dictionary<string, string> ParametersDictionary;
public Dictionary<string, string> AnswerDictionary;
public List<Point> points;
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Text;
namespace IP_Framework
{
class EventHandlerContext // the context needed for the invoke function
{
public EventHandlerFunctions command;
public IContext contextHandler;
public CoreKnownFunctions coreCommand;
public SubModuleFunctions subModuleCommand;
public EventHandlerContext()
{
command = EventHandlerFunctions.InvalidCommand;
coreCommand = CoreKnownFunctions.InvalidCommand;
subModuleCommand = SubModuleFunctions.InvalidCommand;
contextHandler = null;
}
public EventHandlerContext(byte[] initContext, int initSizeOfContext) // this will be changed with an interface for contexts
{
command = EventHandlerFunctions.InvalidCommand;
coreCommand = CoreKnownFunctions.InvalidCommand;
subModuleCommand = SubModuleFunctions.InvalidCommand;
contextHandler = new IContext(initContext, initSizeOfContext);
}
}
class EventHandler
{
private SymptomBasedDetection SymptomBasedModule;
private EpidemyAlert EpidemyModule;
private ImageProcessing ImageModule;
private SymptomLearning SymptomModule;
private DataBaseHandler dbHandler; // TODO after the DB is alive
// all modules should pe private, we need to encapsulate as much as possible
// only this instances should have access to the data in the handler
private static EventHandler instance = new EventHandler();
public static EventHandler GetInstance()
{
return instance;
}
public EventHandler() // this module should get an DB instance for the dataBaseHandler
{
Init(null, 0);
Console.WriteLine("A mers initilizarea!");
}
~EventHandler()
{
this.UnInit(); // this should be like this because we need the same code for forced de-initialization
Console.WriteLine("A mers de-initilizarea!");
}
public bool InvokeCommand(EventHandlerContext handlerContext) // invoke commands between the submodules and also the Core
{
Console.WriteLine("InvokeCommand execution for subModule Handler");
/*if (ValidateContext(handlerContext) == false)
return false;*/
switch (handlerContext.command)
{
case EventHandlerFunctions.Init:
return this.Init(handlerContext.contextHandler.context, handlerContext.contextHandler.sizeOfContext);
case EventHandlerFunctions.UnInit:
return UnInit();
case EventHandlerFunctions.RequestCommand:
return RequestCommand(handlerContext.coreCommand, handlerContext.contextHandler.context, handlerContext.contextHandler.sizeOfContext);
case EventHandlerFunctions.EpidemyAlertModule:
return EpidemyModule.InvokeCommand(handlerContext.subModuleCommand, handlerContext.contextHandler);
case EventHandlerFunctions.ImageProcessingModule:
return ImageModule.InvokeCommand(handlerContext.subModuleCommand, handlerContext.contextHandler);
case EventHandlerFunctions.SymptomLearningModule:
return SymptomModule.InvokeCommand(handlerContext.subModuleCommand, handlerContext.contextHandler);
case EventHandlerFunctions.SymptomBasedDetectionModule:
return SymptomBasedModule.InvokeCommand(handlerContext.subModuleCommand, handlerContext.contextHandler);
case EventHandlerFunctions.DataBaseModule:
return dbHandler.InvokeCommand(handlerContext.subModuleCommand, handlerContext.contextHandler);
case EventHandlerFunctions.InvokeCommand:
return false; // INvoKE COmMAnD
}
return false;
}
private bool RequestCommand(CoreKnownFunctions command, byte[] context, int sizeOfContext) // Sends requests to Core and then process them as we want
{
// invoke commands directly from the core of the program itself
// directly send command to core, where the context should be validated!!!!
// we could return actually a command, not just asking, but its better like this because we can control the state of the module in case of malfunctioning after our call
// also, if we return the command, we can't use the context asked
return true;
}
private bool Init(byte[] context, int sizeOfContext) // Initialize the data using the possible context, it should be checked if context is not null if its mandatory for Init
{
SymptomBasedModule = new SymptomBasedDetection(this);
SymptomBasedModule.Init(context, sizeOfContext);
EpidemyModule = new EpidemyAlert(this);
EpidemyModule.Init(context, sizeOfContext);
ImageModule = new ImageProcessing(this);
ImageModule.Init(context, sizeOfContext);
SymptomModule = new SymptomLearning(this);
SymptomModule.Init(context, sizeOfContext);
dbHandler = new DataBaseHandler(this);
dbHandler.Init(context, sizeOfContext);
return true;
}
private bool UnInit() // unInit all the modules and destroy all data left in memory
{
SymptomBasedModule.UnInit();
EpidemyModule.UnInit();
ImageModule.UnInit();
SymptomModule.UnInit();
return true;
}
private bool ValidateContext(EventHandlerContext contextContainer)
{
if (ReferenceEquals(contextContainer, null)) // useless until EventHandlerContext becomes a class, not a struct
return false;
if (contextContainer.contextHandler.sizeOfContext == 0)
return false;
if (ReferenceEquals(contextContainer.contextHandler.context, null))
return false;
return true;
}
}
public enum EventHandlerFunctions // all the things the Handler should/can do
{
InvalidCommand = 0,
Init = 1,
InvokeCommand,
RequestCommand,
UnInit,
SymptomBasedDetectionModule = 100,
EpidemyAlertModule,
ImageProcessingModule,
SymptomLearningModule,
DataBaseModule,
}
public enum CoreKnownFunctions // this should be placed in Core, for everybody to add complexity needed
{
InvalidCommand = 0,
DiagnosisUnInit = 1,
DiagnosisRestart,
DiagnosisTriggerDiagnostic,
DiagnosisInvoke,
}
public enum SubModuleFunctions // all the functions for all the modules, should stay categorized!
{
InvalidCommand = 0,
MachineLearningAsk = 1,
MachineLearningGetResults,
MachineLearningStoreResults,
MachineLearningAdapt,
CreateForm = 101,
AskForFormResults,
SaveFormResults,
StartForm,
GetQuestion,
SendResponse,
ImageAddPhoto = 201,
ImageComparePhoto,
ImageStoreResults,
ImageAdapt,
EpidemyCheckForAlert = 301,
EpidemyCheckForAreas,
DataBaseSaveData = 401,
DataBaseDestroyData,
DataBaseQueryData,
DataBaseAlterData,
CheckSigsForUser = 501,
ReloadSigs = 502,
GetAllNotifications = 503
}
public enum DataBaseDefines
{
DatabaseDiseases = 0,
DiseasesFullQuery,
DiseasesSpecificQueryDisease,
DiseasesSpecificQueryPerson,
GetAllDots,
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Text;
namespace Quizzer
{
class QuizzerStrategyContext
{
IQuizzerStrategy quizzerStrategy;
public IQuizzerStrategy GetStrategy()
{
return quizzerStrategy;
}
public void SetContext(Answer.QUESTION_TYPE questionType)
{
switch (questionType)
{
case Answer.QUESTION_TYPE.QUESTION_SICKNESS_LEVEL:
quizzerStrategy = new QuestionSicknessLevelStrategy();
break;
case Answer.QUESTION_TYPE.QUESTION_BOOLEAN:
quizzerStrategy = new QuestionBooleanStrategy();
break;
case Answer.QUESTION_TYPE.QUESTION_NUMBER:
quizzerStrategy = new QuestionNumberStrategy();
break;
}
}
}
}
<file_sep>import web
import json
render = web.template.render('templates3/')
urls = (
'/resources', 'resources'
)
class resources:
def GET(self):
resp = {'contents': ['Breast Cancer', 'Breast Tumour']}
web.header('Content-Type', 'application/json')
web.header('Access-Control-Allow-Origin', 'http://localhost:4200')
return json.dumps(resp)
if __name__ == "__main__":
app = web.application(urls, globals())
app.run()
<file_sep>using System;
using System.Collections.Generic;
using System.Text;
using MongoDB.Driver;
using MongoDB.Bson;
namespace IP_Framework.InternalDbHandler
{
class DBInstance
{
public IMongoDatabase databaseInstance = null;
public DBInstance()
{
MongoClient client = new MongoClient(Config.CONNECTION_STRING);
databaseInstance = client.GetDatabase(Config.DB_NAME);
}
public void InsertDocument(IMongoCollection<BsonDocument> collection, BsonDocument document)
{
collection.InsertOne(document);
}
public void ShowDataInCollection(IMongoCollection<BsonDocument> collection)
{
var documents = collection.Find(new BsonDocument()).ToList();
foreach (BsonDocument doc in documents)
{
Console.WriteLine(doc.ToString());
}
}
}
}
<file_sep>using IP_Framework;
using Microsoft.AspNetCore.Razor.Language.Extensions;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Text;
using IP_Framework.InternalDbHandler;
using IP_Framework.Utils;
using System.Linq;
using MongoDB.Driver;
using MongoDB.Bson;
namespace Quizzer
{
public class SymptomsHolder
{
private ISet<QuSignature> signatures;
private Dictionary<string, HashSet<QuSignature>> symptomToSignatures;
private ISet<string> chekckedSymtpoms;
private const double minValidPercentage = 0.5;
private const double minCorrectPercentage = 0.75;
public SymptomsHolder(ISet<QuSignature> signatures)
{
symptomToSignatures = new Dictionary<string, HashSet<QuSignature>>();
this.signatures = signatures;
foreach(QuSignature signature in signatures)
{
foreach(var symptom in signature.symptoms)
{
if (!symptomToSignatures.ContainsKey(symptom.Key))
{
symptomToSignatures.Add(symptom.Key, new HashSet<QuSignature>());
symptomToSignatures[symptom.Key].Add(signature);
}
else
{
symptomToSignatures[symptom.Key].Add(signature);
}
}
}
chekckedSymtpoms = new HashSet<string>();
}
public Question GetNextQuestion()
{
foreach(QuSignature signature in signatures)
{
foreach(var symptom in signature.symptoms)
{
Question question = new Question(symptom.Key, symptom.Value.questionString, symptom.Value.GetQuestionType());
if (!chekckedSymtpoms.Contains(symptom.Key))
{
chekckedSymtpoms.Add(symptom.Key);
return question;
}
}
}
return null;
}
private Question ComputeNextQuestion()
{
return null;
}
public int GetSignaturesCount()
{
return signatures.Count;
}
public async System.Threading.Tasks.Task<string> GetJsonVerdictAsync(int id)
{
JObject jObject = new JObject();
JArray jArray = new JArray();
jObject.Add("verdict", jArray);
List<QuSignature> verdicts = new List<QuSignature>();
foreach(QuSignature signature in signatures)
{
if(((double)signature.currentPositiveScore / (double)signature.initialScore) > minCorrectPercentage)
{
verdicts.Add(signature);
}
}
UserHandler userHandler = new UserHandler(Singleton<DBInstance>.Instance);
var collection = userHandler.GetCollection();
foreach (QuSignature signature in verdicts)
{
var document = new BsonDocument
{
{"disease", signature.name },
{"date", DateTime.Now.ToString() }
};
jArray.Add(signature.name);
var filter = Builders<BsonDocument>.Filter.Eq("userid", id.ToString());
var update = Builders<BsonDocument>.Update.Push("diseases", document);
var result = await collection.UpdateOneAsync(filter, update);
}
if (jArray.Count == 0)
{
jArray.Add("nimic"); // verdictul o sa contina "nimic" daca nu ai adaugat nimic.
}
return jObject.ToString();
}
public void ProcessAnswer(Answer answer)
{
QuizzerStrategyContext strategyContext = new QuizzerStrategyContext();
strategyContext.SetContext(answer.GetAnswerType());
string correspondingSymptom = answer.GetCorrespondingSympton();
IList<QuSignature> removedSignatures = new List<QuSignature>();
foreach(var signature in symptomToSignatures[correspondingSymptom])
{
if(!strategyContext.GetStrategy().ApplyAnswerToSignature(signature, correspondingSymptom, answer))
{
double percentage = (double)signature.currentScore / (double)signature.initialScore;
if (percentage < minValidPercentage)
{
removedSignatures.Add(signature);
}
}
}
foreach(QuSignature signature in removedSignatures)
{
foreach(var symptom in signature.symptoms)
{
symptomToSignatures[symptom.Key].Remove(signature);
}
signatures.Remove(signature);
}
}
}
}
<file_sep>using System;
namespace IP_Framework.API
{
public class Image
{
byte[] image { get; set; }
String type { get; set; }
}
}
<file_sep>PRIORITY_HIGH
if(hasSymptom('Tumora')) log('Naspa de tine');
var symptomsDurere = ['Durere f', 'Durere c'];
for(var i = 0; i < symptomsDurere.length; i++) {
if(!hasSymptom(symptomsDurere[i])) {
return false;
}
}
addNewSymptom('Smecheras');
log("test");
return true;<file_sep>using System;
using System.Collections.Generic;
using System.Text;
namespace IP_Framework
{
class SymptomLearning : IModule
{
private EventHandler fatherHandler;
private String text = "SymptomLearning constructor";
public SymptomLearning(EventHandler father)
{
fatherHandler = father;
Console.WriteLine(text);
}
public override bool InvokeCommand(SubModuleFunctions command, IContext contextHandler)
{
Console.WriteLine("InvokeCommand execution for SymptomLearning subModule");
SymptomLearningContext subModuleContextHandler = contextHandler as SymptomLearningContext;
switch (command)
{
case SubModuleFunctions.MachineLearningAdapt:
// improve machine learning
return true;
case SubModuleFunctions.MachineLearningAsk:
// query machine learning
return true;
case SubModuleFunctions.MachineLearningGetResults:
// query results
return true;
case SubModuleFunctions.MachineLearningStoreResults:
// store results for improvements
return true;
default:
return false;
}
}
public override bool Init(byte[] context, int sizeOfContext)
{
Console.WriteLine("Init execution");
return true;
}
public override bool UnInit()
{
Console.WriteLine("UnInit execution");
return true;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using IP_Framework.InternalDbHandler;
using MongoDB.Bson;
namespace IP_Framework
{
class EpidemyAlert : IModule
{
private EventHandler fatherHandler;
public static double AreaAroundYuu = 0.2;
public static int AreaAroundYuuCases = 5;
public static double NeighourHood = 1.5;
public static int NeighourHoodCases = 20;
public static double Town = 10;
public static int TownCases = 150;
public static double Country = 100;
public static int CountryCases = 1000;
public EpidemyAlert(EventHandler father)
{
fatherHandler = father;
}
public String CreateConvexHauls(List<Point> points)
{
List<List<Point>> finalResultList = new List<List<Point>>();
foreach (List<Point> list in ConvexHaul.CalculateHull(points, AreaAroundYuu))
{
finalResultList.Add(list);
}
foreach (List<Point> list in ConvexHaul.CalculateHull(points, NeighourHood))
{
finalResultList.Add(list);
}
foreach (List<Point> list in ConvexHaul.CalculateHull(points, Town))
{
finalResultList.Add(list);
}
foreach (List<Point> list in ConvexHaul.CalculateHull(points, Country))
{
finalResultList.Add(list);
}
String JSON = "{result : [";
foreach (var list in finalResultList)
{
JSON = JSON + "[";
foreach (var point in list)
{
JSON = JSON + "{" + point.x + ", " + point.y + "},";
}
JSON = JSON.TrimEnd(',');
JSON = JSON + "],";
}
JSON = JSON.TrimEnd(',');
JSON = JSON + "]}";
Console.WriteLine(JSON);
return JSON;
}
public String CheckIfPointsCauseAlert(List<Point> points, Point user, String disease)
{
String JSON = "{areas : [";
int counterForAreaAroundYuu = 0;
int counterForNeighourHood = 0;
int counterForTown = 0;
int counterForCountry = 0;
foreach (Point point in points)
{
if (ConvexHaul.Distance(point, user) < AreaAroundYuu)
counterForAreaAroundYuu++;
if (ConvexHaul.Distance(point, user) < NeighourHood)
counterForNeighourHood++;
if (ConvexHaul.Distance(point, user) < Town)
counterForTown++;
if (ConvexHaul.Distance(point, user) < Country)
counterForCountry++;
}
DBModule instance = Utils.Singleton<DBModule>.Instance;
NotificationsHandler notifHandler = instance.GetNotifHandler();
if (counterForAreaAroundYuu >= AreaAroundYuuCases)
{
JSON = JSON + "{\"AreaAroundYou\" : 1},";
notifHandler.InsertNotificationToAllAffectedUsers(user, AreaAroundYuu, disease);
}
else
{
JSON = JSON + "{\"AreaAroundYou\" : 0},";
}
if (counterForNeighourHood >= NeighourHoodCases)
{
JSON = JSON + "{\"NeighourHood\" : 1},";
notifHandler.InsertNotificationToAllAffectedUsers(user, NeighourHood, disease);
}
else
{
JSON = JSON + "{\"NeighourHood\" : 0},";
}
if (counterForTown >= TownCases)
{
JSON = JSON + "{\"Town\" : 1},";
notifHandler.InsertNotificationToAllAffectedUsers(user, Town, disease);
}
else
{
JSON = JSON + "{\"Town\" : 0},";
}
if (counterForCountry >= CountryCases)
{
JSON = JSON + "{\"Country\" : 1}]}";
notifHandler.InsertNotificationToAllAffectedUsers(user, Country, disease);
}
else
{
JSON = JSON + "{\"Country\" : 0}]}";
}
return JSON;
}
public override bool InvokeCommand(SubModuleFunctions command, IContext contextHandler)
{
Console.WriteLine("InvokeCommand execution for EpidemyAlert subModule");
EpidemyContext subModuleContextHandler = contextHandler as EpidemyContext;
if (subModuleContextHandler == null)
return false;
DBModule instance = Utils.Singleton<DBModule>.Instance;
UserHandler userHandler = instance.GetUserHandler();
NotificationsHandler notifHandler = instance.GetNotifHandler();
List<Point> points;
switch (command)
{
case SubModuleFunctions.EpidemyCheckForAreas:
if (subModuleContextHandler.specificSearch != null)
{
points = userHandler.GetPointsForDisease(subModuleContextHandler.specificSearch);
}
else
{
points = userHandler.GetPoints();
}
subModuleContextHandler.json = CreateConvexHauls(points);
return true;
case SubModuleFunctions.EpidemyCheckForAlert:
points = userHandler.GetPointsForDisease(subModuleContextHandler.specificSearch);
String user_id = subModuleContextHandler.user_id;
Point user = userHandler.GetPointsForUser(user_id);
if(user != null)
subModuleContextHandler.json = CheckIfPointsCauseAlert(points, user, subModuleContextHandler.specificSearch);
return true;
case SubModuleFunctions.GetAllNotifications:
BsonArray notifs = notifHandler.GetAllNotifs(subModuleContextHandler.specificSearch);
subModuleContextHandler.json = notifs.ToString();
return true;
default:
return false;
}
}
public override bool Init(byte[] context, int sizeOfContext)
{
Console.WriteLine("Init execution");
return true;
}
public override bool UnInit()
{
Console.WriteLine("UnInit execution");
return true;
}
}
}
<file_sep>using MongoDB.Bson;
using MongoDB.Bson.Serialization.Attributes;
using System;
using System.Collections.Generic;
using System.Text;
namespace Quizzer
{
public class QuSymptom
{
public static class SymptomTypes
{
public static string NIVEL_DURERE = "NIVEL_DURERE";
}
public enum NivelDurere : int
{
DURERE_DELOC = 0,
DURERE_MICA = 1,
DURERE_MEDIE = 2,
DURERE_MARE = 3
}
public Answer.QUESTION_SICKNESS_LEVEL min_durere;
public Answer.QUESTION_SICKNESS_LEVEL max_durere;
public string tip;
public string questionString;
public int importanta;
public string min_pain;
public string max_pain;
[BsonRepresentation(BsonType.Double, AllowTruncation = true)]
public double min;
[BsonRepresentation(BsonType.Double, AllowTruncation = true)]
public double max;
public bool valoare;
public Answer.QUESTION_TYPE GetQuestionType()
{
if (tip == "interval")
{
return Answer.QUESTION_TYPE.QUESTION_NUMBER;
}
if (tip == "existenta")
{
return Answer.QUESTION_TYPE.QUESTION_BOOLEAN;
}
if (tip == "nivel_durere")
{
return Answer.QUESTION_TYPE.QUESTION_SICKNESS_LEVEL;
}
return Answer.QUESTION_TYPE.QUESTION_BOOLEAN;
}
public void SetPainLevel()
{
if(min_pain == null)
{
return;
}
switch (min_pain)
{
case "deloc":
min_durere = Answer.QUESTION_SICKNESS_LEVEL.ABSENT;
break;
case "mic":
min_durere = Answer.QUESTION_SICKNESS_LEVEL.LITTLE;
break;
case "mediu":
min_durere = Answer.QUESTION_SICKNESS_LEVEL.MEDIUM;
break;
case "mare":
min_durere = Answer.QUESTION_SICKNESS_LEVEL.HIGH;
break;
}
if (max_pain == null)
{
return;
}
switch (max_pain)
{
case "deloc":
max_durere = Answer.QUESTION_SICKNESS_LEVEL.ABSENT;
break;
case "mic":
max_durere = Answer.QUESTION_SICKNESS_LEVEL.LITTLE;
break;
case "mediu":
max_durere = Answer.QUESTION_SICKNESS_LEVEL.MEDIUM;
break;
case "mare":
max_durere = Answer.QUESTION_SICKNESS_LEVEL.HIGH;
break;
}
}
};
}
<file_sep># ProiectIP_B4
A part of a class project.
This repo has two services, one in Python and one in .Net.
The .Net one should be capable of generating quizes that are supposed to detect diseases if some json signatures are given beforehand.
Also this code is capable of detecting epidemies if the geographic location of the users is given and some symptoms have been declared in the quizes.
The Python one is a neural network capable of detecting pulmonary and brain cancer in images.
<file_sep>import pandas as pd
import numpy as np
import os
from glob import glob
import itertools
import fnmatch
import random
import matplotlib.pylab as plt
import seaborn as sns
import cv2
import imageio# import imresize, imread
import sklearn
from sklearn import model_selection
from sklearn.model_selection import train_test_split, KFold, cross_val_score, StratifiedKFold, learning_curve, GridSearchCV
from sklearn.metrics import confusion_matrix, make_scorer, accuracy_score
from sklearn.linear_model import LogisticRegression
from sklearn.tree import DecisionTreeClassifier
from sklearn.neighbors import KNeighborsClassifier
from sklearn.discriminant_analysis import LinearDiscriminantAnalysis
from sklearn.naive_bayes import GaussianNB
from sklearn.svm import SVC, LinearSVC
from sklearn.ensemble import RandomForestClassifier, GradientBoostingClassifier
import keras
from keras import backend as K
from keras.callbacks import Callback, EarlyStopping, ReduceLROnPlateau, ModelCheckpoint
from keras.preprocessing.image import ImageDataGenerator
from keras.utils.np_utils import to_categorical
from keras.models import Sequential, model_from_json
from keras.optimizers import SGD, RMSprop, Adam, Adagrad, Adadelta
from keras.layers import Dense, Dropout, Activation, Flatten, BatchNormalization, Conv2D, MaxPool2D, MaxPooling2D
# save np.load
np_load_old = np.load
# modify the default parameters of np.load
np.load = lambda *a,**k: np_load_old(*a, allow_pickle=True, **k)
print("Success!")
imagePatches = glob('/home/stefy/cpp/ProiectIP/IDC_regular_ps50_idx5/**/*.png', recursive=True)
"""
for filename in imagePatches[0:10]:
print(filename)
"""
print("Images loaded: " + str(len(imagePatches)))
image_name = "/home/stefy/cpp/ProiectIP/IDC_regular_ps50_idx5/10258/0/10258_idx5_x851_y1751_class0.png" #Image to be used as query
def plotImage(image_location):
image = cv2.imread(image_name)
image = cv2.resize(image, (50,50))
plt.imshow(cv2.cvtColor(image, cv2.COLOR_BGR2RGB)); plt.axis('off')
plt.show()
return
#plotImage(image_name)
# Plot Multiple Images
bunchOfImages = imagePatches
i_ = 0
plt.rcParams['figure.figsize'] = (10.0, 10.0)
plt.subplots_adjust(wspace=0, hspace=0)
print("\n\n")
"""
for l in bunchOfImages[:25]:
#print(l)
im = cv2.imread(l)
im = cv2.resize(im, (50, 50))
plt.subplot(5, 5, i_+1) #.set_title(l)
plt.imshow(cv2.cvtColor(im, cv2.COLOR_BGR2RGB)); plt.axis('off')
#plt.show()
i_ += 1
plt.show()
"""
def randomImages(a):
r = random.sample(a, 4)
plt.figure(figsize=(16,16))
plt.subplot(131)
plt.imshow(cv2.imread(r[0]))
plt.subplot(132)
plt.imshow(cv2.imread(r[1]))
plt.subplot(133)
plt.imshow(cv2.imread(r[2]))
plt.show()
#randomImages(imagePatches)
#In 6
print("In 6:\n\n")
patternZero = '*class0.png'
patternOne = '*class1.png'
classZero = fnmatch.filter(imagePatches, patternZero)
classOne = fnmatch.filter(imagePatches, patternOne)
#In 7
print("In 7:\n\n")
def proc_images(lowerIndex,upperIndex):
"""
Returns two arrays:
x is an array of resized images
y is an array of labels
"""
x = []
y = []
WIDTH = 50
HEIGHT = 50
for img in imagePatches[lowerIndex:upperIndex]:
full_size_image = cv2.imread(img)
x.append(cv2.resize(full_size_image, (WIDTH,HEIGHT), interpolation=cv2.INTER_CUBIC))
if img in classZero:
y.append(0)
elif img in classOne:
y.append(1)
else:
return
return x,y
#In 8
print("In 8:\n\n")
X,Y = proc_images(100001,110000)
df = pd.DataFrame()
df["images"]=X
df["labels"]=Y
X2=df["images"]
Y2=df["labels"]
X2=np.array(X2)
imgs0=[]
imgs1=[]
imgs0 = X2[Y2==0] # (0 = no IDC, 1 = IDC)
imgs1 = X2[Y2==1]
#In 9
print("In 9:\n\n")
def describeData(a,b):
print('Total number of images: {}'.format(len(a)))
print('Number of IDC(-) Images: {}'.format(np.sum(b==0)))
print('Number of IDC(+) Images: {}'.format(np.sum(b==1)))
print('Percentage of positive images: {:.2f}%'.format(100*np.mean(b)))
print('Image shape (Width, Height, Channels): {}'.format(a[0].shape))
describeData(X2,Y2)
#In 10
print("In 10:\n\n")
dict_characters = {0: 'IDC(-)', 1: 'IDC(+)'}
print(df.head(10))
print("")
print(dict_characters)
#In 11
print("In 11:\n\n")
def plotOne(a,b):
"""
Plot one numpy array
"""
plt.subplot(1,2,1)
plt.title('IDC (-)')
plt.imshow(a[0])
plt.subplot(1,2,2)
plt.title('IDC (+)')
plt.imshow(b[0])
#plotOne(imgs0, imgs1)
#plt.show()
#In 12
print("In 12:\n\n")
def plotTwo(a,b):
"""
Plot a bunch of numpy arrays sorted by label
"""
for row in range(3):
plt.figure(figsize=(20, 10))
for col in range(3):
plt.subplot(1,8,col+1)
plt.title('IDC (-)')
plt.imshow(a[0+row+col])
plt.axis('off')
plt.subplot(1,8,col+4)
plt.title('IDC (+)')
plt.imshow(b[0+row+col])
plt.axis('off')
plt.show()
#plotTwo(imgs0, imgs1)
#In 13
print("In 13:\n\n")
def plotHistogram(a):
"""
Plot histogram of RGB Pixel Intensities
"""
plt.figure(figsize=(10,5))
plt.subplot(1,2,1)
plt.imshow(a)
plt.axis('off')
plt.title('IDC(+)' if Y[1] else 'IDC(-)')
histo = plt.subplot(1,2,2)
histo.set_ylabel('Count')
histo.set_xlabel('Pixel Intensity')
n_bins = 30
plt.hist(a[:,:,0].flatten(), bins= n_bins, lw = 0, color='r', alpha=0.5)
plt.hist(a[:,:,1].flatten(), bins= n_bins, lw = 0, color='g', alpha=0.5)
plt.hist(a[:,:,2].flatten(), bins= n_bins, lw = 0, color='b', alpha=0.5)
plt.show()
#plotHistogram(X2[100])
#In 14
print("In 14:\n\n")
X=np.array(X)
X=X/255.0
X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size=0.2)
# Reduce Sample Size for DeBugging
X_train = X_train[0:300000]
Y_train = Y_train[0:300000]
X_test = X_test[0:300000]
Y_test = Y_test[0:300000]
print("Training Data Shape:", X_train.shape)
print("Testing Data Shape:", X_test.shape)
#In 15
print("In 15:\n\n")
#plotHistogram(X_train[100])
#In 16
print("In 16:\n\n")
# Encode labels to hot vectors (ex : 2 -> [0,0,1,0,0,0,0,0,0,0])
Y_trainHot = to_categorical(Y_train, num_classes = 2)
Y_testHot = to_categorical(Y_test, num_classes = 2)
#In 17
print("In 17:\n\n")
lab = df['labels']
dist = lab.value_counts()
sns.countplot(lab)
print(dict_characters)
#In 18
print("In 18:\n\n")
# Deal with imbalanced class sizes below
# Make Data 1D for compatability upsampling methods
X_trainShape = X_train.shape[1]*X_train.shape[2]*X_train.shape[3]
X_testShape = X_test.shape[1]*X_test.shape[2]*X_test.shape[3]
X_trainFlat = X_train.reshape(X_train.shape[0], X_trainShape)
X_testFlat = X_test.reshape(X_test.shape[0], X_testShape)
#print("X_train Shape: ",X_train.shape)
#print("X_test Shape: ",X_test.shape)
#print("X_trainFlat Shape: ",X_trainFlat.shape)
#print("X_testFlat Shape: ",X_testFlat.shape)
from imblearn.over_sampling import RandomOverSampler
from imblearn.under_sampling import RandomUnderSampler
#ros = RandomOverSampler(ratio='auto')
ros = RandomUnderSampler()
X_trainRos, Y_trainRos = ros.fit_sample(X_trainFlat, Y_train)
X_testRos, Y_testRos = ros.fit_sample(X_testFlat, Y_test)
# Encode labels to hot vectors (ex : 2 -> [0,0,1,0,0,0,0,0,0,0])
Y_trainRosHot = to_categorical(Y_trainRos, num_classes = 2)
Y_testRosHot = to_categorical(Y_testRos, num_classes = 2)
#print("X_train: ", X_train.shape)
#print("X_trainFlat: ", X_trainFlat.shape)
#print("X_trainRos Shape: ",X_trainRos.shape)
#print("X_testRos Shape: ",X_testRos.shape)
#print("Y_trainRosHot Shape: ",Y_trainRosHot.shape)
#print("Y_testRosHot Shape: ",Y_testRosHot.shape)
for i in range(len(X_trainRos)):
height, width, channels = 50,50,3
X_trainRosReshaped = X_trainRos.reshape(len(X_trainRos),height,width,channels)
#print("X_trainRos Shape: ",X_trainRos.shape)
#print("X_trainRosReshaped Shape: ",X_trainRosReshaped.shape)
for i in range(len(X_testRos)):
height, width, channels = 50,50,3
X_testRosReshaped = X_testRos.reshape(len(X_testRos),height,width,channels)
#print("X_testRos Shape: ",X_testRos.shape)
#print("X_testRosReshaped Shape: ",X_testRosReshaped.shape)
dfRos = pd.DataFrame()
dfRos["labels"]=Y_trainRos
labRos = dfRos['labels']
distRos = lab.value_counts()
sns.countplot(labRos)
print(dict_characters)
#In 19
print("In 19:\n\n")
from sklearn.utils import class_weight
class_weight = class_weight.compute_class_weight('balanced', np.unique(Y_train), Y_train)
print("Old Class Weights: ",class_weight)
from sklearn.utils import class_weight
class_weight2 = class_weight.compute_class_weight('balanced', np.unique(Y_trainRos), Y_trainRos)
print("New Class Weights: ",class_weight2)
#In 20
print("In 20:\n\n")
# Helper Functions Learning Curves and Confusion Matrix
class MetricsCheckpoint(Callback):
"""Callback that saves metrics after each epoch"""
def __init__(self, savepath):
super(MetricsCheckpoint, self).__init__()
self.savepath = savepath
self.history = {}
def on_epoch_end(self, epoch, logs=None):
for k, v in logs.items():
self.history.setdefault(k, []).append(v)
np.save(self.savepath, self.history)
def plotKerasLearningCurve():
plt.figure(figsize=(10,5))
metrics = np.load('logs.npy')[()]
filt = ['acc'] # try to add 'loss' to see the loss learning curve
for k in filter(lambda x : np.any([kk in x for kk in filt]), metrics.keys()):
l = np.array(metrics[k])
plt.plot(l, c= 'r' if 'val' not in k else 'b', label='val' if 'val' in k else 'train')
x = np.argmin(l) if 'loss' in k else np.argmax(l)
y = l[x]
plt.scatter(x,y, lw=0, alpha=0.25, s=100, c='r' if 'val' not in k else 'b')
plt.text(x, y, '{} = {:.4f}'.format(x,y), size='15', color= 'r' if 'val' not in k else 'b')
plt.legend(loc=4)
plt.axis([0, None, None, None])
plt.grid()
plt.xlabel('Number of epochs')
def plot_confusion_matrix(cm, classes,
normalize=False,
title='Confusion matrix',
cmap=plt.cm.Blues):
"""
This function prints and plots the confusion matrix.
Normalization can be applied by setting `normalize=True`.
"""
plt.figure(figsize = (5,5))
plt.imshow(cm, interpolation='nearest', cmap=cmap)
plt.title(title)
plt.colorbar()
tick_marks = np.arange(len(classes))
plt.xticks(tick_marks, classes, rotation=90)
plt.yticks(tick_marks, classes)
if normalize:
cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]
thresh = cm.max() / 2.
for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):
plt.text(j, i, cm[i, j],
horizontalalignment="center",
color="white" if cm[i, j] > thresh else "black")
plt.tight_layout()
plt.ylabel('True label')
plt.xlabel('Predicted label')
def plot_learning_curve(history):
plt.figure(figsize=(8,8))
plt.subplot(1,2,1)
plt.plot(history.history['acc'])
plt.plot(history.history['val_acc'])
plt.title('model accuracy')
plt.ylabel('accuracy')
plt.xlabel('epoch')
plt.legend(['train', 'test'], loc='upper left')
plt.savefig('./accuracy_curve.png')
#plt.clf()
# summarize history for loss
plt.subplot(1,2,2)
plt.plot(history.history['loss'])
plt.plot(history.history['val_loss'])
plt.title('model loss')
plt.ylabel('loss')
plt.xlabel('epoch')
plt.legend(['train', 'test'], loc='upper left')
plt.savefig('./loss_curve.png')
#In 21
print("In 21:\n\n")
def runKerasCNNAugment(a,b,c,d,e,f):
"""
Run Keras CNN: https://github.com/fchollet/keras/blob/master/examples/mnist_cnn.py
"""
batch_size = 128
num_classes = 2
epochs = 12
# img_rows, img_cols = a.shape[1],a.shape[2]
img_rows,img_cols=50,50
input_shape = (img_rows, img_cols, 3)
model = Sequential()
model.add(Conv2D(32, kernel_size=(3, 3),
activation='relu',
input_shape=input_shape,strides=e))
model.add(Conv2D(64, (3, 3), activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(0.25))
model.add(Flatten())
model.add(Dense(128, activation='relu'))
model.add(Dropout(0.5))
model.add(Dense(num_classes, activation='softmax'))
model.compile(loss=keras.losses.categorical_crossentropy,
optimizer=keras.optimizers.Adadelta(),
metrics=['accuracy'])
#model = keras.models.load_model("de_la_Aky.rn")
datagen = ImageDataGenerator(
featurewise_center=False, # set input mean to 0 over the dataset
samplewise_center=False, # set each sample mean to 0
featurewise_std_normalization=False, # divide inputs by std of the dataset
samplewise_std_normalization=False, # divide each input by its std
zca_whitening=False, # apply ZCA whitening
rotation_range=20, # randomly rotate images in the range (degrees, 0 to 180)
width_shift_range=0.2, # randomly shift images horizontally (fraction of total width)
height_shift_range=0.2, # randomly shift images vertically (fraction of total height)
horizontal_flip=True, # randomly flip images
vertical_flip=True) # randomly flip images
history = model.fit_generator(datagen.flow(a,b, batch_size=32),
steps_per_epoch=len(a) / 32, epochs=epochs,class_weight=f, validation_data = [c, d],callbacks = [MetricsCheckpoint('logs')])
score = model.evaluate(c,d, verbose=0)
print('\nKeras CNN #1C - accuracy:', score[1],'\n')
y_pred = model.predict(c)
map_characters = {0: 'IDC(-)', 1: 'IDC(+)'}
print('\n', sklearn.metrics.classification_report(np.where(d > 0)[1], np.argmax(y_pred, axis=1), target_names=list(map_characters.values())), sep='')
Y_pred_classes = np.argmax(y_pred,axis=1)
Y_true = np.argmax(d,axis=1)
model.save("model_test.rn")
plotKerasLearningCurve()
plt.show()
plot_learning_curve(history)
plt.show()
confusion_mtx = confusion_matrix(Y_true, Y_pred_classes)
plot_confusion_matrix(confusion_mtx, classes = list(dict_characters.values()))
plt.show()
runKerasCNNAugment(X_trainRosReshaped, Y_trainRosHot, X_testRosReshaped, Y_testRosHot,2,class_weight2)
np.load = np_load_old<file_sep>import web
import shutil
import PIL
from PIL import Image
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
def split_image(img,size = (50,50)):
maxX, maxY = img.width, img.height
cols = maxX//size[0]
rows = maxY//size[1]
patches = [[0 for x in range(rows)] for y in range(cols)]
print(len(patches),len(patches[0]))
for x in range(1,maxX,50):
for y in range(1,maxY,50):
patch = img.crop((x,y,x+50,y+50))
patches[x//50][y//50] = patch
return patches
render = web.template.render('templates/')
db = web.database(
dbn='mysql',
host='127.0.0.1',
port=3306,
user='stefy',
pw='Stefan2000',
db='pytest'
)
urls = (
'/', 'index',
'/add', 'add',
'/upload_image', 'upload_image',
'/upload_book','upload_book',
'/upload','Upload',
'/result','result'
)
class index:
def GET(self):
print("something")
todos = db.select('carti')
return render.index(todos)
class add:
def POST(self):
i = web.input()
n = db.insert('carti', isbn = i.isbn,titlu=i.titlu,autor=i.autor)
raise web.seeother('/')
class upload_book:
def GET(self):
print("another thing")
return render.upload_book()
class upload_image:
def GET(self):
print("yet another thing")
return render.upload_image()
class Upload:
def POST(self):
x = web.input(myfile={})
print(type(x))
print(type(x['myfile']))
web.debug(x['myfile'].filename) # This is the filename
#web.debug(x['myfile'].value) # This is the file contents
#web.debug(x['myfile'].file.read()) # Or use a file(-like) object
w = open("templates/images/resources/tmp.png",'wb')
w.write(x['myfile'].file.read())
img = Image.open("templates/images/resources/tmp.png")
patches = split_image(img)
print(len(patches),len(patches[0]))
raise web.seeother('/result')
class result:
def GET(self):
raise web.seeother('/')
def POST(self):
raise web.seeother('/')
if __name__ == "__main__":
app = web.application(urls, globals())
app.run()<file_sep>using System;
using System.Collections.Generic;
using System.Text;
namespace IP_Framework
{
class ImageProcessing : IModule
{
private EventHandler fatherHandler;
private String text = "ImageProcessing constructor";
public ImageProcessing(EventHandler father)
{
fatherHandler = father;
Console.WriteLine(text);
}
public override bool InvokeCommand(SubModuleFunctions command, IContext contextHandler)
{
Console.WriteLine("InvokeCommand execution for Image subModule");
ImageContext subModuleContextHandler = contextHandler as ImageContext;
switch (command)
{
case SubModuleFunctions.ImageAdapt:
// improve machine learning
return true;
case SubModuleFunctions.ImageAddPhoto:
// add data to machine learning
return true;
case SubModuleFunctions.ImageComparePhoto:
// query machine learning
return true;
case SubModuleFunctions.ImageStoreResults:
// store results for machine learning
return true;
default:
return false;
}
}
public override bool Init(byte[] context, int sizeOfContext)
{
Console.WriteLine("Init execution");
return true;
}
public override bool UnInit()
{
Console.WriteLine("UnInit execution");
return true;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Text;
using MongoDB.Driver;
using MongoDB.Bson;
namespace IP_Framework.InternalDbHandler
{
class UserHandler
{
private static IMongoCollection<BsonDocument> collection = null;
private static DBInstance dBInstance;
public UserHandler(DBInstance dBInstance)
{
UserHandler.dBInstance = dBInstance;
collection = dBInstance.databaseInstance.GetCollection<BsonDocument>(Config.COLLECTION_USERS_NAME);
}
public void ShowData()
{
dBInstance.ShowDataInCollection(collection);
}
public void InsertUser(UserWrapper user)
{
// TODO :)
BsonArray simptome = new BsonArray { };
dBInstance.InsertDocument(collection,
new BsonDocument
{
{ "userid", user.userid },
{ "simptome", simptome },
{ "lat", user.lat},
{ "lon", user.lon }
}
);
}
public IMongoCollection<BsonDocument> GetCollection()
{
return collection;
}
public List<Point> GetPoints()
{
List<Point> points = new List<Point>();
var documents = collection.Find(new BsonDocument()).ToList();
foreach (BsonDocument doc in documents)
{
try
{
double lon = (double)doc["lon"].ToDouble() * Math.PI / 180.0;
double lat = (double)doc["lat"].ToDouble() * Math.PI / 180.0;
Point p = new Point(lon, lat);
points.Add(p);
}
catch (Exception e)
{
Console.WriteLine(e);
}
}
return points;
}
public List<Point> GetPointsForDisease(String disease)
{
List<Point> points = new List<Point>();
var documents = collection.Find(new BsonDocument()).ToList();
foreach (BsonDocument doc in documents)
{
try
{
var simptoms = doc["simptome"].AsBsonArray;
foreach (var simptom in simptoms)
{
if (simptom == disease)
{
double lon = (double)doc["lon"].ToDouble() * Math.PI / 180.0;
double lat = (double)doc["lat"].ToDouble() * Math.PI / 180.0;
Point p = new Point(lon, lat);
points.Add(p);
break;
}
}
}
catch (Exception e)
{
Console.WriteLine(e);
}
}
return points;
}
public Point GetPointsForUser(String user_id)
{
var documents = collection.Find(new BsonDocument()).ToList();
foreach (BsonDocument doc in documents)
{
try
{
var id = doc["userid"].ToString();
if (id == user_id)
{
double lon = (double)doc["lon"].ToDouble() * Math.PI / 180.0;
double lat = (double)doc["lat"].ToDouble() * Math.PI / 180.0;
Point p = new Point(lon, lat);
return p;
}
}
catch (Exception e)
{
Console.WriteLine(e);
}
}
return null;
}
public List<BsonDocument> GetCollectionData()
{
var documents = collection.Find(new BsonDocument()).ToList();
return documents;
}
}
}
<file_sep>using System;
namespace IP_Framework.API
{
public class SymptomPair
{
public String string1 { get; set; }
public String string2 { get; set; }
}
}
<file_sep>using System;
using IP_Framework.API;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore;
namespace IP_Framework
{
class Program
{
static void Main(string[] args)
{
EventHandler newHandler = new EventHandler();
byte[] array = new byte[100];
EventHandlerContext context = new EventHandlerContext(array, 100);
// InternalDbHandler.DBModule internalDB = Utils.Singleton<InternalDbHandler.DBModule>.Instance;
// internalDB.GetUserHandler().ShowData();
// UserWrapper user = new UserWrapper("3");
// internalDB.GetUserHandler().InsertUser(user);
Console.WriteLine(newHandler.InvokeCommand(context));
CreateWebHostBuilder(args).Build().Run();
}
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<WebStartup>();
}
}
<file_sep>using MongoDB.Bson;
using MongoDB.Bson.Serialization.Attributes;
using MongoDB.Bson.Serialization.IdGenerators;
using System;
using System.Collections.Generic;
using System.Text;
namespace Quizzer
{
public class QuSignature
{
public Dictionary<string, QuSymptom> symptoms;
public string name;
public int initialScore;
public int currentScore;
public int currentPositiveScore;
[BsonId(IdGenerator = typeof(StringObjectIdGenerator))]
[BsonRepresentation(BsonType.ObjectId)]
public string ID { get; set; }
public QuSignature()
{
initialScore = 0;
currentPositiveScore = 0;
}
public void ComputeInitialScore()
{
foreach (var symptom in symptoms)
{
initialScore += symptom.Value.importanta;
}
currentScore = initialScore;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Text;
namespace IP_Framework
{
class GloballyAvailableFunctions
{
}
abstract class IModule
{
public abstract bool InvokeCommand(SubModuleFunctions command, IContext contextHandler);
public abstract bool Init(byte[] context, int sizeOfContext);
public abstract bool UnInit();
}
}
<file_sep>Prima iteratie de framework, WIP
<file_sep>using System;
using System.Collections.Generic;
using System.Text;
using System;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks.Sources;
using Newtonsoft.Json;
using Quizzer;
using IP_Framework.InternalDbHandler;
using IP_Framework.Utils;
namespace Quizzer
{
public class QuSymptomsParser
{
private ISet<QuSignature> signatures;
public ISet<QuSignature> GetSignatures()
{
return signatures;
}
public QuSymptomsParser()
{
signatures = new HashSet<QuSignature>();
}
private string NormalizeJson(string json)
{
return json.Replace("\"deloc\"", "0")
.Replace("\"mic\"", "1")
.Replace("\"mediu\"", "2")
.Replace("\"tare\"", "3");
}
private Answer.QUESTION_SICKNESS_LEVEL DurereNumToEnum(int num)
{
switch (num)
{
case 0:
return Answer.QUESTION_SICKNESS_LEVEL.ABSENT;
case 1:
return Answer.QUESTION_SICKNESS_LEVEL.LITTLE;
case 2:
return Answer.QUESTION_SICKNESS_LEVEL.MEDIUM;
case 3:
return Answer.QUESTION_SICKNESS_LEVEL.HIGH;
default:
return Answer.QUESTION_SICKNESS_LEVEL.ABSENT;
}
}
private void ParseJson(string json)
{
Dictionary<string, QuSymptom> symptoms;
json = NormalizeJson(json);
QuSignature quSignature = new QuSignature();
quSignature = JsonConvert.DeserializeObject<QuSignature>(json);
quSignature.ComputeInitialScore();
foreach (var item in quSignature.symptoms)
{
if (item.Value.tip == QuSymptom.SymptomTypes.NIVEL_DURERE)
{
item.Value.min_durere = DurereNumToEnum((int)(item.Value.min));
item.Value.max_durere = DurereNumToEnum((int)(item.Value.max));
}
}
// QuSignature quSignature = new QuSignature(symptoms);
// quSignature.symptoms = symptoms;
signatures.Add(quSignature);
// Console.WriteLine(symptoms["glicemie"].tip);
}
public void FeedSignatures()
{
DBModule instance = Singleton<DBModule>.Instance;
QuizSigsHandler sigsHandler = instance.GetSigsHandler();
signatures = sigsHandler.GetSignatures();
}
}
}
<file_sep>using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Text;
namespace Quizzer
{
public class Question
{
private string questionText;
private string correspondingSymptom;
private Answer.QUESTION_TYPE questionType;
public string GetCorrespondingSymptom()
{
return correspondingSymptom;
}
public Answer.QUESTION_TYPE GetQuestionType()
{
return questionType;
}
public string GetQuestionText()
{
return questionText;
}
private void SetQuestionText(string questionText)
{
this.questionText = questionText;
}
public Question(string symptomName, string questionText, Answer.QUESTION_TYPE questionType)
{
QuizzerStrategyContext quizzerStrategyContext = new QuizzerStrategyContext();
quizzerStrategyContext.SetContext(questionType);
this.questionText = questionText;
this.questionType = questionType;
this.correspondingSymptom = symptomName;
}
public string ToJson(int id)
{
dynamic jsonObject = new JObject();
jsonObject.id = id;
jsonObject.question = questionText;
switch (questionType)
{
case Answer.QUESTION_TYPE.QUESTION_NUMBER:
jsonObject.tip = "interval";
break;
case Answer.QUESTION_TYPE.QUESTION_SICKNESS_LEVEL:
jsonObject.tip = "nivel_durere";
break;
case Answer.QUESTION_TYPE.QUESTION_BOOLEAN:
jsonObject.tip = "existenta";
break;
}
return jsonObject.ToString();
}
}
}
<file_sep>
namespace IP_Framework.API
{
public class Symptomes
{
public SymptomPair[] symptoms { get; set; }
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Text;
namespace Quizzer
{
interface IQuizzerStrategy
{
string GetQuestionString(string symptomName);
bool ApplyAnswerToSignature(QuSignature signature, string symptomName, Answer answer);
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Text;
namespace IP_Framework
{
// the user wrapper. todo everything here
class UserWrapper
{
public string userid { get; set; }
List<string> Symptoms { get; set; }
public String lat { get; set; }
public String lon { get; set; }
public UserWrapper(string userid)
{
this.userid = userid;
Symptoms = new List<string>();
lat = "";
lon = "";
}
public void AddNewSymptom(string symptom)
{
Symptoms.Add(symptom);
}
public bool HasSymptom(string Symptom)
{
return Symptoms.Contains(Symptom);
}
public bool HasSymptomInArea(string Symptom)
{
return true;
}
public void SetLon(String lon)
{
this.lon = lon;
}
public void SetLat(String lat)
{
this.lat = lat;
}
}
}
<file_sep>using MongoDB.Driver.Core.Events;
using System;
using System.Collections.Generic;
using System.Text;
namespace Quizzer
{
public class QuizHandler
{
private Dictionary<long, Quiz> quizes;
public QuizHandler()
{
quizes = new Dictionary<long, Quiz>();
}
public void RemoveById(long id)
{
if (quizes.ContainsKey(id))
{
quizes.Remove(id);
}
}
public Question GetQuestion(long id)
{
if (quizes.ContainsKey(id))
{
return quizes[id].GetNextQuestion();
}
else
{
QuSymptomsParser symptomsParser = new QuSymptomsParser();
symptomsParser.FeedSignatures();
ISet <QuSignature> signatures = symptomsParser.GetSignatures();
SymptomsHolder symptomsHolder = new SymptomsHolder(signatures);
Quiz quiz = new Quiz(symptomsHolder);
quizes.Add(id, quiz);
quiz.BeginQuiz();
return quiz.GetNextQuestion();
}
}
public Quiz GetQuizById(int id)
{
return quizes[id];
}
public bool ProcessAnswer(long id, Answer answer)
{
if (quizes.ContainsKey(id))
{
return quizes[id].ProcessAnswer(answer);
}
return false;
}
}
}
<file_sep>using System;
namespace IP_Framework.API
{
public class FormQuestion
{
private String question;
private int id;
private String type;
public FormQuestion(String question, int id, String type)
{
this.question = question;
this.id = id;
this.type = type;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Jint; // javascript interpretor for .net
namespace IP_Framework
{
class Signature
{
public static class PriorityConstants
{
public const string PRIORITY_HIGH = "PRIORITY_HIGH";
public const string PRIORITY_MEDIUM = "PRIORITY_HIGH";
public const string PRIORITY_LOW = "PRIORITY_HIGH";
};
public string sigData { get; set; }
int _priority;
public int priority {
get {
return _priority;
}
set {
if (value <= 0) _priority = 0;
else if (value > 10) _priority = 10;
else { _priority = value; }
}
}
}
class Sandbox : IModule
{
static class Messages
{
public const string VALIDATION_OK = "OK";
}
private Engine engine; // javascript engine
private UserWrapper userInstance;
private List<Signature> signatures;
private string ValidateJS(string javascriptCode)
{
string[] badWords =
{
"function", "class", "window", "document", "promise",
"async", "await", "let", "const"
};
foreach (var word in badWords)
{
if (javascriptCode.Contains(word))
{
return word;
}
}
return "OK";
}
private void Execute(string Rules)
{
string JSCode = @"function Signature() {" + Environment.NewLine;
JSCode += Rules + Environment.NewLine;
JSCode += @"}" + Environment.NewLine + "Signature()";
//Console.Write(JSCode);
engine.Execute(JSCode);
}
public void ExecuteAllSigs()
{
foreach (var sig in signatures)
{
Execute(sig.sigData);
}
}
// loads all signatures
public void LoadSignatures(string sigFolderPath)
{
signatures = new List<Signature>();
foreach (var file in Directory.EnumerateFiles(sigFolderPath))
{
Signature sig = new Signature();
string sigData = File.ReadAllText(file);
sig.priority = 1;
if (sigData.Contains(Signature.PriorityConstants.PRIORITY_HIGH))
{
sig.priority = 3;
}
else if (sigData.Contains(Signature.PriorityConstants.PRIORITY_MEDIUM))
{
sig.priority = 2;
}
else if (sigData.Contains(Signature.PriorityConstants.PRIORITY_LOW))
{
sig.priority = 1;
}
sigData = sigData.Replace(Signature.PriorityConstants.PRIORITY_HIGH, ":(")
.Replace(Signature.PriorityConstants.PRIORITY_MEDIUM, "")
.Replace(Signature.PriorityConstants.PRIORITY_LOW, "");
if (ValidateJS(sigData) == Messages.VALIDATION_OK)
{
sig.sigData = sigData;
signatures.Add(sig);
}
}
signatures = signatures.OrderByDescending(x => x.priority).ToList();
}
public override bool Init(byte[] context, int sizeOfContext)
{
// todo scos user din context
userInstance = new UserWrapper("Cornel");
return true;
}
private void ResetEngine()
{
engine = new Engine()
.SetValue("log", new Action<object>(Console.WriteLine))
.SetValue("hasSymptom", new Func<string, bool>(userInstance.HasSymptom))
.SetValue("hasSymptomInArea", new Func<string, bool>(userInstance.HasSymptom))
.SetValue("addNewSymptom", new Action<string>(userInstance.AddNewSymptom));
}
public override bool InvokeCommand(SubModuleFunctions command, IContext contextHandler)
{
switch (command)
{
case SubModuleFunctions.CheckSigsForUser:
ResetEngine();
ExecuteAllSigs();
return true;
case SubModuleFunctions.ReloadSigs:
LoadSignatures("../../../signatures");
return true;
default:
return false;
}
}
public override bool UnInit()
{
return true;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Text;
namespace IP_Framework.InternalDbHandler
{
class DBModule
{
private static UserHandler userHandler;
private static QuizSigsHandler sigsHandler;
private static NotificationsHandler notifHandler;
public DBModule()
{
userHandler = new UserHandler(Utils.Singleton<DBInstance>.Instance);
sigsHandler = new QuizSigsHandler(Utils.Singleton<DBInstance>.Instance);
notifHandler = new NotificationsHandler(Utils.Singleton<DBInstance>.Instance);
}
public UserHandler GetUserHandler()
{
return userHandler;
}
public QuizSigsHandler GetSigsHandler()
{
return sigsHandler;
}
public NotificationsHandler GetNotifHandler()
{
return notifHandler;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Text;
namespace IP_Framework.API
{
public class DiagnosticReport
{
private String name;
private Double percentage;
public DiagnosticReport(String name, Double percentage)
{
this.name = name;
this.percentage = percentage;
}
public string GetName()
{
return name;
}
public Double GetPercentage()
{
return percentage;
}
}
}
<file_sep>using Microsoft.AspNetCore.Antiforgery.Internal;
using MongoDB.Driver.Core.Events;
using Quizzer;
using System;
using System.Collections.Generic;
using System.Text;
namespace IP_Framework
{
class SymptomBasedDetection : IModule
{
private EventHandler fatherHandler;
private String text = "SymptomBasedDetection constructor";
private QuizHandler quizHandler;
public SymptomBasedDetection(EventHandler father)
{
fatherHandler = father;
Console.WriteLine(text);
}
public override bool InvokeCommand(SubModuleFunctions command, IContext contextHandler)
{
Console.WriteLine("InvokeCommand execution for Form SubModule");
Question question;
SymptomContext symptomContext = contextHandler as SymptomContext;
switch (command)
{
case SubModuleFunctions.GetQuestion:
question = quizHandler.GetQuestion(symptomContext.id);
if (question == null)
{
symptomContext.response = "invalid";
return true;
}
symptomContext.response = question.ToJson(symptomContext.id);
return true;
case SubModuleFunctions.SendResponse:
Answer answer = InitAnswer(symptomContext);
quizHandler.ProcessAnswer(symptomContext.id, answer);
question = quizHandler.GetQuestion(symptomContext.id);
if(question == null && quizHandler.GetQuizById(symptomContext.id).IsQuizFinished())
{
symptomContext.response = quizHandler.GetQuizById(symptomContext.id).GetSymptomsHolder().GetJsonVerdictAsync(symptomContext.id).Result;
quizHandler.RemoveById(symptomContext.id);
return true;
}
symptomContext.response = question.ToJson(symptomContext.id);
return true;
default:
return false;
}
}
private Answer InitAnswer(SymptomContext context)
{
Quiz currentQuiz = quizHandler.GetQuizById(context.id);
Answer.QUESTION_TYPE answerType = currentQuiz.GetCurrentQuestionType();
Answer answer = new Answer(answerType, currentQuiz.GetCurrentSymptom());
switch (answerType)
{
case Answer.QUESTION_TYPE.QUESTION_BOOLEAN:
if (context.status > 0)
{
answer.SetAnswerBoolean(Answer.QUESTION_BOOLEAN.TRUE);
}
else
{
answer.SetAnswerBoolean(Answer.QUESTION_BOOLEAN.FALSE);
}
break;
case Answer.QUESTION_TYPE.QUESTION_NUMBER:
answer.SetAnswerNumeric(context.status);
break;
case Answer.QUESTION_TYPE.QUESTION_SICKNESS_LEVEL:
switch (context.status)
{
case 0:
answer.SetAnswerSicknessLevel(Answer.QUESTION_SICKNESS_LEVEL.ABSENT);
break;
case 1:
answer.SetAnswerSicknessLevel(Answer.QUESTION_SICKNESS_LEVEL.LITTLE);
break;
case 2:
answer.SetAnswerSicknessLevel(Answer.QUESTION_SICKNESS_LEVEL.MEDIUM);
break;
case 3:
answer.SetAnswerSicknessLevel(Answer.QUESTION_SICKNESS_LEVEL.HIGH);
break;
}
break;
}
return answer;
}
public override bool Init(byte[] context, int sizeOfContext)
{
Console.WriteLine("Init execution");
quizHandler = new QuizHandler();
return true;
}
public override bool UnInit()
{
Console.WriteLine("UnInit execution");
return true;
}
}
}
<file_sep>import os
import numpy as np
from PIL import Image
"""
returns patches, a matrix of PIL.Image objects of the given size
"""
def split_image(img, size = (50,50)):
maxX, maxY = img.width, img.height
cols = (maxX+size[0]-1)//size[0]
rows = (maxY+size[1]-1)//size[1]
patches = [[0 for x in range(rows)] for y in range(cols)]
new_im = Image.new('RGB',(cols*size[0],rows*size[1]),color=(255,255,255))
new_im.paste(img)
print(len(patches),len(patches[0]))
for x in range(1,maxX,50):
for y in range(1,maxY,50):
patch = new_im.crop((x,y,x+50,y+50))
patches[x//50][y//50] = patch
return patches
def split_file(filename,size = (50,50)):
if(not os.path.isfile(filename)):
return 0
img = Image.open(filename)
return split_image(img)
split_file('8863.png')
<file_sep>using System;
using System.Collections.Generic;
using System.Text;
namespace Quizzer
{
class QuestionSicknessLevelStrategy : IQuizzerStrategy
{
public bool ApplyAnswerToSignature(QuSignature signature, string symptomName, Answer answer)
{
Answer.QUESTION_SICKNESS_LEVEL minRequiredSicknessLevel = signature.symptoms[symptomName].min_durere;
Answer.QUESTION_SICKNESS_LEVEL maxRequiredSicknessLevel = signature.symptoms[symptomName].max_durere;
Answer.QUESTION_SICKNESS_LEVEL answerValue = answer.GetAnswerSicknessLevel();
if (answerValue >= minRequiredSicknessLevel && answerValue <= maxRequiredSicknessLevel)
{
signature.currentPositiveScore += signature.symptoms[symptomName].importanta;
return true;
}
signature.currentScore -= signature.symptoms[symptomName].importanta;
return false;
}
public string GetQuestionString(string symptomName)
{
return ("Te doare " + symptomName + "? Daca da, cat de tare?");
}
}
}
<file_sep>namespace IP_Framework
{
class Point
{
public double x { get; set; }
public double y { get; set; }
public Point()
{
x = 0.0f;
y = 0.0f;
}
public Point(double x, double y)
{
this.x = x;
this.y = y;
}
public static bool operator >(Point A, Point B)
{
if (A.x != B.x)
{
return A.y > B.y;
}
return A.x > B.x;
}
public static bool operator <(Point A, Point B)
{
if (A.x != B.x)
{
return A.y < B.y;
}
return A.x < B.x;
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Text;
namespace IP_Framework.API
{
public class Command
{
public int uid { get; set; }
public string command { get; set; }
public String[] parameters { get; set; }
}
}
<file_sep>if(hasSymptom('pl mica') && hasSymptom('Smecheras')) log('Fraier');<file_sep>using System;
using System.Collections.Generic;
using System.Text;
namespace Quizzer
{
class QuestionBooleanStrategy : IQuizzerStrategy
{
public bool ApplyAnswerToSignature(QuSignature signature, string symptomName, Answer answer)
{
bool requiredAnswer = signature.symptoms[symptomName].valoare;
bool answerValue = answer.GetAnswerBoolean();
if (requiredAnswer == answerValue)
{
signature.currentPositiveScore += signature.symptoms[symptomName].importanta;
return true;
}
signature.currentScore -= signature.symptoms[symptomName].importanta;
return false;
}
public string GetQuestionString(string symptomName)
{
return ("Te doare " + symptomName + "?");
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Text;
using MongoDB.Bson;
using MongoDB.Driver;
using Newtonsoft.Json.Linq;
namespace IP_Framework.InternalDbHandler
{
class NotificationsHandler
{
private static IMongoCollection<BsonDocument> collection = null;
private static DBInstance dBInstance;
public bool InsertNotification(BsonDocument doc)
{
collection.InsertOne(doc);
return true;
}
public bool InsertNotificationToAllAffectedUsers(Point user, double distance, String disease)
{
Point point = new Point();
DBModule instance = Utils.Singleton<DBModule>.Instance;
UserHandler userHandler = instance.GetUserHandler();
var documents = userHandler.GetCollectionData();
foreach (BsonDocument doc in documents)
{
try
{
point.x = (double)doc["lon"].ToDouble() * Math.PI / 180.0;
point.y = (double)doc["lat"].ToDouble() * Math.PI / 180.0;
if (ConvexHaul.Distance(user, point) < distance)
{
BsonDocument document = new BsonDocument();
document["id_user"] = doc["userid"];
document["text"] = disease;
BsonArray temp = new BsonArray();
document["links"] = temp;
InsertNotification(document);
}
}
catch (Exception e)
{
Console.WriteLine(e);
}
}
return true;
}
public NotificationsHandler(DBInstance dBInstance)
{
NotificationsHandler.dBInstance = dBInstance;
collection = dBInstance.databaseInstance.GetCollection<BsonDocument>(Config.COLLECTION_NOTIFICATIONS);
}
public void ShowData()
{
dBInstance.ShowDataInCollection(collection);
}
public BsonArray GetAllNotifs(String user_id)
{
List<Point> points = new List<Point>();
BsonArray notifs = new BsonArray();
var documents = collection.Find(new BsonDocument()).ToList();
foreach (BsonDocument doc in documents)
{
try
{
if (doc["id_user"] == user_id)
{
doc["category"] = "Epidemie";
doc.Remove("_id");
notifs.Add(doc);
}
}
catch (Exception e)
{
Console.WriteLine(e);
}
}
return notifs;
}
}
}
<file_sep>using System;
using IP_Framework.InternalDbHandler;
using IP_Framework.Utils;
using Microsoft.AspNetCore.Mvc;
using Microsoft.CodeAnalysis;
using Newtonsoft.Json.Linq;
using System.Net.Http;
using MongoDB.Bson;
namespace IP_Framework.API
{
[Route("api/v1/detectionapi")]
[ApiController]
public class DetectionApiController : ControllerBase
{
[HttpPost("example")]
public string Post([FromForm] Symptomes symptomeList)
{
var json = symptomeList.ToString();
IContext context = new IContext(json);
EventHandlerContext eventHandlerContext = new EventHandlerContext();
eventHandlerContext.contextHandler = context;
eventHandlerContext.command = EventHandlerFunctions.SymptomLearningModule;
eventHandlerContext.subModuleCommand = SubModuleFunctions.MachineLearningStoreResults;
EventHandler eventHandler = new EventHandler();
eventHandler.InvokeCommand(eventHandlerContext);
var response = HttpContext.Response;
response.Headers.Add("Access-Control-Allow-Headers", "Content-Type");
response.Headers.Add("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
response.Headers.Add("Access-Control-Allow-Origin", "*");
return "succes";
}
[HttpPost("check-epidemic-haul")]
public string PostHaul( [FromBody] JObject data)
{
EventHandler eventHandler = new EventHandler();
EpidemyContext context = new EpidemyContext();
if (data.ContainsKey("disease"))
{
context.specificSearch = data["disease"].ToObject<String>();
}
else
{
context.specificSearch = null;
}
EventHandlerContext eventHandlerContext = new EventHandlerContext();
eventHandlerContext.contextHandler = context;
eventHandlerContext.command = EventHandlerFunctions.EpidemyAlertModule;
eventHandlerContext.subModuleCommand = SubModuleFunctions.EpidemyCheckForAreas;
eventHandler.InvokeCommand(eventHandlerContext);
var response = HttpContext.Response;
response.Headers.Add("Access-Control-Allow-Headers", "Content-Type");
response.Headers.Add("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
response.Headers.Add("Access-Control-Allow-Origin", "*");
return context.json;
}
[HttpPost("get-question")]
public string Post([FromBody] JObject data) {
int id = data["id"].ToObject<int>();
byte[] idBytes = BitConverter.GetBytes(id);
IContext context = new SymptomContext(id, 0);
EventHandlerContext eventHandlerContext = new EventHandlerContext(idBytes, idBytes.Length);
eventHandlerContext.command = EventHandlerFunctions.SymptomBasedDetectionModule;
eventHandlerContext.subModuleCommand = SubModuleFunctions.GetQuestion;
eventHandlerContext.contextHandler = context;
EventHandler eventHandler = EventHandler.GetInstance();
eventHandler.InvokeCommand(eventHandlerContext);
var response = HttpContext.Response;
if(response != null) {
response.Headers.Add("Access-Control-Allow-Headers", "Content-Type");
response.Headers.Add("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
response.Headers.Add("Access-Control-Allow-Origin", "*");}
return (context as SymptomContext).response;
}
[HttpOptions("get-question")]
public void QuestionOptions()
{
var response = HttpContext.Response;
response.Headers.Add("Access-Control-Allow-Headers", "Content-Type");
response.Headers.Add("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
response.Headers.Add("Access-Control-Allow-Origin", "*");
return;
}
[HttpOptions("send-response")]
public void ResponseOptions()
{
var response = HttpContext.Response;
response.Headers.Add("Access-Control-Allow-Headers", "Content-Type");
response.Headers.Add("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
response.Headers.Add("Access-Control-Allow-Origin", "*");
return;
}
[HttpPost("send-response")]
public string PostResponse([FromBody] JObject data)
{
//TODO: de scos cod redundant
int id = data["id"].ToObject<int>();
float status = data["status"].ToObject<float>();
byte[] idBytes = BitConverter.GetBytes(id);
IContext context = new SymptomContext(id, status);
EventHandlerContext eventHandlerContext = new EventHandlerContext(idBytes, idBytes.Length);
eventHandlerContext.command = EventHandlerFunctions.SymptomBasedDetectionModule;
eventHandlerContext.subModuleCommand = SubModuleFunctions.SendResponse;
eventHandlerContext.contextHandler = context;
EventHandler eventHandler = EventHandler.GetInstance();
eventHandler.InvokeCommand(eventHandlerContext);
var response = HttpContext.Response;
if (response != null)
{
response.Headers.Add("Access-Control-Allow-Headers", "Content-Type");
response.Headers.Add("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
response.Headers.Add("Access-Control-Allow-Origin", "*");
}
return (context as SymptomContext).response;
}
[HttpPost("check-epidemic")]
public String GetEpidemic([FromBody] JObject data)
{
EventHandler eventHandler = new EventHandler();
EpidemyContext context = new EpidemyContext();
context.specificSearch = data["disease"].ToObject<String>();
context.user_id = data["user_id"].ToObject<String>();
EventHandlerContext eventHandlerContext = new EventHandlerContext();
eventHandlerContext.contextHandler = context;
eventHandlerContext.command = EventHandlerFunctions.EpidemyAlertModule;
eventHandlerContext.subModuleCommand = SubModuleFunctions.EpidemyCheckForAlert;
eventHandler.InvokeCommand(eventHandlerContext);
var response = HttpContext.Response;
response.Headers.Add("Access-Control-Allow-Headers", "Content-Type");
response.Headers.Add("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
response.Headers.Add("Access-Control-Allow-Origin", "*");
return context.json;
}
[HttpPost("get-notifications")]
public string GetNotifs([FromBody] JObject data)
{
EventHandler eventHandler = new EventHandler();
EpidemyContext context = new EpidemyContext();
context.specificSearch = data["id"].ToObject<String>();
EventHandlerContext eventHandlerContext = new EventHandlerContext();
eventHandlerContext.contextHandler = context;
eventHandlerContext.command = EventHandlerFunctions.EpidemyAlertModule;
eventHandlerContext.subModuleCommand = SubModuleFunctions.GetAllNotifications;
eventHandler.InvokeCommand(eventHandlerContext);
var response = HttpContext.Response;
response.Headers.Add("Access-Control-Allow-Headers", "Content-Type");
response.Headers.Add("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
response.Headers.Add("Access-Control-Allow-Origin", "*");
return context.json;
}
[HttpOptions("get-notifications")]
public void NotificationOptions()
{
var response = HttpContext.Response;
response.Headers.Add("Access-Control-Allow-Headers", "Content-Type");
response.Headers.Add("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
response.Headers.Add("Access-Control-Allow-Origin", "*");
return;
}
[HttpPost("get-internal-id")]
public async System.Threading.Tasks.Task<string> GetEpidemicAsync([FromBody] String id)
{
DBModule internalDB = Singleton<DBModule>.Instance;
Console.WriteLine(id);
var documents = internalDB.GetUserHandler().GetCollectionData();
foreach (BsonDocument doc in documents)
try {
{
Console.WriteLine(doc.ToString());
if ((String)doc["userid"] == id)
return "Exists";
}
}
catch(Exception e)
{
Console.WriteLine("Bad data");
}
//return "exists";
HttpClient client = new HttpClient();
var responseString = await client.GetStringAsync("https://auth-service-ip.herokuapp.com/dbAPI/diagnosisInfo/" + id);
UserWrapper user = new UserWrapper(id);
string toBeSearched = "\"longitude\":";
string lon = responseString.Substring(responseString.IndexOf(toBeSearched) + toBeSearched.Length);
lon = lon.Remove(lon.Length - 1);
Console.WriteLine(lon);
String lat = responseString.Split(',')[1];
toBeSearched = "\"latitude\":";
lat = lat.Substring(lat.IndexOf(toBeSearched) + toBeSearched.Length);
Console.WriteLine(lat);
user.SetLat(lat);
user.SetLon(lon);
internalDB.GetUserHandler().InsertUser(user);
return "Created";
}
}
}
<file_sep>using Microsoft.VisualStudio.TestTools.UnitTesting;
using IP_Framework.API;
using System;
using System.Collections.Generic;
using System.Text;
using Moq;
using Microsoft.AspNetCore.Http;
using Newtonsoft.Json;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json.Linq;
using System.Linq;
namespace IP_Framework.API.Tests
{
[TestClass()]
public class DetectionApiControllerTests
{
private TestContext testContextInstance;
public TestContext TestContext
{
get { return testContextInstance; }
set { testContextInstance = value; }
}
[TestMethod()]
public void PostTest()
{
String[] eyeQuestions = { "\"Simti durere la nivelul ochilor?\"", "\"Ai roseata in ochi prezenta?\"" , "\"Ai experimentat recent o lacrimare intensa a ochilor?\"" };
var request = new Mock<HttpRequest>();
request.Setup(x => x.Scheme).Returns("http");
request.Setup(x => x.Host).Returns(HostString.FromUriComponent("http://localhost:5080"));
request.Setup(x => x.PathBase).Returns(PathString.FromUriComponent("/api/v1/detectionapi/get-question"));
String str = "{\"id\":1,\"status\":37.3}";
var httpContext = Mock.Of<HttpContext>(_ =>
_.Request == request.Object
);
var controllerContext = new ControllerContext()
{
HttpContext = httpContext,
};
var controller = new DetectionApiController()
{
ControllerContext = controllerContext,
};
String expected = "{@ \"id\": 1,@\"question\": \"Te rugam sa introduci temperatura corpului tau:\",@\"tip\": \"interval\"@}";
expected = expected.Replace("@", "\n");
//Act
JObject json = JObject.Parse(str);
string actual = controller.Post(json);
String question = actual.Split(',')[1];
String toBeSearched = "\"question\": ";
question = question.Substring(question.IndexOf(toBeSearched) + toBeSearched.Length);
if(question == "\"Te rugam sa introduci temperatura corpului tau:\"")
{
var secondStr = "{\"id\": 1, \"status\":37.3}";
var secondJson = JObject.Parse(secondStr);
var sendResponse = controller.PostResponse(secondJson);
JObject statusEsential = JObject.Parse("{\"id\": 1, \"status\":1}");
JObject statusOthers = JObject.Parse("{\"id\": 1, \"status\":0}");
while (!sendResponse.Contains("verdict"))
{
TestContext.WriteLine(sendResponse);
question = sendResponse.Split(',')[1];
question = question.Substring(question.IndexOf(toBeSearched) + toBeSearched.Length);
if (eyeQuestions.Contains(question))
sendResponse = controller.PostResponse(statusEsential);
else
sendResponse = controller.PostResponse(statusOthers);
}
string verdict = sendResponse.Split("\"")[3];
actual = verdict;
}
expected = "conjunctivita";
//Assert
Assert.AreEqual(expected, actual);
}
}
}<file_sep>using MongoDB.Bson;
using MongoDB.Bson.Serialization;
using MongoDB.Driver;
using Quizzer;
using System;
using System.Collections.Generic;
using System.Reflection.Metadata;
using System.Text;
namespace IP_Framework.InternalDbHandler
{
class QuizSigsHandler
{
private static IMongoCollection<BsonDocument> collection = null;
private static DBInstance dBInstance;
public QuizSigsHandler(DBInstance dBInstance)
{
QuizSigsHandler.dBInstance = dBInstance;
collection = dBInstance.databaseInstance.GetCollection<BsonDocument>(Config.COLLECTION_QUIZSIGS);
}
public void ShowData()
{
dBInstance.ShowDataInCollection(collection);
}
public void InsertUser(UserWrapper user)
{
// TODO :)
BsonArray simptome = new BsonArray { };
dBInstance.InsertDocument(collection,
new BsonDocument
{
{ "userid", user.userid },
{ "simptome", simptome }
}
);
}
public List<Point> GetPoints()
{
List<Point> points = new List<Point>();
var documents = collection.Find(new BsonDocument()).ToList();
foreach (BsonDocument doc in documents)
{
try
{
double lon = (double)doc["lon"] * Math.PI / 180.0;
double lat = (double)doc["lat"] * Math.PI / 180.0;
Point p = new Point(lon, lat);
points.Add(p);
}
catch (Exception e)
{
Console.WriteLine(e);
}
}
return points;
}
public List<Point> GetPointsForDisease(String disease)
{
List<Point> points = new List<Point>();
var documents = collection.Find(new BsonDocument()).ToList();
foreach (BsonDocument doc in documents)
{
try
{
if (doc["disease"] == disease)
{
double lon = (double)doc["lon"] * Math.PI / 180.0;
double lat = (double)doc["lat"] * Math.PI / 180.0;
Point p = new Point(lon, lat);
points.Add(p);
}
}
catch (Exception e)
{
Console.WriteLine(e);
}
}
return points;
}
public ISet<QuSignature> GetSignatures()
{
ISet<QuSignature> signatures = new HashSet<QuSignature>();
var documents = collection.Find(new BsonDocument()).ToList();
foreach (BsonDocument doc in documents)
{
QuSignature signature = new QuSignature();
signature = BsonSerializer.Deserialize<QuSignature>(doc);
foreach(QuSymptom symptom in signature.symptoms.Values)
{
symptom.SetPainLevel();
}
signature.ComputeInitialScore();
signatures.Add(signature);
}
return signatures;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Text;
namespace Quizzer
{
class QuestionNumberStrategy : IQuizzerStrategy
{
public bool ApplyAnswerToSignature(QuSignature signature, string symptomName, Answer answer)
{
double minRequiredAnswer = signature.symptoms[symptomName].min;
double maxRequiredAnswer = signature.symptoms[symptomName].max;
double answerValue = answer.GetAnswerNumeric();
if (answerValue >= minRequiredAnswer && answerValue <= maxRequiredAnswer)
{
signature.currentPositiveScore += signature.symptoms[symptomName].importanta;
return true;
}
signature.currentScore -= signature.symptoms[symptomName].importanta;
return false;
}
public string GetQuestionString(string symptomName)
{
return ("Estimeaza numeric valoarea " + symptomName + ".");
}
}
}
<file_sep>using System;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.InteropServices.WindowsRuntime;
using System.Text;
namespace Quizzer
{
public class Quiz
{
public enum QUIZ_STATE
{
INIT,
ANSWERING,
ANSWERED,
FINISHED
}
QUIZ_STATE quizState;
private IList<Answer> answers;
private IList<Question> questions;
private int currentQuestionNumber;
private ISet<int> askedQuestions;
private SymptomsHolder symptomsHolder;
private Answer.QUESTION_TYPE currentQuestionType;
private string currentSymptomType;
private const int maxQuestionCount = 7;
private const int finalSignatureCount = 3;
public Answer.QUESTION_TYPE GetCurrentQuestionType()
{
return currentQuestionType;
}
public string GetCurrentSymptom()
{
return currentSymptomType;
}
public Quiz(SymptomsHolder symptomsHolder)
{
quizState = QUIZ_STATE.INIT;
questions = new List<Question>();
answers = new List<Answer>();
askedQuestions = new HashSet<int>();
currentQuestionNumber = 0;
this.symptomsHolder = symptomsHolder;
}
public bool BeginQuiz()
{
if (quizState != QUIZ_STATE.INIT)
{
return false;
}
quizState = QUIZ_STATE.ANSWERED;
return true;
}
public SymptomsHolder GetSymptomsHolder()
{
return symptomsHolder;
}
public Question GetNextQuestion()
{
if (quizState != QUIZ_STATE.ANSWERED)
{
return null;
}
if (askedQuestions.Count >= maxQuestionCount || symptomsHolder.GetSignaturesCount() <= finalSignatureCount)
{
quizState = QUIZ_STATE.FINISHED;
return null;
}
quizState = QUIZ_STATE.ANSWERING;
Question nextQuestion = symptomsHolder.GetNextQuestion();
if(nextQuestion == null)
{
quizState = QUIZ_STATE.FINISHED;
return null;
}
currentQuestionType = nextQuestion.GetQuestionType();
currentSymptomType = nextQuestion.GetCorrespondingSymptom();
return nextQuestion;
}
public bool IsQuizFinished()
{
return quizState == QUIZ_STATE.FINISHED;
}
public bool ProcessAnswer(Answer answer)
{
if (quizState != QUIZ_STATE.ANSWERING || answer.GetAnswerType() != currentQuestionType)
{
return false;
}
symptomsHolder.ProcessAnswer(answer);
answers.Add(answer);
currentQuestionNumber++;
quizState = QUIZ_STATE.ANSWERED;
return true;
}
public IList<Answer> GetAnswers()
{
if (quizState != QUIZ_STATE.FINISHED)
{
return null;
}
return answers;
}
}
}
<file_sep>import web
import shutil
import PIL
from PIL import Image
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
from tensorflow import keras
from keras import layers
from keras.utils.np_utils import to_categorical
import cv2
import numpy as np
import sklearn
import os
from image_functions import *
render = web.template.render('templates/')
db = web.database(
dbn='mysql',
host='127.0.0.1',
port=3306,
user='stefy',
pw='<PASSWORD>',
db='pytest'
)
urls = (
'/', 'index',
'/add', 'add',
'/upload_image', 'upload_image',
'/upload_book','upload_book',
'/upload','Upload',
'/result','result',
'/images/(.*)','get_image'
)
class index:
def GET(self):
print("something")
todos = db.select('carti')
return render.index(todos)
class add:
def POST(self):
i = web.input()
n = db.insert('carti', isbn = i.isbn,titlu=i.titlu,autor=i.autor)
raise web.seeother('/')
class upload_book:
def GET(self):
print("another thing")
return render.upload_book()
class upload_image:
def GET(self):
print("yet another thing")
return render.upload_image()
class Upload:
def POST(self):
x = web.input(myfile={})
print(type(x))
print(type(x['myfile']))
web.debug(x['myfile'].filename) # This is the filename
#web.debug(x['myfile'].value) # This is the file contents
#web.debug(x['myfile'].file.read()) # Or use a file(-like) object
w = open("static/images/resources/tmp.png",'wb')
w.write(x['myfile'].file.read())
w.close()
#"""
total, blanks, pozitives, percent = analyse_by_name(
"static/images/resources/tmp.png",
"static/images/resources/tmp_rez.png",
"the_one")
#"""
#total, blanks, pozitives, percent = 1,2,3,4
w = open("templates/images/resources/tmp_rez.png",'rb')
w.close()
print(render.result(total,blanks,pozitives, percent,"images/resources/tmp_rez.png"))
return render.result(total,blanks,pozitives, percent,"images/resources/tmp_rez.png")
class result:
def GET(self):
raise web.seeother('/')
def POST(self):
raise web.seeother('/')
class get_image:
def GET(self,fileName):
imageBinary = open("/templates/images/"+fileName,'rb').read()
return imageBinary
if __name__ == "__main__":
app = web.application(urls, globals())
app.run()<file_sep>import sys
import os
import numpy as np
from glob import glob
from PIL import Image
def global_image_path(b,x,y,pic):
return '/home/stefy/cpp/ProiectIP/IDC_regular_ps50_idx5/' + pic + '/' + str(b) + '/' + pic + '_idx5_x' + str(x) + '_y' + str(y) + '_class' + str(b) + '.png'
def save_image(pic):
if(not os.path.isdir('/home/stefy/cpp/ProiectIP/IDC_regular_ps50_idx5/' + pic)):
print(pic + ' - unsuccessfull')
return
imagePatches = glob('/home/stefy/cpp/ProiectIP/IDC_regular_ps50_idx5/' + pic + '/**/*.png', recursive=True)
#print(type(imagePatches))
#print(type(imagePatches[0]))
#print(imagePatches[0])
path = '/home/stefy/cpp/ProiectIP/IDC_regular_ps50_idx5/' + pic + '/0/' + pic + '_idx5_x951_y851_class0.png'
def image_path(b,x,y):
return global_image_path(b,x,y,pic)
#print(path)
#print(imagePatches.__contains__(image_path(0,951,851)))
maxX = 0
maxY = 0
for x in range(1,10002,50):
for y in range(1,10002,50):
if imagePatches.__contains__(image_path(0,x,y)):
#contains[x//50][y//50] = 0
if(x > maxX): maxX = x
if(y > maxY): maxY = y
elif imagePatches.__contains__(image_path(1,x,y)):
#contains[x//50][y//50] = 1
if(x > maxX): maxX = x
if(y > maxY): maxY = y
#else: contains[x//50][y//50] = -1
#contains = np.zeros([maxX//50+1,maxY//50+1])
old_img = Image.open('/home/stefy/cpp/ProiectIP/IDC_regular_ps50_idx5/' + pic + '/' + pic+".png")
#print(maxX+49,maxY+49)
#print(old_img.width,old_img.height)
if( (int)(old_img.width) == (int)(maxX+49) and (int)(old_img.height) == (int)(maxY+49) ):
print(pic + ' - file already exists')
return
new_im = Image.new('RGB',(maxX+49,maxY+49),color=(255,255,255))
#new_im.save("blank.jpg")
for x in range(1,maxX+1,50):
for y in range(1,maxY+1,50):
if imagePatches.__contains__(image_path(0,x,y)):
#contains[x//50][y//50] = 0
im_to_paste = Image.open(image_path(0,x,y))
new_im.paste(im_to_paste,(x,y))
elif imagePatches.__contains__(image_path(1,x,y)):
#contains[x//50][y//50] = 1
im_to_paste = Image.open(image_path(1,x,y))
new_im.paste(im_to_paste,(x,y))
#else: contains[x//50][y//50] = -1
#print(contains)
#print(contains.shape)
new_im.save('/home/stefy/cpp/ProiectIP/IDC_regular_ps50_idx5/' + pic + '/' + pic+".png")
#print(maxX,maxY)
#print(len(imagePatches))
print(pic + ' - successfull')
#save_image('8955')
def add_blank(pic):
if(not os.path.isdir('/home/stefy/cpp/ProiectIP/IDC_regular_ps50_idx5/' + pic)):
print(pic + ' - unsuccessfull')
return
if( os.path.isfile(global_image_path(0,1,1,pic)) or os.path.isfile(global_image_path(0,1,1,pic)) ):
print(pic + ' - file already exists')
return
blank = Image.new('RGB',(50,50),color=(255,255,255))
#print(blank.width,blank.height)
blank.save(global_image_path(0,1,1,pic))
print(pic + ' - successfull')
#"""
for i in range(8863,16900):
#add_blank(str(i))
save_image(str(i))
#"""
#save_image('8863')<file_sep>using System;
using System.Collections.Generic;
using System.Text;
namespace IP_Framework
{
class DataBaseHandler : IModule
{
private EventHandler fatherHandler;
private String text = "DataBaseHandler constructor";
public DataBaseHandler(EventHandler father)
{
fatherHandler = father;
Console.WriteLine(text);
}
public override bool InvokeCommand(SubModuleFunctions command, IContext contextHandler)
{
Console.WriteLine("InvokeCommand execution for Database subModule");
DataBaseContext subModuleContextHandler = contextHandler as DataBaseContext;
string answer;
switch (command)
{
case SubModuleFunctions.DataBaseAlterData:
// modify data
answer = "Ai apelat db-ul cu comanda AlterData, dar inca nu e definit un raspuns";
contextHandler.answer = Encoding.ASCII.GetBytes(answer);
contextHandler.sizeOfAnswer = answer.Length;
return true;
case SubModuleFunctions.DataBaseDestroyData:
// remove data
answer = "Ai apelat db-ul cu comanda DestroyData, dar inca nu e definit un raspuns";
contextHandler.answer = Encoding.ASCII.GetBytes(answer);
contextHandler.sizeOfAnswer = answer.Length;
return true;
case SubModuleFunctions.DataBaseQueryData:
// search data
return true;
case SubModuleFunctions.DataBaseSaveData:
// save data
answer = "Ai apelat db-ul cu comanda SaveData, dar inca nu e definit un raspuns";
contextHandler.answer = Encoding.ASCII.GetBytes(answer);
contextHandler.sizeOfAnswer = answer.Length;
return true;
default:
return false;
}
}
public override bool Init(byte[] context, int sizeOfContext)
{
Console.WriteLine("Init execution");
// here we should create the databases needed, or import them, actually
return true;
}
public override bool UnInit()
{
Console.WriteLine("UnInit execution");
return true;
}
public Dictionary<DataBaseDefines, string> DefinesTranslationDictionary = new Dictionary<DataBaseDefines, string>
(
);
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Text;
namespace IP_Framework.InternalDbHandler
{
static class Config
{
public static string CONNECTION_STRING = "mongodb+srv://cosmin:12345666@<EMAIL>.mongodb.net/test?retryWrites=true&w=majority";
public static string DB_NAME = "cancer";
public static string COLLECTION_USERS_NAME = "users";
public static string COLLECTION_QUIZSIGS = "quizsigs";
public static string COLLECTION_NOTIFICATIONS = "notifications";
}
}
<file_sep>import web
import shutil
import PIL
from PIL import Image
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
from tensorflow import keras
from keras import layers
from keras.utils.np_utils import to_categorical
import cv2
import numpy as np
import sklearn
import os
from image_functions3 import *
import json
render = web.template.render('templates2/')
urls = (
'/', 'index',
'/add', 'add',
'/upload_image', 'upload_image',
'/upload_book','upload_book',
'/upload','Upload',
'/result','result',
'/images/(.*)','get_image',
'/resources','resources'
)
class index:
def GET(self):
print("something")
return render.index()
class add:
def POST(self):
i = web.input()
raise web.seeother('/')
class upload_book:
def GET(self):
print("another thing")
return render.upload_book()
class upload_image:
def GET(self):
print("yet another thing")
return render.upload_image()
class Upload:
def OPTIONS(self):
'''Respond to options requests'''
web.ctx.status = '204'
web.header('Access-Control-Allow-Origin', 'http://localhost:4200')
return ""
def POST(self):
x = web.input(image_to_process={})
print(type(x))
print(type(x['image_to_process']))
img_name = x['image_to_process'].filename
print(img_name) # This is the filename
#web.debug(x['myfile'].value) # This is the file contents
#web.debug(x['myfile'].file.read()) # Or use a file(-like) object
w = open("static/images/resources/" + img_name,'wb')
w.write(x['image_to_process'].file.read())
w.close()
prob, rez_path = analyse_img_name(img_name)
web.header('Content-Type', 'application/json')
web.header('Access-Control-Allow-Origin', 'http://localhost:4200')
#return render.response(rez_path)
resp = {
'prob': prob,
'result': '/' + rez_path
}
return json.dumps(resp)
class result:
def GET(self):
raise web.seeother('/')
def POST(self):
raise web.seeother('/')
class get_image:
def GET(self,fileName):
imageBinary = open("/templates/images/"+fileName,'rb').read()
return imageBinary
class resources:
def GET(self):
resp = {'contents': ['Breast Cancer', 'Breast Tumour']}
web.header('Content-Type', 'application/json')
web.header('Access-Control-Allow-Origin', 'http://localhost:4200')
return json.dumps(resp)
if __name__ == "__main__":
app = web.application(urls, globals())
app.run()<file_sep>using System;
using System.Collections.Generic;
namespace IP_Framework
{
class ConvexHaul
{
private static double EPSILON = 1e-8;
private static double R = 6376;
public static double Distance(Point p1, Point p2)
{
return R * Math.Acos(Math.Sin(p1.y) * Math.Sin(p2.y) +
Math.Cos(p1.y) * Math.Cos(p2.y) * Math.Cos(p1.x - p2.x));
//return Math.Sqrt((p1.x - p2.x) * (p1.x - p2.x) + (p1.y - p2.y) * (p1.y - p2.y));
}
private static List<List<Point>> DivideRegions(List<Point> points, double acceptedSize = 10)
{
List<List<int>> adjecent = new List<List<int>>();
for (int i = 0; i < points.Count; i++)
{
adjecent.Add(new List<int>());
}
for (int i = 0; i < points.Count; i++)
{
for (int j = i + 1; j < points.Count; j++)
{
if (Distance(points[i], points[j]) <= acceptedSize)
{
adjecent[i].Add(j);
adjecent[j].Add(i);
}
}
}
List<bool> visited = new List<bool>();
for (int i = 0; i < points.Count; i++)
{
visited.Add(false);
}
List<List<Point>> regions = new List<List<Point>>();
for (int i = 0; i < points.Count; i++)
{
if (visited[i])
{
continue;
}
visited[i] = true;
List<Point> region = new List<Point>();
Stack<int> recursive = new Stack<int>();
recursive.Push(i);
region.Add(points[i]);
while (recursive.Count > 0)
{
int node = recursive.Pop();
foreach (int neighbour in adjecent[node])
{
if (visited[neighbour])
{
continue;
}
visited[neighbour] = true;
recursive.Push(neighbour);
region.Add(points[neighbour]);
}
}
if (region.Count > 0)
{
regions.Add(region);
}
}
return regions;
}
private static double Aria(Point A, Point B, Point C)
{
return A.x * B.y + B.x * C.y + C.x * A.y - C.x * B.y - B.x * A.y - A.x * C.y;
}
private static int Compare(Point A, Point B, Point C)
{
double delta = Aria(A, B, C);
if (delta > EPSILON)
return 1;
if (delta < -EPSILON)
return -1;
return 0;
}
private static List<Point> GetConvexHull(List<Point> region)
{
if (region.Count < 3)
return region;
Point leftBottom = region[0];
int index = 0;
for (int i = 1; i < region.Count; i++)
{
if (leftBottom > region[i])
{
index = i;
leftBottom = region[i];
}
};
List<Point> sortedRegion = new List<Point>();
for (int i = 0; i < region.Count; i++)
{
if (i != index)
{
sortedRegion.Add(region[i]);
}
}
sortedRegion.Sort(
(A, B) => (Compare(A, B, leftBottom))
);
List<Point> hull = new List<Point>();
for (int counter = 0; counter < region.Count; counter++)
{
hull.Add(new Point(0, 0));
}
hull[0] = leftBottom;
hull[1] = sortedRegion[0];
int top = 1;
for (int i = 1; i < sortedRegion.Count; i++)
{
while (top >= 1 && Compare(hull[top - 1], hull[top], sortedRegion[i]) < 1)
{
top--;
}
top++;
hull[top] = sortedRegion[i];
}
List<Point> result = new List<Point>();
for (int i = 0; i <= top; i++)
{
result.Add(hull[i]);
}
return result;
}
public static List<List<Point>> CalculateHull(List<Point> points, double acceptedSize)
{
List<List<Point>> regions = DivideRegions(points, acceptedSize);
List<List<Point>> hulls = new List<List<Point>>();
foreach (List<Point> region in regions)
{
hulls.Add(GetConvexHull(region));
}
return hulls;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Text;
namespace Quizzer
{
public class Answer
{
public enum QUESTION_TYPE
{
QUESTION_SICKNESS_LEVEL,
QUESTION_BOOLEAN,
QUESTION_NUMBER
}
public enum QUESTION_SICKNESS_LEVEL
{
NONE,
ABSENT,
LITTLE,
MEDIUM,
HIGH
}
public enum QUESTION_BOOLEAN
{
NONE,
TRUE,
FALSE
}
private int correspondingQuestionID;
private QUESTION_TYPE answerType;
private QUESTION_SICKNESS_LEVEL answerSicknessLevel;
private QUESTION_BOOLEAN answerBoolean;
private float answerNumeric;
private string correspondingSymptom;
public string GetCorrespondingSympton()
{
return correspondingSymptom;
}
public Answer(QUESTION_TYPE answerType, string correspondingSymptom)
{
this.answerType = answerType;
this.correspondingSymptom = correspondingSymptom;
this.correspondingQuestionID = correspondingQuestionID;
}
public int GetCorrespondingQuestionID()
{
return correspondingQuestionID;
}
public QUESTION_TYPE GetAnswerType()
{
return answerType;
}
public QUESTION_SICKNESS_LEVEL GetAnswerSicknessLevel()
{
if (answerType != QUESTION_TYPE.QUESTION_SICKNESS_LEVEL)
{
return QUESTION_SICKNESS_LEVEL.NONE;
}
return answerSicknessLevel;
}
public bool SetAnswerSicknessLevel(QUESTION_SICKNESS_LEVEL answerSicknessLevel)
{
if (answerType != QUESTION_TYPE.QUESTION_SICKNESS_LEVEL)
{
return false;
}
this.answerSicknessLevel = answerSicknessLevel;
return true;
}
public bool GetAnswerBoolean()
{
if (answerType != QUESTION_TYPE.QUESTION_BOOLEAN)
{
return true;
}
if(answerBoolean == QUESTION_BOOLEAN.TRUE)
{
return true;
}
return false;
}
public bool SetAnswerBoolean(QUESTION_BOOLEAN answerBoolean)
{
if (answerType != QUESTION_TYPE.QUESTION_BOOLEAN)
{
return false;
}
this.answerBoolean = answerBoolean;
return true;
}
public float GetAnswerNumeric()
{
if(answerType != QUESTION_TYPE.QUESTION_NUMBER)
{
return -1;
}
return this.answerNumeric;
}
public bool SetAnswerNumeric(float answerNumeric)
{
if (answerType != QUESTION_TYPE.QUESTION_NUMBER)
{
return false;
}
this.answerNumeric = answerNumeric;
return true;
}
}
}
<file_sep>
namespace IP_Framework.API
{
public class Response
{
int id { get; set; }
double status { get; set; }
}
}
| a5c96d4d207403c460fb96fb6527ebba5711b416 | [
"JavaScript",
"Markdown",
"C#",
"Python",
"Text"
] | 53 | Python | IvanovCosmin/ProiectIP_B4 | d275ddde35be0771beca76a6aa49b9fef2e00008 | d80a979e8f9e27da16963c0e99c61a4ded3f126a |
refs/heads/master | <file_sep>let A = parseFloat(prompt("Digite o valor de A"));
let B = parseFloat(prompt("Digite o valor de B"));
let C = parseFloat(prompt("Digite o valor de C"));
let delta = (B * B) - (4*A*C);
if(delta < 0 || A == 0){
document.write("Impossivel calcular");
}else{
let x1 = (B - Math.sqrt(delta)) / (2 * A);
let x2 = (B + Math.sqrt(delta)) / (2 * A);
document.write("1º Raiz = "+x1+" // ");
document.write("2º Raiz = "+x2);
} | bf95c52df9c3d78022afb97d41d40036269203fe | [
"JavaScript"
] | 1 | JavaScript | emilylmenezes/calculator-bhaskara | c444a78f58614dfceaefceb1b8a81a0065268ec3 | 50c580775755317d8ff4de4eda0ab810f7613224 |
refs/heads/main | <file_sep>// Libraries
import {Resolver, Query, FieldResolver, Root} from 'type-graphql';
// Model
import {User, UserModel} from './user.model';
import {Quiz, QuizModel} from '../quiz/quiz.model';
@Resolver(() => User)
export default class UserResolvers {
@Query(() => [User])
async getUsers(): Promise<User[]> {
try {
return await UserModel.find({});
} catch (error) {
return error;
}
}
@FieldResolver(() => [Quiz], {name: 'quizzes'})
async quizzesArray(@Root() user: User): Promise<(Quiz | null)[]> {
try {
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
console.log(user?.name);
return await Promise.all(
user.quizzes.map(async quizId => QuizModel.findById(quizId)),
);
} catch (error) {
return error;
}
}
}
<file_sep>import {IS_PROD, PROD_ORIGIN, DEV_ORIGIN} from '../constants';
export default {
origin: IS_PROD ? PROD_ORIGIN : DEV_ORIGIN,
credentials: true,
};
<file_sep>export const PORT = process.env.PORT || 8000;
export const {MONGO_APP_URL} = process.env;
export const IS_PROD = process.env.NODE_ENV === 'production';
export const PROD_ORIGIN = 'prod.url';
export const DEV_ORIGIN = 'http://localhost:8080';
<file_sep>// Libraries
import {Field, ObjectType, ID, GraphQLISODateTime} from 'type-graphql';
import {
prop as Property,
getModelForClass,
modelOptions,
} from '@typegoose/typegoose';
import {ObjectId} from 'mongodb';
// Models
import {Question, QuestionModel} from '../question/question.model';
@modelOptions({options: {allowMixed: 0, customName: 'quizzes'}})
@ObjectType({description: 'The Quiz model'})
export class Quiz {
@Field(() => ID, {description: 'Quiz MongoDB ObjectID'})
id: ObjectId;
@Property({required: true, trim: true})
@Field({description: 'Name of the Quiz'})
name: string;
@Property({required: true})
@Field(() => GraphQLISODateTime, {description: 'Start time of the Quiz'})
startTime: Date;
@Property({required: true})
@Field(() => GraphQLISODateTime, {description: 'End time of the Quiz'})
endTime: Date;
@Property({default: []})
@Field(() => [String], {
description: 'An array containing the IDs of the questions',
name: 'questionIds',
})
questions: string[];
@Field(() => [Question], {
description:
'An array containing the details of all the questions in this quiz.',
name: 'questions',
})
async questionsArray(): Promise<(Question | null)[]> {
try {
return await Promise.all(
this.questions.map(questionId => QuestionModel.findById(questionId)),
);
} catch (error) {
return error;
}
}
@Property({default: []})
@Field(() => [String], {
description: 'A list of all the instructions for the quiz',
})
instructions: string[];
@Property({default: []})
@Field(() => [String], {
description:
'An array of objects containing the student id and corresponding marks',
})
submissions: {id: string; marks: number}[];
@Property({default: false})
@Field({description: 'Status of the quiz (published or unpublished)'})
active: boolean;
}
export const QuizModel = getModelForClass(Quiz);
<file_sep>import 'reflect-metadata';
import 'dotenv/config';
// Libraries
import {ApolloServer} from 'apollo-server-express';
import express from 'express';
import cors from 'cors';
// Config
import {init as initMongoose} from './config/mongoose';
import {init as initFirebase} from './config/firebase';
import CORS_OPTIONS from './config/cors';
// Schema
import {schema} from './schema';
// Utils
import winston from './config/winston';
// Constants
import {PORT, IS_PROD} from './constants';
(async () => {
const logger = winston('Express');
initMongoose();
initFirebase();
const app = express();
app.use(cors(CORS_OPTIONS));
const apolloServer = new ApolloServer({
schema: await schema,
playground: !IS_PROD,
debug: !IS_PROD,
});
apolloServer.applyMiddleware({
app,
cors: CORS_OPTIONS,
});
app.listen(PORT, () => logger.info(`Server Started on Port ${PORT}`));
})();
| 384d989253cbcef63bf120a4aa4313eb1dd2d2f2 | [
"TypeScript"
] | 5 | TypeScript | SriramPatibanda/project-nutella | 357cc9dcfcf5f6bab827da75dcd7a26a6a2bef5f | f202b946778ae72199d4d7b232143a90eb1ad4eb |
refs/heads/master | <file_sep>import { Component, OnInit } from '@angular/core';
import { PersonService } from '../person.service';
import { person } from '../person';
@Component({
selector: 'app-read',
templateUrl: './read.component.html',
styleUrls: ['./read.component.css']
})
export class ReadComponent implements OnInit {
data:person[]=[];
constructor(private personService:PersonService) { }
ngOnInit() {
this.data=this.personService.getDetails();
}
Details(){
console.log(this.data)
}
}
<file_sep>import { Component, OnInit } from '@angular/core';
import { person } from '../person';
import { PersonService } from '../person.service';
@Component({
selector: 'app-create',
templateUrl: './create.component.html',
styleUrls: ['./create.component.css']
})
export class CreateComponent implements OnInit {
data:person[]=[];
constructor(private personService:PersonService) { }
ngOnInit() {
}
Onsubmit(){
console.log(this.data)
this.personService.addPerson(new person(
this.data['firstname'],
this.data['lastname'],
this.data['middlename'],
this.data['email'],
this.data['password']
))
}
}
<file_sep>import { Injectable } from '@angular/core';
import { person } from './person';
@Injectable()
export class PersonService {
data:person[]=[];
constructor() { }
addPerson(persons:person) {
this.data.push(persons);
}
getDetails(){
return this.data;
}
findUser(email: String): person {
for(let i=0;i<this.data.length;i++){
if(this.data[i].email === email){
return this.data[i];
} else {
return null;
}
}
}
// findUser(email: String): person {
// for(let i=0;i<this.data.length;i++){
// if(this.data[i].email === email){
// return this.data[i];
// } else {
// return null;
// }
// }
// }
// //
}
<file_sep>import { Component, OnInit } from '@angular/core';
import { person } from '../person';
import { PersonService } from '../person.service';
@Component({
selector: 'app-delete',
templateUrl: './delete.component.html',
styleUrls: ['./delete.component.css']
})
export class DeleteComponent implements OnInit {
data:person
constructor(private personService: PersonService) { }
findUser(email: any) {
}
ngOnInit() {
}
}
<file_sep>import { Component, OnInit } from '@angular/core';
import { PersonService } from '../person.service';
import { person } from '../person';
@Component({
selector: 'app-update',
templateUrl: './update.component.html',
styleUrls: ['./update.component.css']
})
export class UpdateComponent implements OnInit {
person: person;
foundUser: boolean;
dataFoundClassInfo = "";
dataMessage = '';
constructor(private personService: PersonService) { }
ngOnInit() {
}
findUser(email: HTMLInputElement) {
this.person = this.personService.findUser(email.value);
console.log(this.person);
if(this.person!=null){
console.log('found');
this.dataMessage = 'User found';
this.dataFoundClassInfo = "alert alert-success";
} else {
this.foundUser = true;
console.log('not found');
this.dataMessage = 'User not found';
this.dataFoundClassInfo = "alert alert-danger";
}
}
// findUser(email: any) {
// this.Person []= this.personService.findUser(email);
// }
// getUser(persons:person){
// //this.person.push(persons);
// console.log(this.person);
// return this.person;
}
<file_sep>export class person {
constructor( public firstname: string,
public lastname:string,
public middlename:string,
public email:string,
public password:string){
}
} | 4d989011c2c285d590256409ad36fdb6a1e92da6 | [
"TypeScript"
] | 6 | TypeScript | jvinukumar/crud | 08391e3d7cacf2dfdf324012f16625c518a10197 | 895046de651a8fbab396583834cc2cea4a1f7373 |
refs/heads/master | <repo_name>devcronberg/486assignments<file_sep>/ControllerSimple/solution/ControllerSimple/Controllers/HomeController.cs
using System.Web.Mvc;
using Teknologisk;
namespace ControllerSimple.Controllers
{
public class HomeController : Controller
{
IPersonRepository r = new PersonRepositoryMem();
public ActionResult Index()
{
return View(r.GetAll());
}
[HttpGet]
public ActionResult Edit(int id)
{
return View(r.Get(id));
}
[HttpPost]
public ActionResult Edit(Person p)
{
if (ModelState.IsValid)
{
r.Update(p);
return RedirectToAction("Index");
}
else
{
return View(p);
}
}
[HttpGet]
public ActionResult Delete(int id)
{
r.Delete(id);
return RedirectToAction("Index");
}
[HttpGet]
public ActionResult Create()
{
return View();
}
[HttpPost]
public ActionResult Create(Person p)
{
if (ModelState.IsValid)
{
r.Create(p);
return RedirectToAction("Index");
}
else
{
return View(p);
}
}
[HttpGet]
public ActionResult Details(int id)
{
return View(r.Get(id));
}
}
}
| 00af892861a2c47a49587c338847557e4b5745bb | [
"C#"
] | 1 | C# | devcronberg/486assignments | a7343804751fbffe48d803859c2f56e4b02b329a | 4a531816bed99cece9a5df2d475c726e7cc41da2 |
refs/heads/master | <file_sep>import React from "react";
import Auxi from "../../hoc/Auxi";
export default props => {
return (
<Auxi>
<div>toolber,Slidebar,dropdown</div>
<main>{props.children}</main>
</Auxi>
);
};
<file_sep>import React from "react";
export default props => {
const order = Object.keys(props.ingredients).map(igKey => {
return (
<li key={igKey}>
<span style={{ textTransform: "capitalize" }}>{igKey}</span> :{" "}
{props.ingredients[igKey]}
</li>
);
});
return (
<div>
<h1>Your Order</h1>
<h3>Following ingredients of your delicious Burger</h3>
<ul>{order}</ul>
<p>Continue to checkout?</p>
</div>
);
};
| 623a3916d4a9329e18cac99905cd8478539ff644 | [
"JavaScript"
] | 2 | JavaScript | Sandipan16/MyBurgerApp | e79244ca5057e13e5eb658111ce6ce2fe851bca6 | b3ec9e32dfa92a36ddad7b95d9d6f057cbe3a843 |
refs/heads/master | <file_sep>export {useDeptNew} from './dept-new/'
export {useAssignUser} from './assign-user/'
<file_sep>import {Layout, Avatar, Menu, Dropdown, Breadcrumb} from 'ant-design-vue'
import {SettingOutlined, SearchOutlined,MenuFoldOutlined, MenuUnfoldOutlined} from '@ant-design/icons-vue';
export default {
[Layout.Header.name]: Layout.Header,
[Avatar.name]: Avatar,
[Menu.name]: Menu,
[Menu.Divider.name]: Menu.Divider,
SettingOutlined,
Dropdown,
SearchOutlined,
[Breadcrumb.name]: Breadcrumb,
[Breadcrumb.Item.name]: Breadcrumb.Item,
MenuFoldOutlined, MenuUnfoldOutlined
}
| af5a0f23ff6353e609e46b325c4c8ebeedbc23ee | [
"TypeScript"
] | 2 | TypeScript | ruanzhijun/vue3-antd | 9881fe94a2f2015b9f88b1b60006c2b47570c6ef | 96d24c6c1b5acf3de6ff1259531449b27031b428 |
refs/heads/master | <repo_name>Lemonszz/BetterCompass<file_sep>/src/main/java/party/lemons/bettercompass/BetterCompass.java
package party.lemons.bettercompass;
import net.minecraftforge.fml.ModLoadingContext;
import net.minecraftforge.fml.common.Mod;
import net.minecraftforge.fml.config.ModConfig;
import party.lemons.bettercompass.config.BCConfig;
/**
* Created by Sam on 3/02/2018.
*/
@Mod(BetterCompass.MODID)
public class BetterCompass
{
public static final String MODID = "bettercompass";
public BetterCompass()
{
ModLoadingContext modLoadingContext = ModLoadingContext.get();
modLoadingContext.registerConfig(ModConfig.Type.COMMON, BCConfig.COMMON_SPEC);
modLoadingContext.registerConfig(ModConfig.Type.CLIENT, BCConfig.CLIENT_SPEC);
}
}<file_sep>/README.md
# Better Compass
Better Compass lets you set your compass wherever you want!
Simply right click with a normal compass to set it's position. By default compass will face towards the world spawn as usual.
You can simply put your compass in a crafting bench to clear the link.
If you prefer to keep the standard compass, you can enable the "Use Homing Compass Instead" option which creates a new type of compass.
<file_sep>/src/main/java/party/lemons/bettercompass/item/ModItems.java
package party.lemons.bettercompass.item;
import net.minecraft.item.Item;
import net.minecraft.item.Items;
import net.minecraftforge.client.event.ModelRegistryEvent;
import net.minecraftforge.client.model.ModelLoader;
import net.minecraftforge.event.RegistryEvent;
import net.minecraftforge.eventbus.api.SubscribeEvent;
import net.minecraftforge.fml.common.Mod;
import net.minecraftforge.registries.ObjectHolder;
import party.lemons.bettercompass.BetterCompass;
/**
* Created by Sam on 3/02/2018.
*/
@Mod.EventBusSubscriber(modid = BetterCompass.MODID)
public class ModItems
{
@ObjectHolder("minecraft:compass")
public static final Item compass = Items.COMPASS;
@SubscribeEvent
public static void registerItems(RegistryEvent.Register<Item> event)
{
event.getRegistry().register(new ItemCustomCompass());
}
}
<file_sep>/src/main/resources/META-INF/mods.toml
modLoader="javafml"
loaderVersion="[28,)"
[[mods]]
modId="bettercompass"
version="${file.jarVersion}"
displayName="Better Compass"
description='''
Better Compass
''' | b8167469961da42e95c554b36c44348136681eaa | [
"Markdown",
"Java",
"TOML"
] | 4 | Java | Lemonszz/BetterCompass | 8a55862a7278f44d8e59430c7ff8588a547d180b | 9a4a6619aa654602175ebd85f720ccc9b0e1c2c9 |
refs/heads/master | <repo_name>manurajsathyarajan/splunk-devops-plugin<file_sep>/splunk-devops-extend/src/main/java/com/splunk/splunkjenkins/console/SplunkConsoleTaskListenerDecorator.java
package com.splunk.splunkjenkins.console;
import org.jenkinsci.plugins.workflow.job.WorkflowRun;
import org.jenkinsci.plugins.workflow.log.TaskListenerDecorator;
import javax.annotation.Nonnull;
import java.io.OutputStream;
public class SplunkConsoleTaskListenerDecorator extends TaskListenerDecorator {
transient PipelineConsoleDecoder decoder;
String source;
public SplunkConsoleTaskListenerDecorator(WorkflowRun run) {
this.decoder = new PipelineConsoleDecoder(run);
this.source = run.getUrl() + "console";
}
@Nonnull
@Override
public OutputStream decorate(@Nonnull OutputStream outputStream) {
if (decoder == null) {
//resume from restart
decoder = new PipelineConsoleDecoder(null);
}
//called for every step
return new LabelConsoleLineStream(outputStream, source, decoder);
}
}
<file_sep>/splunk-devops-extend/src/main/java/com/splunk/splunkjenkins/console/SplunkTaskListenerFactory.java
package com.splunk.splunkjenkins.console;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import com.splunk.splunkjenkins.SplunkJenkinsInstallation;
import com.splunk.splunkjenkins.model.EventRecord;
import com.splunk.splunkjenkins.model.EventType;
import com.splunk.splunkjenkins.utils.SplunkLogService;
import hudson.Extension;
import hudson.model.Queue;
import org.jenkinsci.plugins.workflow.flow.FlowExecutionOwner;
import org.jenkinsci.plugins.workflow.job.WorkflowRun;
import org.jenkinsci.plugins.workflow.log.TaskListenerDecorator;
import javax.annotation.CheckForNull;
import javax.annotation.Nonnull;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.ExecutionException;
import java.util.logging.Level;
import java.util.logging.Logger;
import static com.splunk.splunkjenkins.model.EventType.CONSOLE_LOG;
@Extension
public class SplunkTaskListenerFactory implements TaskListenerDecorator.Factory {
private static final Logger LOGGER = Logger.getLogger(SplunkConsoleTaskListenerDecorator.class.getName());
private static final int CACHED_LINES_LIMIT = 200;
private static final ConcurrentLinkedQueue<EventRecord> consoleQueue = new ConcurrentLinkedQueue<>();
private static final LoadingCache<WorkflowRun, SplunkConsoleTaskListenerDecorator> cachedDecorator = CacheBuilder.newBuilder()
.weakKeys()
.maximumSize(1024)
.build(new CacheLoader<WorkflowRun, SplunkConsoleTaskListenerDecorator>() {
@Override
public SplunkConsoleTaskListenerDecorator load(WorkflowRun key) {
return new SplunkConsoleTaskListenerDecorator(key);
}
});
@CheckForNull
@Override
public TaskListenerDecorator of(@Nonnull FlowExecutionOwner flowExecutionOwner) {
if (!SplunkJenkinsInstallation.get().isPipelineFilterEnabled()) {
return null;
}
if (SplunkJenkinsInstallation.get().isEventDisabled(CONSOLE_LOG)) {
return null;
}
try {
Queue.Executable executable = flowExecutionOwner.getExecutable();
if (executable instanceof WorkflowRun) {
WorkflowRun run = (WorkflowRun) executable;
if (SplunkJenkinsInstallation.get().isJobIgnored(run.getUrl())) {
return null;
}
return cachedDecorator.get(run);
}
} catch (IOException x) {
LOGGER.log(Level.WARNING, null, x);
} catch (ExecutionException e) {
LOGGER.finer("failed to load cached decorator");
}
return null;
}
public static void enqueue(EventRecord record) {
boolean added = consoleQueue.add(record);
if (!added) {
LOGGER.warning("failed to add log " + record.getMessageString());
} else if (consoleQueue.size() > CACHED_LINES_LIMIT) {
flushLog();
}
}
public static void flushLog() {
EventRecord record;
List<EventRecord> pendingRecords = new ArrayList<>();
try {
while ((record = consoleQueue.poll()) != null) {
pendingRecords.add(record);
}
SplunkLogService.getInstance().sendBatch(pendingRecords, EventType.CONSOLE_LOG);
} catch (Throwable ex) {
LOGGER.log(Level.SEVERE, "flush log error", ex);
}
}
public static void removeCache(WorkflowRun run) {
cachedDecorator.invalidate(run);
}
}
| def43693e20b7096d83e5c51400689cc32e76e2b | [
"Java"
] | 2 | Java | manurajsathyarajan/splunk-devops-plugin | 705e5e13e3c8b5e81577b424512188d2abebfeec | 946a268265a422db0d7f9f7ca3633923f6caba21 |
refs/heads/master | <repo_name>zksfyz/kubevela<file_sep>/apis/core.oam.dev/v1alpha2/appdeploy_types.go
/*
Copyright 2020 The KubeVela Authors.
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.
*/
package v1alpha2
import (
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"github.com/oam-dev/kubevela/apis/standard.oam.dev/v1alpha1"
)
// ApplicationDeploymentSpec defines how to describe an upgrade between different application
type ApplicationDeploymentSpec struct {
// TargetApplicationName contains the name of the applicationConfiguration that we need to upgrade to.
// Here we use an applicationConfiguration as a revision of an application, thus the name alone is suffice
TargetApplicationName string `json:"targetApplicationName"`
// SourceApplicationName contains the name of the applicationConfiguration that we need to upgrade from.
// it can be empty only when it's the first time to deploy the application
SourceApplicationName string `json:"sourceApplicationName,omitempty"`
// The list of component to upgrade in the application.
// We only support single component application so far
// TODO: (RZ) Support multiple components in an application
// +optional
ComponentList []string `json:"componentList,omitempty"`
// RolloutPlan is the details on how to rollout the resources
RolloutPlan v1alpha1.RolloutPlan `json:"rolloutPlan"`
// RevertOnDelete revert the rollout when the rollout CR is deleted
// It will remove the target application from the kubernetes if it's set to true
// +optional
RevertOnDelete *bool `json:"revertOnDelete,omitempty"`
}
// ApplicationDeploymentStatus defines the observed state of ApplicationDeployment
type ApplicationDeploymentStatus struct {
v1alpha1.RolloutStatus `json:",inline"`
// LastTargetApplicationName contains the name of the application that we upgraded to
// We will restart the rollout if this is not the same as the spec
LastTargetApplicationName string `json:"lastTargetApplicationName"`
// LastSourceApplicationName contains the name of the application that we need to upgrade from.
// We will restart the rollout if this is not the same as the spec
LastSourceApplicationName string `json:"lastSourceApplicationName,omitempty"`
}
// ApplicationDeployment is the Schema for the ApplicationDeployment API
// +kubebuilder:object:root=true
// +kubebuilder:resource:categories={oam}
// +kubebuilder:subresource:status
type ApplicationDeployment struct {
metav1.TypeMeta `json:",inline"`
metav1.ObjectMeta `json:"metadata,omitempty"`
Spec ApplicationDeploymentSpec `json:"spec,omitempty"`
Status ApplicationDeploymentStatus `json:"status,omitempty"`
}
// ApplicationDeploymentList contains a list of ApplicationDeployment
// +kubebuilder:object:root=true
type ApplicationDeploymentList struct {
metav1.TypeMeta `json:",inline"`
metav1.ListMeta `json:"metadata,omitempty"`
Items []ApplicationDeployment `json:"items"`
}
<file_sep>/docs/examples/rollout/README.md
# Rollout Example
Here is an example of how to rollout an application with a component of type CloneSet.
## Install Kruise
```shell
helm install kruise https://github.com/openkruise/kruise/releases/download/v0.7.0/kruise-chart.tgz
```
## Rollout steps
1. Install CloneSet based workloadDefinition
```shell
kubectl apply -f docs/examples/rollout/clonesetDefinition.yaml
```
2. Apply an application
```shell
kubectl apply -f docs/examples/rollout/app-source.yaml
```
Wait for the application's status to be "running"
3. Prepare the application for rolling out
```shell
kubectl apply -f docs/examples/rollout/app-source-prep.yaml
```
Wait for the applicationConfiguration "test-rolling-v1" `Rolling Status` to be "RollingTemplated"
4. Modify the application image and apply
```shell
kubectl apply -f docs/examples/rollout/app-target.yaml
```
Wait for the applicationConfiguration "test-rolling-v2" `Rolling Status` to be "RollingTemplated"
5. Apply the application deployment CR
```shell
kubectl apply -f docs/examples/rollout/app-deploy.yaml
```
Check the status of the ApplicationDeployment and see the step by step rolling out<file_sep>/pkg/controller/common/rollout/rollout_webhook_test.go
package rollout
import (
"context"
"net/http"
"net/http/httptest"
"testing"
"k8s.io/klog/v2"
"github.com/oam-dev/kubevela/apis/standard.oam.dev/v1alpha1"
)
func Test_callWebhook(t *testing.T) {
ctx := context.TODO()
type args struct {
resource klog.KMetadata
phase v1alpha1.RollingState
w v1alpha1.RolloutWebhook
}
var tests []struct {
name string
statusCode int
body string
args args
wantErr bool
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
// generate a test server so we can capture and inspect the request
testServer := httptest.NewServer(http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) {
res.WriteHeader(tt.statusCode)
res.Write([]byte(tt.body))
}))
defer func() { testServer.Close() }()
if err := callWebhook(ctx, tt.args.resource, tt.args.phase, tt.args.w); (err != nil) != tt.wantErr {
t.Errorf("callWebhook() error = %v, wantErr %v", err, tt.wantErr)
}
})
}
}
| 523c49f6c924b54142b5573c56869fc439a10384 | [
"Markdown",
"Go"
] | 3 | Go | zksfyz/kubevela | 720781908027efb19e5af96e7feb0d434cf1383d | 88762dbb6b606474f0a307ea016eb691adfa17f6 |
refs/heads/master | <file_sep>package com.foreverstudents.passwords;
import android.app.Fragment;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.foreverstudents.passwords.model.util.MD5Util;
import com.foreverstudents.passwords.model.util.WebServices;
public class SignUpFragment extends Fragment {
private EditText mUsernameEditText;
private EditText mPasswordEditText;
private EditText mConfirmPasswordEditText;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_sign_up,
container, false);
mUsernameEditText = (EditText)rootView.findViewById(R.id.edit_text_username);
mPasswordEditText = (EditText)rootView.findViewById(R.id.edit_text_password);
mConfirmPasswordEditText = (EditText)rootView.findViewById(R.id.edit_text_confirm_password);
Button signUpButton = (Button)rootView.findViewById(R.id.button_sign_up);
signUpButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
String username = mUsernameEditText.getText().toString();
String password = mPasswordEditText.getText().toString();
String confirmPassword = mConfirmPasswordEditText.getText().toString();
if (check(username, password, confirmPassword)) {
new SignUpTask().execute(username, password);
}
}
});
return rootView;
}
private boolean check(String username, String password, String confirmPassword) {
if (username == null || username.length() < 6) {
Toast.makeText(getActivity(), "Username length cannot < 6", Toast.LENGTH_SHORT).show();
return false;
}
if (username == null || username.length() > 45) {
Toast.makeText(getActivity(), "Username length cannot > 45", Toast.LENGTH_SHORT).show();
return false;
}
if (password == null || password.length() < 6) {
Toast.makeText(getActivity(), "Password cannot < 6", Toast.LENGTH_SHORT).show();
return false;
}
if (password == null || password.length() > 255) {
Toast.makeText(getActivity(), "Password cannot > 255", Toast.LENGTH_SHORT).show();
return false;
}
if (confirmPassword == null || !confirmPassword.equals(password)) {
Toast.makeText(getActivity(), "Passwords don't match", Toast.LENGTH_SHORT).show();
return false;
}
return true;
}
private class SignUpTask extends AsyncTask<String, Void, String> {
private ProgressDialog progressDialog;
@Override
protected String doInBackground(String... params) {
if (params.length == 2) {
String username = params[0];
String password = params[1];
String md5Password = <PASSWORD>(password);
return WebServices.signUp(username, md5Password);
}
return null;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = ProgressDialog.show(getActivity(), "", "Please wait...");
}
@Override
protected void onPostExecute(String result) {
progressDialog.dismiss();
if (result != null && result.equals("1")) {
Toast.makeText(getActivity(), "SUCCESS", Toast.LENGTH_SHORT).show();
getActivity().finish();
} else {
Toast.makeText(getActivity(), "FAIL", Toast.LENGTH_SHORT).show();
}
}
}
}
<file_sep>package com.foreverstudents.passwords;
import android.app.ActionBar;
import android.app.Activity;
import android.os.Bundle;
public class SignInActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final ActionBar actionBar = getActionBar();
actionBar.setDisplayShowHomeEnabled(false);
setContentView(R.layout.activity_sign_in);
if (savedInstanceState == null) {
getFragmentManager().beginTransaction().add(R.id.container, new SignInFragment()).commit();
}
}
}
<file_sep>package com.foreverstudents.passwords;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.DialogInterface;
import android.os.Bundle;
public class DeleteAccountDialogFragment extends DialogFragment {
private String mAccountId;
private DeleteAccountDialogFragmentCallbacks mCallbacks;
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setMessage("Are you sure to delete this account?")
.setPositiveButton("YES", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
mCallbacks.onDidDeleteAccount(mAccountId);
}
})
.setNegativeButton("NO", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
});
return builder.create();
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
mCallbacks = (DeleteAccountDialogFragmentCallbacks)activity;
}
@Override
public void onDetach() {
super.onDetach();
mCallbacks = null;
}
public void setAccountId(String accountId) {
mAccountId = accountId;
}
public interface DeleteAccountDialogFragmentCallbacks {
void onDidDeleteAccount(String accountId);
}
}
| cd162661304f6b34f0eb579bbfa8b46a3f196a71 | [
"Java"
] | 3 | Java | foreverstudents/passwords_android | d9042964f96adc792d1a5c20229fbeebd72a46df | b337bda02a08946f68573e21d6244901d7483737 |
refs/heads/master | <file_sep>from __future__ import with_statement
import socket
class TCP_Server(object):
"""This is to communicate with a server over Ethernet using TCP/IP."""
def __init__(self,ip_address):
"""ip_address may be given as address:port. If :port is omitted, port
number 2000 is assumed."""
from thread import allocate_lock
self.timeout = 1.0
object.__init__(self)
if ip_address.find(":") >= 0:
self.ip_address = ip_address.split(":")[0]
self.port = int(ip_address.split(":")[1])
else: self.ip_address = ip_address; self.port = 2000
self.connection = None # network connection
# This is to make the query method multi-thread safe.
self.lock = allocate_lock()
def __repr__(self):
return self.__class__.__name__+"('"+self.ip_address+":"+str(self.port)+"')"
def write(self,command):
"""Send a command that does not generate a reply"""
with self.lock: # Allow only one thread at a time inside this function.
for retry in 1,2:
self.connect()
if not self.connected(): return
try:
self.connection.sendall(command+"\n")
except socket.error: # in case of "Connection reset by peer"...
print "send: lost connection to '"+self.ip_address+"'"
self.disconnect()
continue
# Make sure that the connection is still "alive".
self.connection.settimeout(0.0001)
try:
t = self.connection.recv(1024)
if len(t) == 0:
print "send check: '"+self.ip_address+"' closed connection"
self.disconnect()
continue
if len(t) > 0:
print "write: command '%s' generated unexpected reply %r" % (command,t)
self.disconnect()
continue
except socket.timeout: pass
except socket.error: # in case of "Connection reset by peer"
print "send check: lost connection to '"+self.ip_address+"'"
self.diconnect()
continue
self.connection.settimeout(self.timeout)
return
def query(self,command):
"""Send a command that generates a reply, and return the reply."""
with self.lock: # Allow only one thread at a time inside this function.
for retries in 1,2:
self.connect()
if not self.connected(): return ""
try: self.connection.sendall(command+"\n")
except socket.error: # in case of "Connection reset by peer"...
print "send: lost connection to '"+self.ip_address
self.disconnect()
continue
try:
reply = self.connection.recv(4096)
##print "received "+str(len(reply))+" bytes"
if len(reply) == 0:
print "receive: '"+self.ip_address+"' closed connection."
self.disconnect()
continue
while reply.find("\n") == -1:
t = self.connection.recv(4096)
##print "received "+str(len(t))+" bytes"
if len(t) == 0:
print "receive: '"+self.ip_address+"' closed connection"
self.disconnect()
return reply
reply += t
reply = reply.strip("\n")
return reply
except socket.timeout:
print "receive: connection to '"+self.ip_address+"' timed out"
self.disconnect()
continue
except socket.error:
print "receive: lost connection to '"+self.ip_address+"'"
self.disconnect()
continue
return ""
def connect(self):
"Establishes a TCP connection, if not already established"
self.flush() # Make sure the receiving queue is empty.
if not self.connected():
self.connection = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
self.connection.settimeout(self.timeout)
try: self.connection.connect((self.ip_address,self.port))
except socket.error:
self.connection = None
print "Failed to connect to '"+self.ip_address+"', port",self.port
if self.connection: self.connection.settimeout(self.timeout)
def connected(self):
"Return True if the connection is establisched, False otherwise"
if self.connection == None: return False
try: self.connection.getpeername()
except socket.error: return False
return True
def flush(self):
"Flush the receiving queue"
if not self.connected(): return
try:
self.connection.settimeout(0.000001)
t = self.connection.recv(1024)
if len(t) == 0:
print "flush: '"+self.ip_address+"' closed connection"
self.disconnect()
return
while len(t) > 0:
t = self.connection.recv(1024)
if len(t) == 0:
print "flush: '"+self.ip_address+"' closed connection"
self.disconnect()
return
except socket.timeout: pass
except socket.error: # in case of "Connection reset by peer"
print "flush: lost connection to '"+self.ip_address+"'"
self.disconnect()
return
self.connection.settimeout(self.timeout)
def disconnect(self):
"Shuts down the current TCP connection"
if self.connection != None:
self.connection.close()
self.connection = None
def reconnect(self):
self.disconnect(); self.connect();
class subsystem:
def __init__(self,server,name=""):
self.__server__ = server
self.__name__ = name
def __getattr__(self,attr):
##print "subsystem.__getattr__(%r)" % attr
if attr == "__members__": return self.__getmembers__()
if self.__dict__.has_key(attr): return self.__dict__[attr]
if attr.startswith("__") or attr.endswith("__"):
raise AttributeError, "'subsystem' has no attribute '%s'" % attr
if self.__name__: name = self.__name__+"."+attr
else: name = attr
return subsystem(self.__server__,name)
def __setattr__(self,attr,val):
##print "subsystem.__setattr__(%r,%r)" % (attr,val)
if attr.startswith("__") or attr.endswith("__"):
self.__dict__[attr] = val
return
if not hasattr(self,"__server__"): return
if not hasattr(self,"__name__"): return
if self.__name__: name = self.__name__+"."+attr
else: name = attr
val = str(val)
##print "write","%s=%s" % (name,val)
self.__server__.write("%s=%s" % (name,val))
def __getmembers__(self):
if not hasattr(self,"__server__"): return []
if not hasattr(self,"__name__"): return []
names = self.__server__.query(self.__name__).split("\n")
while "" in names: names.remove("")
return names
def __getsubmembers__(self,name):
if not hasattr(self,"__server__"): return []
if not hasattr(self,"__name__"): return []
if self.__name__: name = self.__name__+"."+name
##print "__getsubmembers__: query %r" % name
names = self.__server__.query(name).split("\n")
while "" in names: names.remove("")
return names
def __content__(self):
members = self.__getmembers__()
if len(members) > 1: return self
if len(members) == 1:
member = members[0]
##print "member %r" % member
submembers = self.__getsubmembers__(member)
##print "submembers %r" % submembers
if len(submembers) > 0: return self
return self.__server__.query(self.__name__)
def __repr__(self):
##print "subsystem.__repr__()"
content = self.__content__()
if type(content) == str: return repr(content)
return "subsystem(%r,%r)" % (self.__server__,self.__name__)
def __str__(self):
content = self.__content__()
if type(content) == str: return content
return self.__server__.query(self.__name__)
def __float__(self):
from numpy import nan
try: return float(str(self))
except: return nan
def __int__(self):
try: return int(str(self))
except: return 0
server = TCP_Server("id14timing.cars.aps.anl.gov:2000")
timing_system = subsystem(server)
<file_sep>#!/usr/bin/env python
"""
Control panel for thermoelectric circulating water chiller.
Author: <NAME>, <NAME>
Date created: 2009-06-01
Date last modified: 2019-05-21
Fault Codes:
The fault byte is a bit map (0 = OK, 1 = Fault):
value| CA number | bit | fault
0| 0 | | no faults
1| 1 | bit 0 | Tank Level Low
4| 3 | bit 2 | Temperature above alarm range
16| 5 | bit 4 | RTD Fault
32| 6 | bit 5 | Pump Fault
128| 8 | bit 7 | Temperature below alarm range
"""
import wx
##import CA; CA.monitor_always = False
from EditableControls import ComboBox,TextCtrl # customized versions
from oasis_chiller import chiller
from numpy import nan,isnan
from Panel import BasePanel,PropertyPanel
__version__ = "2.2" # title
class OasisChillerPanel(BasePanel):
name = "OasisChiller"
title = "Oasis Chiller DL"
standard_view = [
"Set Point",
"Actual Temperature",
]
def __init__(self,parent=None):
parameters = [
[[PropertyPanel,"Set Point", chiller,"VAL" ],{"unit":"C","refresh_period":1.0}],
[[PropertyPanel,"Actual Temperature", chiller,"RBV" ],{"unit":"C","read_only":True,"refresh_period":1.0}],
[[PropertyPanel,"Faults",chiller,"faults"],{"refresh_period":1.0}],
]
BasePanel.__init__(self,
parent=parent,
name=self.name,
title=self.title,
parameters=parameters,
standard_view=self.standard_view,
subname=True,
subpanels=[SettingsPanel],
)
class SettingsPanel(BasePanel):
name = "settings"
title = "Settings"
standard_view = [
"Port",
"High Limit",
"Low Limit",
"Nom. update rate",
"Act. update rate",
]
def __init__(self,parent=None):
parameters = [
[[PropertyPanel,"Port", chiller,"COMM" ],{"refresh_period":1.0}],
[[PropertyPanel,"Low Limit", chiller,"LLM" ],{"unit":"C","refresh_period":1.0}],
[[PropertyPanel,"High Limit",chiller,"HLM"],{"unit":"C","refresh_period":1.0}],
[[PropertyPanel,"Feedback P1",chiller,"P1"],{"format":"%g","refresh_period":1.0}],
[[PropertyPanel,"Feedback I1",chiller,"I1"],{"format":"%g","refresh_period":1.0}],
[[PropertyPanel,"Feedback D1",chiller,"D1"],{"format":"%g","refresh_period":1.0}],
[[PropertyPanel,"Feedback P2",chiller,"P2"],{"format":"%g","refresh_period":1.0}],
[[PropertyPanel,"Feedback I2",chiller,"I2"],{"format":"%g","refresh_period":1.0}],
[[PropertyPanel,"Feedback D2",chiller,"D2"],{"format":"%g","refresh_period":1.0}],
[[PropertyPanel,"Nom. update rate",chiller,"SCAN"],{"format":"%.3f","unit":"s","refresh_period":1.0}],
[[PropertyPanel,"Act. update rate",chiller,"SCANT"],{"format":"%.3f","unit":"s","refresh_period":1.0}],
]
BasePanel.__init__(self,
parent=parent,
name=self.name,
title=self.title,
parameters=parameters,
standard_view=self.standard_view,
subname=True,
)
if __name__ == '__main__':
from pdb import pm
# Needed to initialize WX library
if not "app" in globals(): app = wx.App(redirect=False)
panel = OasisChillerPanel()
app.MainLoop()
<file_sep>"""Combination motor for slit gap and center, based on motor for individual
blades
<NAME>, 14 Dec 2010 - Jun 28, 2017
"""
__version__ = "1.0.1"
class gap(object):
"""Combination motor for slit"""
def __init__(self,blade1,blade2):
self.blade1 = blade1
self.blade2 = blade2
def get_value(self):
return self.blade1.value-self.blade2.value
value = property(get_value)
class center(object):
"""Combination motor"""
def __init__(self,blade1,blade2):
self.blade1 = blade1
self.blade2 = blade2
def get_value(self):
return (self.blade1.value+self.blade2.value)/2
value = property(get_value)
class tilt(object):
"""Combination motor"""
name = "tilt"
from persistent_property import persistent_property
offset = persistent_property("offset",0.0)
sign = persistent_property("sign",+1)
unit = persistent_property("unit","mrad")
def __init__(self,m1,m2,distance=1.0,name=None,unit=None):
self.m1 = m1
self.m2 = m2
self.distance = distance
if name is not None: self.name = name
if unit is not None: self.unit = unit
def get_dial(self):
"""Readback value, in dial units"""
return self.theta(self.m1.dial,self.m2.dial)
def set_dial(self,value):
self.m1.dial,self.m2.dial = \
self.x1_x2(self.m1.dial,self.m2.dial,value)
dial = property(get_dial,set_dial)
def get_command_dial(self):
"""Target value, in dial units"""
return self.theta(self.m1.command_dial,self.m2.command_dial)
def set_command_dial(self,value):
self.m1.command_dial,self.m2.command_dial = \
self.x1_x2(self.m1.command_dial,self.m2.command_dial,value)
command_dial = property(get_command_dial,set_command_dial)
def get_value(self):
"""Readback value, in user units, taking into account offset"""
return self.user_from_dial(self.dial)
def set_value(self,value):
self.dial = self.dial_from_user(value)
value = property(get_value,set_value)
def get_command_value(self):
"""Target value, in user units, taking into account offset"""
return self.user_from_dial(self.dial)
def set_command_value(self,command_value):
self.dial = self.dial_from_user(command_value)
command_value = property(get_command_value,set_command_value)
def theta(self,x1,x2):
"""Tilt angle in mrad as function of jack positions in mm"""
return (x1-x2)/self.distance
def x1_x2(self,x1,x2,theta):
"""New positions for new tilt angle in mm"""
# Keep the center constant
dtheta = theta - self.theta(x1,x2)
dx = dtheta*self.distance
x1,x2 = x1 + dx/2,x2 - dx/2
return x1,x2
def user_from_dial(self,value): return value * self.sign + self.offset
def dial_from_user(self,value): return (value - self.offset) / self.sign
if __name__ == "__main__":
from EPICS_motor import motor
print('motor("14IDC:m12").value = %.6f # mir2X1' % motor("14IDC:m12").value)
print('motor("14IDC:m13").value = %.6f # mir2X2' % motor("14IDC:m13").value)
print('motor("14IDC:mir2Th").value = %.6f' % motor("14IDC:mir2Th").value)
mir2X1 = motor("14IDC:m12",name="mir2X1") # H mirror X1-upstream
mir2X2 = motor("14IDC:m13",name="mir2X2") # H mirror X1-downstream
print("mir2X1.__prefix__ = %r" % mir2X1.__prefix__)
print("mir2X2.__prefix__ = %r" % mir2X2.__prefix__)
print("mir2X1.value = %.6f" % mir2X1.value)
print("mir2X2.value = %.6f" % mir2X2.value)
mir2Th = tilt(mir2X1,mir2X2,distance=1.045,name="mir2Th")
print("mir2Th.offset = %r" % mir2Th.offset)
print("mir2Th.value = %.6f" % mir2Th.value)
stepsize = 0.000416*2/1.045
print("mir2Th.value += %.6f" % (stepsize*3))
self = mir2Th
<file_sep>from GigE_camera import GigE_camera,sleep
from time import time
from numpy import average,sum
# id14b-prosilica1 - Microscope camera
# id14b-prosilica2 - Wide-field camera
# id14b-prosilica3 - Laser beam profile at sample
# id14b-prosilica4 - Laser beam profile in beam conditioning box
camera = GigE_camera("id14b-prosilica1.cars.aps.anl.gov",
use_multicast=False)
camera.pixel_format = "Rgb24"
camera.start()
t = time()
while not camera.has_image:
print camera.state
if time()-t > 2.0 and not "started" in camera.state:
print ("Prosilica image unreadable (%s)" % camera.state)
break
if time()-t > 5.0:
print ("image acquistion timed out (%s)" % camera.state)
break
sleep(0.1)
print "acquisition time %.3fs" % (time()-t)
R,G,B = image = camera.rgb_array
camera.stop()
I = float(sum(image))/image.size
print "average: %g counts/pixel" % I
print "fraction of pixels >0: %g" % average(image != 0)
def rotate(image,angle):
"""A rotated version of the input image.
'angle' is in units of deg, positive = counterclockwise.
'angle' must be a multiple of 90 deg"""
if angle % 360 == 0: return image
if angle % 360 == 90: return image.transpose(0,2,1)[:,:,::-1]
if angle % 360 == 180: return image[:,::-1,::-1]
if angle % 360 == 270: return image.transpose(0,2,1)[:,::-1,:]
return image
image2 = rotate(image,90)
# Display the image
from pylab import *
chart = figure(figsize=(8,8))
imshow(minimum(image2,255).T,cmap=cm.gray,origin='upper',interpolation='nearest')
show()
<file_sep>Ensemble.ip_address = 'pico7.niddk.nih.gov:2000'
GigE_camera.MicroscopeCamera.camera.IP_addr = 'pico14.niddk.nih.gov'
GigE_camera.MicroscopeCamera.ip_address = 'pico7.niddk.nih.gov:2002'
GigE_camera.WideFieldCamera.camera.IP_addr = 'pico3.niddk.nih.gov'
GigE_camera.WideFieldCamera.ip_address = 'pico7.niddk.nih.gov:2001'
MicroscopeCamera.ImageWindow.Center = (680.0, 512.0)
MicroscopeCamera.Mirror = False
MicroscopeCamera.NominalPixelSize = 0.000517
MicroscopeCamera.Orientation = -90
MicroscopeCamera.camera.IP_addr = 'pico14.niddk.nih.gov'
MicroscopeCamera.x_scale = -1.0
MicroscopeCamera.y_scale = 1.0
MicroscopeCamera.z_scale = -1.0
WideFieldCamera.ImageWindow.Center = (713.0, 511.0)
WideFieldCamera.Mirror = False
WideFieldCamera.NominalPixelSize = 0.002445
WideFieldCamera.Orientation = -90
WideFieldCamera.camera.IP_addr = 'pico3.niddk.nih.gov'
WideFieldCamera.x_scale = -1.0
WideFieldCamera.y_scale = 1.0
WideFieldCamera.z_scale = -1.0
laser_oscilloscope.ip_address = 'pico21.niddk.nih.gov:2000'
laser_scope.ip_address = 'femto10.niddk.nih.gov:2000'
rayonix_detector.ip_address = 'pico7.niddk.nih.gov:2222'
sample.phi_motor_name = 'SamplePhi'
sample.phi_scale = 1.0
sample.rotation_center = (-0.8944974374999999, -0.22401040878981504)
sample.x_motor_name = 'SampleX'
sample.x_scale = 1.0
sample.xy_rotating = False
sample.y_motor_name = 'SampleY'
sample.y_scale = 1.0
sample.z_motor_name = 'SampleZ'
sample.z_scale = 1.0
timing_system.ip_address = 'pico23.niddk.nih.gov:2000'
xray_oscilloscope.ip_address = 'pico9.niddk.nih.gov:2000'
xray_scope.ip_address = 'pico21.niddk.nih.gov:2000'
timing_system.ip_address_and_port = 'pico23.niddk.nih.gov:2002'
timing_system.prefix = 'NIH:TIMING.'<file_sep>"""
Shorthand notation for timing sequences
Author: <NAME>
Date created: 2018-10-02
Date last modified: 2010-05-13
"""
__version__ = "1.2" # temperature ramp starting with hold_low
from logging import debug,info,warn,error
from Ensemble_SAXS_pp import Sequence,Sequences,sequence,seq,sequences
def expand_sequence(s,report=None):
if report: report(format_report("Original",s))
operations = [
quote_binary_numbers,
quote_strings,
expand_SI_units,
add_toplevel_dictionary,
add_dictionaries,
fix_repeat_syntax,
expand_generators,
add_constructors,
add_expanders,
expand_generators,
]
for operation in operations:
new = operation(s)
if new != s:
s = new
if report: report(format_report(name(operation),s))
return s
def delay_sequences(s,report=None):
if report: report(format_report("Original",s))
operations = [
quote_binary_numbers,
quote_strings,
expand_SI_units,
add_toplevel_dictionary,
add_dictionaries,
fix_repeat_syntax,
expand_generators,
delays_to_sequences,
]
for operation in operations:
new = operation(s)
if new != s:
s = new
if report: report(format_report(name(operation),s))
return s
def expand(s,report=None):
if report: report(format_report("Original",s))
operations = [
quote_binary_numbers,
quote_strings,
expand_SI_units,
add_toplevel_dictionary,
add_dictionaries,
fix_repeat_syntax,
expand_generators,
]
for operation in operations:
new = operation(s)
if new != s:
s = new
if report: report(format_report(name(operation),s))
return s
def name(operation): return operation.__name__.replace("_"," ").capitalize()
def format_report(name,s):
return name+"\n"+",\n".join(split_list(s))+"\n"
def delays_to_sequences(s,report=None):
## "{'delays': [0.001, 0.00178, 0.00316, 0.00562, 0.01, 0.0178, 0.0316, 0.0562]}"
dictionary = eval(s)
parameters = dictionary["delays"]
sequences = []
for parameter in parameters:
if type(parameter) == dict: sequences += [Sequence(**parameter)]
else: sequences += [Sequence(parameter)]
s = repr(sequences)
return s
def quote_binary_numbers(s):
""" S=001 -> S='101' """
from re import sub
# S=001 -> S='101'
s = sub(r"(^|[=:\[\({])([01]{3,5})([ ,=:*\]\)}]|$)",r"\1'\2'\3",s)
# (...)(...)(...) defining three groups: pre-match, substitute, post-match
# ^|[ ,=\[\(]) = begin of string of any of the characters space, comma, [, or (
# [01]{3,5} = 0 or 1, repeated 3 to 5 times
# [ ,=\]\)]|$ = any of the characters space, comma, ], ), or end of string
# \1 \2 \3, matching groups defined by grouping parentheses (...)(...)(...)
return s
def quote_strings(s):
""" PP=Flythru-4 -> PP='Flythru-4' """
from re import sub
# seq=NIH:i5c1 -> seq="NIH:i5c1"
s = sub(r"(NIH:[A-Za-z0-9_-]*)",r"'\1'",s)
# PP=Flythru-4 -> PP='Flythru-4', but not 'pairs(-10us,...'
s = sub(r"=([A-Za-z][A-Za-z0-9_-]*)([^A-Za-z0-9_\(])",r"='\1'\2",s)
# {enable:'111'} {'enable':'111'}
s = sub(r"([^A-Za-z0-9_'])([A-Za-z][A-Za-z0-9_-]*):",r"\1'\2':",s)
return s
def expand_SI_units(s):
from re import sub
SI_prefixes = {"p":"e-12","n":"e-9","u":"e-6","m":"e-3"}
for p in SI_prefixes: s = sub("([0-9])"+p,r"\1"+SI_prefixes[p],s)
s = sub("([0-9])s",r"\1",s)
return s
def add_toplevel_dictionary(s):
from re import sub
keyword = r"[a-zA-Z_]+"
s = sub("^("+keyword+"=.*)",r"dict(\1)",s)
return s
def add_dictionaries_1(s):
from re import sub
key = r"[<KEY>
interger = r"[0-9]+"
floating_point_number = r"([0-9]+[.]*[0-9]*e[0-9]+)"
number = "("+interger+'|'+floating_point_number+")"
string = r"('[^']*')"
value = "("+number+"|"+string+")"
list = "([("+value+" *,)*"+value+"])"
expr = "("+value+"|"+list+")"
expr = value
key_value_pair = "("+key+"="+expr+")"
argument_list = '('+key_value_pair+', *)*'+key_value_pair
incomplete_argument_list = value+', *'+argument_list
pattern = '('+argument_list+')'
s = sub(pattern,r"dict(\1)",s)
return s
def add_dictionaries(s):
from re import sub
key = r"[<KEY>
value = r"[0-9A-Za-z-'+*]+"
pair = key+"="+value
argument_list = '('+pair+', *)*'+pair
argument_list_in_parenteses = r'\('+argument_list+r'\)'
lookbehind = r'(?<=[^A-Za-z_])'
pattern = lookbehind+'('+argument_list_in_parenteses+')'
s = sub(pattern,r"dict\1",s)
pattern = '^('+argument_list_in_parenteses+')' # ^=begin of string
s = sub(pattern,r"dict\1",s)
incomplete_argument_list = value+', *'+argument_list
incomplete_argument_list_in_parenteses = r'\('+incomplete_argument_list+r'\)'
pattern = lookbehind+'('+incomplete_argument_list_in_parenteses+')'
s = sub(pattern,r"dict(delay=\1)",s)
return s
def add_constructors(s):
from re import sub
s = sub("{","Sequences(**{",s)
s = sub("}","})",s)
return s
def fix_repeat_syntax(s):
"""Sequences(nan,SEQ='100')*32 -> [Sequences(nan,SEQ='100')]*32"""
from re import sub
T = split_list(s)
for i in range(0,len(T)):
t = T[i]
t = sub(r"^(.*\(.*\))\*([0-9]+)$",r"[\1]*\2",t)
T[i] = t
s = ", ".join(T)
return s
def expand_generators(s):
from flatten import flatten
from numpy import nan # for eval
t = eval("["+s+"]")
t = flatten(t)
s = repr(t).strip("[]")
return s
def add_expanders(s):
T = split_list(s)
for i in range(0,len(T)):
t = T[i]
if t.startswith("Sequences("): t += "[:]"
T[i] = t
s = ", ".join(T)
return s
def lin_series(start,end,step,interleave=None):
"""Linear series"""
from numpy import arange,finfo
eps = finfo(float).eps
t = arange(start,end+eps,step)
t = [round_exp(x,3) for x in t]
t = list(t)
if interleave is not None: t = interleave_value(t,interleave)
return t
def log_series(start,end,steps_per_decade=4,interleave=None):
"""Geometric series"""
from numpy import log10,arange,finfo
eps = finfo(float).eps
t = 10**arange(log10(start),log10(end+eps)+1e-3,1./steps_per_decade)
t = [round_exp(x,3) for x in t]
# Make sure end point is included.
if end <= t[-1]*1.01: t[-1] = end
else: t += [end]
t = list(t)
if interleave is not None: t = interleave_value(interleave,t)
return t
def interleave_value(t0,series,begin=False,end=False):
"""Add t0 between every element of *series*"""
T = []
if begin: T += [t0]
if len(series) > 0: T += [series[0]]
for t in series[1:]: T += [t0,t]
if end: T += [t0]
return T
interleave = interleave_value
def pairs(t0,series):
"""preceed every elelemt of *series* with t0"""
T = []
for t in series: T += [t0,t]
return T
pair = pairs
def arange(start,end,step=1.0):
"""list of value from *start* to *end*, inclusive *end*"""
from numpy import arange,finfo,sign
eps = finfo(float).eps
s = sign(end-start)
step = s*abs(step)
values = arange(start,end*(1+s*2*eps),step)
values = list(values)
return values
def ramp(low=20.0,high=24.0,step=1.0,hold=1,hold_low=None,hold_high=None,repeat=1):
"""List of values from *low* to *high* and back to *low* again"""
from numpy import sign
if hold_low is None: hold_low = hold
if hold_high is None: hold_high = hold
s = sign(high-low)
step = s*abs(step)
values = (
[low ]*hold_low +
arange(low,high-step,step) +
[high]*hold_high +
arange(high,low-step,step)
)
values = values*repeat
return values
def power(T0=1.0,N_per_decade=4,N_power=6,reverse=False):
"""Power titration series
T0: highest transmission level
reverse=False: falling
reverse=True: rising
"""
from numpy import log10,arange
t = T0 * 10**(-arange(0.,N_power)/N_per_decade)
t = [round_exp(x,3) for x in t]
t = list(t)
if reverse: t = t[::-1]
return t
def round_exp(x,n):
"""Round floating point number to *n* decimal digits in the mantissa"""
return float(("%."+str(n)+"g") % x)
def split_list(s):
"""Split a comma-separated list, with out breaking up list elements
enclosed in backets or parentheses"""
start = 0
level = 0
elements = []
for i in range(0,len(s)):
if s[i] in ["(","[",'{']: level += 1
if s[i] in [")","]",'}']: level -= 1
if s[i] == "," and level == 0:
end = i
element = s[start:end].strip()
if element: elements += [element]
start = i+1
end = len(s)
element = s[start:end].strip()
if element: elements += [element]
return elements
if __name__ == "__main__":
from pdb import pm
import logging
logging.basicConfig(level=logging.DEBUG,format="[%(levelname)-5s] %(module)s.%(funcName)s: %(message)s")
from instrumentation import *
s = "-10us,interleave(-10us,lin_series(-100ps,75ps,25ps)+log_series(100ps,1us,steps_per_decade=4)),-10us"
s = '-10us,interleave(-10us,log_series(10ms,178ms,steps_per_decade=4)),-10us'
s = '(-10us,PP=Flythru-48),interleave(-10us,log_series(10ms,178ms,steps_per_decade=4)),-10us'
s = "(144, S=[110]*5+[101]), (1440, S=[100]*8+[101]), (14400, S=[100]*89+[101])"
s = "(nan, PLP=Period-48, SEQ=010)*5, (nan, PLP=Period-144, SEQ=100), (264+1*144, SEQ=101), (nan, SEQ=100)*2, (264+4*144, SEQ=101), (nan, SEQ=100)*4, (264+9*144, SEQ=101), (nan, SEQ=100)*8, (264+18*144, SEQ=101), (nan, SEQ=100)*16, (264+35*144, SEQ=101), (nan, SEQ=100)*32, (264+68*144, SEQ=101)"
##s = "(-10us, PLP=Flythru-4), -10us, (264, SEQ=1010), 528, 792, 1056, (-10us, SEQ=1111), -10us"
s = '[enable=011]*4+[enable=111]'
s = "[(pp=Period-48, enable=010)]*5, (image=0, pp=Period-144, enable=100), (264+1*144, enable=101), [(image=0, enable=100)]*2, (264+4*144, enable=101), (image=0, enable=100)*4, (264+9*144, enable=101), (image=0, enable=100)*8, (264+18*144, enable=101), (image=0, enable=100)*16, (264+35*144, enable=101), (image=0, enable=100)*32, (264+68*144, enable=101)"
s = '{enable:111}'
##print('add_dictionaries("hsc=\'H-56\',pp=\'Flythru-4\',seq=\'NIH:i1\',delays=[]")')
##print('add_toplevel_dictionary("hsc=\'H-56\',pp=\'Flythru-4\',seq=\'NIH:i1\'")')
print("x=expand_sequence(sequence_modes.acquisition.value,report=debug)")
print("x=expand_sequence(scan_configuration.points.value,report=debug)")
print("x=expand_sequence(temperature_configuration.list.value,report=debug)")
print("x=expand_sequence(power_configuration.list.value,report=debug)")
print("x=delay_sequences(delay_configuration.delay_configuration.value,report=debug)")
print('max(arange(-2,2,0.05))')
<file_sep>#!/bin/env python
"""
Start servers automatically
Author: <NAME>,
Date created: 2017-10-23
Date last modified: 2019-03-21
"""
__version__ = "1.0.5" # proc.cmdline exception (psutil.NoSuchProcess, was: psutil.ProcessZombie)
from logging import debug,info,warn,error
import traceback
class Server(object):
from persistent_property import persistent_property
label = persistent_property("servers.{name}.label","")
command = persistent_property("servers.{name}.command","")
logfile_basename = persistent_property("servers.{name}.logfile_basename","servers")
enabled = persistent_property("servers.{name}.enabled",True)
value_code = persistent_property("servers.{name}.value_code","True")
format_code = persistent_property("servers.{name}.format_code","str(value)")
test_code = persistent_property("servers.{name}.test_code","value")
def __init__(self,name,command=None):
self.name = name
if command is not None: self.command = command
def get_running(self):
return process_running(self.command_line)
def set_running(self,value):
if value != self.running:
if value: self.start()
else: self.stop()
running = property(get_running,set_running)
def start(self):
"""Execute the command in a subprocess.
The standard ouput and standard error output are redirected to a
logfile."""
from subprocess import Popen
Popen(self.command_line,stdin=None,stdout=None,stderr=None,
close_fds=True)
def stop(self):
terminate_process(self.command_line)
@property
def command_line(self):
from sys import executable as python
command = "from redirect import *; redirect(%r); %s" % \
(self.logfile_basename,self.command)
command_line = [python,"-c",command]
return command_line
def get_log(self):
try: value = file(self.log_filename,"rb").read()
except IOError: value = ""
return value
def set_log(self,value):
file(self.log_filename,"wb").write(value)
log = property(get_log,set_log)
def get_stdout(self):
try: value = file(self.stdout_filename,"rb").read()
except IOError: value = ""
return value
def set_stdout(self,value):
file(self.stdout_filename,"wb").write(value)
stdout = property(get_stdout,set_stdout)
def get_stderr(self):
try: value = file(self.stderr_filename,"rb").read()
except IOError: value = ""
return value
def set_stderr(self,value):
file(self.stderr_filename,"wb").write(value)
stderr = property(get_stderr,set_stderr)
@property
def log_filename(self):
from redirect import log_filename
return log_filename(self.logfile_basename)
@property
def stdout_filename(self):
from redirect import stdout_filename
return stdout_filename(self.logfile_basename)
@property
def stderr_filename(self):
from redirect import stderr_filename
return stderr_filename(self.logfile_basename)
@property
def test_code_OK(self):
"""Is the code for this test executable?"""
exec("from instrumentation import *")
from numpy import nan,isnan
value = self.value
try: eval(self.test_code); OK = True
except Exception,msg:
warn("value: %s: %s\n%s" % (self.test_code,msg,traceback.format_exc()))
OK = False
return OK
@property
def value(self):
"""Current value of diagnostic"""
exec("from instrumentation import *")
from numpy import nan,isnan
try: value = eval(self.value_code)
except Exception,msg:
warn("value: %s: %s\n%s" % (self.value_code,msg,traceback.format_exc()))
value = ""
return value
@property
def formatted_value(self):
"""Current value of diagnostic as string"""
value = self.value
from numpy import nan,isnan
try: text = eval(self.format_code)
except Exception,msg:
warn("value: %s with value=%r: %s\n%s" % (self.format_code,value,msg,
traceback.format_exc()))
text = str(value)
return text
@property
def OK(self):
"""Did this test pass OK?"""
exec("from instrumentation import *")
from numpy import nan,isnan
value = self.value
try: passed = eval(self.test_code)
except: passed = True
return passed
class Servers(object):
"""Collection of Server objects"""
name = "servers"
from persistent_property import persistent_property
N = persistent_property("N",0)
servers = {}
def __getitem__(self,i):
if not i in self.servers: self.servers[i] = Server("%d" % (i+1))
return self.servers[i]
def __len__(self): return self.N
def __iter__(self):
for i in range(0,len(self)):
if i < len(self): yield self[i]
def get_running(self):
return all([server.running for server in self if server.enabled])
def set_running(self,value):
for server in self:
if server.enabled:
if value != server.running: server.running = value
running = property(get_running,set_running)
def get_Nrunning(self):
return sum([server.running for server in self if server.enabled])
Nrunning = property(get_Nrunning)
servers = Servers()
def process_running(command_line):
"""Is there at least one process running matching command_line somewhere in
the pathname or comand line arguments?
command_line: string or list of strings
"""
import psutil
if not isinstance(command_line,basestring):
command_line = " ".join(command_line)
running = False
for proc in psutil.process_iter():
try: arg_list = proc.cmdline()
except: arg_list = []
if command_line in " ".join(arg_list): running = True; break
return running
def terminate_process(command_line):
"""Terminate all running processes, matching command_line somewhere in
the pathname or comand line arguments
command_line: string or list of strings
"""
import psutil
if not isinstance(command_line,basestring):
command_line = " ".join(command_line)
for proc in psutil.process_iter():
try: arg_list = proc.cmdline()
except psutil.AccessDenied: arg_list = []
except psutil.ZombieProcess: arg_list = []
if command_line in " ".join(arg_list): proc.kill()
if __name__ == "__main__":
""""for testing"""
from pdb import pm
import logging
logging.basicConfig(level=logging.DEBUG,format="%(asctime)s %(levelname)s: %(message)s")
from time import time
self = server = servers[0]
print('servers.N = %r' % servers.N)
for i in range(0,len(servers)):
print('servers[%d].label = %r' % (i,servers[i].label))
print('servers[%d].command = %r' % (i,servers[i].command))
##print('')
##for i in range(0,len(servers)):
## print('servers[%d].running = %r' % (i,servers[i].running))
##print('servers.Nrunning = %r' % servers.Nrunning)
print('print servers[5].log')
<file_sep>from inspect import getfile
from os.path import dirname
def f(): pass
dir=dirname(getfile(f))
<file_sep>"""
<NAME>, APS 27 Oct 2007
The is to scan the Gigabaudics PADL3-10-11 delay line
control bit 3 has got a very high attenuation, making te Lock-to-Clock loose
synchtonization.
This is to perform a full range scan avioding the defective delay.
(50 % of the full range).
"""
from timing_system import *
class broken_delayline (object):
def __init__(self,bit=3):
object.__init__(self)
self.name = "allowed count"
self.bit = bit # broken bit
def get_value(self):
"""reads current value and removes broken bit"""
count = psd1.count
count = int(round(count))
low_mask = (1<<self.bit)-1
high_mask = ~((1<<(self.bit+1))-1)
allowed_count = ((count & high_mask)>>1) | (count & low_mask)
return allowed_count
def set_value(self,value):
value = int(round(value))
"""insert bit 3 = before writing count to hardware"""
low_mask = (1<<self.bit)-1
high_mask = ~((1<<self.bit)-1)
count = ((value & high_mask)<<1) | (value & low_mask)
psd1.count = count
value = property(get_value,set_value,doc="allowed count")
allowed_count = broken_delayline(bit=3)
<file_sep>show_in_list = True
title = 'Detector Configuration'
motor_names = ['collect.detector_configuration', 'xray_scope.setup', 'laser_scope.setup']
names = ['detectors', 'xray_scope_setup', 'laser_scope_setup', 'motor2']
motor_labels = ['Detectors', 'X-ray Scope Setup', 'Laser Scope Setup']
widths = [280, 170, 170]
line0.xray_scope.setup = 'NIH SAXS-WAXS'
line0.laser_scope.setup = 'NIH SAXS-WAXS'
line0.updated = '2019-05-28 20:24:36'
line1.xray_scope.setup = 'NIH FPGA diagnostics'
line1.laser_scope.setup = 'FPGA diagnostics'
line1.updated = '2019-01-28 18:17:10'
line0.description = 'SAXS/WAXS'
line1.description = 'FPGA diagnostics'
command_rows = [0]
line0.detectors = 'xray_detector, xray_scope, laser_scope'
line0.collect.detector_configuration = 'xray_detector, xray_scope, laser_scope'
nrows = 9
line2.description = 'SAXS/WAXS static'
line2.collect.detector_configuration = 'xray_detector, xray_scope'
line2.xray_scope.setup = 'NIH SAXS-WAXS'
line2.laser_scope.setup = ''
line2.updated = '2019-05-28 19:49:55'
line3.description = 'NIH:Channel-Cut-Scan'
line3.collect.detector_configuration = 'xray_scope'
line3.updated = '2019-01-28 18:16:58'
line3.xray_scope.setup = 'NIH Channel Cut Scan'
line4.description = 'NIH:Slit-Scan'
line4.collect.detector_configuration = 'xray_scope'
line4.updated = '2019-03-18 17:06:12'
line4.xray_scope.setup = 'NIH Slit Scan'
line5.description = 'X-Ray Alignment'
line5.collect.detector_configuration = ''
line5.updated = '2019-01-29 08:48:16'
line5.xray_scope.setup = 'Alignment'
line5.laser_scope.setup = ''
row_height = 20
line6.xray_scope.setup = 'APS Channel Cut Scan'
line6.updated = '2019-01-29 17:04:44'
line6.description = 'APS:Channel-Cut-Scan'
description_width = 180
line7.description = 'NIH:X-Ray Beam Check'
line7.collect.detector_configuration = 'xray_scope'
line7.updated = '2019-01-29 22:55:00'
line7.xray_scope.setup = 'NIH X-Ray Beam Check'
line8.collect.detector_configuration = 'xray_detector'
line8.updated = '2019-02-04 11:50:52'
line8.xray_scope.setup = '<NAME>'
line8.laser_scope.setup = ''
line8.description = '<NAME>'<file_sep>zoom_levels = [7, 10, 12.5, 16, 20, 25, 32, 40, 50, 63, 90]
zoom_level = 32.0
dt = 0.05
title = 'Lab Microscope'<file_sep>"""<NAME>, 27 Jun 2012 - 9 Nov 2012"""
from pdb import pm
from numpy import *
import lauecollect_new as lauecollect
##from interpolate_2D import interpolate_2D
from lauecollect_new import interpolate_2D
from matplotlib.mlab import griddata
from pylab import *
lauecollect.param.path = "//id14bxf/data/anfinrud_1211/Data/Laue/PYP-E46Q-H/PYP-E46Q-H46.1-288K"
phi = 0
PHI,Z,X,Y,OFFSET = array(lauecollect.align_table())[0:5]
phi1,phi2 = unique(PHI)[0:2]
nsteps_phi = 5
phis = arange(phi1,phi2+1e-6,(phi2-phi1)/(nsteps_phi-1))
nsteps_z = 22
z1,z2 = min(Z),max(Z)
zs = arange(z1,z2+1e-6,(z2-z1)/(nsteps_z-1))
phis2d,zs2d = meshgrid(phis,zs)
##offsets2d = griddata(PHI,Z,OFFSET,phis2d,zs2d)
offsets2d = array([[interpolate_2D(PHI,Z,OFFSET,phi,z) for phi in phis]
for z in zs])
figure(figsize=(8.5,11))
subplot(211)
plot(zs2d,offsets2d)
xlabel("GonZ[mm]"); ylabel("offset[mm]")
legend(["%.3f deg" % x for x in phis])
grid()
subplot(212)
imshow(offsets2d,cmap=cm.jet,interpolation="nearest")
colorbar()
xticks(xticks()[0],["%.3f" % x for x in phis],rotation=90)
yticks(yticks()[0],["%.3f" % y for y in zs])
xlabel("Phi[deg]"); ylabel("GonZ[mm]")
show()
<file_sep>#!/usr/bin/env python
"""Instruct the ADXV image display application to display a live image during
data collection
Author: <NAME>
Date created: 2019-06-02
Date last modified: 2019-06-02
"""
from ADXV_live_image import ADXV_live_image
from Panel import BasePanel,PropertyPanel,ButtonPanel,TogglePanel,TweakPanel
import wx
from numpy import inf
__version__ = "1.0"
class ADXV_Live_Image_Panel(BasePanel):
name = "ADXV_Live_Image_Panel"
title = "ADXV Live Image"
standard_view = [
"Live image",
"ADXV status",
"Filename",
"Live filename",
"Refresh interval",
]
parameters = [
[[TogglePanel, "Live image",ADXV_live_image,"live_image"],{"type":"Off/On","refresh_period":0.25}],
[[PropertyPanel,"ADXV status",ADXV_live_image,"online"],{"type":"Offline/Online","read_only":True,"refresh_period":0.25}],
[[PropertyPanel,"Filename",ADXV_live_image,"image_filename"],{"read_only":True,"refresh_period":1.0}],
[[PropertyPanel,"Live filename",ADXV_live_image,"live_image_filename"],{"read_only":True,"refresh_period":0.25}],
[[PropertyPanel,"IP Address",ADXV_live_image,"ip_address"],{"refresh_period":1.0}],
[[PropertyPanel,"Refresh interval",ADXV_live_image,"refresh_interval"],{"format":"%g","unit":"s","refresh_period":1.0}],
]
def __init__(self,parent=None):
BasePanel.__init__(self,
parent=parent,
name=self.name,
title=self.title,
icon="ADXV",
parameters=self.parameters,
standard_view=self.standard_view,
label_width=140,
width=260,
refresh=False,
live=False,
)
self.Bind(wx.EVT_CLOSE,self.OnClose)
def OnClose(self,event=None):
# Shut down background tasks.
ADXV_live_image.live_image = False
self.Destroy()
if __name__ == '__main__':
from pdb import pm # for debugging
from redirect import redirect
redirect("ADXV_Live_Image_Panel")
import wx
app = wx.App(redirect=False)
panel = ADXV_Live_Image_Panel()
app.MainLoop()
<file_sep>"""Are two Python objects considered the same?
Author: <NAME>
Date created: 2019-01-39
"""
__version__ = "1.0.1" # allclose too relaxed
def same(x,y):
"""Are two Python objects considered the same?"""
try:
if x == y: return True
except: pass
try:
from numpy import isnan
if isnan(x) and isnan(y): return True
except: pass
## try:
## from numpy import allclose
## if allclose(x,y): return True
## except: pass
return False
<file_sep>oas"""Data Collection for Wang Group
Author: <NAME>
Date created: 2018-05-24
Date last modified: 2018-05-24
"""
__version__ = "1.0" #
from pdb import pm # for debugging
import logging
logging.basicConfig(level=logging.DEBUG,format="%(asctime)s: %(levelname)s %(message)s")
from instrumentation import ccd,timing_sequencer,timing_system
from numpy import *
if True:
timepoints = [300]
nlaser = 10
directory = "//femto-data/C/Data/2018.06/Test/test3"
file_basename = "test3_11"
filenames = ["%s/%s_%gs.mccd" % (directory,file_basename,t) for t in timepoints]
dt = timing_system.hsct*48
it0 = max(nlaser,2)+1 # number seqeunces before t=0
N = it0 + int(rint(max(timepoints)/dt))+1+50
# Laser pulse burst is centered at t=0.
laser_on = array([0]*N)
nlaser1 = nlaser; nlaser2 = nlaser-nlaser1
laser_on[it0-nlaser1:it0+nlaser2] = 1
xray_on = array([0]*N)
for t in timepoints: xray_on[it0 + int(rint(t/dt))] = 1
ms_on = xray_on
# Trigger X-ray detector after X-ray ms shutter pulse
xdet_on = roll(ms_on,1)
# Additional detector triggers to clear zingers (must be >100 ms ealier)
xdet_on += roll(ms_on,-2)
image_numbers = cumsum(xdet_on)
save_filenames = [""]*max(image_numbers)
j = 0
for i in range(0,N):
if image_numbers[i] > 0 and xray_on[i-1]:
save_filenames[image_numbers[i]-1] = filenames[j]
j += 1
save_image_numbers = range(1,max(image_numbers)+1)
waitt = array([dt]*N)
npulses = array([1]*N)
def setup():
timing_sequencer.acquire(laser_on=laser_on,
npulses=npulses,waitt=waitt,burst_waitt=waitt,
image_numbers=image_numbers,
ms_on=ms_on,xdet_on=xdet_on,
xosct_on=xray_on,losct_on=laser_on)
timing_system.image_number.count = 0
##ccd.acquire_images(save_image_numbers,save_filenames)
def start(): timing_sequencer.acquisition_start()
def finish():
from time import sleep
while timing_sequencer.image_number < max(save_image_numbers): sleep(dt)
timing_sequencer.acquisition_cancel()
def cancel(): timing_sequencer.acquisition_cancel()
def collect():
setup()
start()
finish()
print("timing_system.ip_address = %r" % timing_system.ip_address)
print("timing_system.cache_timeout = %r" % timing_system.cache_timeout)
print("")
print("setup()")
print("start()")
print("finish()")
print("collect()")
##collect()
<file_sep>#!/usr/bin/env python
"""
Prosilica GigE CCD cameras.
Author: <NAME>
Date created: 2017-04-13
Date last modified: 2018-10-30
Configuration:
from DB import dbset
dbset("GigE_camera.WideFieldCamera.camera.IP_addr","pico3.niddk.nih.gov")
dbset("GigE_camera.MicroscopeCamera.camera.IP_addr","pico14.niddk.nih.gov")
dbset("GigE_camera.WideFieldCamera.ip_address","pico20.niddk.nih.gov:2001")
dbset("GigE_camera.MicroscopeCamera.ip_address","pico20.niddk.nih.gov:2002")
"""
__version__ = "2.0.1" # logging
from logging import debug,info,warn,error
from GigE_camera import GigE_camera
class Camera(GigE_camera):
from persistent_property import persistent_property
IP_addr = persistent_property("GigE_camera.{name}.camera.IP_addr",
"pico3.niddk.nih.gov")
use_multicast = persistent_property("GigE_camera.{name}.use_multicast",False)
buffer_size = 10
def __init__(self,name):
GigE_camera.__init__(self)
self.name = name
self.filenames = {}
def get_acquiring(self):
return self.acquisition_started
def set_acquiring(self,value):
if value: self.start()
else: self.stop()
acquiring = property(get_acquiring,set_acquiring)
def monitor(self):
if self.auto_resume: self.resume()
self.save_current_image()
def acquire_sequence(self,framecounts,filenames):
"""Save a series of images"""
for framecount,filename in zip(framecounts,filenames):
if not framecount in self.filenames:
self.filenames[framecount] = []
if not filename in self.filenames[framecount]:
self.filenames[framecount] += [filename]
def save_current_image(self):
"""Check whether the last acquired image needs to be saved
and save it."""
if len(self.filenames) > 0:
frame_count = self.frame_count
if frame_count in self.filenames:
for filename in self.filenames[frame_count]:
self.save_image(self.rgb_data,filename)
del self.filenames[frame_count]
def save_image(self,rgb_data,filename):
from PIL import Image
image = Image.new('RGB',(self.width,self.height))
image.frombytes(rgb_data)
image = self.rotated_image(image)
from os import makedirs; from os.path import dirname,exists
if not exists(dirname(filename)): makedirs(dirname(filename))
info("Saving %r" % filename)
from thread import start_new_thread
start_new_thread(image.save,(filename,))
# in degrees counter-clockwise
orientation = persistent_property("{name}.Orientation",0)
def rotated_image(self,image):
"""image: PIL image object"""
return image.rotate(self.orientation)
camera = Camera("MicroscopeCamera")
self = camera # for debugging
from tcp_server_single_threaded import tcp_server
server = tcp_server(globals=globals(),locals=locals())
server.ip_address_and_port_db = "GigE_camera.MicroscopeCamera.ip_address"
server.idle_timeout = 1.0
##server.idle_callbacks += [camera.monitor]
##server.idle_callbacks += [camera.resume]
##server.idle_callbacks += [camera.save_current_image]
def run(name):
camera.name = name
server.ip_address_and_port_db = "GigE_camera.%s.ip_address" % name
server.run()
def set_defaults():
from DB import dbset
dbset("GigE_camera.WideFieldCamera.camera.IP_addr","pico3.niddk.nih.gov")
dbset("GigE_camera.MicroscopeCamera.camera.IP_addr","pico14.niddk.nih.gov")
dbset("GigE_camera.WideFieldCamera.ip_address","pico20.niddk.nih.gov:2001")
dbset("GigE_camera.MicroscopeCamera.ip_address","pico20.niddk.nih.gov:2002")
if __name__ == "__main__":
from time import time # for timing
import logging
logging.basicConfig(level=logging.INFO,format="%(asctime)s %(levelname)s %(message)s")
from sys import argv
if len(argv) > 1: run(argv[1])
print('camera.acquiring = True')
print('camera.monitor()')
print('run("MicroscopeCamera")')
print('run("WideFieldCamera")')
<file_sep>#!/usr/bin/env python
"""BioCARS Methods
Author: <NAME>, <NAME>
Date created: 2018-09-21
Date last modified: 2018-09-21
"""
__version__ = "1.0.1" # autoreload
from SavedPositionsPanel_2 import SavedPositionsPanel
if __name__ == '__main__':
from pdb import pm # for debugging
import logging # for debugging
from tempfile import gettempdir
logfile = gettempdir()+"/BioCARS_Methods_testing_Panel.log"
logging.basicConfig(level=logging.INFO,filename=logfile,
format="%(asctime)s %(levelname)s: %(message)s")
import autoreload
import wx
app = wx.App(redirect=False)
from instrumentation import * # -> globals()
panel = SavedPositionsPanel(name="BioCARS_methods_testing",globals=globals())
app.MainLoop()
<file_sep>images = ['/data/pub/junk/new_fpga/xray_images/Test-1_001.mccd']<file_sep>from id14 import GonX,GonY,GonZ
from time import time,sleep
x0 = 3.873; y0 = 5.285; z0 = 8.5
GonZ.readback_slop = 0.030
def goto_start():
GonX.value = x0 ; GonY.value = y0 ; GonZ.value = z0
while (GonX.moving or GonY.moving or GonZ.moving): sleep(0.1)
def test_xyz():
dx = 0.002; dy = 0.002; dz = 0.240 # mm
goto_start()
for i in range(1,5):
t0 = time()
GonX.value = x0+i*dx ; GonY.value = y0+i*dy ; GonZ.value = z0+i*dz
while (GonX.moving or GonY.moving or GonZ.moving): sleep(0.01)
t = time()-t0
print t
def test_z():
dz = 0.240 # mm
goto_start()
for i in range(1,5):
t0 = time()
GonZ.value = z0+i*dz
while GonZ.moving: sleep(0.01)
t = time()-t0
print t
def measure_speed():
goto_start()
dz = 5 # mm
t0 = time()
GonZ.value = z0+dz
sleep (0.05)
while GonZ.moving: sleep(0.05)
t = time()-t0
v = dz/t
print "t=%.3f, v=%.3f" % (t,v)
def continuous_test():
while True: test_xyz()
continuous_test()
<file_sep>"""
Manage settings for different locations / instruments
Author: <NAME>
Date: Jun 12, 2015
Date: May 21, 2018
"""
__version__ = "1.0.8" # timing_system.prefix
parameters = r"""
#descriptions names default_values choices
"Wide-Field Camera IP Address" GigE_camera.WideFieldCamera.camera.IP_addr \"id14b-prosilica2.cars.aps.anl.gov\" \"pico3.niddk.nih.gov\"
"Wide-Field Camera Server IP Address" GigE_camera.WideFieldCamera.ip_address \"nih-instrumentation.cars.aps.anl.gov:2001\" \"pico20.niddk.nih.gov:2001\"
"Wide-Field Camera Pixel Size [mm]" WideFieldCamera.NominalPixelSize 0.00465 0.002445
"Wide-Field Camera Orientation [deg]" WideFieldCamera.Orientation 0 90,180,-90
"Wide-Field Camera Mirror" WideFieldCamera.Mirror False True
"Wide-Field Camera Crosshair" WideFieldCamera.ImageWindow.Center (680,512)
"Wide-Field Camera X Scale Factor" WideFieldCamera.x_scale 1.0 -1.0
"Wide-Field Camera Y Scale Factor" WideFieldCamera.y_scale 1.0 -1.0
"Wide-Field Camera Z Scale Factor" WideFieldCamera.z_scale 1.0 -1.0
"Microscope Camera IP Address" GigE_camera.MicroscopeCamera.camera.IP_addr \"id14b-prosilica1.cars.aps.anl.gov\" \"pico22.niddk.nih.gov\"
"Microscope Camera Server IP Address" GigE_camera.MicroscopeCamera.ip_address \"nih-instrumentation.cars.aps.anl.gov:2002\" \"pico20.niddk.nih.gov:2002\"
"Microscope Camera Pixel Size [mm]" MicroscopeCamera.NominalPixelSize 0.000526 0.000517
"Microscope Camera Orientation [deg]" MicroscopeCamera.Orientation 0 90,180,-90
"Microscope Camera Mirror" MicroscopeCamera.Mirror False True
"Microscope Camera Crosshair" MicroscopeCamera.ImageWindow.Center (680,512)
"Microscope Camera X Scale Factor" MicroscopeCamera.x_scale 1.0 -1.0
"Microscope Camera Y Scale Factor" MicroscopeCamera.y_scale 1.0 -1.0
"Microscope Camera Z Scale Factor" MicroscopeCamera.z_scale 1.0 -1.0
"X Stage" sample.x_motor_name \"SampleX\" \"GonX\"
"Y Stage" sample.y_motor_name \"SampleY\" \"GonY\"
"Z Stage" sample.z_motor_name \"SampleZ\" \"GonZ\"
"Phi Motor" sample.phi_motor_name \"SamplePhi\" \"Phi\"
"XY Rotating" sample.xy_rotating True False
"Rotation Center" sample.rotation_center (0.0,0.0)
"Ensemble Server IP Address" Ensemble.ip_address \"nih-instrumentation.aps.anl.gov:2000\" \"pico20.niddk.nih.gov:2000\",\"172.21.46.206:2000\"
"Timing System IP Address" timing_system.ip_address_and_port \"id14timing2.cars.aps.anl.gov:2000\" \"pico23.niddk.nih.gov:2000\",\"pico24.niddk.nih.gov:2000\",\"pico25.niddk.nih.gov:2000\"
"Timing System EPICS Record" timing_system.prefix \"NIH:TIMING.\" \"NIH:TIMING3.\"
"Rayonix Detector IP Address" rayonix_detector.ip_address \"mx340hs.cars.aps.anl.gov:2222\" \"pico19.niddk.nih.gov:2222\"
"X-Ray Oscilloscope IP Address" xray_scope.ip_address \"id14b-xscope.cars.aps.anl.gov:2000\" \"pico21.niddk.nih.gov:2000\",\"femto10.niddk.nih.gov:2000\"
"Laser Oscilloscope IP Address" laser_scope.ip_address \"id14l-scope.cars.aps.anl.gov:2000\" \"femto10.niddk.nih.gov:2000\",\"pico21.niddk.nih.gov:2000\"
"""
class Configurations(object):
"""Manage settings for different locations / instruments"""
from table import table
parameters = table(text=parameters)
def get_values(self,configuration_name):
"""list of Python objects of builtin Python data types"""
from DB import dbget
prefix = "configurations/"+configuration_name+"." if configuration_name else ""
values = []
for name,default_value in zip(self.parameters.names,self.parameters.default_values):
s = dbget(prefix+name)
if s == "": s = default_value
dtype = type(eval(default_value))
try: value = dtype(eval(s))
except: value = eval(default_value)
values += [value]
return values
def set_values(self,configuration_name,values):
from DB import dbput
prefix = "configurations/"+configuration_name+"." if configuration_name else ""
for name,value,default_value,current_value in \
zip(self.parameters.names,values,self.default_values,self.current_values):
dbput(prefix+name,tostr(value,type(default_value),current_value))
def get_current_values(self): return self.get_values("")
def set_current_values(self,values): self.set_values("",values)
current_values = property(get_current_values,set_current_values)
def get_default_values(self):
return [eval(v) for v in self.parameters.default_values]
default_values = property(get_default_values)
def get_configuration_names(self):
"""List of currently in use configuration names, e.g.
"BioCARS Diffractometer","NIH Diffractometer","LCLS Diffractometer" """
from DB import dbdir
return dbdir("configurations")
configuration_names = property(get_configuration_names)
def get_current_configuration(self):
"""Which of the currently define configurations is closest to the current
settings?"""
values = self[""]
names = self.configuration_names
N = [sum([v1 == v2 for v1,v2 in zip(self[name],values)]) for name in names]
name = names[N.index(max(N))] if len(N)>0 else ""
return name
current_configuration = property(get_current_configuration)
def __getitem__(self,configuration_name):
return self.get_values(configuration_name)
def __setitem__(self,configuration_name,values):
return self.set_values(configuration_name,values)
def get_choices(self):
"""List of lists of Python objects of builtin Python data types"""
default_values = self.parameters.default_values
choices = self.parameters.choices
choices = default_values+","+choices
choices = [eval(c) for c in choices]
return choices
choices = property(get_choices)
def show(self,configuration_name=""):
s = "Configuration: "+self.current_configuration+"\n\n"
s += "Choices:\n"
for n in self.configuration_names: s += "- "+n+"\n"
s += "\n"
for n,v in zip(self.parameters.descriptions,self[configuration_name]):
s += "%-40s: %s\n" % (n,v)
print s
configurations = Configurations()
def tostr(value,dtype,default_value):
"""String represenation of a value"""
try: value = dtype(value)
except: value = default_value
value = repr(value)
return value
if __name__ == "__main__":
self = configurations # for debugging
print 'print self.parameters'
print 'self.show()'
<file_sep>#!/usr/bin/env python
from Rayonix_Detector_Panel_old import *
if __name__ == '__main__':
import Rayonix_Detector_Panel_old as module
from inspect import getfile
file = getfile(module).replace(".pyc",".py")
execfile(file)
<file_sep>#!/usr/bin/env python
"""Grapical User Interface for X-ray beam stabilization
<NAME>, Nov 23, 2015 - Oct 25, 2017
"""
from pdb import pm # for debugging
import logging
from tempfile import gettempdir
logfile = gettempdir()+"/XRayBeamCheckPanel.log"
logging.basicConfig(level=logging.DEBUG,
format="%(asctime)s %(levelname)s: %(message)s",
logfile=logfile,
)
from logging import debug,warn,info,error
from xray_beam_check import Xray_Beam_Check
from Panel import BasePanel,PropertyPanel,ButtonPanel,TogglePanel,TweakPanel
from BeamProfile_window import BeamProfile
from TimeChart import TimeChart
from persistent_property import persistent_property
import wx
__version__ = "1.1.2" # logging
class XrayBeamCheckPanel(BasePanel,Xray_Beam_Check):
title = "X-Ray Beam Check"
standard_view = [
"X [mrad]",
"Y [V]",
"X Corr. [mrad]",
"Y Corr. [V]",
"X Scan",
"Y Scan",
"X Correction",
"Y Correction",
]
def __init__(self,parent=None):
Xray_Beam_Check.__init__(self)
parameters = [
[[PropertyPanel,"Timing Mode", self.settings,"timing_mode" ],{"choices":self.settings.timing_modes}],
[[PropertyPanel,"Beamline Mode", self.settings,"beamline_mode"],{"choices":self.settings.beamline_modes}],
[[TimeChart, "X Control History",self.log,"date time","x_control"],{"axis_label":"Control X [mrad]","name":self.name+".TimeChart"}],
[[TimeChart, "Y Control History",self.log,"date time","y_control"],{"axis_label":"Control Y [V]" ,"name":self.name+".TimeChart"}],
[[PropertyPanel,"Logfile", self.log,"filename" ],{}],
[[TweakPanel, "X [mrad]", self,"x_control" ],{"digits":4}],
[[TweakPanel, "Y [V]", self,"y_control" ],{"digits":4}],
[[PropertyPanel,"X Corr. [mrad]", self,"x_control_corrected"],{"digits":4,"read_only":True}],
[[PropertyPanel,"Y Corr. [V]", self,"y_control_corrected"],{"digits":4,"read_only":True}],
[[TogglePanel, "X Scan", self,"x_scan_running" ],{"type":"Start/Cancel"}],
[[TogglePanel, "Y Scan", self,"y_scan_running" ],{"type":"Start/Cancel"}],
[[ButtonPanel, "X Correction", self,"apply_x_correction" ],{"label":"Apply"}],
[[ButtonPanel, "Y Correction", self,"apply_y_correction" ],{"label":"Apply"}],
]
BasePanel.__init__(self,
parent=parent,
name=self.name,
title=self.title,
parameters=parameters,
standard_view=self.standard_view,
subpanels=[Settings],
)
class Settings(BasePanel,Xray_Beam_Check.Settings):
title = "Settings"
standard_view = [
"X1 Motor",
"X2 Motor",
"Y Motor",
"X Resolution [mrad]",
"Y Resolution [V]",
"X Scan Step [mrad]",
"Y Scan Step [V]",
"X Aperture Motor",
"Y Aperture Motor",
"X Aperture (scan) [mm]",
"Y Aperture (scan) [mm]",
"X Aperture (norm) [mm]",
"Y Aperture (norm) [mm]",
]
def __init__(self,parent=None):
Xray_Beam_Check.__init__(self)
parameters = [
[[PropertyPanel,"Timing System", self,"timing_system_ip_address"],{}],
[[PropertyPanel,"Oscilloscope", self,"scope_ip_address" ],{}],
[[PropertyPanel,"X1 Motor", self,"x1_motor" ],{}],
[[PropertyPanel,"X2 Motor", self,"x2_motor" ],{}],
[[PropertyPanel,"Y Motor", self,"y_motor" ],{}],
[[TweakPanel, "X Resolution [mrad]",self,"x_resolution" ],{"digits":4}],
[[TweakPanel, "Y Resolution [V]", self,"y_resolution" ],{"digits":4}],
[[TweakPanel, "X Scan Step [mrad]", self,"dx_scan" ],{"digits":4}],
[[TweakPanel, "Y Scan Step [V]", self,"dy_scan" ],{"digits":4}],
[[PropertyPanel,"X Aperture Motor", self,"x_aperture_motor" ],{}],
[[PropertyPanel,"Y Aperture Motor", self,"y_aperture_motor" ],{}],
[[TweakPanel, "X Aperture [mm]", self,"x_aperture" ],{"digits":4}],
[[TweakPanel, "Y Aperture [mm]", self,"y_aperture" ],{"digits":4}],
[[TweakPanel, "X Aperture (scan) [mm]",self,"x_aperture_scan"],{"digits":4}],
[[TweakPanel, "Y Aperture (scan) [mm]",self,"y_aperture_scan"],{"digits":4}],
[[TweakPanel, "X Aperture (norm) [mm]",self,"x_aperture_norm"],{"digits":4}],
[[TweakPanel, "Y Aperture (norm) [mm]",self,"y_aperture_norm"],{"digits":4}],
]
BasePanel.__init__(self,
parent=parent,
name=self.name,
title=self.title,
parameters=parameters,
standard_view=self.standard_view,
subname=False,
)
if __name__ == '__main__':
from pdb import pm
import logging
from tempfile import gettempdir
logfile = gettempdir()+"/XRayBeamCheckPanel.log"
logging.basicConfig(level=logging.DEBUG,
format="%(asctime)s %(levelname)s: %(message)s",
logfile=logfile,
)
from logging_filename import log_to_file
log_to_file(logfile+"2","DEBUG")
# Needed to initialize WX library
if not "app" in globals(): app = wx.App(redirect=False)
panel = XrayBeamCheckPanel()
app.MainLoop()
##import threading; info("%r" % threading.enumerate())
<file_sep>"""Caching of Channel Access
Author: <NAME>
Date created: 2018-10-24
Date last modified: 2019-03-19
"""
__version__ = "1.0.5" # performance optimization
from logging import debug,info,warn,error
from cache import Cache
cache = Cache("CA")
def caget_cached(PV_name):
"""Value of Channel Access (CA) Process Variable (PV)"""
from CA import caget,camonitor
camonitor(PV_name,callback=CA_cache_update)
value = caget(PV_name,timeout=0)
if value is None:
if cache.exists(PV_name): value = cache.get(PV_name)
if value is None: value = caget(PV_name)
if value is None: warn("Failed to get PV %r" % PV_name)
return value
def CA_cache_update(PV_name,value,formatted_value):
"""Handle Process Variable (PV) update"""
value = str(value)
if not cache.exists(PV_name) or value != cache.get(PV_name):
##debug("%s=%s" % (PV_name,value))
cache.set(PV_name,value)
if __name__ == "__main__":
from pdb import pm # for debugging
import logging # for debugging
from time import time # for timing
logging.basicConfig(
level=logging.DEBUG,
format="%(asctime)s %(levelname)s %(module)s.%(funcName)s: %(message)s",
)
PV_name = "NIH:TIMING.registers.cmcnd.count"
print('caget_cached(PV_name) # should be 20228')
from CA import caget
print('caget(PV_name) # should be 20228')
print('cache.get(PV_name) # should be 20228')
print('cache.set(PV_name,"20228")')
<file_sep>"""
FPGA Timing System
Author: <NAME>
Date created: 2007-04-02
Date last modified: 2019-05-29
"""
from logging import debug,info,warn,error
__version__ = "8.6.1" # high_speed_chopper defaults to "Julich"
def Parameter(name,default_value=0.0):
"""A propery object to be used inside a class"""
def get(self):
class_name = getattr(self,"name",self.__class__.__name__)
parameter_name = class_name+"."+name
t = getattr(self,"timing_system",timing_system)
value = t.parameter(parameter_name,default_value)
return value
get.default_value = default_value # save for inspection
def set(self,value):
class_name = getattr(self,"name",self.__class__.__name__)
parameter_name = class_name+"."+name
t = getattr(self,"timing_system",timing_system)
t.set_parameter(parameter_name,value,default_value)
return property(get,set)
from functools import total_ordering
@total_ordering
class Register(object):
"""User-programmable parameter of FPGA timing system"""
sign = 1
def __init__(self,timing_system,name,min=None,max=None,
min_count=None,max_count=None):
"""
name: mnemonic or hexadecimal address as string
stepsize: resolution in units of seconds
min: minimum count
max: maximum count
min_count: minimum count
max_count: maximum count
"""
self.timing_system = timing_system
self.name = name
if min != None: self.min = min
if max != None: self.max = max
if min_count != None: self.min_count = min_count
if max_count != None: self.max_count = max_count
self.unit = ""
timing_system.add_register(self)
# for sorting
def __eq__(self,other): return self.name == other.name
def __ne__(self,other): return not self == other
def __lt__(self,other): return self.name < other.name
def get_count(self):
"""The content of a register as integer value"""
return self.timing_system.register_count(self.name)
def set_count(self,count):
from numpy import isnan
if isnan(count): return
self.timing_system.set_register_count(self.name,self.next_count(count))
count = property(get_count,set_count)
def monitor(self,callback,*args,**kwargs):
"""Call callback routine when 'count' property changes"""
if not self.monitor_active(callback,*args,**kwargs):
new_thread = kwargs.get("new_thread",True)
if "new_thread" in kwargs: del kwargs["new_thread"]
# Make sure caching monitors are set up first:
from CA_cached import caget_cached
caget_cached(self.PV_name)
from CA import camonitor
def monitor_callback(PV_name,value,formatted_value):
callback(*args,**kwargs)
monitor_callback.callback = callback
monitor_callback.args = args
monitor_callback.kwargs = kwargs
camonitor(self.PV_name,callback=monitor_callback,new_thread=new_thread)
def monitor_clear(self,callback=None,*args,**kwargs):
from CA import camonitors,camonitor_clear
if callback is None: camonitor_clear(self.PV_name)
else:
for f in camonitors(self.PV_name):
if getattr(f,"callback",None) == callback \
and getattr(f,"args",[]) == args \
and getattr(f,"kwargs",{}) == kwargs:
camonitor_clear(self.PV_name,f)
def monitor_active(self,callback,*args,**kwargs):
from CA import camonitors
active = False
for f in camonitors(self.PV_name):
pass
if (getattr(f,"callback",None) == callback
and getattr(f,"args",[]) == args
and getattr(f,"kwargs",{}) == kwargs):
active = True
return active
@property
def monitors(self):
"""list of callback routines"""
monitors = []
from CA import camonitors
for f in camonitors(self.PV_name):
if hasattr(f,"callback"): monitors += [f.callback]
return monitors
@property
def PV_name(self):
"""Process variable name for EPICS Channel Access"""
return self.timing_system.prefix+"registers."+self.name+".count"
def get_min_count(self):
"""Lowest allowed count"""
if hasattr(self,"__min_count__"): return self.__min_count__
return 0
def set_min_count(self,value):
if value < 0: value = 0
self.__min_count__ = value
min_count = property(get_min_count,set_min_count)
def get_max_count(self):
"""Highest allowed count"""
if hasattr(self,"__max_count__"): return self.__max_count__
return 2**self.bits-1
def set_max_count(self,value):
self.__max_count__ = value
max_count = property(get_max_count,set_max_count)
min = min_count
max = max_count
def next_count(self,count):
"""Round value to the next allowed integer count"""
from numpy import rint,clip,isnan,nan
if isnan(count): return nan
if count < self.min_count: count = self.min_count
if count > self.max_count: count = self.max_count
count = toint(rint(count))
return count
def next(self,value):
"""What is noext closes possible value to the given user value the reigster
can hold?
value: user value"""
count = self.count_from_value(value)
value = self.value_from_count(count)
return value
@property
def description(self):
return self.timing_system.register_property(self.name,"description","")
@property
def address(self):
return self.timing_system.register_property(self.name,"address")
@property
def bit_offset(self):
return self.timing_system.register_property(self.name,"bit_offset")
@property
def bits(self):
return self.timing_system.register_property(self.name,"bits")
def get_value(self):
"""User value of the delay in units of seconds"""
return self.user_from_dial(self.dial)
def set_value(self,value): self.dial = self.dial_from_user(value)
value = property(get_value,set_value)
def get_dial(self):
"""Delay controlled by the register in units of seconds"""
return self.dial_from_count(self.count)
def set_dial(self,value): self.count = self.count_from_dial(value)
dial = property(get_dial,set_dial)
def count_from_value(self,value):
"""Convert user value to integer register count"""
return self.count_from_dial(self.dial_from_user(value))
def value_from_count(self,count):
"""Convert integer register count to user value"""
return self.user_from_dial(self.dial_from_count(count))
def count_from_dial(self,dial_value):
"""Convert delay in seconds to integer register count"""
count = self.next_count(dial_value/self.stepsize)
return count
def dial_from_count(self,count):
"""Convert integer register count to delay in seconds"""
dial_value = count*self.stepsize
return dial_value
def user_from_dial(self,value): return value * self.sign + self.offset
def dial_from_user(self,value): return (value - self.offset) / self.sign
stepsize = Parameter("stepsize",1.0)
offset = Parameter("offset",0.0)
def __repr__(self): return self.name
def get_PP_enabled(self):
value = False
if self.channel is not None: value = self.channel.PP_enabled
return value
def set_PP_enabled(self,value):
if self.channel is not None: self.channel.PP_enabled = value
PP_enabled = property(get_PP_enabled,set_PP_enabled)
def get_special(self):
value = ""
if self.channel is not None: value = self.channel.special
return value
def set_special(self,value):
if self.channel is not None: self.channel.special = value
special = property(get_special,set_special)
@property
def channel(self):
channel = None
if self.name.startswith("ch") and "_" in self.name:
count = self.name.split("_")[0].replace("ch","")
try:
channel_number = int(count)-1
channel = timing_system.channels[channel_number]
except: pass
return channel
register = Register # alias
class Timing_Register(Register):
"""Register representing a time delay, with a scale factor, converting count to a
delay value in units of seconds"""
def __init__(self,timing_system,name,stepsize=1.,min=None,max=None,sign=1,
unit="s",min_count=None,max_count=None):
"""
name = mnemonic or hexadecimal address as string
stepsize = resolution in units of seconds
min = minimum dial value
max = maximum dial value
min_count = minimum count
max_count = maximum count
sign = +1 or -1, for dial to user value conversion
offset = for dial to user value conversion
"""
timing_system.Register.__init__(self,timing_system,name)
self.stepsize_ref = "parameters."+self.name+".stepsize"
if stepsize is not None: self.stepsize_ref = stepsize
self.sign = sign
self.unit = unit
if min is not None: self.min_dial = min
if max is not None: self.max_dial = max
if min_count != None: self.min_count = min_count
if max_count != None: self.max_count = max_count
def get_stepsize(self):
if type(self.stepsize_ref) == str:
expr = "self.timing_system."+self.stepsize_ref
try: stepsize = eval(expr)
except Exception,msg:
warn("%s.stepsize: %s: %s" % (self.name,expr,msg)); stepsize = 1
else: stepsize = self.stepsize_ref # numeric value
return stepsize
def set_stepsize(self,value):
if type(self.stepsize_ref) == str:
cmd = "self.timing_system.%s=%r" % (self.stepsize_ref,value)
try: exec(cmd)
except Exception,msg: warn("%.stepsize: %s: %s" % (self.name,cmd,msg))
else: self.stepsize_ref = value
stepsize = property(get_stepsize,set_stepsize)
def get_dial(self):
"""Delay controlled by the register in units of seconds"""
return self.count*self.stepsize
def set_dial(self,value): self.count = int(round(value/self.stepsize))
dial = property(get_dial,set_dial)
def get_value(self):
"""User value of the delay in units of seconds"""
return self.user_from_dial(self.dial)
def set_value(self,value): self.dial = self.dial_from_user(value)
value = property(get_value,set_value)
command_value = value
def define_value(self,value):
"modifies the user to dial offset such that the new user value is 'value'"
self.offset = value - self.dial * self.sign
# user = dial*sign + offset; offset = user - dial*sign
def get_min_dial(self): return self.dial_from_count(self.min_count)
def set_min_dial(self,value):
try: self.min_count = int(round(value/self.stepsize))
except: pass
min_dial = property(get_min_dial,set_min_dial,doc="Lowest allowed value in s")
def get_max_dial(self): return self.dial_from_count(self.max_count)
def set_max_dial(self,value):
try: self.max_count = int(round(value/self.stepsize))
except: pass
max_dial = property(get_max_dial,set_max_dial,doc="Highest allowed value in s")
def get_min(self): return self.user_from_dial(self.min_dial)
def set_min(self,value): self.min_dial = self.dial_from_user(value)
min = property(get_min,set_min,doc="Low limit in user units")
def get_max(self): return self.user_from_dial(self.max_dial)
def set_max(self,value): self.max_dial = self.dial_from_user(value)
max = property(get_max,set_max,doc="High limit in user units")
def count_from_value(self,value):
"""Convert user value to integer register count"""
return self.count_from_dial(self.dial_from_user(value))
def value_from_count(self,count):
"""Convert integer register count to user value"""
return self.user_from_dial(self.dial_from_count(count))
def count_from_dial(self,dial_value):
"""Convert user value to integer register count"""
count = self.next_count(dial_value/self.stepsize)
return count
def dial_from_count(self,count):
"""Convert integer register count to user value"""
dial_value = count*self.stepsize
return dial_value
def next(self,value):
"""What is noext closes possible value to the given user value the reigster
can hold?
value: user value"""
count = self.count_from_value(value)
value = self.value_from_count(count)
return value
offset = Parameter("offset",0.0)
def user_from_dial(self,value): return value * self.sign + self.offset
def dial_from_user(self,value): return (value - self.offset) / self.sign
timing_register = Timing_Register # alias
class Channel(object):
"""Output of the timing system"""
total_count = 24
__count__ = -1
__mnemonic__ = ""
def __init__(self,timing_system,count=-1,mnemonic="",name=None):
"""count: 0,1, ... 23
mnemonic: e.g. 'xosct'
name: e.g. 'ch1'
"""
self.timing_system = timing_system
self.count = count
self.__mnemonic__ = mnemonic
if name is not None:
if self.count < 0:
try: self.count = int(name.replace("ch",""))-1
except ValueError: pass
if self.count < 0:
try: self.count = int(name.replace("channels(","").replace(")",""))
except ValueError: pass
if self.count < 0:
error("name: expecting ch1..ch24 or channel(0..23), got %r" % name)
@property
def name(self): return self.name_of_count(self.count)
@staticmethod
def name_of_count(count):
##name = "channel(%r)" % count
name = "ch%d" % (int(count)+1)
return name
def get_count(self):
count = self.__count__
if count == -1 and self.__mnemonic__:
count = self.count_of_mnemonic(self.__mnemonic__)
return count
def set_count(self,value):
self.__count__ = value
count = property(get_count,set_count)
def count_of_mnemonic(self,mnemonic):
"""Channel index: 0-23"""
for i in range(0,self.total_count):
name = self.name_of_count(i)
if self.timing_system.parameter(name+".mnemonic","") == mnemonic:
count = i; break
else: count = -1
return count
from numpy import nan
PP_enabled = Parameter("PP_enabled",False)
description = Parameter("description","")
mnemonic = Parameter("mnemonic","")
offset_HW = Parameter("offset",nan)
offset_sign = Parameter("offset_sign",1.0)
offset_sign_choices = 1,-1
pulse_length_HW = Parameter("pulse_length",nan)
offset_PP = Parameter("offset_PP",nan)
pulse_length_PP = Parameter("pulse_length_PP",nan)
counter_enabled = Parameter("counter_enabled",0)
sign = Parameter("sign",1)
timed = Parameter("timed","") # timing relative to pump or probe
timed_choices = "pump","probe","period"
gated = Parameter("gated","") # enable?
gated_choices = "pump","probe","detector"
repeat_period = Parameter("repeat_period","") # how often?
repeat_period_choices = "pulse","burst start","burst end","image","50 ms","100 ms",""
on = Parameter("on",True)
bit_code = Parameter("bit_code",0)
special = Parameter("special","")
special_choices = (
"ms", # X-ray millisecond shutter
"ms_legacy", # X-ray millisecond shutter
"trans", # Sample trannslation trigger
"pso", # Picosecond oscillator reference clock
"nsf", # Nanosecond laser flashlamp trigger
)
def get_pulse_length(self):
from numpy import nan,isnan
value = nan
if not isnan(self.pulse_length_PP):
value = self.pulse_length_PP*self.timing_system.hsct
elif not isnan(self.pulse_length_HW): value = self.pulse_length_HW
return value
def set_pulse_length(self,value):
self.pulse_length_HW = value
pulse_length = property(get_pulse_length,set_pulse_length)
def get_offset(self):
from numpy import isnan
value = 0.0
if not isnan(self.offset_PP):
value = self.offset_PP*self.timing_system.hsct
elif not isnan(self.offset_HW): value = self.offset_HW
return value
def set_offset(self,value):
self.offset_HW = value
offset = property(get_offset,set_offset)
@property
def channel_number(self): return self.count
def register(name,*args,**kwargs):
"""Define a property corresponding to a register
name: e.g. "state"
"""
def get(self):
return self.timing_system.Register(self.timing_system,self.register_name(name),*args,**kwargs)
return property(get)
def timing_register(name,*args,**kwargs):
"""Define a property corresponding to a timing register"""
def get(self):
return self.timing_system.Timing_Register(self.timing_system,self.register_name(name),*args,**kwargs)
return property(get)
def register_name(self,name):
"""name: e.g. "state","delay" """
return "ch%d_%s" % (self.count+1,name)
@property
def delay(self):
"""Register"""
return self.timing_system.Timing_Register(self.timing_system,self.register_name("delay"),
stepsize="bct/2",max_count=712799)
@property
def fine(self):
"""Register"""
return self.timing_system.Register(self.timing_system,self.register_name("fine"))
@property
def enable(self):
"""Generate pulse every millisecond?"""
return self.timing_system.Register(self.timing_system,self.register_name("enable"))
@property
def state(self):
"""Current level: 0=low,1=high"""
return self.timing_system.Register(self.timing_system,self.register_name("state"))
@property
def pulse(self):
"""Output pulse duration"""
return self.timing_system.Timing_Register(self.timing_system,self.register_name("pulse"),
stepsize="bct*4")
pulse_choices = [1e-3,2e-3,3e-3,10e-3,30e-3,100e-3]
@property
def input(self):
"""Configured as input?"""
return self.timing_system.Register(self.timing_system,self.register_name("input"))
@property
def override(self):
"""Override Piano player? [0=pass,1=overide]"""
return self.timing_system.Register(self.timing_system,self.register_name("override"))
@property
def override_state(self):
"""Override state [0=low,1=high]"""
return self.timing_system.Register(self.timing_system,self.register_name("override_state"))
@property
def trig_count(self):
"""Trigger count [0-4294967295]"""
return self.timing_system.Register(self.timing_system,self.register_name("trig_count"))
@property
def acq_count(self):
"""Acquisition count [0-2147483647]"""
return self.timing_system.Register(self.timing_system,self.register_name("acq_count"))
@property
def acq(self):
"""Acquiring? [0=discard,1=save]"""
return self.timing_system.Register(self.timing_system,self.register_name("acq"))
def get_output_status(self):
"""PP = pass piano player state, Low, High = override"""
if not self.override.count: status = "PP"
else: status = "Low" if self.override_state.count == 0 else "High"
return status
def set_output_status(self,value):
if value.capitalize() == "High":
self.override.count = True
self.override_state.count = True
if value.capitalize() == "Low":
self.override.count = True
self.override_state.count = False
if value.upper() == "PP":
self.override.count = False
output_status = property(get_output_status,set_output_status)
output_status_choices = ["PP","Low","High"]
@property
def specout(self):
"""Special output: 0=normal, 1=70.4 MHz"""
return self.timing_system.Register(self.timing_system,self.register_name("specout"))
@property
def stepsize(self):
"""Resolution in seconds"""
return 0.5*self.timing_system.bct
def user_from_dial(self,value): return value * self.sign + self.offset
def dial_from_user(self,value): return (value - self.offset) / self.sign
def count_from_value(self,value):
"""Convert user value to integer register count"""
return self.count_from_dial(self.dial_from_user(value))
def value_from_count(self,count):
"""Convert integer register count to user value"""
return self.user_from_dial(self.dial_from_count(count))
def count_from_dial(self,dial_value):
"""Convert user value to integer register count"""
count = self.next_count(dial_value/self.stepsize)
return count
def dial_from_count(self,count):
"""Convert integer register count to user value"""
dial_value = count*self.stepsize
return dial_value
from numpy import inf
min_count = 0
max_count = inf
min_dial = 0.0
max_dial = inf
def get_min(self): return self.user_from_dial(self.min_dial)
def set_min(self,value): self.min_dial = self.dial_from_user(value)
min = property(get_min,set_min,doc="Low limit in user units")
def get_max(self): return self.user_from_dial(self.max_dial)
def set_max(self,value): self.max_dial = self.dial_from_user(value)
max = property(get_max,set_max,doc="High limit in user units")
def next_count(self,count):
"""Round value to the next allowed integer count"""
from numpy import rint,clip,isnan,nan
if isnan(count): return nan
count = clip(count,self.min_count,self.max_count)
count = toint(count)
return count
def next(self,value):
"""What is noext closes possible value to the given user value the reigster
can hold?
value: user value"""
count = self.count_from_value(value)
value = self.value_from_count(count)
return value
def __repr__(self):
return self.name
class Variable(object):
"""Software-defined parameter controlling the timing,
not associated with any hardware register in the FPGA"""
def __init__(self,timing_system,name,stepsize=None,sign=1):
"""name: common base name for registers
sign: user to dial scale factor
stepsize: e.g. 1 or "hlct"
"""
self.timing_system = timing_system
self.name = name
self.stepsize_ref = "parameters."+self.name+".stepsize"
if stepsize is not None: self.stepsize_ref = stepsize
self.sign = sign
timing_system.add_variable(self)
def get_stepsize(self):
if type(self.stepsize_ref) == str:
expr = "self.timing_system."+self.stepsize_ref
try: stepsize = eval(expr)
except Exception,msg:
warn("%s.stepsize: %s: %s" % (self.name,expr,msg)); stepsize = 1
else: stepsize = self.stepsize_ref # numeric value
return stepsize
def set_stepsize(self,value):
if type(self.stepsize_ref) == str:
cmd = "self.timing_system.%s=%r" % (self.stepsize_ref,value)
try: exec(cmd)
except Exception,msg: warn("%.stepsize: %s: %s" % (self.name,cmd,msg))
else: self.stepsize_ref = value
stepsize = property(get_stepsize,set_stepsize)
def get_dial(self):
"""Delay controlled by the register in units of seconds"""
return self.count*self.stepsize
def set_dial(self,value): self.count = int(round(value/self.stepsize))
dial = property(get_dial,set_dial)
def next(self,value):
"""Round user value to the next possible value, given the step size"""
dial_value = self.dial_from_user(value)
count = int(round(dial_value/self.stepsize))
dial_value = count*self.stepsize
value = self.user_from_dial(dial_value)
return value
def get_value(self):
"User value of the delay in units of seconds"
return self.user_from_dial(self.dial)
def set_value(self,value): self.dial = self.dial_from_user(value)
value = property(get_value,set_value)
count = Parameter("count",0)
offset = Parameter("offset",0.0)
def user_from_dial(self,value): return value * self.sign + self.offset
def dial_from_user(self,value): return (value - self.offset) / self.sign
from numpy import inf
min = -inf
max = inf
def __repr__(self): return self.name
class Parameters(object):
def __init__(self,timing_system):
self.__timing_system__ = timing_system
def __getattr__(self,name):
"""The value of a parameter stored on the timing system"""
# Called when 'x.name' is evaluated.
# It is only invoked if the attribute wasn't found the usual ways.
# __members__ is used for auto completion, browsing and "dir".
if name == "__members__": return self.__timing_system__.parameter_names
if name.startswith("__") and name.endswith("__"):
raise RuntimeError("attribute %r not found" % name)
return self.__timing_system__.parameter(name)
def __setattr__(self,name,value):
if name.startswith("__") and name.endswith("__"):
object.__setattr__(self,name,value)
else: self.__timing_system__.set_parameter(name,value)
class Configuration(object):
"""Settings"""
parameters = [
"clk_src.count", # Bunch clock source [0=RF IN,1=Ch1,...24=Ch24,25=RJ45:1,29=350MHz]
"sbclk_src.count", # Single-bunch clock source [1=Ch1,...24=Ch24,27=RJ45:3]
"clk_div.count", # Clock divider? [0=1,1=2,2=3,...7=8]
"clk_dfs_mode.count", # Clock DFS frequency mode [0=low freq,1=high freq]
"clk_dll_mode.count", # Clock DLL frequency mode [0=low freq,1=high freq]
"clk_mul.count", # Clock multiplier [0=N/A,1=2,2=3,...31=32]
"clk_shift_stepsize",
"clock_period_external",
"clock_period_internal",
"p0_div_1kHz.count",
"clk_88Hz_div_1kHz.count",
"hlc_div",
"nsl_div",
"p0fd2.count",
"p0d2.count",
"p0_shift.offset",
"psod3.offset",
"hlcnd.count",
"hlcnd.offset",
"hlcad.offset",
"hlctd.offset",
]
channel_parameters = [
"PP_enabled",
"input.count",
"description",
"mnemonic",
"special",
"specout.count",
"offset_HW",
"offset_sign",
"pulse_length_HW",
"offset_PP",
"pulse_length_PP",
"counter_enabled",
"enable.count",
"timed",
"gated",
"override.count",
"state.count",
]
def __init__(self,name):
"""name: 'BioCARS', or 'LaserLab'"""
self.name = name
def save(self):
"""Store current FPGA settings on local file system"""
from DB import dbset
for par in self.parameters:
value = eval("timing_system."+par)
dbset("timing_system_configurations/%s.%s" % (self.name,par),value)
for channel in timing_system.channels:
for name in self.channel_parameters:
value = eval("channel."+name)
db_name = "timing_system_configurations/%s.%s.%s" % (self.name,channel.name,name)
dbset(db_name,value)
def load(self):
"""Upload save settings to FPGA timign system"""
from DB import db
from numpy import nan,inf # for eval
for par in self.parameters:
default_value = eval("timing_system.%s" % par)
value = db("timing_system_configurations/%s.%s" % (self.name,par),default_value)
if not equal(value,default_value):
execute("timing_system.%s = %r" % (par,value),locals=locals(),globals=globals())
for channel in timing_system.channels:
for name in self.channel_parameters:
default_value = eval("channel."+name)
db_name = "timing_system_configurations/%s.%s.%s" % (self.name,channel.name,name)
value = db(db_name,default_value)
if not equal(value,default_value):
execute("channel.%s = %r" % (name,value),locals=locals(),globals=globals())
def __repr__(self): return "Configuration(%r)" % self.name
class TimingSystem(object):
"""FPGA Timing system"""
name = "timing_system"
from persistent_property import persistent_property
prefix = persistent_property("prefix","NIH:TIMING.")
prefixes = persistent_property("prefixes",[
"NIH:TIMING.",
"TESTBENCH:TIMING.",
"LASERLAB:TIMING.",
])
all_register_names = persistent_property("all_register_names",[])
Register = Register
Timing_Register = Timing_Register
Channel = Channel
Variable = Variable
Parameters = Parameters
Configuration = Configuration
def __init__(self):
from CA import camonitor
camonitor(self.prefix+"registers",callback=self.register_names_callback)
def register_names_callback(self,PV_name,value,char_value):
self.all_register_names = value.split(";")
def __repr__(self): return "timing_system"
def get_ip_address(self):
from CA import cainfo
ip_address = cainfo(self.prefix+"registers","IP_address")
return ip_address
def set_ip_address(self,value): pass
ip_address = property(get_ip_address,set_ip_address)
from persistent_property import persistent_property
port = persistent_property("port","2002")
def get_ip_address_and_port(self):
ip_address_and_port = self.ip_address+":"+self.port
return ip_address_and_port
def set_ip_address_and_port(self,ip_address_and_port):
self.port = ip_address_and_port.split(":")[-1]
ip_address_and_port = property(get_ip_address_and_port,set_ip_address_and_port)
@property
def online(self):
online = self.ip_address != ""
return online
def register_monitor(self,name,callback,*args,**kwargs):
from CA import camonitor
def monitor_callback(PV_name,value,formatted_value):
callback(*args,**kwargs)
monitor_callback.callback = callback
monitor_callback.args = args
monitor_callback.kwargs = kwargs
camonitor(self.register_PV_name(name),callback=monitor_callback)
def register_monitor_clear(self,name):
from CA import camonitor_clear
camonitor_clear(self.register_PV_name(name))
def register_PV_name(self,name):
"""Process variable name for EPICS Channel Access"""
return self.prefix+"registers."+name+".count"
def variable_property(name,*args,**kwargs):
"""A propery object that is a timing register"""
def get(self): return self.Variable(self,name,*args,**kwargs)
return property(get)
def timing_register(name,*args,**kwargs):
"""A propery object that is a timing register"""
def get(self): return self.Timing_Register(self,name,*args,**kwargs)
return property(get)
def Parameter(name,default_value=0.0):
"""A propery object that is te value if a timing parameter stored
in the timing system"""
def get(self): return self.parameter(name,default_value)
def set(self,value): self.set_parameter(name,value,default_value)
return property(get,set)
register_dict = {}
def add_register(self,register):
"""register: register object"""
self.register_dict[repr(register)] = register
self.__dict__[repr(register)] = register # helpful for auto-complete
def register(self,name):
if name in self.register_dict: return self.register_dict[name]
else: return self.Register(self,name)
##elif name in self.all_register_names: return self.Register(self,name)
##else: raise RuntimeError("Is %r a register?" % name)
from collections import MutableMapping
class Registers(MutableMapping):
def __init__(self,timing_system): self.timing_system = timing_system
def __getitem__(self,name): return self.timing_system.register(name)
def __getattr__(self,name): return self.timing_system.register(name)
def __len__(self): return len(self.timing_system.all_register_names)
def __contains__(self,name): return name in self.timing_system.all_register_names
def __iter__(self):
for name in self.timing_system.all_register_names: yield name
def __repr__(self): return "timing_system.registers"
def __setitem__(self,name,value): pass
def __delitem__(self,name): pass
@property
def registers(self): return self.Registers(self)
##@property
##def registers(self): return self.register_dict.values()
@property
def register_names(self): return self.register_dict.keys()
@property
def _all_register_names(self): return self.get_property("registers").split(";")
@property
def channel_names(self):
return ["ch%d" % (i+1) for i in range(0,self.Channel.total_count)]
def channel(self,i): return self.Channel(self,i)
class Channels(object):
Channel = Channel
def __init__(self,timing_system): self.timing_system = timing_system
def __getitem__(self,i): return self.Channel(self.timing_system,i)
def __getattr__(self,mnemonic): return self.Channel(self.timing_system,mnemonic=mnemonic)
def __len__(self): return self.Channel.total_count
def __iter__(self):
for i in range(0,len(self)):
if i < len(self): yield self[i]
@property
def channels(self): return self.Channels(self)
@property
def channel_mnemonics(self):
return [self.channels[i].mnemonic for i in range(len(self.channels))]
def channel_register_name(self,name):
register_name = ""
properties = [p for p in dir(Channel) if type(getattr(self.Channel,p)) == property]
for channel in self.channels:
if name.startswith(channel.mnemonic+"_"):
for prop in properties:
if name == channel.mnemonic+"_"+prop:
register_name = channel.name+"_"+prop
return register_name
variable_dict = {}
def add_variable(self,variable):
"""register: register object"""
self.variable_dict[repr(variable)] = variable
self.__dict__[repr(variable)] = variable # helpful for auto-complete
def variable(self,name): return self.variable_dict[name]
@property
def variables(self): return self.variable_dict.values()
@property
def variable_names(self): return self.variable_dict.keys()
def __getattr__(self,name):
"""A register object"""
##warn("__getattr__(%r)" % name)
# Called when 'x.name' is evaluated.
# It is only invoked if the attribute wasn't found the usual ways.
if name.startswith("__") and name.endswith("__"):
raise AttributeError("attribute %r not found" % name)
##debug("Is %r a register?" % name)
if name in self.channel_names: return self.Channel(self,name=name)
elif name in self.register_dict: return self.register_dict[name]
elif name in self.variable_dict: return self.variable_dict[name]
elif name in self.all_register_names: return self.Register(self,name)
elif self.channel_register_name(name): return self.Register(self,self.channel_register_name(name))
elif name in self.channel_mnemonics: return self.channels[self.channel_mnemonics.index(name)]
else: raise AttributeError("Is %r a register?" % name)
##else: return self.parameter(name)
def register_count(self,name):
"""Reads the content of a register as integer value"""
from numpy import nan
name = "registers.%s.count" % name
value = self.get_property(name)
try: return int(value)
except ValueError: return nan
def set_register_count(self,name,value):
"""Loads an integer value into the register"""
from numpy import isnan
if isnan(value): return
value = "%d" % value
name = "registers.%s.count" % name
self.set_property(name,value)
def register_property(self,name,property_name,default_value=0):
"""Information about the register
property_name: 'address','bit_offset','bits'"""
from numpy import nan
full_name = "registers.%s.%s" % (name,property_name)
string_value = self.get_property(full_name)
try: value = type(default_value)(eval(string_value))
except Exception,msg:
if type(default_value) != str:
if string_value != "":
debug("%s: %r(%r): %s" % (full_name,type(default_value),string_value,msg))
value = default_value
else: value = string_value
if string_value == "": error("%r defaulting to %r" % (full_name,value))
# Convert from signed to unsigned int
# (Channel Access does not support unsigend int)
if type(value) == int: value = unsigned_int(value)
return value
def set_register_property(self,name,property_name,value):
"""Information about the register.
property_name: 'address','bit_offset','bits'"""
from numpy import isnan
if isnan(value): return
value = "%d" % value
name = "registers.%s.%s" % (name,property_name)
self.set_property(name,value)
def parameter(self,name,default_value=0.0):
"""This retreives a calibration constant from non-volatile memory of the
FPGA."""
from numpy import nan,inf
value = self.get_property("parameters."+name)
try: value = type(default_value)(eval(value))
except Exception,msg:
if value != "": debug("timing_system: parameter: %s: %r(%r): %s" %
(name,type(default_value),value,msg))
value = default_value
return value
def set_parameter(self,name,value,default_value=None):
"""This stores a calibration constant in non-volatile memory in the FPGA."""
##debug("set_parameter(%r,%r)" % (name,value))
property_name = "parameters.%s" % name
from same import same
str_value = repr(value)
if default_value is not None and same(value,default_value): str_value = "" # deletes property
self.set_property(property_name,str_value)
@property
def parameter_names(self): return self.get_property("parameters").split(";")
@property
def parameters(self): return self.Parameters(self)
def get_property(self,name):
"""Retreive a register content ot parameter, using Channel Access
return value: string"""
PV_name = self.prefix+name
##from CA import caget
##value = caget(PV_name)
from CA_cached import caget_cached
value = caget_cached(PV_name)
if value is None:
debug("Failed to get PV %r" % PV_name)
value = ""
# Convert from signed to unsigned int (Channel Access does not support unsigend int)
if type(value) == int and value < 0: value = value+0x100000000
if type(value) != str: value = str(value)
##debug("%r: returning %.80r" % (name,value))
return value
def set_property(self,name,value):
"""Modify a register content ot parameter, using Channel Access
value: string"""
from CA import caput
##debug("caput(%r,%r,wait=True)" % (self.prefix+name,value))
caput(self.prefix+name,value,wait=True)
# Clock periods
def get_clock_period(self):
"""Clock period in s (ca. 2.8 ns)"""
if self.clk_src.count == 29: return self.clock_period_internal
else: return self.clock_period_external
def set_clock_period(self,value):
if self.clk_src.count == 29: self.clock_period_internal = value
else: self.clock_period_external = value
clock_period = property(get_clock_period,set_clock_period)
clock_period_external = Parameter("clock_period_external",1/351933984.)
clock_period_internal = Parameter("clock_period_internal",1/350000000.)
def get_bct(self):
"""Bunch clock period in s (ca. 2.8 ns)"""
if self.clk_on.count == 0: T = self.clock_period
else: T = self.clock_period/self.clock_multiplier*self.clock_divider
return T
def set_bct(self,value):
if self.clk_on.count == 0: self.clock_period = value
else: self.clock_period = value*self.clock_multiplier/self.clock_divider
bct = property(get_bct,set_bct)
def get_clock_divider(self):
"""Clock scale factor"""
value = self.clk_div.count+1
return value
def set_clock_divider(self,value):
from numpy import rint
value = int(rint(value))
if 1 <= value <= 32: self.clk_div.count = value-1
else: warn("%r must be in range 1 to 32.")
clock_divider = property(get_clock_divider,set_clock_divider)
def get_clock_multiplier(self):
"""Clock scale factor"""
value = (self.clk_mul.count+1)/2
return value
def set_clock_multiplier(self,value):
from numpy import rint
value = int(rint(value))
if 1 <= value <= 32: self.clk_mul.count = 2*value-1
else: warn("%r must be in range 1 to 32.")
clock_multiplier = property(get_clock_multiplier,set_clock_multiplier)
def get_P0t(self):
"""Single-bunch clock period (ca. 3.6us)"""
from numpy import nan
try: value = self.hsct/self.p0_div_1kHz.count
except ZeroDivisionError: value = nan
return value
def set_P0t(self,value):
from numpy import rint
try: self.p0_div_1kHz.count = rint(self.hsct/value)
except ZeroDivisionError: pass
P0t = property(get_P0t,set_P0t)
def get_hsct(self):
"""High-speed chopper rotation period (ca. 1 ms)"""
return self.bct*4*self.clk_88Hz_div_1kHz.count
def set_hsct(self,value):
from numpy import rint
try: self.clk_88Hz_div_1kHz.count = rint(value/(self.bct*4))
except ZeroDivisionError: pass
hsct = property(get_hsct,set_hsct)
def get_hlct(self):
"""X-ray pulse repetiton period.
Selected by the heatload chopper.
Depends on the nummber of slots in the X-ray beam path:
period = hlct / 12 * number of slots
(ca 12 ms with one slot) Number of slots: 1,4,12"""
return self.hsct*self.hlc_div
def set_hlct(self,value):
from numpy import rint
try: self.hlc_div = rint(value/self.hsct)
except ZeroDivisionError: pass
hlct = property(get_hlct,set_hlct)
hlc_div = Parameter("hlc_div",12)
def get_hlc_nslots(self):
"""Number of slots of the heatload chopper in the X-ray beam"""
from numpy import rint,nan
try: nslots = rint(12./self.hlc_div)
except ZeroDivisionError: nslots = nan
return nslots
def set_hlc_nslots(self,nslots):
from numpy import rint
try: self.hlc_div = rint(12./nslots)
except ZeroDivisionError: pass
hlc_nslots = property(get_hlc_nslots,set_hlc_nslots)
def get_nslt(self):
"""ns laser flash lamp period (ca. 100 ms)"""
return self.hsct*self.nsl_div
def set_nslt(self,value):
from numpy import rint
self.nsl_div = rint(value/self.hsct)
nslt = property(get_nslt,set_nslt)
nsl_div = Parameter("nsl_div",96)
clk_shift_stepsize = Parameter("clk_shift_stepsize",8.594e-12)
def reset_dcm(self):
"""Reinitialize digital clock mananger"""
from time import sleep
self.clk_shift_reset.count = 1
sleep(0.2)
self.clk_shift_reset.count = 0
xd = Parameter("xd",0.000985971429) # X-ray pulse timing
delay = variable_property("delay",stepsize=1e-12) # Ps laser to X-ray delay
lxd = ps_lxd = delay # For backward compatibility
laser_on = Parameter("laser_on",False) # fire ps and ns lasers?
laseron = laser_on # For backward compatibility
waitt = variable_property("waitt",stepsize="hlct")
npulses = Parameter("npulses",1) # pulses per burst
burst_waitt = variable_property("burst_waitt",stepsize="hlct")
burst_delay = variable_property("burst_delay",stepsize="hlct")
bursts_per_image = Parameter("bursts_per_image",1)
sequence = Parameter("sequence","") # more flexible replacement for bursts_per_image
acquisition_sequence = Parameter("acquisition_sequence","") # used when acquiring data
temp_inc_on = Parameter("temp_inc_on",False)
image_number_inc_on = Parameter("image_number_inc_on",False)
pass_number_inc_on = Parameter("pass_number_inc_on",False)
# For sample translation stage
translate_mode = Parameter("translate_mode","")
transc = Parameter("transc",0)
pump_on = Parameter("pump_on",False)
transon = variable_property("trans.on",stepsize=1) # For backward compatibility
mson = variable_property("ms.on", stepsize=1) # For backward compatibility
xoscton = variable_property("xosct.on",stepsize=1) # For backward compatibility
# Ps oscillator coarse delay [0-11.2 ns, step 2.8 ns]
psod1 = timing_register("psod1",stepsize="bct",max_count=4)
# Ps oscillator fine delay [0-2.8ns, step 9 ps]
psod2 = timing_register("psod2",stepsize="clk_shift_stepsize")
# Ps oscillator coarse delay [0-7.1 ns, step 7.1 ns]
psod3 = timing_register("psod3",stepsize="bct*2.5",max_count=1)
# P0 fine tune delay [0-8.4ns,step 2.8ns]
p0fd = timing_register("p0fd",stepsize="bct")
# P0 delay [0-5.8us,step 11ns]
p0d = timing_register("p0d",stepsize="bct*4")
# P0 actual fine delay [0-8.4ns,step 2.8ns,read-only]
p0afd = timing_register("p0afd",stepsize="bct")
# P0 actual delay [0-3.6us,step 11ns,read-only]
p0ad = timing_register("p0ad",stepsize="bct*4")
# P0 fine tune delay [0-8.4ns,step 2.8ns]
p0fd2 = timing_register("p0fd2",stepsize="bct")
# P0 delay 2 [0-5.8us,step 11ns]
p0d2 = timing_register("p0d2",stepsize="bct*4")
def object_property(type,*args,**kwargs):
"""Define a property corresponding to a timing register"""
##info("object_property(%r,%r)" % (args,kwargs))
def get(self): return type(self,*args,**kwargs)
return property(get)
class P0_shift(Timing_Register):
def __init__(self,timing_system,*args,**kwargs):
timing_system.Timing_Register.__init__(self,timing_system,*args,**kwargs)
def get_count(self):
count = self.timing_system.p0d2.count*4 + (self.timing_system.p0fd2.count + 2) % 4
return count
def set_count(self,count):
from numpy import rint
count = int(rint(count))
self.timing_system.p0d2.count = count / 4
self.timing_system.p0fd2.count = (count - 2) % 4
count = property(get_count,set_count)
max_count = 1296-1
p0_shift = object_property(P0_shift,"p0_shift",stepsize="bct")
# Ps laser delay 1 [0-20.47ns,step 10ps] (phase of seed beam)
psd1 = timing_register("psd1",stepsize=10.048e-12)
# The "psd1.offset" parameter needs to be determined empirically and changes with
# the length of the cables that route the clock and trigger signals
# from the FPGA to the Lok-to-Clock and Spitfire TDG.
# tweak psd1.offset on both directions, until the amplifier
# output pulse timing toggles between two delays, spaced by 14.2 ns, with equal
# probability. Then set psd1.offset to the midpoint of the two values.
#psd1.offset = 1.2630336e-08 # Schotte, Mar 3, 2015
# Heatload choppernominal delay
hlcnd = timing_register("hlcnd",stepsize="bct*4")
# This offset determines when the heatload chopper opening window is centered
# on the high speed chopper opening window.
# At 82.3 Hz the opening window should be centered on the 12th high speed
# chopper transmission after the FPGA t=0.
#hlcnd.offset = -0.0056959639810284885 # Schotte, 4 Mar 2015, 82-Hz mode
# Heatload chopper transient delay
hlctd = timing_register("hlctd",stepsize="bct*4")
# Heatload chopper actual delay, read only [0-24ms,step 12ns]
hlcad = timing_register("hlcad",stepsize="bct*4")
# ChemMat chopper nominal delay
cmcnd = timing_register("cmcnd",stepsize="bct*4")
# ChemMat chopper transient delay
cmctd = timing_register("cmctd",stepsize="bct*4")
# ChemMat chopper actual delay, read only [0-24ms,step 12ns]
cmcad = timing_register("cmcad",stepsize="bct*4")
configuration = Parameter("configuration","BioCARS")
def save_configuration(self):
self.Configuration(self.configuration).save()
def load_configuration(self):
self.Configuration(self.configuration).load()
@property
def configurations(self): return configuration_names()
class CMCD(object):
"""ChemMat chopper delay (=phase)"""
def __init__(self,timing_system):
self.timing_system = timing_system
def get_command_value(self):
return self.timing_system.cmcnd.value
def set_command_value(self,value):
self.timing_system.cmcnd.value = value
command_value = property(get_command_value,set_command_value)
def get_value(self):
return self.timing_system.cmcad.value
set_value = set_command_value
value = property(get_value,set_value)
@property
def moving(self): return not self.settled
@property
def settled(self):
settled = abs(self.value - self.command_value) <= self.tolerance
return settled
default_tolerance = "200e-9"
def get_tolerance(self):
return self.timing_system.parameter("cmc.tolerance",self.default_tolerance)
def set_tolerance(self,value):
self.timing_system.set_parameter("cmc.tolerance",value,self.default_tolerance)
tolerance = property(get_tolerance)
@property
def cmcd(self):
"""ChemMat chopper delay (=phase)"""
return self.CMCD(self)
high_speed_chopper = Parameter("chopper","Julich")
high_speed_chopper_choices = "Julich","ChemMat"
@property
def high_speed_chopper_phase(self):
register = self.hsc.delay
if self.high_speed_chopper == "Julich": register = self.hsc.delay
if self.high_speed_chopper == "ChemMat": register = self.cmcnd
return register
cache = 0 # for backwards compatbility
cache_timeout = 0 # for backwards compatbility
use_CA = True # for backwards compatbility
timing_system = TimingSystem()
parameters = Parameters(timing_system)
def equal(a,b):
"""Do a and b have the same value?"""
return repr(a) == repr(b)
def execute(command,locals=None,globals=None):
from numpy import nan,inf
debug("timing_system: %r: %s" % (self.name,command))
try: exec(command,locals,globals)
except Exception,msg: error("timing_system: %r failed:%s" % (command,msg))
def configuration_names():
"""All saved settings"""
from DB import dbdir
names = dbdir("timing_system_configurations")
return names
def configurations():
"""All saved settings"""
configurations = [Configuration(name) for name in configuration_names()]
return configurations
def round_next (x,step):
"""Rounds x up or down to the next multiple of step."""
if step == 0: return x
return round(x/step)*step
def toint(x):
"""Try to convert x to an integer number without raising an exception."""
try: return int(x)
except: return x
def unsigned_int(value):
"""Convert from signed to unsigned int
(Channel Access does not support unsigend int)"""
if type(value) == int and value < 0: value = value+0x100000000
return value
from timing_sequence import timing_sequencer
def update_channels():
"""Convert parametert from format 'channel(0).special' to 'ch1.special'"""
def default_value(obj): return getattr(getattr(obj,"fget",None),"default_value",None)
properties = [n for n in dir(Channel) if default_value(getattr(Channel,n)) is not None]
default_values = [repr(default_value(getattr(Channel,n))) for n in properties]
for i in range(0,24):
for prop,default_value in zip(properties,default_values):
name = "parameters.channel(%d).%s" % (i,prop)
value = timing_system.get_property(name)
if value and value != default_value:
new_name = "parameters.ch%d.%s" % (i+1,prop)
new_value = timing_system.get_property(new_name)
if new_value != value:
info("%s=%s" % (new_name,value))
timing_system.set_property(new_name,value)
if value:
none = ""
info("%s=%s" % (name,none))
timing_system.set_property(name,none)
if __name__ == "__main__": # for testing
from pdb import pm # for debugging
##from time import sleep,time
##from CA import caget,caput,cainfo,camonitor,camonitors
##import logging
##logging.basicConfig(level=logging.DEBUG,
## format="%(asctime)s %(levelname)s %(module)s.%(funcName)s: %(message)s",
##)
print('timing_system.prefix = %r' % timing_system.prefix)
print('timing_system.prefixes = %r' % timing_system.prefixes)
print('timing_system.ip_address = %r' % timing_system.ip_address)
print('')
print('timing_system.configuration = %r' % timing_system.configuration)
print('timing_system.configurations = %r' % timing_system.configurations)
print('timing_system.save_configuration()')
print('timing_system.load_configuration()')
print('')
<file_sep>view = 'Custom'
CustomView = [8]<file_sep>#!/usr/bin/env python
"""Control panel to save and restore motor positions.
Author: <NAME>
Date created: 2017-06-28
Date last modified: 2018-10-25
"""
__version__ = "2.0" # using SavedPositionsPanel_2
import wx
from SavedPositionsPanel_2 import SavedPositionsPanel
app = wx.App(redirect=False)
from instrumentation import * # -> globals()
name = "beamline_configuration"
SavedPositionsPanel(name=name,globals=globals())
app.MainLoop()
<file_sep>#!/usr/bin/env python
from Timing_Channel_Configuration_Panel import *
if __name__ == '__main__':
import Timing_Channel_Configuration_Panel as module
from inspect import getfile
file = getfile(module).replace(".pyc",".py")
execfile(file)
<file_sep>clk_src.count = 25
sbclk_src.count = 27
clk_div.count = 0
clk_dfs_mode.count = 1
clk_dll_mode.count = 0
clk_mul.count = 7
clk_shift_stepsize = 8.594e-12
clock_period_external = 2.841441861258077e-09
clock_period_internal = 2.857142857142857e-09
p0_div_1kHz.count = 275
clk_88Hz_div_1kHz.count = 89100
hlc_div = 12
nsl_div = 48
ch1.input.count = 0
ch1.description = 'X scope trig'
ch1.mnemonic = 'xosct'
ch1.special = ''
ch1.specout.count = 0
ch1.offset_HW = 6.064410534873015e-06
ch1.pulse_length_HW = nan
ch1.offset_PP = nan
ch1.pulse_length_PP = nan
ch1.enable.count = 0
ch1.timed = 'probe'
ch1.gated = ''
ch1.override.count = 0
ch1.state.count = 0
ch2.input.count = 0
ch2.description = 'HLC ext freq'
ch2.mnemonic = 'hlc'
ch2.special = ''
ch2.specout.count = 0
ch2.offset_HW = nan
ch2.pulse_length_HW = nan
ch2.offset_PP = nan
ch2.pulse_length_PP = nan
ch2.enable.count = 0
ch2.timed = ''
ch2.gated = ''
ch2.override.count = 0
ch2.state.count = 0
ch3.input.count = 1
ch3.description = 'HLC enc IN'
ch3.mnemonic = ''
ch3.special = ''
ch3.specout.count = 0
ch3.offset_HW = nan
ch3.pulse_length_HW = nan
ch3.offset_PP = nan
ch3.pulse_length_PP = nan
ch3.enable.count = 0
ch3.timed = ''
ch3.gated = ''
ch3.override.count = 0
ch3.state.count = 0
ch4.input.count = 0
ch4.description = 'HS chop'
ch4.mnemonic = 'hsc'
ch4.special = ''
ch4.specout.count = 0
ch4.offset_HW = -0.0009859719999999999
ch4.pulse_length_HW = nan
ch4.offset_PP = nan
ch4.pulse_length_PP = nan
ch4.enable.count = 1
ch4.timed = ''
ch4.gated = ''
ch4.override.count = 0
ch4.state.count = 0
ch5.input.count = 1
ch5.description = 'HS chop IN'
ch5.mnemonic = ''
ch5.special = ''
ch5.specout.count = 0
ch5.offset_HW = nan
ch5.pulse_length_HW = nan
ch5.offset_PP = nan
ch5.pulse_length_PP = nan
ch5.enable.count = 0
ch5.timed = ''
ch5.gated = ''
ch5.override.count = 0
ch5.state.count = 0
ch6.input.count = 0
ch6.description = 'ms shutter'
ch6.mnemonic = 'ms'
ch6.special = 'ms'
ch6.specout.count = 0
ch6.offset_HW = nan
ch6.pulse_length_HW = nan
ch6.offset_PP = -15.0
ch6.pulse_length_PP = 2.0
ch6.enable.count = 0
ch6.timed = 'probe'
ch6.gated = 'probe'
ch6.override.count = 0
ch6.state.count = 0
ch7.input.count = 0
ch7.description = 'X det trig'
ch7.mnemonic = 'xdet'
ch7.special = ''
ch7.specout.count = 0
ch7.offset_HW = nan
ch7.pulse_length_HW = nan
ch7.offset_PP = -6.0
ch7.pulse_length_PP = 1.0
ch7.enable.count = 0
ch7.timed = 'period'
ch7.gated = 'detector'
ch7.override.count = 0
ch7.state.count = 0
ch8.input.count = 0
ch8.description = 'L cam trig'
ch8.mnemonic = 'lcam'
ch8.special = ''
ch8.specout.count = 0
ch8.offset_HW = 6.822639999999999e-06
ch8.pulse_length_HW = nan
ch8.offset_PP = nan
ch8.pulse_length_PP = nan
ch8.enable.count = 0
ch8.timed = 'pump'
ch8.gated = 'pump'
ch8.override.count = 0
ch8.state.count = 0
ch9.input.count = 0
ch9.description = 'S cam shutter'
ch9.mnemonic = 's1'
ch9.special = ''
ch9.specout.count = 0
ch9.offset_HW = nan
ch9.pulse_length_HW = nan
ch9.offset_PP = -15.0
ch9.pulse_length_PP = 15.0
ch9.enable.count = 0
ch9.timed = 'pump'
ch9.gated = 'pump'
ch9.override.count = 1
ch9.state.count = 1
ch10.input.count = 0
ch10.description = 'S cam LED'
ch10.mnemonic = 'scl'
ch10.special = ''
ch10.specout.count = 0
ch10.offset_HW = nan
ch10.pulse_length_HW = nan
ch10.offset_PP = 0.0
ch10.pulse_length_PP = 72.0
ch10.enable.count = 0
ch10.timed = 'period'
ch10.gated = ''
ch10.override.count = 1
ch10.state.count = 1
ch11.input.count = 0
ch11.description = 'sample trans'
ch11.mnemonic = 'trans'
ch11.special = 'trans'
ch11.specout.count = 0
ch11.offset_HW = nan
ch11.pulse_length_HW = nan
ch11.offset_PP = 0.0
ch11.pulse_length_PP = 3.0
ch11.enable.count = 0
ch11.timed = 'period'
ch11.gated = ''
ch11.override.count = 0
ch11.state.count = 0
ch12.input.count = 0
ch12.description = 'Diagnostics 1'
ch12.mnemonic = ''
ch12.special = ''
ch12.specout.count = 2
ch12.offset_HW = nan
ch12.pulse_length_HW = nan
ch12.offset_PP = nan
ch12.pulse_length_PP = nan
ch12.enable.count = 0
ch12.timed = ''
ch12.gated = ''
ch12.override.count = 0
ch12.state.count = 0
ch13.input.count = 0
ch13.description = 'ps L oscill'
ch13.mnemonic = 'pso'
ch13.special = 'pso'
ch13.specout.count = 1
ch13.offset_HW = nan
ch13.pulse_length_HW = nan
ch13.offset_PP = nan
ch13.pulse_length_PP = nan
ch13.enable.count = 0
ch13.timed = 'pump'
ch13.gated = ''
ch13.override.count = 0
ch13.state.count = 0
ch14.input.count = 0
ch14.description = 'ps L trig'
ch14.mnemonic = 'pst'
ch14.special = ''
ch14.specout.count = 0
ch14.offset_HW = 2.3975699999999997e-06
ch14.pulse_length_HW = nan
ch14.offset_PP = nan
ch14.pulse_length_PP = nan
ch14.enable.count = 0
ch14.timed = 'pump'
ch14.gated = 'pump'
ch14.override.count = 0
ch14.state.count = 0
ch15.input.count = 0
ch15.description = ''
ch15.mnemonic = 'psg'
ch15.special = ''
ch15.specout.count = 0
ch15.offset_HW = nan
ch15.pulse_length_HW = nan
ch15.offset_PP = nan
ch15.pulse_length_PP = nan
ch15.enable.count = 0
ch15.timed = 'pump'
ch15.gated = 'pump'
ch15.override.count = 0
ch15.state.count = 0
ch16.input.count = 0
ch16.description = 'L scope trig'
ch16.mnemonic = 'losct'
ch16.special = ''
ch16.specout.count = 0
ch16.offset_HW = 5.89053e-06
ch16.pulse_length_HW = nan
ch16.offset_PP = nan
ch16.pulse_length_PP = nan
ch16.enable.count = 0
ch16.timed = 'pump'
ch16.gated = ''
ch16.override.count = 0
ch16.state.count = 0
ch17.input.count = 0
ch17.description = 'ns L flash'
ch17.mnemonic = 'nsf'
ch17.special = 'nsf'
ch17.specout.count = 0
ch17.offset_HW = -0.00062272
ch17.pulse_length_HW = nan
ch17.offset_PP = nan
ch17.pulse_length_PP = nan
ch17.enable.count = 0
ch17.timed = 'pump'
ch17.gated = ''
ch17.override.count = 0
ch17.state.count = 0
ch18.input.count = 0
ch18.description = 'ns L Q-sw'
ch18.mnemonic = 'nsq'
ch18.special = ''
ch18.specout.count = 0
ch18.offset_HW = 5.937699906971199e-06
ch18.pulse_length_HW = nan
ch18.offset_PP = nan
ch18.pulse_length_PP = nan
ch18.enable.count = 0
ch18.timed = 'pump'
ch18.gated = 'pump'
ch18.override.count = 0
ch18.state.count = 0
ch19.input.count = 0
ch19.description = 'ns L 2 flash'
ch19.mnemonic = ''
ch19.special = ''
ch19.specout.count = 0
ch19.offset_HW = nan
ch19.pulse_length_HW = nan
ch19.offset_PP = nan
ch19.pulse_length_PP = nan
ch19.enable.count = 0
ch19.timed = 'period'
ch19.gated = ''
ch19.override.count = 0
ch19.state.count = 1
ch20.input.count = 0
ch20.description = 'CW laser'
ch20.mnemonic = 'cwl'
ch20.special = ''
ch20.specout.count = 0
ch20.offset_HW = nan
ch20.pulse_length_HW = nan
ch20.offset_PP = 0.0
ch20.pulse_length_PP = 72.0
ch20.enable.count = 0
ch20.timed = 'period'
ch20.gated = ''
ch20.override.count = 0
ch20.state.count = 0
ch21.input.count = 0
ch21.description = ''
ch21.mnemonic = 's3'
ch21.special = ''
ch21.specout.count = 0
ch21.offset_HW = nan
ch21.pulse_length_HW = nan
ch21.offset_PP = nan
ch21.pulse_length_PP = 2.0
ch21.enable.count = 0
ch21.timed = ''
ch21.gated = ''
ch21.override.count = 0
ch21.state.count = 0
ch22.input.count = 0
ch22.description = ''
ch22.mnemonic = ''
ch22.special = ''
ch22.specout.count = 0
ch22.offset_HW = nan
ch22.pulse_length_HW = nan
ch22.offset_PP = nan
ch22.pulse_length_PP = nan
ch22.enable.count = 0
ch22.timed = ''
ch22.gated = ''
ch22.override.count = 0
ch22.state.count = 0
ch23.input.count = 0
ch23.description = 'S cam trig'
ch23.mnemonic = 'sct'
ch23.special = ''
ch23.specout.count = 0
ch23.offset_HW = nan
ch23.pulse_length_HW = nan
ch23.offset_PP = 0.0
ch23.pulse_length_PP = 1.0
ch23.enable.count = 0
ch23.timed = 'period'
ch23.gated = ''
ch23.override.count = 0
ch23.state.count = 0
ch24.input.count = 0
ch24.description = 'Diagnostics 2'
ch24.mnemonic = ''
ch24.special = ''
ch24.specout.count = 3
ch24.offset_HW = nan
ch24.pulse_length_HW = nan
ch24.offset_PP = nan
ch24.pulse_length_PP = nan
ch24.enable.count = 0
ch24.timed = ''
ch24.gated = ''
ch24.override.count = 0
ch24.state.count = 0
ch1.PP_enabled = True
ch2.PP_enabled = False
ch3.PP_enabled = False
ch4.PP_enabled = False
ch5.PP_enabled = False
ch6.PP_enabled = True
ch7.PP_enabled = True
ch8.PP_enabled = True
ch9.PP_enabled = True
ch10.PP_enabled = True
ch11.PP_enabled = True
ch12.PP_enabled = False
ch13.PP_enabled = True
ch14.PP_enabled = True
ch15.PP_enabled = True
ch16.PP_enabled = True
ch17.PP_enabled = True
ch18.PP_enabled = True
ch19.PP_enabled = True
ch20.PP_enabled = True
ch21.PP_enabled = True
ch22.PP_enabled = True
ch23.PP_enabled = True
ch24.PP_enabled = False
ch1.offset_sign = 1.0
ch2.offset_sign = 1.0
ch3.offset_sign = 1.0
ch4.offset_sign = -1.0
ch5.offset_sign = 1.0
ch6.offset_sign = 1.0
ch7.offset_sign = 1.0
ch8.offset_sign = 1.0
ch9.offset_sign = 1.0
ch10.offset_sign = 1.0
ch11.offset_sign = 1.0
ch12.offset_sign = 1.0
ch13.offset_sign = 1.0
ch14.offset_sign = 1.0
ch15.offset_sign = 1.0
ch16.offset_sign = 1.0
ch17.offset_sign = 1.0
ch18.offset_sign = 1.0
ch19.offset_sign = 1.0
ch20.offset_sign = 1.0
ch21.offset_sign = 1.0
ch22.offset_sign = 1.0
ch23.offset_sign = 1.0
ch24.offset_sign = 1.0
ch1.counter_enabled = 1
ch2.counter_enabled = 0
ch3.counter_enabled = 0
ch4.counter_enabled = 0
ch5.counter_enabled = 0
ch6.counter_enabled = 0
ch7.counter_enabled = 1
ch8.counter_enabled = 0
ch9.counter_enabled = 0
ch10.counter_enabled = 0
ch11.counter_enabled = 0
ch12.counter_enabled = 0
ch13.counter_enabled = 0
ch14.counter_enabled = 0
ch15.counter_enabled = 0
ch16.counter_enabled = 1
ch17.counter_enabled = 0
ch18.counter_enabled = 0
ch19.counter_enabled = 0
ch20.counter_enabled = 0
ch21.counter_enabled = 0
ch22.counter_enabled = 0
ch23.counter_enabled = 0
ch24.counter_enabled = 0
p0_shift.offset = -1.284332e-06
psod3.offset = 7.68e-09
hlcnd.offset = -0.005304142253945342
hlcad.offset = -0.005304108156643007
hlctd.offset = 1.1365768090935692e-08
p0fd2.count = 2
p0d2.count = 113
hlcnd.count = 556270<file_sep>#!/usr/bin/env python
"""Cavro Centris Syringe Pump
<NAME>, Jun 8, 2017 - Jun 8, 2017
"""
from cavro_centris_syringe_pump_IOC import syringe_pump_IOC
from Panel import BasePanel,PropertyPanel,ButtonPanel,TogglePanel,TweakPanel
import wx
from numpy import inf
__version__ = "1.0.2" # baud rate
class TemperatureControllerIOCPanel(BasePanel):
name = "TemperatureControllerIOCPanel"
title = "Temperature Controller IOC"
standard_view = [
"Enabled",
"EPICS Record",
"Port",
]
parameters = [
[[TogglePanel,"Enabled",syringe_pump_IOC,"EPICS_enabled"],{"type":"Off/On","refresh_period":1.0}],
[[PropertyPanel,"EPICS Record",syringe_pump_IOC,"prefix"],{"refresh_period":1.0,"choices":["NIH:PUMP","TEST:PUMP"]}],
[[PropertyPanel,"Port",syringe_pump_IOC,"port_name"],{"read_only":True}],
]
def __init__(self,parent=None):
BasePanel.__init__(self,
parent=parent,
name=self.name,
title=self.title,
parameters=self.parameters,
standard_view=self.standard_view,
label_width=90,
refresh=True,
live=True,
)
self.Bind(wx.EVT_CLOSE,self.OnClose)
def OnClose(self,event=None):
temperature_controller_IOC.EPICS_enabled = False
self.Destroy()
if __name__ == '__main__':
from pdb import pm # for debugging
import logging
from tempfile import gettempdir
logging.basicConfig(level=logging.DEBUG,format="%(asctime)s: %(message)s",
filename=gettempdir()+"/temperature_controller_debug.log")
temperature_controller.logging = True
if not "app" in globals(): app = wx.App(redirect=False) # to initialize WX...
panel = TemperatureControllerIOCPanel()
app.MainLoop()
<file_sep>"""
Script to characterize the MAR CCD detector
<NAME>, 11 Feb 2009
"""
from id14 import * # Beamline instrumentation
from os import makedirs
from os.path import exists,dirname,basename
from numpy import array,where,isnan,amax,zeros,rint,isinf,nansum,nanmax,sum,average
from textfile import read,save
scan_dir = "/data/anfinrud_0902/Data/MARCCD/readout_noise_raw4"
npasses = 32
def acquire():
"Acquires a series of images"
# Make sure directory exists
if not exists (scan_dir): makedirs (scan_dir)
for i in range(0,npasses):
ccd.start()
ccd.readout()
while ccd.state() != "idle": sleep(0.1)
sleep(5)
filename = "%s/%03d.mccd" % (scan_dir,i+1)
ccd.save_image(filename)
while ccd.state() != "idle": sleep(0.1)
sleep(5)
filename = "%s/%03d_raw.mccd" % (scan_dir,i+1)
ccd.save_raw_image(filename)
while ccd.state() != "idle": sleep(0.1)
sleep(5)
def analyze():
"""Processes the dataset in directory 'scan_dir' """
# for debugging
global filenames,pos,I0,curr,sum_image,ave_image,peakI,x,y,r,image,I
logfile = "%s/scan.log" % scan_dir
filenames,pos,I0,curr = read(logfile,labels=
"filename,DetY[mm],I0[Vs],bunchcurrent[mA]")
nimages = len(filenames)
# Find the peak position. This first image might be an empty image.
# Thus use an averaged image to determine the peak position.
print "Finding peak",
w,h = imagesize(scan_dir+"/"+filenames[0])
sum_image = zeros((w,h))
count = 0
for i in range(0,nimages):
image = numimage(scan_dir+"/"+filenames[i])
if isinf(nanmax(image)): print "!",; continue # skip saturated images
print ".",
sum_image += image
count += 1
if count>=5: break
ave_image = sum_image/count
peakI = nanmax(ave_image)
peakpos = where(ave_image == peakI)
x,y = peakpos[0][0],peakpos[1][0]
print x,y
r = int(rint(boxsize/2))
I = array([nan]*nimages)
for i in range(0,nimages):
image = numimage(scan_dir+"/"+filenames[i])
I[i] = average(image[x-r:x+r+1,y-r:y+r+1])
print "%g\t%g" % (pos[i],I[i])
outfile = "%s/scan.txt" % scan_dir
save([pos,I,I0,curr],outfile,labels=
"DetY[mm],I[counts],I0[Vs],bunchcurrent[mA]")
def imagesize(filename):
"""Get width and height in pixels as (w,h) pair"""
from PIL import Image
image = Image.open(filename)
return image.size
def numimage(filename):
"""Load an image as numpy array"""
from PIL import Image
from numpy import array,where,nan,inf
image = Image.open(filename)
image = array(image.convert("I"),float).T
image[where(image == 0)] = nan
image[where(image == 65535)] = inf
image -= 10 # undo MAR CCD image software offset
return image
if __name__ == "__main__":
"for testing"
acquire()
<file_sep>"""
Optical Freeze Detector Agent with on-axis laser
Authors: <NAME>
Date created: 26 Feb 2018 - original optical freeze detection agent
Date last modified: March 2 2019
Utilizes center 50x50 pixels to measure mean value within
The server connects to Microscope Camera and analyses every incoming image in the region of analysis.
The reported values are MEAN and STDEV. Based on MEAN and Threshold_mean the server can issue a command to
lunch an intervention.
"""
__version__ = "1.0" # write a comment
from CAServer import casput,casdel, casget
from CA import caget
from datetime import datetime
from thread import start_new_thread
from pdb import pm
import os
from time import sleep,time
from persistent_property import persistent_property
from numpy import nan
from logging import debug,info,warn,error
import traceback
class Optical_Scattering_Server(object):
orientation = persistent_property('orientation', 'horizontal')
on_axis_square_size = persistent_property('on_axis_square_size', (25,25))
warning_threshold = persistent_property('warning_threshold', 100.0)
region_size_x =persistent_property('region_size_x', 10)
region_offset_x =persistent_property('region_offset_x', 0)
region_size_y =persistent_property('region_size_y', 10)
region_offset_y =persistent_property('region_offset_y', 20)
def __init__(self):
self.name = 'sample_frozen_optical'
self.prefix = self.prefix = 'NIH:OPTICAL_SCATTERING'
self.running = False
self.warning = False
self.orient_dic = {}
self.orient_dic['vertical'] ={'up': [(532,0),(732,1024)],
'down':[(1040,0),(1240,1024)]}
self.orient_dic['horizontal'] = {'up':[(697-75,0),(825-75,1360)],
'down':[(865+20,0),(993+20,1360)]}
self.orient_dic['horizontal2'] = {'up':[(0,0),(120,1360)],
'middle':[(512,0),(632,1360)],
'down':[(903,0),(1023,1360)]}
#On-axis uses only middle part and disregards up and down.
self.x_middle = 512 + self.region_offset_x
self.y_middle = 680 + self.region_offset_y
dx = self.region_size_x
dy = self.region_size_y
self.orient_dic['on-axis-h'] = {'up':[(0,0),(0,0)],
'middle':[(self.x_middle-dx,self.y_middle-dy),(self.x_middle+dx,self.y_middle+dy)],
'down':[(0,0),(0,0)]}
self.orient_dic['on-axis-v'] = {'up':[(0,0),(0,0)],
'middle':[(680-dy,512-dx),(680+dy,512+dx)],
'down':[(0,0),(0,0)]}
self.circular_buffer = []
self.scattering = nan
def init(self):
"""
define parameters for current operation
initializes image analyzer
"""
from optical_image_analyzer import image_analyzer
image_analyzer.init()
from CAServer import casput,casmonitor
from CA import caput,camonitor
from numpy import nan
info('initializing the %s server' %self.prefix)
casput(self.prefix+".RBV",nan)
casput(self.prefix+".VAL",nan)
casput(self.prefix+".MEAN_TOP",nan)
casput(self.prefix+".MEAN_BOTTOM",nan)
casput(self.prefix+".MEAN_MIDDLE",nan)
casput(self.prefix+".MEAN",nan)
casput(self.prefix+".STDEV",nan)
casput(self.prefix+'.RUNNING', self.running)
#changable control parameters
casput(self.prefix+'.region_offset_x', self.region_offset_x)
casput(self.prefix+'.region_size_x', self.region_size_x)
casput(self.prefix+'.region_offset_y', self.region_offset_y)
casput(self.prefix+'.region_size_y', self.region_size_y)
casput(self.prefix+'.warning', self.warning)
casput(self.prefix+'.warning_threshold', self.warning_threshold)
casput(self.prefix+".KILL",value = 'write password to kill the process')
#PV with a list of all process variable registered at the current Channel Access Server
casput(self.prefix+".LIST_ALL_PVS",value = self.get_pv_list())
# Monitor client-writable PVs.
casmonitor(self.prefix+".KILL",callback=self.monitor)
casmonitor(self.prefix+".region_size_x",callback=self.monitor)
casmonitor(self.prefix+".region_offset_x",callback=self.monitor)
casmonitor(self.prefix+".region_size_y",callback=self.monitor)
casmonitor(self.prefix+".region_offset_y",callback=self.monitor)
casmonitor(self.prefix+".warning_threshold",callback=self.monitor)
def monitor(self,PV_name,value,char_value):
"""Process PV change requests"""
from CAServer import casput
from CA import caput
info("monitor: %s = %r" % (PV_name,value))
if PV_name == self.prefix + ".KILL":
if value == 'shutdown': #the secret word to shutdown the process is 'shutdown'
self.shutdown()
if PV_name == self.prefix + ".region_size_x":
self.region_size_x = int(value)
if PV_name == self.prefix + ".region_size_y":
self.region_size_y = int(value)
if PV_name == self.prefix + ".region_offset_x":
self.region_offset_x = int(value)
if PV_name == self.prefix + ".region_offset_y":
self.region_offset_y = int(value)
if PV_name == self.prefix + ".warning_threshold":
try:
temp = float(value)
flag = True
except:
error(traceback.format_exc())
flag = False
if flag: self.warning_threshold = float(value)
def shutdown(self):
from CAServer import casdel
info('SHUTDOWN command received. orderly exit initiated for %s' %self.prefix)
self.running = False
self.cleanup()
del self
def get_pv_list(self):
from CAServer import PVs
lst = list(PVs.keys())
return lst
def start(self):
"""run in background"""
info('Freeze detector has started')
from thread import start_new_thread
start_new_thread(self.run,())
def stop(self):
self.running = False
def close(self):
self.running = False
self.cleanup()
def run(self):
from time import sleep,time
self.init()
self.running = True
while self.running:
self.running_timestamp = time()
try:
self.run_once()
except:
error(traceback.format_exc())
warn('Microscope camera is not working')
self.running = False
self.scattering = nan
def run_once(self):
from optical_image_analyzer import image_analyzer
from CAServer import casput, casget
from numpy import rot90
img = image_analyzer.get_image()
debug('image received: image counter %r, image dimensions %r' %(image_analyzer.imageCounter, img.shape))
if self.orientation == 'horizontal2' or self.orientation == 'horizontal' or self.orientation == 'on-axis-h':
img = rot90(img,3,axes=(1,2))
res_dic = self.is_frozen(img)
debug('res_dic = %r' %res_dic)
is_frozen_flag = res_dic['flag']
casput(self.prefix+".MEAN_TOP",round(res_dic['mean_top'],2))
casput(self.prefix+".MEAN_BOTTOM",round(res_dic['mean_bottom'],2))
casput(self.prefix+".MEAN_MIDDLE",round(res_dic['mean_middle'],2))
casput(self.prefix+".MEAN",round(res_dic['mean_value'],2))
casput(self.prefix+".RBV",round(res_dic['mean_value'],2))
casput(self.prefix+".warning",res_dic['mean_value'] >= self.warning_threshold)
casput(self.prefix+".STDEV",round(res_dic['stdev'],2))
self.intervention_enabled = casget(self.prefix+'.INTERVENTION_ENABLED')
casput(self.prefix+".VAL",is_frozen_flag)
if is_frozen_flag and temperature.value < self.frozen_threshold_temperature:
print('freezing detected')
"""Intervention"""
if self.intervention_enabled:
self.retract_intervention()
else:
print('Intervention was disabled')
def is_frozen(self,img):
"""
determines if the images is frozen or not
"""
from optical_image_analyzer import image_analyzer
from numpy import subtract, mean, std, rot90, array
from freeze_intervention import freeze_intervention
from temperature import temperature
from PIL import Image
dx = int(self.region_size_x)
dy = int(self.region_size_y)
self.orient_dic['on-axis-h'] = {'up':[(0,0),(0,0)],
'middle':[(512-dx,680-dy),(512+dx,680+dy)],
'down':[(0,0),(0,0)]}
self.orient_dic['on-axis-v'] = {'up':[(0,0),(0,0)],
'middle':[(680-dy,512-dx),(680+dy,512+dx)],
'down':[(0,0),(0,0)]}
section_up = image_analyzer.masked_section(img,anchors = self.orient_dic[self.orientation]['up'])
section_middle = image_analyzer.masked_section(img,anchors = self.orient_dic[self.orientation]['middle'])
section_down = image_analyzer.masked_section(img,anchors = self.orient_dic[self.orientation]['down'])
flag = False
dict0 = self.analyse(section_up)
dict1 = self.analyse(section_down)
dict2 = self.analyse(section_middle)
## dict0 = {}
## dict1 = {}
## dict2 = {}
## dict0['mean'] = 0
## dict1['mean'] = 0
## dict2['mean'] = 0
mean_top = dict0['mean']
mean_bottom = dict1['mean']
mean_middle = dict2['mean']
if self.orientation == 'on-axis-h' or self.orientation == 'on-axis-v' :
mean_value = dict2['mean']
stdev = dict2['stdev']
else:
mean_value = dict2['mean']-(dict0['mean']/2.)-(dict1['mean']/2.)
stdev = (dict2['stdev']**2-(dict0['stdev']/2)**2-(dict1['stdev']/2)**2)**0.5
self.scattering = round(mean_value,3)
res_dic = {}
res_dic['flag'] = flag
res_dic['mean_top']=mean_top
res_dic['mean_bottom']=mean_bottom
res_dic['mean_middle']=mean_middle
res_dic['mean_value']=mean_value
res_dic['stdev'] = stdev
return res_dic
def analyse(self,array):
from numpy import mean, std
dic = {}
dic['mean'] = mean(array[0,:,:]*1.0+array[1,:,:]*1.0+array[2,:,:]*1.0)
dic['mean_R'] = mean(array[0,:,:])
dic['mean_G'] = mean(array[1,:,:])
dic['mean_B'] = mean(array[2,:,:])
dic['stdev'] = std(array[0,:,:]*1.0+array[1,:,:]*1.0+array[2,:,:]*1.0)
dic['stdev_R'] = std(array[0,:,:])
dic['stdev_G'] = std(array[1,:,:])
dic['stdev_B'] = std(array[2,:,:])
return dic
def cleanup(self):
"""orderly cleanup of all channel access server process variables."""
from CAServer import casdel
lst = self.get_pv_list()
for item in lst:
info('delete PV: %s' % item )
casdel(item)
###Libraries for testing and data processing
def test_folder(self):
folder = '//volumes/data/anfinrud_1810/Test/Laue/opt_images/freezing/Microscope/'
return folder
def get_filenames(self,folder):
import os
from numpy import zeros,asarray
lst_temp = os.listdir(folder)
lst = []
for i in lst_temp:
if '.tiff' in i:
lst.append(i.split('_'))
sorted_lst = sorted(lst,key=lambda x: (x[0],x[1]))
lst_s = []
for i in sorted_lst:
lst_s.append([i[0],folder + '_'.join(i)])
return lst_s
def get_image_from_file(self,filename):
from PIL import Image
from numpy import rot90, array, zeros,flipud, mean, flip, sum
img = array(Image.open(filename))
gray = sum(img,2)
arr = zeros((4,1024,1360))
for i in range(3):
for j in range(1024):
for k in range(1360):
arr[i,j,k] = img[j,k,i]
i = 3
for j in range(1024):
for k in range(1360):
arr[i,j,k] = gray[j,k]
arr = flip(arr,1)
return arr
def get_vector(self,img):
from numpy import mean, sum
dic = {}
dic['mean_total'] = mean(img[3,:,:],axis = 1)
dic['sum_total'] = sum(img[3,:,:],axis = 1)
dic['mean_R'] = mean(img[0,:,:],axis = 1)
dic['sum_R'] = sum(img[0,:,:],axis = 1)
dic['mean_G'] = mean(img[1,:,:],axis = 1)
dic['sum_G'] = sum(img[1,:,:],axis = 1)
dic['mean_B'] = mean(img[2,:,:],axis = 1)
dic['sum_B'] = sum(img[2,:,:],axis = 1)
return dic
def run_test(self):
from time import time
folder = self.test_folder()
filenames = self.get_filenames(folder)
res_lst = []
t1 = time()
i = 0
for name in filenames:
img = self.get_image_from_file(name[1])
result = self.get_vector(img)
self.save_obj(result,name[1].split('.tiff')[0]+'.pickle')
res_lst.append(self.get_vector(img))
print(time()-t1,len(filenames)-i)
i+=1
def save_obj(self,obj, name ):
import pickle
with open(name, 'wb') as f:
pickle.dump(obj, f, pickle.HIGHEST_PROTOCOL)
def load_obj(self,name):
import pickle
with open(name, 'rb') as f:
return pickle.load(f)
def get_all_pickle(self,folder):
lst_temp = os.listdir(folder)
lst = []
for item in lst_temp:
i = item.split('.pickle')[0]
lst.append(i.split('_'))
sorted_lst = sorted(lst,key=lambda x: (x[0],x[1],x[2],x[3]))
lst_s = []
for i in sorted_lst:
lst_s.append([i[0],folder + '_'.join(i),i[2],i[3]])
return lst_s
def test2(self,fr,to, folder = ''):
from matplotlib import pyplot as plt
from time import time
i = 0
if folder =='':
lst = self.get_all_pickle(self.test_folder())
else:
lst = self.get_all_pickle(folder)
for item in lst[fr:to]:
item[1] = item[1] + '.pickle'
arr = self.load_obj(item[1])['mean_total']
plt.plot(arr)
def plot_mean_values(self,folder):
from matplotlib import pyplot as plt
from time import time
from numpy import std
from numpy import asarray
i = 0
arr = []
arrT = []
if folder =='':
lst = self.get_all_pickle(self.test_folder())
else:
lst = self.get_all_pickle(folder)
for item in lst:
item[1] = item[1] + '.pickle'
arr.append(self.load_obj(item[1])['frozen']['mean_value'])
arrT.append(float(item[3])*0.1)
arr = asarray(arr)
arrT = asarray(arrT)
plt.plot(arr)
plt.plot(arrT)
plt.show()
def process_data(self,folder):
from matplotlib import pyplot as plt
from time import time
from numpy import std
from numpy import asarray
result = []
if folder =='':
lst = self.get_all_pickle(self.test_folder())
else:
lst = self.get_all_pickle(folder)
for item in lst:
dic = {}
item[1] = item[1] + '.pickle'
dic['temperature'] = float(item[3])
dic['inserted'] = item[2]
dic['frozen'] = self.load_obj(item[1])['frozen']['flag']
dic['frozen_data'] = self.load_obj(item[1])['frozen']
dic['data'] = self.load_obj(item[1])
result.append(dic)
return result
def plot_all_T(self,T = [0,1],folder = ''):
from matplotlib import pyplot as plt
i =0
for item in T:
num = len(T)*100 +10 +i+1
plt.subplot(num)
self.plot_fixed_temperature(0,2631,folder,T[i])
plt.ylim(30,150)
i+=1
plt.show()
def plot_N_image_slice(self,N,folder):
from matplotlib import pyplot as plt
from time import time
from numpy import std
i = 0
temp_lst
if folder =='':
lst = self.get_all_pickle(self.test_folder())
else:
lst = self.get_all_pickle(folder)
for item in lst[fr:to]:
item[1] = item[1] + '.pickle'
temperature = item[3]
arr = self.load_obj(item[1])['mean_total']
arrG = self.load_obj(item[1])['mean_G']
arrR = self.load_obj(item[1])['mean_R']
arrB = self.load_obj(item[1])['mean_B']
plt.plot(arr, label = 'total', color= 'k')
plt.plot(arrR, label = 'Red', color = 'r')
plt.plot(arrG, label = 'Green' , color = 'g')
plt.plot(arrB, label = 'Blue', color = 'b')
plt.title('Image = %r @ T = %r C' %(N,temperature))
def plot_fixed_temperature(self,fr,to, folder = '',temperature = 0):
from matplotlib import pyplot as plt
from time import time
from numpy import std
i = 0
if folder =='':
lst = self.get_all_pickle(self.test_folder())
else:
lst = self.get_all_pickle(folder)
for item in lst[fr:to]:
item[1] = item[1] + '.pickle'
arr = self.load_obj(item[1])['mean_total']
if temperature == 999 and std(arr) != 0:
plt.plot(arr, label = str(self.load_obj(item[1])['frozen']['mean_value']))
elif abs(float(item[3]) - temperature) < 0.2 and std(arr) != 0:
plt.plot(arr, label = str(self.load_obj(item[1])['frozen']['mean_value']))
i +=1
plt.title('N of images = %r @ T = %r C' %(i,temperature))
def test3(self):
from matplotlib import pyplot as plt
from time import time
lst = self.get_all_pickle(self.test_folder())
lsttt = []
for item in lst:
lsttt.append(self.load_obj(item[1])['frozen']['mean_value'])
#plt.plot(lsttt)
return lsttt
optical_scattering_server = Optical_Scattering_Server()
if __name__ == "__main__":
import autoreload
import logging
from tempfile import gettempdir
import matplotlib.pyplot as plt
logging.basicConfig(level=logging.INFO,
format="%(asctime)s %(levelname)s: %(message)s",
filename=gettempdir()+"/optical_scattering.log",
)
self = optical_scattering_server # for testing
print('self.start()')
print('self.stop()')
print('self.close()')
print('self.is_running = True')
print('self.is_running = False')
<file_sep>EPICS_enabled = True
description = 'Detector distance'
prefix = '14IDB:m3'
target = 185.8<file_sep>description = 'Horiz. mirror jack 2'
prefix = '14IDC:m13'
target = -0.007374189453125114
EPICS_enabled = True<file_sep>#!/bin/bash -l
localdir=`dirname "$0"`
dir=`cd "${localdir}/../../../../../.."; pwd`
exec python "$dir/MicrofluidicsCamera.py" >> ~/Library/Logs/Python.log 2>&1
<file_sep>"""
Data base to save and recall motor positions
Author: <NAME>
Date created: 2019-05-24
Date last modified: 2019-05-31
"""
__version__ = "1.3" # monitor
from logging import debug,info,warn,error
class Configuration_Property(property): pass
class Motor_Property(property): pass
from classproperty import classproperty,ClassPropertyMetaClass
class Configuration(object):
##class Bar(metaclass=ClassPropertyMetaClass): # Python 3+
"""Data base save and recall motor positions"""
__metaclass__ = ClassPropertyMetaClass # Python 2.7
from configuration_server import Configuration_Server
prefix = Configuration_Server.prefix
def __init__(self,name,**kwargs):
# kwargs for backward-compatbility
self.name = name
@classmethod
def register(cls,name):
if not name in cls.configuration_names:
cls.configuration_names += [name]
@classproperty
def configuration_names(cls):
return Configuration.get_global_value("configuration_names",[])
@configuration_names.setter
def configuration_names(cls,value):
Configuration.set_global_value("configuration_names",value)
@classproperty
def configurations(cls):
return [configuration(n) for n in configuration.configuration_names]
def configuration_property(name,default_value=None):
def PV_name(self): return self.configuration_PV_name(name)
def get(self):
if type(default_value) == list: value = self.array_PV(PV_name(self))
else: value = self.get_PV(PV_name(self),default_value)
return value
def set(self,value): self.set_PV(PV_name(self),value)
prop = Configuration_Property(get,set)
return prop
value = configuration_property("value","")
values = configuration_property("values",[])
command_value = configuration_property("command_value","")
title = configuration_property("title","")
description = configuration_property("description","")
matching_description = configuration_property("matching_description","")
closest_descriptions = configuration_property("closest_descriptions","")
command_description = configuration_property("command_description","")
command_rows = configuration_property("command_rows",[])
matching_rows = configuration_property("matching_rows",[])
closest_rows = configuration_property("closest_rows",[])
n_motors = configuration_property("n_motors",0)
descriptions = configuration_property("descriptions",[])
updated = configuration_property("updated",[])
formats = configuration_property("formats",[])
nrows = configuration_property("nrows",0)
motor_names = configuration_property("motor_names",[])
names = configuration_property("names",[])
motor_labels = configuration_property("motor_labels",[])
widths = configuration_property("widths",[])
formats = configuration_property("formats",[])
tolerance = configuration_property("tolerance",[])
description_width = configuration_property("description_width",200)
row_height = configuration_property("row_height",20)
show_apply_buttons = configuration_property("show_apply_buttons",True)
apply_button_label = configuration_property("apply_button_label","Select")
show_define_buttons = configuration_property("show_define_buttons",True)
define_button_label = configuration_property("define_button_label","Update")
show_stop_button = configuration_property("show_stop_button",False)
serial = configuration_property("serial",False)
vertical = configuration_property("vertical",False)
multiple_selections = configuration_property("multiple_selections",False)
are_configuration = configuration_property("are_configuration",[])
motor_configuration_names = configuration_property("motor_configuration_names",[])
are_numeric = configuration_property("are_numeric",[])
current_timestamp = configuration_property("current_timestamp","")
applying = configuration_property("applying",False)
show_in_list = configuration_property("show_in_list",True)
def motor_property(name,default_value=None):
def get(self): return self.Motor_Property(self,name,default_value)
def set(self,value): get(self)[:] = value
return Motor_Property(get,set)
from numpy import nan
current_position = motor_property("current_position")
positions = motor_property("positions",[])
positions_match = motor_property("positions_match",[])
class Motor_Property(object):
def __init__(self,configuration,name,default_value=None):
self.configuration = configuration
self.name = name
self.default_value = default_value
def PV_name(self,i): return self.configuration.motor_PV_name(self.name,i)
def __getitem__(self,i):
if type(i) == slice: value = [x for x in self]
else:
if type(self.default_value) == list:
value = self.configuration.array_PV(self.PV_name(i))
else: value = self.configuration.get_PV(self.PV_name(i),self.default_value)
return value
def __setitem__(self,i,value):
if type(i) == slice:
for j in range(0,len(value)): self[j] = value[j]
else:
self.configuration.set_PV(self.PV_name(i),value)
def __len__(self): return self.configuration.n_motors
def __iter__(self):
for i in range(0,len(self)):
if i < len(self): yield self[i]
def __repr__(self):
return "%s(%s,%r)" % (type(self).__name__,self.configuration,self.name)
class array_PV(object):
def __init__(self,PV_name):
self.PV_name = PV_name
def __getitem__(self,i):
if type(i) == slice: value = self.array
else: value = self.array[i]
return value
def __setitem__(self,i,value):
if type(i) == slice: self.array = value
else:
array = self.array
array[i] = value
self.array = array
def get_array(self):
return Configuration.get_PV(self.PV_name,[])
def set_array(self,value):
from CA import caput
caput(self.PV_name,value)
array = property(get_array,set_array)
def __len__(self): return len(self.array)
def __iter__(self):
for i in range(0,len(self)):
if i < len(self): yield self[i]
def __repr__(self):
return "%s(%r)" % (type(self).__name__,self.PV_name)
def index(self,value): return self.array.index(value)
def __eq__(self,array):
if not hasattr(array,"__len__"): return False
if len(self) != len(array): return False
return all([self[i] == array[i] for i in range(0,len(self))])
def __ne__(self,array): return not self == array
@staticmethod
def get_global_value(name,default_value=None):
return Configuration.get_PV(Configuration.global_PV_name(name),default_value)
@staticmethod
def set_global_value(name,value):
from CA import caput
caput(Configuration.global_PV_name(name),value)
@staticmethod
def global_PV_name(name):
return (Configuration.prefix+"."+name).upper()
def configuration_PV_name(self,name):
return (self.prefix+"."+self.name+"."+name).upper()
def set_motor_value(self,name,motor_num,value):
from CA import caput
caput(self.motor_PV_name(name,motor_num),value)
def motor_PV_name(self,name,motor_num):
return (self.prefix+"."+self.name+".MOTOR"+str(motor_num+1)+"."+name).upper()
@staticmethod
def get_PV(PV_name,default_value=None):
from CA_cached import caget_cached as caget
value = caget(PV_name)
if value is None: value = default_value
if default_value is not None and type(value) != type(default_value):
if type(default_value) == list: value = [value]
else:
try: value = type(default_value)(value)
except: value = default_value
return value
@staticmethod
def set_PV(PV_name,value):
from CA import caput
caput(PV_name,value)
def monitor(self,property_name,callback,*args,**kwargs):
from CA import camonitor
for PV_name in self.PV_names(property_name):
def monitor_callback(PV_name,value,formatted_value):
callback(*args,**kwargs)
monitor_callback.callback = callback
monitor_callback.args = args
monitor_callback.kwargs = kwargs
camonitor(PV_name,callback=monitor_callback,new_thread=True)
def PV_names(self,property_name):
PV_names = []
if hasattr(type(self),property_name):
prop = getattr(type(self),property_name)
if type(prop) == Configuration_Property:
PV_names = [self.configuration_PV_name(property_name)]
if type(prop) == Motor_Property:
PV_names = [self.motor_PV_name(property_name,i)
for i in range(0,self.n_motors)]
return PV_names
def __repr__(self):
return "%s(%r)" % (type(self).__name__,self.name)
configuration = Configuration
config = configuration
class Configurations(object):
"""Name space containing all defined configurations"""
def __getattr__(self,name):
if name == "__members__": return configuration.configuration_names
if name.startswith("__") and name.endswith("__"):
raise AttributeError("%s" % name)
return configuration(name)
configurations = Configurations()
configs = configurations
if __name__ == '__main__': # for testing
from pdb import pm # for debugging
from time import time # for performance testing
import logging
for h in logging.root.handlers[:]: logging.root.removeHandler(h)
logging.basicConfig(level=logging.DEBUG,
format="%(asctime)s %(levelname)s %(module)s.%(funcName)s: %(message)s",
)
##name = "beamline_configuration"
##name = "sequence_modes"
##name = "heat_load_chopper_modes"
##name = "Julich_chopper_modes"
name = "timing_modes"
##name = "sequence_modes"
##name = "delay_configuration"
##name = "temperature_configuration"
##name = "power_configuration"
##name = "scan_configuration"
##name = "alio_diffractometer_saved"
##name = "detector_configuration"
##name = "diagnostics_configuration"
##name = "method"
self = configuration(name=name)
print('self.positions[0][0]')
##print('self.positions[0][:]')
print('self.current_position[0]')
print('self.positions_match[0][0]')
##print('self.positions_match[0][:]')
print('self.descriptions[:]')
##print('self.descriptions[5]')
##print('self.descriptions.index("S-1")')
##print('self.widths != self.widths')
##print('self.widths == self.widths')
##print('self.are_numeric[:]')
def callback(property_name):
value = getattr(self,property_name)
if hasattr(value,"__getitem__"):
value = value[:]
for i in range(0,len(value)):
if hasattr(value[i],"__getitem__"): value[i] = value[i][:]
info("%s = %r" % (property_name,value))
print('self.monitor("nrows",callback,"nrows")')
print('self.monitor("descriptions",callback,"descriptions")')
print('self.monitor("command_rows",callback,"command_rows")')
print('self.monitor("current_position",callback,"current_position")')
print('self.monitor("positions",callback,"positions")')
<file_sep>#!/usr/bin/env python
"""
Substitute for the BioCARS timing system to use at the NIH for testing.
<NAME>, 11 Aug 2014 - 12 Aug 2014
"""
__version__ = "1.0"
from DG535 import DG535
class Pulses(object):
"""Number of pulses per acquisition"""
from numpy import nan
start = nan
doc = "When read return the number of pulses remaining until the burst"\
"ends. When set trigger a burst with the given number of pulses."
def get_value(self):
"""Number of pulses remaining until the burst ends"""
from numpy import ceil,isnan
from time import time
if isnan(self.start): return 0
dt = time() - self.start
period = 1/DG535.burst_frequency
triggers_generated = int(ceil(dt/period))
count = max(DG535.burst_count - triggers_generated,0)
return count
def set_value(self,count):
from time import time
DG535.start_burst(count)
self.start = time()
value = property(get_value,set_value,doc=doc)
pulses = Pulses()
class ContinuousTrigger(object):
"""Is continuous triggering enabled?"""
def get_value(self):
"""Is continuous triggering enabled?"""
return DG535.trigger_mode == "internal"
def set_value(self,value):
if bool(value) == True: DG535.trigger_mode = "internal"
else: DG535.trigger_mode = "single shot"
value = property(get_value,set_value)
continuous_trigger = ContinuousTrigger()
class TMode(object):
"""Trigger mode: 0 = continuous trigger, 1 = counted"""
def get_value(self):
"""0 = continuous trigger, 1 = counted"""
return not continuous_trigger.value
def set_value(self,value): continuous_trigger.value = not value
value = property(get_value,set_value)
tmode = TMode()
class Waitt(object):
"""Waiting time between pulses"""
unit = "s"
stepsize = 1e-6
def get_value(self):
"""Time between susequent X-ray pulse in seconds"""
if DG535.trigger_mode == "burst": return 1/DG535.burst_frequency
else: return 1/DG535.trigger_frequency
def set_value(self,value):
DG535.burst_frequency = 1/value
DG535.trigger_frequency = 1/value
value = property(get_value,set_value)
def get_min(self):
"""Lower limit in seconds"""
return 1e-6
min = property(get_min)
def get_max(self):
"""Upper limit in seconds"""
return 1000.0
max = property(get_max)
def get_choices(self):
"""Upper limit in seconds"""
from numpy import arange
return arange(0,1.05,0.05)
choices = property(get_choices)
def next(self,value):
"""Closest allowed value to the given waitting time in s"""
from numpy import clip
value = clip(value,self.min,self.max)
return value
waitt = Waitt()
# Dummy for compatibility with 14-ID
class transon:
"""Sample translation enabled?"""
value = False
class mson:
"""Millsecond X-ray shutter enabled?"""
value = False
class laseron:
"""Laser trigger enabled?"""
value = False
def toint(x):
"""Convert x to a floating point number.
If not convertible return zero"""
try: return int(x)
except: return 0
def tofloat(x):
"""Convert x to a floating point number.
If not convertible return 'Not a Number'"""
from numpy import nan
try: return float(x)
except: return nan
if __name__ == "__main__": # for testing
from time import sleep
print ""
<file_sep>"""<NAME>, Jan 29, 2016 - Jan 29, 2016"""
from pdb import pm
from logging import warn
try: from rayonix_detector_XPP import ccd
except: warn("rayonix_detector_XPP not available")
from timing_sequence import timing_sequencer
from timing_system import timing_system
from ImageViewer import show_images
from xppdaq import xppdaq # for xppdaq.endrun()
from numpy import *
__version__ = "1.1"
import logging
from tempfile import gettempdir
logging.basicConfig(level=logging.DEBUG,format="%(asctime)s: %(message)s",
filename=gettempdir()+"/lauecollect_debug.log")
dir = "/reg/neh/operator/xppopr/experiments/xppj1216/Data/Test/Test3"
npasses = 10
laser_on = [0,1]
nimages = len(laser_on)*npasses
filenames = []
for i in range(0,npasses):
for on in laser_on:
filenames += [dir+"/%03d_%s.mccd" % (i+1,"on" if on else "off")]
image_numbers = range(1,nimages+1)
laser_on = array(laser_on*npasses)
ms_on = where(laser_on,1,0)
xatt_on = where(laser_on,0,1)
npulses = where(laser_on,1,11)
# The first image in frame transfer mode has a lot of zingers and needs to be
# discarded.
# The detector trigger is connected as external trigger to the FPGA.
# The trigger pulse for the first image starts the timing seqence.
filenames = [dir+"/discard.mccd"]+filenames
def test_FPGA():
timing_sequencer.inton_sync = 0
timing_system.image_number.value = 0
timing_system.pulses.value = 0
timing_sequencer.acquire(laser_on=laser_on,ms_on=ms_on,xatt_on=xatt_on,
npulses=npulses,image_numbers=image_numbers)
def test_DAQ():
ccd.acquire_images_triggered(filenames)
show_images(filenames)
def test():
test_FPGA()
test_DAQ()
print("test_FPGA()")
print("test_DAQ()")
print("test()")
<file_sep>#!/bin/env python
from psana import *
from time import time
##run = "exp=xpptut15:run=240:smd"
run = "exp=xppj1216:run=9:smd:dir=/reg/d/ffb/xpp/xppj1216/xtc:live"
start = time()
ds = DataSource(run)
det = Detector('rayonix',ds.env())
src = Source('rayonix')
for nevent,evt in enumerate(ds.events()):
print nevent
##img = det.raw(evt)
raw = evt.get(Camera.FrameV1,src)
if raw is None: continue
img = raw.data16()
print img.shape
print nevent/(time()-start),"Hz"
import matplotlib.pyplot as plt
##plt.imshow(img,vmin=-2,vmax=2)
##plt.show()
<file_sep># Echo client program
import socket
HOST = '172.16.17.32' # The remote host
PORT = 50000 # The same port as used by the server
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
data = raw_input('what to send? ')
s.connect((HOST, PORT))
s.send(str(data))
data = s.recv(1024)
s.close()
print 'Received', repr(data)
<file_sep>"""
Date: 2019-04-23
"""
from struct import pack,calcsize,Struct
def write_packet(address,bitmask,count):
type = 1
version = 1
length = 16
data = pack(">BBHIII",type,version,length,address,bitmask,count)
return data
write_scruct = Struct(">BBHIII")
def write_packet_2(address,bitmask,count):
type = 1
version = 1
length = 16
data = write_scruct.pack(type,version,length,address,bitmask,count)
return data
address = 0
bitmask = 0
count = 0
if __name__ == "__main__":
from timeit import timeit
setup = "from test_struct import *"
print('write_packet_2(address,bitmask,count)')
print('timeit("data = write_packet(address,bitmask,count)",number=1000000,setup=setup)')
print('timeit("data = write_packet_2(address,bitmask,count)",number=1000000,setup=setup)')
<file_sep>MicroscopeCamera.camera.IP_addr = 'id14b-prosilica1.cars.aps.anl.gov'
MicroscopeCamera.ip_address = 'id14b4.cars.aps.anl.gov:2002'
MicroscopeCamera.mirror = True
WideFieldCamera.camera.IP_addr = 'id14b-prosilica2.cars.aps.anl.gov'
WideFieldCamera.ip_address = 'id14b4.cars.aps.anl.gov:2001'
WideFieldCamera.use_multicast = False
Microscope.camera.IP_addr = 'pico22.niddk.nih.gov'
Microscope.ip_address = '172.16.58.3:2003'
Microscope.use_multicast = False
MicrofluidicsCamera.camera.IP_addr = 'femto5.niddk.nih.gov'
MicrofluidicsCamera.ip_address = '172.16.58.3:2004'
MicrofluidicsCamera.use_multicast = False
Camera.camera.IP_addr = ''
Camera.use_multicast = True
TestBenchCamera.ip_address = u'femto1.niddk.nih.gov:2010'
TestBenchCamera.camera.IP_addr = 'atto1.niddk.nih.gov'<file_sep>#!/usr/bin/env python
"""Rayonix detector control panel for continuous operation
Author: <NAME>
Date created: 2017-05-10
Date last modified: 2019-05-31
"""
from rayonix_detector_continuous import rayonix_detector
from Panel import BasePanel,PropertyPanel,ButtonPanel,TogglePanel,TweakPanel
import wx
from numpy import inf
__version__ = "3.1.1" # title
class Rayonix_Detector_Panel_old(BasePanel):
name = "Rayonix_Detector_Panel_old"
title = "Rayonix Detector [old]"
standard_view = [
"Acquisition",
"X-ray detector image count",
"Image",
"Images left to save",
"Scratch directory",
"Bin factor",
"IP Address",
]
dirs = ["/net/mx340hs/data/tmp","/net/femto-data/C/Data/tmp","//femto-data/C/Data/tmp",
"/Mirror/femto-data/C/Data/tmp"]
ip_address_choices = ["mx340hs.cars.aps.anl.gov:2222","localhost:2222",
"pico5.niddk.nih.gov:2222","pico8.niddk.nih.gov:2222","pico20.niddk.nih.gov:2222"]
parameters = [
[[PropertyPanel,"Status",rayonix_detector,"online"],{"type":"Offline/Online","read_only":True,"refresh_period":1.0}],
[[TogglePanel, "Acquisition",rayonix_detector,"acquiring"],{"type":"Start/Cancel","refresh_period":1.0}],
[[PropertyPanel,"X-ray detector image count",rayonix_detector,"last_image_number"],{"refresh_period":0.25}],
[[PropertyPanel,"Image",rayonix_detector,"current_image_basename"],{"read_only":True,"refresh_period":1.0}],
[[PropertyPanel,"Images left to save",rayonix_detector,"nimages"],{"read_only":True,"refresh_period":1.0}],
[[PropertyPanel,"Scratch image",rayonix_detector,"last_filename"],{"read_only":True,"refresh_period":1.0}],
[[PropertyPanel,"Bin factor",rayonix_detector,"bin_factor"],{"choices":[1,2,3,4,5,6,8],"refresh_period":1.0}],
[[PropertyPanel,"Scratch directory",rayonix_detector,"scratch_directory"],{"choices":dirs,"refresh_period":1.0}],
[[PropertyPanel,"Images to keep",rayonix_detector,"nimages_to_keep"],{"choices":[3,5,10,20],"refresh_period":1.0}],
[[PropertyPanel,"IP address",rayonix_detector,"ip_address"],{"choices":ip_address_choices,"refresh_period":1.0}],
[[PropertyPanel,"Timing mode",rayonix_detector,"timing_mode"],{"choices":rayonix_detector.timing_modes,"refresh_period":1.0}],
[[PropertyPanel,"ADXV live image",rayonix_detector,"ADXV_live_image"],{"type":"Off/On","refresh_period":1.0}],
[[PropertyPanel,"Live image",rayonix_detector,"live_image"],{"type":"Off/On","refresh_period":1.0}],
[[PropertyPanel,"Limit images to keep",rayonix_detector,"limit_files_enabled"],{"type":"Off/On","refresh_period":1.0}],
[[PropertyPanel,"Auto-start",rayonix_detector,"auto_start"],{"type":"Off/On","refresh_period":1.0}],
]
def __init__(self,parent=None):
BasePanel.__init__(self,
parent=parent,
name=self.name,
title=self.title,
icon="Rayonix Detector",
parameters=self.parameters,
standard_view=self.standard_view,
label_width=180,
refresh=False,
live=False,
)
self.Bind(wx.EVT_CLOSE,self.OnClose)
rayonix_detector.limit_files_enabled = True
def OnClose(self,event=None):
# Shut down background tasks.
rayonix_detector.limit_files_enabled = False
rayonix_detector.ADXV_live_image = False
self.Destroy()
if __name__ == '__main__':
from pdb import pm # for debugging
from redirect import redirect
redirect("Rayonix_Detector_Panel_old")
import wx
app = wx.App(redirect=False)
panel = Rayonix_Detector_Panel_old()
app.MainLoop()
<file_sep>history_length = 300
stabilization_RMS = 0.01
stabilization_time = 3.0
title = 'Temperature Configuration'
motor_names = ['collect.temperatures', 'collect.temperature_wait', 'collect.temperature_idle', 'collect.temperature_count']
motor_labels = ['list of temperatures', 'wait', 'Idle\ntemp', 'count']
widths = [410, 35, 65, 50]
line0.description = 'NIH:ramp-16_120_0.5_30_20'
line1.description = 'NIH:ramp-16_100_0.5_30_20'
line0.collect.temperatures = 'ramp(low=-16,high=120,step=0.5,hold_low=30,hold_high=20)'
line1.collect.temperatures = 'ramp(low=-16,high=100.,step=0.5,hold_low=30,hold_high=20)'
line1.updated = '2019-03-21 12:52:55'
row_height = 40
line0.updated = '2019-05-31 01:58:35'
description_width = 130
nrows = 17
line2.description = 'NIH:NCBD'
line2.updated = '2019-03-24 23:33:04'
line2.collect.temperatures = '11.0, 13.5, 35.5'
names = ['list', 'wait', 'idle', 'count']
line0.collect.temperature_wait = 0
line1.collect.temperature_wait = '0'
line2.collect.temperature_wait = '1'
line0.collect.temperature_idle = 22.0
line1.collect.temperature_idle = '22.0'
line2.collect.temperature_idle = '22.0'
command_row = 5
formats = ['%s', '%g', '%g', '%g']
line3.description = 'NIH:RNA-4BP'
line3.collect.temperatures = '-15.35, 20.15, 89.15'
line3.updated = '2019-06-03 01:51:59'
line3.collect.temperature_wait = 1.0
line3.collect.temperature_idle = 22.0
line0.collect.temperature_count = nan
line4.description = 'NIH:ramp-16_80_0.5_30_20'
line4.collect.temperatures = 'ramp(low=-16,high=80,step=0.5,hold_low=30,hold_high=20)'
line4.collect.temperature_wait = 0
line4.collect.temperature_idle = 22.0
line4.updated = '2019-03-21 15:43:15'
line4.collect.temperature_count = nan
line5.description = 'None'
line5.collect.temperatures = ''
line5.collect.temperature_wait = nan
line5.collect.temperature_idle = nan
line5.updated = '2019-03-20 09:00:11'
line6.description = 'NIH:static-discrete-temp'
line6.collect.temperatures = '-16, 0, 20, 40, 60, 80, 100.0, 120'
line6.collect.temperature_wait = 1.0
line6.collect.temperature_idle = 22.0
line6.updated = '2019-02-03 02:22:51'
line7.collect.temperatures = '15, 22, 29, 36, 43'
line7.collect.temperature_wait = 1
line7.collect.temperature_idle = 22.0
line7.collect.temperature_count = nan
line7.updated = '29 Oct 02:23'
line7.description = 'NIH:Thompson'
command_rows = [3]
line8.description = 'NIH:Thompson:T-Jump'
line8.collect.temperatures = '18'
line8.collect.temperature_idle = 18.0
line8.collect.temperature_wait = 1.0
line8.updated = '03 Nov 19:13'
line9.description = 'NIH:Overlap'
line9.collect.temperatures = '22, 25, 47'
line9.collect.temperature_idle = 22.0
line9.collect.temperature_wait = 1.0
line9.collect.temperature_count = nan
line9.updated = '2019-03-21 00:49:19'
line1.collect.temperature_count = nan
line10.description = 'NIH:Water'
line10.collect.temperatures = '19.5, 22, 44'
line10.updated = '2019-03-24 09:17:51'
line10.collect.temperature_wait = 1.0
line10.collect.temperature_idle = 22.0
line11.description = 'NIH:GB3-static'
line12.description = 'NIH:GB3-T-jump'
line11.collect.temperatures = '-12.7, 9, 38.3, 60, 70.3, 81.7, 92, 113.7'
line11.updated = '2019-02-01 18:36:28'
line12.collect.temperatures = '-16, 35, 56.7, 67, 88.7'
line12.updated = '2019-02-01 18:36:38'
line11.collect.temperature_wait = 1.0
line11.collect.temperature_idle = 22.0
line12.collect.temperature_idle = 22.0
line12.collect.temperature_wait = 1.0
line14.collect.temperatures = '56.5, 75.5, 88.5, 93.5'
line14.updated = '2019-03-23 16:20:21'
line14.collect.temperature_wait = 1
line14.collect.temperature_idle = 22.0
line14.collect.temperature_count = nan
line13.collect.temperatures = '-13.5, 8.5, 30.5, 46.5, 68.5'
line13.updated = '2019-03-21 02:14:56'
line13.collect.temperature_wait = 1
line13.collect.temperature_idle = 22.0
line13.collect.temperature_count = nan
line13.description = 'NIH:HAG-static'
line14.description = 'NIH:RNA-T-jump-HT'
line15.collect.temperatures = '-16.0, 19.5, 56.5, 75.5, 88.5'
line15.updated = '2019-03-23 21:21:01'
line15.collect.temperature_wait = 1
line15.collect.temperature_idle = 22.0
line15.collect.temperature_count = nan
line15.description = 'NIH:RNA-T-jump'
line16.description = 'Temp_95.5C'
line16.collect.temperatures = '95.5'
line16.updated = '2019-03-25 05:27:04'
line16.collect.temperature_idle = 22.0
line16.collect.temperature_wait = 1.0<file_sep>"""Executing hardware timed configuration changes on the FPGA timing system
in "Piano Player" mode.
Author: <NAME>
Date created: 2015-05-01
Date last modified: 2019-05-09
"""
__version__ = "6.6.1" # issue: queue_sequeces: dictionary size changed during iteration
from logging import error,info,warn,debug
from numpy import nan,isnan
class Sequence(object):
parameters = {}
def __init__(self,**kwargs):
"""Arguments: delay=100e-12,laser_on=1,..."""
from collections import OrderedDict
from numpy import nan
keys = timing_sequencer.parameters
self.parameters = OrderedDict(zip(keys,[nan]*len(keys)))
for name in kwargs:
alt_name = name.replace("_on",".on")
if not (name in keys or alt_name in keys):
warn("Sequence: unsupported parameter %r" % name)
for key in kwargs: setattr(self,key,kwargs[key])
self.set_defaults()
def __getattr__(self,name):
"""A property"""
# Called when 'x.name' is evaluated.
# It is only invoked if the attribute wasn't found the usual ways.
alt_name = name.replace("_on",".on")
if name in self.parameters: return self.parameters[name]
elif alt_name in self.parameters: return self.parameters[alt_name]
else: return object.__getattribute__(self,name)
def __setattr__(self,name,value):
"""Set a property"""
# Called when 'x.name = y' is evaluated.
alt_name = name.replace("_on",".on")
if name.startswith("__"): object.__setattr__(self,name,value)
elif name in self.parameters: self.parameters[name] = value
elif alt_name in self.parameters: self.parameters[alt_name] = value
else: object.__setattr__(self,name,value)
def set_defaults(self):
"""Fill in unspecified parameters with default values."""
from numpy import isnan
from timing_system import timing_system
for key in self.parameters:
if key in ["pass_number","image_number"]: continue
if isnan(self.parameters[key]):
self.parameters[key] = timing_sequencer.get_default(key)
@property
def descriptor(self):
"""Text representation of the parameters for generating this
sequence"""
p = self.parameters
description = ",".join(["%s=%g"%(k,v) for k,v in zip(p.keys(),p.values())])+","
description += "generator=%r," % "timing_sequence"
description += "generator_version=%r," % __version__
return description
@property
def register_counts(self):
"""list of registers, list of arrays of values"""
from timing_system import timing_system,round_next
from numpy import isnan,where,arange,rint,floor,ceil,array,cumsum
from numpy import zeros,maximum,clip,unique
from sparse_array import sparse_array
delay = self.delay
Tbase = timing_system.hsct # Period of the 987-Hz clock
waitt = round_next(self.waitt,timing_system.waitt.stepsize)
burst_waitt = round_next(self.burst_waitt,timing_system.burst_waitt.stepsize)
burst_delay = round_next(self.burst_delay,timing_system.burst_delay.stepsize)
n = int(rint(waitt/Tbase)) # Sequence length period in 987-Hz cycles
ndt = int(rint(burst_waitt/Tbase)) # X-ray repetition period, in 987-Hz cycles
n_burst_delay = int(rint(burst_delay/Tbase)) # X-ray burst delay, in 987-Hz cycles
n = max(n,ndt*int(self.npulses)) # Make sure the period is long enough for npulses
delay_coarse = int(floor(delay/Tbase))
delay_value = delay - delay_coarse*Tbase
it0 = n_burst_delay + ndt - 2 # First X-ray pulse, in 987-Hz cycles
# The high-speed chopper determines the X-ray pulse timing.
xd = -timing_system.hsc.delay.offset
# If the chopper timing shift is more than 100 ns,
# assume the chopper selects a different bunch with a different timing.
# (e.g super bunch versus single bunch)
# However, if the time shift is more than 4 us, assume the tunnel
# 1-unch selection mode is used so the transmitted X-ray pulse
# arrives at nominally t=0.
if 100e-9 < abs(timing_system.hsc.delay.value) < 4e-6:
xd += timing_system.hsc.delay.value
it_laser = it0-delay_coarse + arange(0,int(self.npulses)*ndt,ndt)
it_xray = it0 + arange(0,int(self.npulses)*ndt,ndt)
t_xray = it_xray*Tbase+xd
t_laser = t_xray - delay
# Trigger X-ray millsecond shutter
pulse_length = timing_system.ms.pulse_length
if self.burst_waitt < 0.010:
# Assume the X-ray is continuously firing at 120 Hz.
t_ms_open = min(t_xray) - timing_system.ms.offset
t_ms_close = max(t_xray) - timing_system.ms.offset + pulse_length
t_ms_open = array([t_ms_open])
t_ms_close = array([t_ms_close])
else:
t_ms_open = t_xray - timing_system.ms.offset
t_ms_close = t_xray - timing_system.ms.offset + pulse_length
it_ms_open = maximum(floor(t_ms_open /Tbase),0).astype(int)
it_ms_close = maximum(ceil(t_ms_close/Tbase),0).astype(int)
it_ms_open = it_ms_open [it_ms_open<n]
it_ms_close = it_ms_close[it_ms_close<n]
ms_inc = sparse_array(n)
ms_inc[it_ms_open] += 1
ms_inc[it_ms_close] -= 1
ms_state_counts = clip(cumsum(ms_inc),0,1)
ms_state_counts = sparse_array(ms_state_counts)
# Trigger X-ray attenuator
pulse_length = timing_system.s3.pulse_length
if self.burst_waitt < 0.010:
# Assume the X-ray is continuously firing at 120 Hz.
t_xatt_open = min(t_xray) - timing_system.s3.offset
t_xatt_close = max(t_xray) - timing_system.s3.offset + pulse_length
t_xatt_open = array([t_xatt_open])
t_xatt_close = array([t_xatt_close])
else:
t_xatt_open = t_xray - timing_system.s3.offset
t_xatt_close = t_xray - timing_system.s3.offset + pulse_length
it_xatt_open = maximum(floor(t_xatt_open /Tbase),0).astype(int)
it_xatt_close = maximum(ceil(t_xatt_close/Tbase),0).astype(int)
it_xatt_open = it_xatt_open [it_xatt_open<n]
it_xatt_close = it_xatt_close[it_xatt_close<n]
xatt_inc = sparse_array(n)
xatt_inc[it_xatt_open] += 1
xatt_inc[it_xatt_close] -= 1
xatt_state_counts = clip(cumsum(xatt_inc),0,1)
xatt_state_counts = sparse_array(xatt_state_counts)
# Detector readout
# Delay: "xdet.offset" (e.g. -6 ms)
# Pulse length "xdet.pulse_length" (e.g. 2 ms)
# After the last X-ray pulse
##t_xdet_rise = max(t_xray) - timing_system.xdet.offset
# At beginning
t_xdet_rise = 0 - timing_system.xdet.offset
t_xdet_fall = t_xdet_rise + timing_system.xdet.pulse_length
t_xdet_rise = array([t_xdet_rise])
t_xdet_fall = array([t_xdet_fall])
it_xdet_rise = maximum(rint(t_xdet_rise /Tbase),0).astype(int)
it_xdet_fall = maximum(rint(t_xdet_fall/Tbase),0).astype(int)
it_xdet_rise = it_xdet_rise [it_xdet_rise<n]
it_xdet_fall = it_xdet_fall[it_xdet_fall<n]
xdet_inc = sparse_array(n)
xdet_inc[it_xdet_rise] += 1
xdet_inc[it_xdet_fall] -= 1
xdet_state_counts = clip(cumsum(xdet_inc),0,1)
xdet_state_counts = sparse_array(xdet_state_counts)
xdet_count_inc = sparse_array(n)
xdet_count_inc[it_xdet_rise] = 1
# Trigger the sample translation after the last X-ray pulse.
t_trans_rise = max(t_xray) - timing_system.trans.offset
t_trans_fall = t_trans_rise + timing_system.trans.pulse_length
t_trans_rise = array([t_trans_rise])
t_trans_fall = array([t_trans_fall])
it_trans_rise = maximum(rint(t_trans_rise /Tbase),0).astype(int)
it_trans_fall = maximum(rint(t_trans_fall/Tbase),0).astype(int)
it_trans_rise = it_trans_rise [it_trans_rise<n]
it_trans_fall = it_trans_fall[it_trans_fall<n]
trans_inc = sparse_array(n)
trans_inc[it_trans_rise] += 1
trans_inc[it_trans_fall] -= 1
trans_state_counts = clip(cumsum(trans_inc),0,1)
trans_state_counts = sparse_array(trans_state_counts)
##trans_state_counts *= int(self.trans_on)
if not self.trans_on: trans_state_counts = sparse_array(n,0)
delay_dial = timing_system.delay.dial_from_user(delay_value)
# Decompose the delay value into an X-ray delay and a laser delay.
ld = xd - delay_dial
# Picosecond laser amplifier trigger.
pst_dial = timing_system.pst.dial_from_user(ld)
pst_count = timing_system.pst.count_from_dial(pst_dial)
pst_delay_counts = sparse_array(n,pst_count)
pst_enable_counts = sparse_array(n)
pst_enable_counts[it_laser] = int(self.laser_on)
# Picosecond oscillator reference clock (Gigabaudics, 10 ps resolution)
psd1_period = 5*timing_system.bct
psd1_dial = timing_system.psd1.dial_from_user(pst_dial) % psd1_period
psd1_count = timing_system.psd1.count_from_dial(psd1_dial)
psd1_counts = sparse_array(n,psd1_count)
# Picosecond oscillator reference clock (course, 7.1 ns resolution)
pso_period = 5*timing_system.bct
pso_coarse_step = timing_system.psod3.stepsize
pso_dial = timing_system.psod3.dial_from_user(pst_dial) % pso_period
psod3_dial = floor(pso_dial/pso_coarse_step)*pso_coarse_step
psod3_count = timing_system.psod3.count_from_dial(psod3_dial)
psod3_counts = sparse_array(n,psod3_count)
# Picosecond oscillator reference clock (fine, 9 ps resolution)
psod2_dial = pso_dial % pso_coarse_step
clk_shift_count = timing_system.psod2.count_from_dial(psod2_dial)
psod2_counts = sparse_array(n,clk_shift_count)
# Laser shutter for LCLS -> ps L gate output
pulse_length = timing_system.psg.pulse_length
if self.burst_waitt < 0.010:
# Assume the laser is continuously firing at 120 Hz.
t_psg_open = min(t_laser) - timing_system.psg.offset
t_psg_close = max(t_laser) - timing_system.psg.offset + pulse_length
t_psg_open = array([t_psg_open])
t_psg_close = array([t_psg_close])
else:
t_psg_open = t_laser - timing_system.psg.offset
t_psg_close = t_laser - timing_system.psg.offset + pulse_length
it_psg_open = maximum(floor(t_psg_open /Tbase),0).astype(int)
it_psg_close = maximum(ceil(t_psg_close/Tbase),0).astype(int)
it_psg_open = it_psg_open [it_psg_open<n]
it_psg_close = it_psg_close[it_psg_close<n]
psg_inc = sparse_array(n)
psg_inc[it_psg_open] += 1
psg_inc[it_psg_close] -= 1
psg_state_counts = clip(cumsum(psg_inc),0,1)
psg_state_counts = sparse_array(psg_state_counts)
##psg_state_counts *= int(self.laser_on)
if not self.laser_on: psg_state_counts = sparse_array(n,0)
# Nanosecond laser Q-switch trigger.
nsq_dial = timing_system.nsq.dial_from_user(ld)
nsq_count = timing_system.nsq.count_from_dial(nsq_dial)
nsq_delay_counts = sparse_array(n,nsq_count)
nsq_enable_counts = sparse_array(n)
nsq_enable_counts[it_laser] = int(self.laser_on)
# Nanosecond laser flashlamp trigger.
nsf_dial = timing_system.nsf.dial_from_user(ld)
nsf_count = timing_system.nsf.count_from_dial(nsf_dial)
nsf_delay_counts = sparse_array(n,nsf_count)
nsf_period = 48 # 20 Hz operation, 10 Hz = 96 counts
it0_nsf = it_laser[0] % nsf_period
it_nsf = range(it0_nsf,n,nsf_period)
nsf_enable_counts = sparse_array(n)
nsf_enable_counts[it_nsf] = 1
# X-ray diagnostics oscilloscope
xosct_count = timing_system.xosct.count_from_value(xd)
xosct_delay_counts = sparse_array(n,xosct_count)
xosct_enable_counts = sparse_array(n)
xosct_enable_counts[it_xray] = int(self.xosct_on)
# Laser diagnostics oscilloscope
losct_count = timing_system.losct.count_from_value(ld)
losct_delay_counts = sparse_array(n,losct_count)
losct_enable_counts = sparse_array(n)
losct_enable_counts[it_laser] = 1
# Laser camera trigger
lcam_count = timing_system.lcam.count_from_value(ld)
lcam_delay_counts = sparse_array(n,lcam_count)
lcam_enable_counts = sparse_array(n)
lcam_enable_counts[it_laser] = int(self.lcam_on)
# Camera shutter to protect the camera from laser flashes.
pulse_length = timing_system.s1.pulse_length
if self.burst_waitt < 0.010:
# Assume the laser is continuously firing at 120 Hz.
t_camshut_open = min(t_laser) - timing_system.s1.offset
t_camshut_close = max(t_laser) - timing_system.s1.offset + pulse_length
t_camshut_open = array([t_camshut_open])
t_camshut_close = array([t_camshut_close])
else:
t_camshut_open = t_laser - timing_system.s1.offset
t_camshut_close = t_laser - timing_system.s1.offset + pulse_length
it_camshut_open = maximum(floor(t_camshut_open /Tbase),0).astype(int)
it_camshut_close = maximum(ceil(t_camshut_close/Tbase),0).astype(int)
it_camshut_open = it_camshut_open [it_camshut_open<n]
it_camshut_close = it_camshut_close[it_camshut_close<n]
camshut_inc = sparse_array(n)
camshut_inc[it_camshut_open] += 1
camshut_inc[it_camshut_close] -= 1
camshut_state_counts = clip(cumsum(camshut_inc),0,1)
# Only close the shutter when the laser is firing.
camshut_state_counts = sparse_array(camshut_state_counts)
##camshut_state_counts *= int(self.laser_on)
if not self.laser_on: camshut_state_counts = sparse_array(n,0)
# Indicate whether data acquisition is running.
acquiring_counts = sparse_array(n,self.acquiring)
registers,counts=[],[]
registers += [timing_system.pst.enable]; counts += [pst_enable_counts]
registers += [timing_system.pst.delay]; counts += [pst_delay_counts]
if self.psg_on: registers += [timing_system.psg.state]; counts += [psg_state_counts]
if self.s1_on: registers += [timing_system.s1.state]; counts += [camshut_state_counts]
registers += [timing_system.nsq.enable]; counts += [nsq_enable_counts]
registers += [timing_system.nsq.delay]; counts += [nsq_delay_counts]
registers += [timing_system.nsf.enable]; counts += [nsf_enable_counts]
registers += [timing_system.nsf.delay]; counts += [nsf_delay_counts]
if self.xdet_on:
registers += [timing_system.xdet.state]; counts += [xdet_state_counts]
registers += [timing_system.xdet_count]; counts += [xdet_count_inc]
registers += [timing_system.trans.state]; counts += [trans_state_counts]
registers += [timing_system.xosct.enable]; counts += [xosct_enable_counts]
registers += [timing_system.xosct.delay]; counts += [xosct_delay_counts]
if self.losct_on: registers += [timing_system.losct.enable]; counts += [losct_enable_counts]
if self.losct_on: registers += [timing_system.losct.delay]; counts += [losct_delay_counts]
registers += [timing_system.lcam.enable]; counts += [lcam_enable_counts]
registers += [timing_system.lcam.delay]; counts += [lcam_delay_counts]
if self.ms_on: registers += [timing_system.ms.state]; counts += [ms_state_counts]
if self.s3_on: registers += [timing_system.s3.state]; counts += [xatt_state_counts]
registers += [timing_system.psod3]; counts += [psod3_counts]
registers += [timing_system.psod2]; counts += [psod2_counts]
registers += [timing_system.acquiring]; counts += [acquiring_counts]
if not isnan(self.image_number):
image_number_counts = sparse_array(n,self.image_number)
registers += [timing_system.image_number]; counts += [image_number_counts]
if not isnan(self.pass_number):
pass_number_counts = sparse_array(n,self.pass_number)
registers += [timing_system.pass_number]; counts += [pass_number_counts]
image_number_inc_counts = sparse_array(n,0)
image_number_inc_counts[0] = self.image_number_inc
registers += [timing_system.image_number_inc]; counts += [image_number_inc_counts]
pass_inc_counts = sparse_array(n,0)
pass_inc_counts[0] = self.pass_number_inc
registers += [timing_system.pass_number_inc]; counts += [pass_inc_counts]
if self.ms_on:
pulses_counts = sparse_array(n,0)
pulses_inc_counts = sparse_array(n)
pulses_inc_counts[it_xray] = 1
registers += [timing_system.pulses_inc]; counts += [pulses_inc_counts]
registers += [timing_system.pulses]; counts += [pulses_counts]
# Channel configuration-based sequence generation
for i in range(0,len(timing_system.channels)):
if timing_system.channels[i].PP_enabled:
r,c = self.channel_register_counts(i)
registers += r; counts += c
return registers,counts
def channel_register_counts(self,i):
"""i: channel number (0-based)"""
from sparse_array import sparse_array
from numpy import rint,floor,array,clip,cumsum
from timing_system import timing_system,round_next
delay = self.delay
Tbase = timing_system.hsct # Period of the 987-Hz clock
waitt = round_next(self.waitt,timing_system.waitt.stepsize)
burst_waitt = round_next(self.burst_waitt,timing_system.burst_waitt.stepsize)
burst_delay = round_next(self.burst_delay,timing_system.burst_delay.stepsize)
n = int(rint(waitt/Tbase)) # Sequence length period in 987-Hz cycles
ndt = int(rint(burst_waitt/Tbase)) # X-ray repetition period, in 987-Hz cycles
n_burst_delay = int(rint(burst_delay/Tbase)) # X-ray burst delay, in 987-Hz cycles
n = max(n,ndt*int(self.npulses)) # Make sure the period is long enough for npulses
delay_coarse = int(floor(delay/Tbase))
delay_value = delay - delay_coarse*Tbase
channel = timing_system.channels[i]
if channel.special == "test":
# Test pattern generator
state_counts = array([1,0]*(n/2)+[0]*(n%2))
state_counts = sparse_array(state_counts)
else:
t0 = channel.offset
dt = channel.pulse_length
repeat = channel.repeat_period # 'pulse','burst','image'
if repeat == 'pulse': T = timing_system.burst_waitt.value
elif repeat == 'burst': T = timing_system.waitt.value
elif repeat == 'image': T = timing_system.bursts_per_image*timing_system.waitt.value
elif repeat == '1 ms': T = Tbase
elif repeat == '50 ms': T = 50*Tbase
elif repeat == '100 ms': T = 100*Tbase
t = array([t0,t0+dt])
it = clip(rint(t/Tbase),0,n-1).astype(int)
it_on,it_off = it.reshape((-1,2)).T
inc = sparse_array(n)
inc[it_on] += 1
inc[it_off] -= 1
state_counts = clip(cumsum(inc),0,1)
state_counts = sparse_array(state_counts)
counts = [state_counts]
registers = [channel.state]
##registers += [channel.delay]
return registers,counts
@property
def t_laser(self):
"""Pump (laser arrival) times in seconds"""
from timing_system import timing_system,round_next
from numpy import isnan,where,arange,rint,floor,ceil,array,cumsum
from numpy import zeros,maximum,clip,unique
from sparse_array import sparse_array
delay = self.delay
Tbase = timing_system.hsct # Period of the 987-Hz clock
waitt = round_next(self.waitt,timing_system.waitt.stepsize)
burst_waitt = round_next(self.burst_waitt,timing_system.burst_waitt.stepsize)
burst_delay = round_next(self.burst_delay,timing_system.burst_delay.stepsize)
n = int(rint(waitt/Tbase)) # Sequence length period in 987-Hz cycles
ndt = int(rint(burst_waitt/Tbase)) # X-ray repetition period, in 987-Hz cycles
n_burst_delay = int(rint(burst_delay/Tbase)) # X-ray burst delay, in 987-Hz cycles
n = max(n,ndt*int(self.npulses)) # Make sure the period is long enough for npulses
delay_coarse = int(floor(delay/Tbase))
delay_value = delay - delay_coarse*Tbase
it0 = n_burst_delay + ndt - 2 # First X-ray pulse, in 987-Hz cycles
# The high-speed chopper determines the X-ray pulse timing.
xd = -timing_system.hsc.delay.offset
# If the chopper timing shift is more than 100 ns,
# assume the chopper selects a different bunch with a different timing.
# (e.g super bunch versus single bunch)
# However, if the time shift is more than 4 us, assume the tunnel
# 1-unch selection mode is used so the transmitted X-ray pulse
# arrives at nominally t=0.
if 100e-9 < abs(timing_system.hsc.delay.value) < 4e-6:
xd += timing_system.hsc.delay.value
it_laser = it0-delay_coarse + arange(0,int(self.npulses)*ndt,ndt)
it_xray = it0 + arange(0,int(self.npulses)*ndt,ndt)
t_xray = it_xray*Tbase+xd
t_laser = t_xray - delay
return t_laser
@property
def t_xray(self):
"""Probe (X-ray arrival) times in seconds"""
from timing_system import timing_system,round_next
from numpy import isnan,where,arange,rint,floor,ceil,array,cumsum
from numpy import zeros,maximum,clip,unique
from sparse_array import sparse_array
delay = self.delay
Tbase = timing_system.hsct # Period of the 987-Hz clock
waitt = round_next(self.waitt,timing_system.waitt.stepsize)
burst_waitt = round_next(self.burst_waitt,timing_system.burst_waitt.stepsize)
burst_delay = round_next(self.burst_delay,timing_system.burst_delay.stepsize)
n = int(rint(waitt/Tbase)) # Sequence length period in 987-Hz cycles
ndt = int(rint(burst_waitt/Tbase)) # X-ray repetition period, in 987-Hz cycles
n_burst_delay = int(rint(burst_delay/Tbase)) # X-ray burst delay, in 987-Hz cycles
n = max(n,ndt*int(self.npulses)) # Make sure the period is long enough for npulses
delay_coarse = int(floor(delay/Tbase))
delay_value = delay - delay_coarse*Tbase
it0 = n_burst_delay + ndt - 2 # First X-ray pulse, in 987-Hz cycles
# The high-speed chopper determines the X-ray pulse timing.
xd = -timing_system.hsc.delay.offset
# If the chopper timing shift is more than 100 ns,
# assume the chopper selects a different bunch with a different timing.
# (e.g super bunch versus single bunch)
# However, if the time shift is more than 4 us, assume the tunnel
# 1-unch selection mode is used so the transmitted X-ray pulse
# arrives at nominally t=0.
if 100e-9 < abs(timing_system.hsc.delay.value) < 4e-6:
xd += timing_system.hsc.delay.value
it_laser = it0-delay_coarse + arange(0,int(self.npulses)*ndt,ndt)
it_xray = it0 + arange(0,int(self.npulses)*ndt,ndt)
t_xray = it_xray*Tbase+xd
t_laser = t_xray - delay
return t_xray
@property
def data(self):
"""Binary sequence data"""
descriptor = self.descriptor
if timing_sequencer.cache_enabled:
packet = timing_sequencer.cache_get(descriptor)
if not timing_sequencer.cache_enabled or len(packet) == 0:
registers,counts = self.register_counts
packet = sequencer_packet(registers,counts,descriptor)
if timing_sequencer.cache_enabled:
timing_sequencer.cache_set(descriptor,packet)
return packet
def __repr__(self):
p = self.parameters
return "Sequence("+",".join(["%s=%r" % (key,p[key]) for key in p])+")"
sequence = Sequence
class TimingSequencer(object):
from persistent_property import persistent_property
from cached_property import cached_property
count = 0
parameters = [
"delay",
"laser_on",
"psg.on",
"waitt",
"npulses",
"burst_waitt",
"burst_delay",
"xosct.on",
"losct.on",
"lcam.on",
"s1.on",
"ms.on",
"xdet.on",
"trans.on",
"trans.bit_code",
"s3.on",
"image_number",
"pass_number",
"image_number_inc",
"pass_number_inc",
"acquiring",
# Calibration constants and parameters
"hlc_div",
"hsc.delay",
"hsc.delay.offset",
"ms.offset",
"ms.pulse_length",
"psg.offset",
"nsf.offset",
"nsq.offset",
"xdet.offset",
"trans.offset",
"trans.pulse_length",
]
def get_default(self,name):
"""Get default value for parameter
name: 'delay','laser_on'... """
from timing_system import timing_system
from numpy import nan
if name == "acquiring": value = False
elif name == "image_number": value = nan
else:
alt_name = name.replace("_on",".on")
if alt_name in self.parameters: name = alt_name
try: value = eval("timing_system.%s_on" % name)
except AttributeError:
try: value = eval("timing_system.%s.value" % name)
except AttributeError: value = eval("timing_system.%s" % name)
return value
def set_default(self,name,value,update=True):
"""Set default value for parameter
name: 'delay','laser_on'... """
alt_name = name.replace("_on",".on")
if alt_name in self.parameters: name = alt_name
from timing_system import timing_system
try:
eval("timing_system.%s_on" % name)
exec("timing_system.%s_on = %r" % (name,value))
except AttributeError:
try:
eval("timing_system.%s.value" % name)
exec("timing_system.%s.value = %r" % (name,value))
except AttributeError:
exec("timing_system.%s = %r" % (name,value))
if update: self.set_default_sequences()
def __getattr__(self,name):
"""A property"""
# Called when 'x.name' is evaluated.
# It is only invoked if the attribute was not found the usual ways.
from timing_system import timing_system
alt_name = name.replace("_",".",1) # xdet_trig_count -> xdet.trig_count
if name in self.parameters: return self.current_value(name)
elif alt_name in self.parameters: return self.current_value(alt_name)
elif hasattr(timing_system,name):
attr = getattr(timing_system,name)
if hasattr(attr,"value"): attr = attr.value
return attr
elif self.hasattr(timing_system,alt_name):
attr = eval("timing_system.%s" % alt_name)
if hasattr(attr,"value"): attr = attr.value
return attr
else: return object.__getattribute__(self,name)
@staticmethod
def hasattr(object,name):
"""name: e.g. 'hsc.delay'"""
try: eval("object.%s" % name); return True
except AttributeError: return False
def __setattr__(self,name,value):
"""Set a property"""
# Called when 'x.name = y' is evaluated.
from timing_system import timing_system
alt_name = name.replace("_",".") # hsc_delay > hsc.delay
if name.startswith("__"): object.__setattr__(self,name,value)
elif name in self.parameters: self.set_default(name,value)
elif alt_name in self.parameters: self.set_default(alt_name,value)
elif hasattr(timing_system,name):
attr = getattr(timing_system,name)
if hasattr(attr,"value"): attr.value = value
else: setattr(timing_system,name,value)
elif self.hasattr(timing_system,alt_name):
attr = eval("timing_system.%s" % alt_name)
if hasattr(attr,"value"): attr.value = value
else: exec("timing_system.%s = %r" % (alt_name,value))
else: object.__setattr__(self,name,value)
def get_ip_address(self):
"""Timing system's network address"""
from timing_system import timing_system
return timing_system.ip_address
def set_ip_address(self,value):
from timing_system import timing_system
timing_system.ip_address = value
ip_address = property(get_ip_address,set_ip_address)
sequence_dir = "/tmp/sequencer_fs"
queue_name = "queue"
queue_filename = sequence_dir+"/"+queue_name
queue_names = "queue1","queue2","queue"
def get_queue(self):
"""Acquisition queue's packet IDs as list of strings"""
return self.queue_content(self.queue_name)
def set_queue(self,IDs):
self.set_queue_content(self.queue_name,IDs)
queue = property(get_queue,set_queue)
def get_current_queue(self):
"""Packet IDs as list of strings"""
return self.queue_content(self.current_queue_name)
def set_current_queue(self,IDs):
self.set_queue_content(self.current_queue_name,IDs)
current_queue = property(get_current_queue,set_current_queue)
def queue_content(self,queue_name):
"""Packet IDs as list of strings
queue_name: "queue" (default) for data acquistion;
"queue1" or "queue2" for idle mode
"""
queue_filename = self.sequence_dir+"/"+queue_name
file_content = self.file(queue_filename)
IDs = file_content.strip("\n").split("\n") if len(file_content) > 0 else []
return IDs
def set_queue_content(self,queue_name,IDs):
"""Packet IDs as list of strings
queue_name: "queue" (default) for data acquistion;
"queue1" or "queue2" for idle mode
IDs: Packet IDs as list of strings
"""
queue_filename = self.sequence_dir+"/"+queue_name
file_content = "\n".join(IDs)+("\n" if len(IDs)>0 else "")
self.put_file(queue_filename,file_content)
# First-time initialization
filenames,file_contents = [],[]
uploaded_files = self.uploaded_files
filename = queue_filename+"_sequence_count"
file_content = "%-20d" % 0
if not filename in uploaded_files: filenames += [filename]; file_contents += [file_content]
filename = queue_filename+"_repeat_count"
file_content = "%-20d" % 0
if not filename in uploaded_files: filenames += [filename]; file_contents += [file_content]
filename = queue_filename+"_max_repeat_count"
file_content = "%-20d" % 1
if file_content != self.file(filename): filenames += [filename]; file_contents += [file_content]
self.put_files(filenames,file_contents)
def get_idle(self):
"""Is the idle queue being executed?"""
return self.current_queue_name != self.queue_name
def set_idle(self,value):
if value: self.next_queue_name = self.default_queue_name
else: self.next_queue_name = self.queue_name
idle = property(get_idle,set_idle)
def get_queue_active(self):
"""Is the data acquistion queue actively beeing executed?"""
return self.current_queue_name == self.queue_name
def set_queue_active(self,value):
if value: self.next_queue_name = self.queue_name
else: self.next_queue_name = self.default_queue_name
queue_active = property(get_queue_active,set_queue_active)
def _get_queue_length(self):
"""How many sequences are left in the acquisition queue?"""
return len(self.queue)
def set_queue_length(self,value):
if value == 0: self.queue = []
queue_length = property(_get_queue_length,set_queue_length)
def get_current_queue_length(self):
"""How many sequences are left in the idle or acquisition queue?"""
return len(self.current_queue)
def set_current_queue_length(self,value):
if value == 0: self.current_queue = []
current_queue_length = property(get_current_queue_length,
set_current_queue_length)
def get_queue_length(self,queue_name):
"""How many sequences are left in the queue?"""
return len(self.queue_content(queue_name))
@property
def generator(self):
"""Sequence generator Python module name"""
return self.current_sequence_property("generator","")
@property
def generator_version(self):
"""Sequence generator Python module version number"""
return self.current_sequence_property("generator_version","")
def current_sequence_property(self,name,default_value=None,dtype=None):
"""
name: e.g. 'mode','delay','laseron','count'
dtype: data type
"""
descriptor = self.descriptor
return self.property_value(self.descriptor,name,default_value,dtype)
def current_value(self,name):
"""Get the value of a parameter from the currently executing sequence
name: e.g. 'mode','delay','laseron','count'
dtype: data type
"""
if name in ["pass_number","image_number"]:
from timing_system import timing_system
value = getattr(timing_system,name)
if hasattr(value,"value"): value = value.value
else: value = self.property_value(self.descriptor,name)
return value
def property_value(self,descriptor,name,default_value=None,dtype=None):
"""Extract a value from a sequence descriptor
descriptor: comma separated list
e.g. 'mode=Stepping-48,delay=0.0316,laseron=True,count=6'
name: e.g. 'mode','delay','laseron','count'
"""
if default_value is None and dtype is not None: default_value = dtype()
def default():
if default_value is None: return self.get_default(name)
else: return default_value
value = None
for record in descriptor.split(","):
parts = record.split("=")
key = parts[0]
if key != name: continue
if len(parts) < 2: value = default()
else:
value = parts[1]
try:
value = eval(value)
if dtype is not None: value = dtype(value)
except: value = default()
if value is None: value = default()
return value
def get_running(self):
"""Is the command currently running?"""
running = self.current_sequence_length > 0
running = running and self.interrupt_enabled
running = running and self.interrupt_handler_enabled
return running
def set_running(self,value,update=None):
if bool(value) == True:
if update is None: self.update()
else: update()
self.interrupt_handler_enabled = 1
if bool(value) == False:
self.default_queue_name = ""
self.next_queue_name = ""
running = property(get_running,set_running)
def set_queue_sequences(self,
sequences,
queue_name=None,
default_queue_name=None,
next_queue_name=None,
):
"""Queue a timing sequence for execution.
sequences: list of seqence objects
queue_name: "queue" (default) for data acquistion;
"queue1" or "queue2" for idle mode
default_queue_name: make this queue the new default when ready
next_queue_name: switch to this queue when ready
"""
if queue_name is None: queue_name = self.queue_name
self.queue_sequences[queue_name] = sequences
if default_queue_name is not None:
self.default_queue_name_requested = default_queue_name
if next_queue_name is not None:
self.next_queue_name_requested = next_queue_name
self.updating_queues = True
queue_sequences = {}
default_queue_name_requested = None
next_queue_name_requested = None
def update_queues(self):
queue_sequences = dict(self.queue_sequences)
for queue_name in queue_sequences:
if self.updating_queues_cancelled: break
sequences = queue_sequences[queue_name]
self.set_queue_content(queue_name,[seq.id for seq in sequences])
filenames = []
file_contents = []
uploaded_files = self.uploaded_files
for i,sequence in enumerate(sequences):
if self.updating_queues_cancelled: break
filename = self.sequence_dir+"/"+sequence.id
if not filename in filenames:
if not filename in uploaded_files:
if sequence.is_cached:
filenames += [filename]
file_contents += [sequence.data]
if self.updating_queues_cancelled: break
self.put_files(filenames,file_contents)
for filename in filenames:
if filename not in uploaded_files: uploaded_files += [filename]
for i,sequence in enumerate(sequences):
if self.updating_queues_cancelled: break
filename = self.sequence_dir+"/"+sequence.id
if filename not in uploaded_files:
if not sequence.is_cached:
info("Generating packets: %d/%d" % (i+1,len(sequences)))
file_content = sequence.data
self.put_file(filename,file_content)
uploaded_files += [filename]
# Switch queue when ready
if self.default_queue_name_requested is not None:
self.default_queue_name = self.default_queue_name_requested
self.default_queue_name_requested = None
if self.next_queue_name_requested is not None:
self.next_queue_name = self.next_queue_name_requested
self.next_queue_name_requested = None
from thread_property_2 import thread_property
updating_queues = thread_property(update_queues)
updating_queues_cancelled = False
def wait_for_queue_ready(self,queue_name):
from time import sleep
if not self.get_queue_ready(queue_name):
info("%r not ready" % queue_name)
while not self.get_queue_ready(queue_name): sleep(0.5)
info("%r ready" % queue_name)
@property
def queue_ready(self):
return self.get_queue_ready(self.queue_name)
@property
def queue_files_uploaded(self):
return self.get_queue_files_uploaded(self.queue_name)
def get_queue_files_uploaded(self,queue_name):
uploaded_count = self.get_queue_uploaded_file_count(queue_name)
count = self.get_queue_file_count(queue_name)
uploaded = uploaded_count >= count
return uploaded
def get_queue_ready(self,queue_name):
"""Are there a sufficient number of files uploaded to start executing
this queue?"""
uploaded_count = self.get_queue_uploaded_file_count(queue_name)
count = self.get_queue_file_count(queue_name)
ready = uploaded_count >= count or uploaded_count > 2
return ready
def get_queue_file_count(self,queue_name):
IDs = list(set(self.queue_content(queue_name)))
count = len(IDs)
return count
def get_queue_uploaded_file_count(self,queue_name):
IDs = list(set(self.queue_content(queue_name)))
filenames = [self.sequence_dir+"/"+ID for ID in IDs]
uploaded_files = self.uploaded_files
count = sum([filename in uploaded_files for filename in filenames])
return count
def get_queue_files_uploaded(self,queue_name):
"""Are there a sufficient number of files uploaded to start executing
this queue?"""
IDs = self.queue_content(queue_name)
filenames = [self.sequence_dir+"/"+ID for ID in IDs]
uploaded_files = self.uploaded_files
uploaded = all([filename in uploaded_files for filename in filenames])
return uploaded
def set_default_sequences(self,sequences=None):
"""Define what is executed when the sequencer queue is empty
sequence: sequence object
"""
if sequences is None: sequences = [Sequence()]
queue_name = "queue1" if self.current_queue_name != "queue1" else "queue2"
self.set_queue_sequences(
sequences,
queue_name,
default_queue_name=queue_name,
next_queue_name=queue_name,
)
def clear_default_packet(self):
"""This makes sure not sequence is executing when the sequencer queue
is empty."""
self.default_sequence_active = 0
def get_interrupt_enabled(self):
"""Is the interrupt generator enabled?"""
from timing_system import timing_system
return timing_system.inton_sync.count == 1
def set_interrupt_enabled(self,value):
from timing_system import timing_system
if bool(value) == False:
timing_system.inton_sync.count = 0
timing_system.inton.count = 0
else: timing_system.inton.count = 1
interrupt_enabled = property(get_interrupt_enabled,set_interrupt_enabled)
enabled = interrupt_enabled
def get_trigger_armed(self):
"""Is the system waiting for an external trigger?"""
from timing_system import timing_system
armed = timing_system.inton.count == 1 \
and timing_system.inton_sync.count == 0
return armed
def set_trigger_armed(self,value):
"""Is the system waiting for an extrnal trigger?"""
from timing_system import timing_system
if bool(value) == True:
timing_system.inton_sync.count = 0
timing_system.inton.count = 1
if bool(value) == False:
timing_system.inton.count = 0
trigger_armed = property(get_trigger_armed,set_trigger_armed)
def timing_system_property(name):
"""Count value of a timing system register"""
def get(self):
from timing_system import timing_system
return getattr(timing_system,name).count
def set(self,value):
from timing_system import timing_system
getattr(timing_system,name).count = value
return property(get,set)
# 1-kHz clock cycles since restart of timing_system
trigger_count = tclk_count = timing_system_property("tclk_count")
sequence_count = intcount = timing_system_property("intcount")
def driver_property(name,type=None,default_value=None,
terminator="\n"):
"""sysfs-style kernel variable of sequencer driver"""
driver_dir = "/proc/sys/dev/sequencer"
def get(self):
value = self.file(driver_dir+"/"+name)
if type == str:
if terminator:
if value.endswith(terminator):
value = value[0:-len(terminator)]
elif type:
try: value = type(value)
except: value = default_value if default_value else type()
return value
def set(self,value):
if type == str:
if terminator:
if not value.endswith(terminator): value += terminator
elif type == bool: value = repr(int(value))
elif type: value = repr(value)
self.put_file(driver_dir+"/"+name,value)
return property(get,set)
def file_property(name,type=None,default_value=None,directory="",
terminator=None):
"""sysfs-style kernel variable of sequencer driver"""
def get(self):
value = self.file(directory+"/"+name)
if type == str:
if terminator:
if value.endswith(terminator):
value = value[0:-len(terminator)]
elif type:
try: value = type(value)
except: value = default_value if default_value else type()
return value
def set(self,value):
if type == str:
if terminator:
if not value.endswith(terminator): value += terminator
elif type == bool: value = repr(int(value))
elif type: value = repr(value)
self.put_file(directory+"/"+name,value)
return property(get,set)
sequence_active = driver_property("sequence_active",int,nan)
default_sequence_active = driver_property("default_sequence_active",int,nan)
queue_sequence_count = driver_property("queue_sequence_count",int,nan)
current_queue_name = driver_property("queue_name",str,"")
next_queue_name = driver_property("next_queue_name",str,"")
next_queue_sequence_count = driver_property("next_queue_sequence_count",int,nan)
default_queue_name = driver_property("default_queue_name",str,"")
current_sequence_length = driver_property("current_sequence_length",int,nan)
sequence_queue_interrupt_count_max = \
driver_property("sequence_queue_interrupt_count_max",int,nan)
sequence_queue_interrupt_count = \
driver_property("sequence_queue_interrupt_count",int,nan)
sequence_queue_packets = driver_property("sequence_queue_packets",int,nan)
sequence_queue_bytes = driver_property("sequence_queue_bytes",int,nan)
buffer_size = driver_property("buffer_size",int,nan)
buffer_length = driver_property("buffer_length",int,nan)
interrupt_handler_enabled = driver_property("interrupt_handler_enabled",int,nan)
reset = driver_property("reset",int,nan)
version = driver_property("version",str)
debug_level = driver_property("debug_level",int,nan)
__descriptor__ = cached_property(driver_property("descriptor",str),0.9)
@property
def descriptor(self):
"""Parameters of currently playing sequence as string"""
from timing_system import timing_system
value = timing_system.get_property("sequencer.descriptor")
return value
def get_queue_sequence_count(self):
return self.queue_property(self.queue_name,"sequence_count")
def set_queue_sequence_count(self,value):
self.set_queue_property(self.queue_name,"sequence_count",value)
queue_sequence_count = property(get_queue_sequence_count,
set_queue_sequence_count)
def get_current_queue_sequence_count(self):
return self.queue_property(self.current_queue_name,"sequence_count")
def set_current_queue_sequence_count(self,value):
self.set_queue_property(self.current_queue_name,"sequence_count",value)
current_queue_sequence_count = property(get_current_queue_sequence_count,
set_current_queue_sequence_count)
def get_queue_repeat_count(self):
return self.queue_property(self.queue_name,"repeat_count")
def set_queue_repeat_count(self,value):
self.set_queue_property(self.queue_name,"repeat_count",value)
queue_repeat_count = property(get_queue_repeat_count,
set_queue_repeat_count)
def get_current_queue_repeat_count(self):
return self.queue_property(self.current_queue_name,"repeat_count")
def set_current_queue_repeat_count(self,value):
self.set_queue_property(self.current_queue_name,"repeat_count",value)
current_queue_repeat_count = property(get_current_queue_repeat_count,
set_current_queue_repeat_count)
def get_queue_max_repeat_count(self):
return self.queue_property(self.queue_name,"max_repeat_count")
def set_queue_max_repeat_count(self,value):
self.set_queue_property(self.queue_name,"max_repeat_count",value)
queue_max_repeat_count = property(get_queue_max_repeat_count,
set_queue_max_repeat_count)
def get_current_queue_max_repeat_count(self):
return self.queue_property(self.current_queue_name,"max_repeat_count")
def set_current_queue_max_repeat_count(self,value):
self.set_queue_property(self.current_queue_name,"max_repeat_count",value)
current_queue_max_repeat_count = property(
get_current_queue_max_repeat_count,
set_current_queue_max_repeat_count)
def queue_property(self,queue_filename,name):
"""name: "repeat_count" or "max_repeat_count" """
if not queue_filename.startswith("/"):
queue_filename = self.sequence_dir+"/"+queue_filename
count = self.file(queue_filename+"_"+name)
try: count = int(count)
except: count = nan
return count
def set_queue_property(self,queue_filename,name,value):
"""name: "repeat_count" or "max_repeat_count" """
if not queue_filename.startswith("/"):
queue_filename = self.sequence_dir+"/"+queue_filename
string = "%r" % value if not isnan(value) else ""
string = string.ljust(20) # leave room for growth
if string != "": string += "\n"
self.put_file(queue_filename+"_"+name,string)
@property
def uploaded_files(self):
"""Full pathnames of files on the timing system's file system"""
return self.files(self.sequence_dir+"/*")
def files(self,pattern):
"""List of filenames on the timing system's file system
pattern: e.g. '/tmp/sequence-*.bin' """
# Work-around for buffer overflow in wildcard expansion
# on server side (if directory contains 5520 entries).
if pattern.endswith("/*"):
directory = pattern[:-2]
from file_server import wget
filelist = wget("//"+self.ip_address+directory)
files = filelist.strip("\n").split("\n") if len(filelist)>0 else []
files = [directory+"/"+f for f in files]
else:
from file_server import wdir
filelist = wdir("//"+self.ip_address+pattern)
files = filelist.strip("\n").split("\n") if len(filelist)>0 else []
return files
def file(self,filename):
"""The content of a file on the timing system's file system
filename: e.g. '/proc/sys/dev/seqeuncer/interrupt_enabled' """
from file_server import wget
if filename:
content = wget("//"+self.ip_address+filename)
##debug("timing_sequencer: %s: %.20r..." % (filename,content))
else: content = ""
return content
def remove(self,filename):
"""Delete a file from the timing system's file system
filename: e.g. '/tmp/sequence/cache' """
from file_server import wdel
wdel(self.ip_address+filename)
def put_file(self,filename,content):
"""Put file to the file system if the timing system"""
report_if_not_valid_pathname(filename)
from file_server import wput,wdel
if len(content) > 0: wput(content,self.ip_address+filename)
else: wdel(self.ip_address+filename)
def put_files(self,filenames,contents):
"""Group transfer of serveral files to the file system if the timing
system"""
if len(filenames) > 0:
s = "Transferring %d files:\n" % len(filenames)
for i in range(0,min(len(filenames),2)):
s += " %s: %d bytes\n" % (filenames[i],len(contents[i]))
##debug(s)
from time import time
self.last_filenames = filenames
n = sum([len(content) for content in contents])
t0 = time()
debug("Transferring %d bytes of data to timing system" % n)
for (filename,content) in zip(filenames,contents):
self.put_file(filename,content)
dt = time()-t0
debug("Transferred %d bytes in %.3f s (%.0f bytes/s)" % (n,dt,float(n)/dt))
def telnet(self,command):
"""Execute a system command on the timing system's CPU and return
the result"""
from telnet import telnet
return telnet(self.ip_address,command)
cache_enabled = persistent_property("cache_data",True)
def cache_set(self,key,data):
"""Temporarily store binary data for fast restreival
key: string"""
from os.path import exists,dirname;
from os import makedirs
for filename in self.cache_filenames(key):
if not exists(dirname(filename)): makedirs(dirname(filename))
try: file(filename,"wb").write(data); break
except: pass
def cache_get(self,key):
"""Retreive temporarily stored binary data
key: string"""
data = ""
for filename in self.cache_filenames(key):
try: data = file(filename,"rb").read(); break
except: pass
return data
def cache_clear(self):
"""Erase temporarily stored binary data on the locate drive"""
from shutil import rmtree
try: rmtree(self.cache_dir)
except: pass
def get_cache_size(self):
"""How many cached data objects are there?"""
from os import listdir
try: return len(listdir(self.cache_dir))
except: return 0
def set_cache_size(self,value):
if value == 0: self.cache_clear()
cache_size = property(get_cache_size,set_cache_size)
def cache_filenames(self,key):
"""Where to store the data associated with key"""
# If the key exceeds 254 characters, it needs to be shortened
# by hashing, otherwise the file system would not allow it
# to be used as a filename.
filenames = []
filename = self.cache_dir+"/"+key
if valid_pathname(filename): filenames += [filename]
filenames += [self.cache_dir+"/"+hash(key)]
return filenames
@property
def cache_dir(self):
"""Where to store temparary files"""
from tempfile import gettempdir
basedir = gettempdir()
dir = basedir+"/sequencer/cache"
return dir
def get_remote_cache_size(self):
"""How many sequences are stored in the memory of the FPGA timing
system?"""
return len(self.remote_sequence_files)
def set_remote_cache_size(self,value):
if value == 0:
for file in self.remote_sequence_files: self.remove(file)
remote_cache_size = property(get_remote_cache_size,set_remote_cache_size)
@property
def remote_sequence_files(self):
"""Which sequences are stored in the memory of the FPGA timing system?"""
files = self.files(self.sequence_dir+"/*")
## /tmp/sequencer_fs/f0e55f6b071d6b1f0cc341b2cce2451e
from re import match,compile
pattern = compile("^"+self.sequence_dir+"/"+"[0-9a-f]{32}$")
files = [file for file in files if match(pattern,file)]
return files
def update(self):
"""Execute sequence using the current default parameters"""
self.set_default_sequences()
self.interrupt_enabled = True
def acquire(self,delays=None,laser_on=None,
waitt=None,npulses=None,burst_waitt=None,burst_delay=None,
ms_on=None,s3_on=None,
xdet_on=None,xosct_on=None,losct_on=None,trans_on=None,lcam_on=None,
image_numbers=None,
xatt_on=None):
"""For data acquisition
delays: list of laser pump to X-ray probe time in seconds
laser_on: Trigger the ps laser? True or False
nst_on: Trigger the ns laser? True or False
image_numbers: series number
ms_on: Open X-ray millisecond shutter? True or False
xatt_on: Attenuate X-ray beam? True or False
"""
debug("Timing Sequencer: Building sequence list...")
from timing_system import timing_system
timing_system.clear_cache(); timing_system.cache += 1
var_lists = delays,laser_on,waitt,npulses,burst_waitt,burst_delay,\
image_numbers,ms_on,xatt_on,s3_on,trans_on
if to_tuple(var_lists) not in self.sequence_cache:
from numpy import nan,isnan,where
N = 0
for var_list in var_lists:
if var_list is not None: N = len(var_list)
if xatt_on is not None: s3_on = xatt_on
if delays is None: delays = [nan]*N
if laser_on is None: laser_on = [nan]*N
if waitt is None: waitt = [nan]*N
if npulses is None: npulses = [nan]*N
if burst_waitt is None: burst_waitt = [nan]*N
if burst_delay is None: burst_delay = [nan]*N
if image_numbers is None: image_numbers = [nan]*N
if ms_on is None: ms_on = [1]*N
if s3_on is None: s3_on = [0]*N
if xdet_on is None: xdet_on = [1]*N
if xosct_on is None: xosct_on = [1]*N
if losct_on is None: losct_on = [1]*N
if trans_on is None: trans_on = [1]*N
if lcam_on is None: lcam_on = laser_on
# Optimize image numbering
image_number_inc = [i==0 or image_numbers[i] == image_numbers[i-1]+1
for i in range(0,N)]
image_numbers = where(image_number_inc,nan,image_numbers)
sequences = []
for i in range(0,N):
sequences += [Sequence(
delay=delays[i],
laser_on=laser_on[i],
waitt=waitt[i],
npulses=npulses[i],
burst_waitt=burst_waitt[i],
burst_delay=burst_delay[i],
ms_on=ms_on[i],
s3_on=s3_on[i],
xdet_on=xdet_on[i],
xosct_on=xosct_on[i],
losct_on=losct_on[i],
lcam_on=lcam_on[i],
trans_on=trans_on[i],
pass_number=1,
image_number=image_numbers[i],
image_number_inc=image_number_inc[i],
acquiring=1,
)]
self.sequence_cache[to_tuple(var_lists)] = sequences
sequences = self.sequence_cache[to_tuple(var_lists)]
self.set_queue_sequences(sequences)
timing_system.cache -= 1
def acquisition_start(self):
"""To be called after 'acquire'"""
self.queue_active = False
self.wait_for_queue_ready()
self.image_number = 0
self.pass_number = 0
self.pulses = 0
self.queue_active = True
def acquisition_cancel(self):
"""End current data collection"""
self.acquiring = False
sequence_cache = {}
def __repr__(self): return "timing_sequencer"
timing_sequencer = TimingSequencer()
def to_tuple(X):
return tuple([tuple(x) if x is not None else None for x in X])
def sequencer_packet(registers,counts,descriptor=None):
"""Binary data packet for the timing sequencer (for one image for example)
registers: list of timing register objects
counts: list of interger arrays, one array for each register
"""
# Find the times when register counts change.
N = max([len(c) for c in counts])
from timing_system import timing_system
period = timing_system.hlc_div # 247 Hz: 4, 82.3 Hz: 12
packets = {}
def append(packets,key,data):
packets[key] = packets.get(key,"")+data
from sparse_array import starts
for ireg in range(0,len(registers)):
register = registers[ireg]
name = register.name
# Change registers
if not name.endswith("_count"): # ordinary register
for it in starts(counts[ireg]):
count = counts[ireg][it]
packet = write_packet(register,count)
append(packets,(it,ireg),packet)
if name.endswith("_count"): # count register
for it in starts(counts[ireg]):
count = counts[ireg][it]
packet = increment_packet(register,count)
append(packets,(it,ireg),packet)
# Generate reports
if name == timing_system.xdet.state.name:
for it in starts(counts[ireg]):
count = counts[ireg][it]
packet = report_packet(register)
append(packets,(it,ireg),packet)
if name.endswith("_count"):
for it in starts(counts[ireg]):
count = counts[ireg][it]
if count != 0:
packet = report_packet(register)
append(packets,(it,ireg),packet)
if name.endswith("_acq"):
for it in starts(counts[ireg]):
count = counts[ireg][it]
packet = report_packet(register)
append(packets,(it,ireg),packet)
if name == "image_number":
for it in starts(counts[ireg]):
count = counts[ireg][it]
packet = report_packet(register)
append(packets,(it,ireg),packet)
if name == "image_number_inc":
for it in starts(counts[ireg]):
count = counts[ireg][it]
if count != 0:
packet = report_packet(timing_system.image_number)
append(packets,(it,ireg),packet)
if name == "pass_number":
for it in starts(counts[ireg]):
count = counts[ireg][it]
packet = report_packet(register)
append(packets,(it,ireg),packet)
if name == "pass_number_inc":
for it in starts(counts[ireg]):
count = counts[ireg][it]
if count != 0:
packet = report_packet(timing_system.pass_number)
append(packets,(it,ireg),packet)
if name == "acquiring":
for it in starts(counts[ireg]):
count = counts[ireg][it]
packet = report_packet(register)
append(packets,(it,ireg),packet)
# Assemble packets in correct sequence order
interrupt_data = [""]*N
if N>0:
interrupt_data[0] += interrupt_count_packet(N)
if descriptor: interrupt_data[0] += descriptor_packet(descriptor)
for it in range(0,N):
for ireg in range(0,len(registers)):
if (it,ireg) in packets: interrupt_data[it] += packets[it,ireg]
interrupt_count = (it+1) % period
interrupt_data[it] += interrupt_packet(interrupt_count,period)
data = ""
data += index_packets(interrupt_data)
for it in range(0,N): data += interrupt_data[it]
return data
def packet(type=0,payload=""):
"""Timing sequencer instruction
Return value: binary data
"""
if isinstance(type,str): type = type_codes[type]
from struct import pack
fmt = ">BBH"
version = 1
header_size = len(pack(fmt,type,version,0))
length = header_size+len(payload)
data = pack(fmt,type,version,length)+payload
return data
def interrupt_packet(interrupt_count,period):
"""Timing sequencer instruction to wait for an interrupt
Format: type (8bits),version (8bits),length (16bits),
interrupt count (8bits),period (8bits)
Return value: binary data as string, length: 6 bytes
"""
from struct import pack
data = packet("interrupt",pack(">BB",interrupt_count,period))
return data
def write_packet(register,count):
"""Timing sequencer instruction to write a register
Format: type (8bits),version (8bits),length (16bits),
address (32bits),bitmask (32bits),value (32bits), total 16 bytes
register: e.g. pson
count: integer number
Return value: binary data as string
"""
from struct import pack
count_bitmask = ((1 << register.bits) - 1)
converted_count = toint(count) & count_bitmask
if converted_count != count:
warn("register %r, mask 0x%X: converting count %r to %r" %
(register,count_bitmask,count,converted_count))
count = converted_count
bitmask = count_bitmask << register.bit_offset
address = register.address
bit_count = count << register.bit_offset
data = packet("write",pack(">III",address,bitmask,bit_count))
return data
def increment_packet(register,count):
"""Timing sequencer instruction to write a register
Format: type (8bits),version (8bits),length (16bits),
address (32bits),bitmask (32bits),value (32bits), total 16 bytes
register: e.g. pson
count: integer number
Return value: binary data as string
"""
if count != 0:
##debug("timing_seqence: increment_packet(%r,%r)" % (register,count))
from struct import pack
count_bitmask = ((1 << register.bits) - 1)
if count != toint(count) & count_bitmask:
warn("write_packet(%r,%r): converting count to %r" %
(register,count,toint(count) & count_bitmask))
count = toint(count) & count_bitmask
bitmask = count_bitmask << register.bit_offset
address = register.address
bit_count = count << register.bit_offset
data = packet("increment",pack(">III",address,bitmask,bit_count))
else: data = ""
return data
def descriptor_packet(descriptor):
"""Timing sequencer instruction
descriptor: Parameter list as string
Format: type (8bits),version (8bits),length (16bits),
string(variable length)
Return value: binary data as string
"""
data = packet("descriptor",descriptor)
return data
def output_packet(message):
"""Timing sequencer instruction
message: string
Format: type (8bits),version (8bits),length (16bits),
string(variable length)
Return value: binary data as string
"""
data = packet("output",message)
return data
def sequence_length_packet(sequence_length):
"""How long is the sequence of instructions following in bytes?
Timing sequencer instruction
sequence_length: interger, number of bytes
Format: type (8bits),version (8bits),length (16bits),
packet_length(32 bits)
Return value: binary data as string, length: 8 bytes
"""
from struct import pack
data = packet("sequence length",pack(">I",sequence_length))
return data
def interrupt_count_packet(interrupt_count):
"""How long will the sequence of instructions following take to execute?
Timing sequencer instruction
packet_length: interger, number of bytes
Format: type (8bits),version (8bits),length (16bits),
packet_length(32 bits)
Return value: binary data as string, length: 8 bytes
"""
from struct import pack
data = packet("interrupt count",pack(">I",interrupt_count))
return data
def report_packet(register):
"""Timing sequencer instruction to report the value of a register
Format: type (8bits),version (8bits),length (16bits),
address (32bits),bitmask (32bits),string(variable length)
register: object e.g. timing_system.image_number
count: integer number
Return value: binary data as string
"""
from struct import pack
count_bitmask = ((1 << register.bits) - 1)
bitmask = count_bitmask << register.bit_offset
address = register.address
name = register.name
data = packet("report",pack(">II",address,bitmask) + name)
return data
def index_packets(interrupt_data):
"""Table of offsets encoded as binary data.
May be multiple packets if maximum packet size is exceeded."""
# How many offsets can be stored in an index packet?
header_size = len(packet())
from struct import pack
offset_size = len(pack(">I",0))
max_packet_size = 2**16-1
max_payload_size = max_packet_size - header_size
N_max = max_payload_size/offset_size
N = len(interrupt_data)
total_length = 0
for it0 in range(0,N,N_max):
n = min(N-it0,N_max)
total_length += header_size + n*offset_size
offset = total_length
data = ""
for it0 in range(0,N,N_max):
index_data = ""
n = min(N-it0,N_max)
for it in range(it0,it0+n):
index_data += pack(">I",offset)
offset += len(interrupt_data[it])
data += packet("index",index_data)
assert len(data) == total_length
return data
def descriptor(data):
"""Parameter list as string
data: binary data a string"""
from struct import unpack
descriptor = ""
i = 0
while i < len(data):
type,version,length = unpack(">BBH",data[i:i+4])
if type == 3:
payload = data[i+4:i+length]
descriptor = payload
break
i += length
return descriptor
def packet_representation(data):
"""String
data: binary data a string"""
from struct import unpack,pack
text = ""
i = 0
interrupt_count = 0
while i < len(data):
type,version,length = unpack(">BBH",data[i:i+4])
header_size = len(packet())
payload = data[i+header_size:i+length]
type_name = type_names.get(type,"unknown")
payload_repr = ""
if type_name == "interrupt":
count,period = unpack(">BB",payload)
payload_repr = "%r/%r" % (count,period)
interrupt_count += 1
if type_name == "write":
address,bitmask,bit_count = unpack(">III",payload)
payload_repr = "addr=0x%08X, mask=0x%08X, count=0x%08X" \
% (address,bitmask,bit_count)
if type_name == "increment":
address,bitmask,bit_count = unpack(">III",payload)
payload_repr = "addr=0x%08X, mask=0x%08X, count=0x%08X" \
% (address,bitmask,bit_count)
if type_name == "descriptor":
descriptor = payload
payload_repr = descriptor.replace(",",",\n").strip("\n")
if type_name == "output":
output = payload
payload_repr = "%r" % output
if type_name == "sequence length":
sequence_length, = unpack(">I",payload)
payload_repr = "%r bytes" % sequence_length
if type_name == "interrupt count":
count, = unpack(">I",payload)
payload_repr = "%r total" % count
if type_name == "report":
address,bitmask = unpack(">II",payload[0:8])
name = payload[8:]
payload_repr = "addr=0x%08X, mask=0x%08X, name=%r" \
% (address,bitmask,name)
if type_name == "index":
offset_size = len(pack(">I",0))
N = len(payload)/offset_size
addresses = []
for j in range(0,N):
address = unpack(">I",payload[j*offset_size:(j+1)*offset_size])
addresses += ["%6d" % address]
payload_repr = []
for j in range(0,N,8):
payload_repr += [",".join(addresses[j:j+8])]
payload_repr = "\n".join(payload_repr)
prefix = "%-5d: %-4d %-15s " % (i,interrupt_count,type_name)
lines = payload_repr.split("\n")
for line in lines[:1]: text += prefix + abbreviate(line) + "\n"
for line in lines[1:]: text += " "*len(prefix) + abbreviate(line) + "\n"
i += length
return text
def abbreviate(text,max_length = 240):
"""Shorten a string indixcating omitted part using elipsis ('...')"""
if len(text) > max_length:
text = text[0:max_length-16-3]+"..."+text[-16:]
return text
type_codes = {
"interrupt": 0,
"write": 1,
"increment": 2,
"descriptor": 3,
"output": 4,
"sequence length": 5,
"interrupt count": 6,
"report": 7,
"index": 8,
}
type_names = dict(zip(type_codes.values(),type_codes.keys()))
def toint(x):
"""Force conversion to integer"""
try: return int(x)
except: return 0
def hash(text):
"""Calcualte the hash of a string, using the MD5 (Message Digest version 5)
alorithm.
Return value: ACSCII encoded hexadecimal number of 32 digits"""
import hashlib
m = hashlib.md5()
m.update(text)
hash = m.hexdigest()
return hash
def instantiate(x): return x()
@instantiate
class lxd(object):
"""Laser to X-ray time delay"""
name = "lxd"
timeout = 2.0
from numpy import nan
__new_value__ = nan
__last_move__ = 0
def get_value(self): return timing_sequencer.delay
def set_value(self,value):
from time import time
timing_sequencer.delay = value
self.__new_value__ = value
self.__last_move__ = time()
value = property(get_value,set_value)
def get_moving(self):
from time import time
moving = timing_sequencer.delay != self.__new_value__ and \
time() <= self.__last_move__ + self.timeout
return moving
def set_moving(self,value): pass
moving = property(get_moving,set_moving)
def hexdump(data):
"""Print string as hexdecimal numbers
data: string"""
s = ""
for x in data: s += "%02X " % ord(x)
return s
def report_if_not_valid_pathname(filename):
"""Report if this filename is not usable on Embedded uClinux 2.2."""
if not valid_pathname(filename):
warn("%r contains part of %d characters, exceeding liit of 254." %
(filename,longest_pathname_component(filename)))
def valid_pathname(filename):
"""Is this filename is not usable on Linux or MacOS?"""
valid = (longest_pathname_component(filename) <= 254)
return valid
def longest_pathname_component(filename):
n = max([len(x) for x in filename.split("/")])
return n
if __name__ == "__main__":
from pdb import pm # for debugging
import logging
logging.basicConfig(level=logging.DEBUG,format="%(asctime)s %(levelname)s: %(message)s")
##import timing_system as t; t.DEBUG = True
from timing_system import timing_system
from numpy import arange
from time import time,sleep # for timing
from Ensemble_SAXS_pp import Ensemble_SAXS
from timing_system import timing_system
##sequence = Sequence()
##self = sequence # for debugging
self = timing_sequencer # for debugging
i = 23 # channel number
print('timing_system.prefix = %r' % timing_system.prefix)
print('timing_system.ip_address = %r' % timing_system.ip_address)
print('')
##print('registers,counts = Sequence().register_counts')
##print('')
##print('timing_sequencer.cache_size = 0')
##print('timing_sequencer.update()')
##print('timing_sequencer.running = False')
##print('timing_sequencer.running = True')
print('print packet_representation(index_packets([""]*2))')
print('print packet_representation(descriptor_packet("x=1,y=2"))')
<file_sep>"""
Run on "mond" node "daq-xpp-mon05.pcdsn" or "daq-xpp-mon06.pcdsn".
Only one instance can run per node.
Setup:
ssh daq-xpp-mon06.pcdsn
source /reg/g/psdm/etc/ana_env.sh
DAQ Control - (uncheck) Record Run - Begin Running
<NAME>, Jan 22, 2016
"""
from psana import *
from logging import info,warn,debug
ds = DataSource('shmem=XPP.0:stop=no')
src = Source('rayonix')
t0 = 0
print("Setup complete")
for evt in ds.events():
debug("Waiting for event...")
raw = evt.get(Camera.FrameV1,src)
debug("Got event")
if raw is None: continue
t = evt.get(EventId).fiducials()
print('Fiducial %d (+%d)' % (t,t-t0))
t0 = t
<file_sep>#!/bin/env python
"""EPICS Channel Archiver
Process variable history
Test:
curl "Content-Type: text/xml" -X POST -d @request.data http://everest.cars.aps.anl.gov/archive/cgi/ArchiveDataServer.cgi
Source:
https://github.com/EPICSTools/ChannelArchiver/tree/master/XMLRPCServer
<NAME>, Nov 23, 2015 - Nov 23, 2015
"""
__version__ = "1.0"
# based on file "XMLRPCServer/request.data"
request_template = """\
<?xml version="1.0"?>
<methodCall>
<methodName>archiver.values</methodName>
<params>
<!-- key -->
<param><value><i4>{0[key]:d}</i4></value></param>
<!-- channel name array -->
<param>
<value>
<array>
<data>
<value><string>{0[PV_name]}</string></value>
</data>
</array>
</value>
</param>
<!-- start time -->
<param><value><i4>{0[start_time]:.0f}</i4></value></param>
<param><value><i4>0</i4></value></param>
<!-- start time -->
<param><value><i4>{0[end_time]:.0f}</i4></value></param>
<param><value><i4>0</i4></value></param>
<!-- count -->
<param><value><i4>{0[count]:d}</i4></value></param>
<!-- how -->
<param><value><i4>{0[how]:d}</i4></value></param>
</params>
</methodCall>\
"""
URL = "http://everest.cars.aps.anl.gov/archive/cgi/ArchiveDataServer.cgi"
def PV_history(PV_name,start_time=0,end_time=None,count=1000000,key=2,how=3,
URL=URL):
"""Process variable history
start_time: number of seconds since Jan 1, 1970, 00:00:00 UST
end_time: number of seconds since Jan 1, 1970, 00:00:00 UST
count: maximum number of values to return
key: which archive? 1 = full archive, 2 = current archive
URL: e.g. "http://everest.cars.aps.anl.gov/archive/cgi/ArchiveDataServer.cgi"
Return value: list of timettamps, list of floating point values
"""
from time import time
if end_time is None: end_time = time()+3600
# Negative time are interperted as relative to now.
if start_time < 0: start_time += time()
if end_time < 0: end_time += time()
params = dict(PV_name=PV_name,start_time=start_time,end_time=end_time,
count=count,key=key,how=how)
request = request_template.format(params)
from httplib import HTTPConnection
from urlparse import urlparse
u = urlparse(URL)
headers = {"Content-type": "text/xml"}
conn = HTTPConnection(u.netloc)
conn.request("POST",u.path,request,headers)
response = conn.getresponse()
data = response.read()
data = data.replace("\r\n","\n") # DOS to UNIX
# Parse XML data, extract item "value"
from xml.etree import ElementTree
from StringIO import StringIO
tree = ElementTree.parse(StringIO(data))
values = []; timestamps = []
name = ""; severity = "0"
for node in tree.iter():
if node.tag == "name": name = node.text
if node.tag == "i4" and name == "sevr": severity = node.text
if severity == "0":
if node.tag == "i4" and name == "secs": timestamps += [node.text]
if node.tag == "i4" and name == "nano":
timestamps[-1] += "."+node.text
if node.tag == "double" and name == "value": values += [node.text]
values = [float(v) for v in values]
timestamps = [float(t) for t in timestamps]
return timestamps,values
def date_time(seconds):
"""Current date and time as formatted ASCII text, precise to 1 ms
seconds: time elapsed since 1 Jan 1970 00:00:00 UST"""
from datetime import datetime
timestamp = str(datetime.fromtimestamp(seconds))
return timestamp
if __name__ == "__main__":
from time import time
day = 86400
print('timestamps,values = PV_history("14IDA:DAC1_4.VAL",start_time=-7*day,key=2)')
print('for t,v in zip(timestamps,values): print date_time(t),v')
<file_sep>"""This script is to test various implementations of the Python to EPICS
interface.
EpicsCA: Matt Newille, U Chicago
epics: Matt Newille, U Chicago
CA: <NAME>, NIH
<NAME>, APS, 17 Apr 2010
"""
from CA import caput,caget,cainfo,PV # choices: EpicsCA, epics, CA
# PVs used by lauecollect
PVs = [
"Mt:TopUpTime2Inject",
"14IDA:Slit1Hsize.VAL",
"14IDA:Slit1Vsize.VAL",
"14IDC:mir1Th.RBV",
"14IDC:mir2Th.RBV",
"ACIS:ShutterPermit",
"PA:14ID:A_SHTRS_CLOSED.VAL",
"14IDA:shutter_auto_enable1",
"14IDB:B1Bi0.VAL",
"14IDB:Dliepcr1:Out1Mbbi",
"14IDA:DAC1_4.VAL",
"14IDC:mir2Th.VAL",
"14IDB:beamCheckV",
"14IDB:beamCheckH",
"14IDA:DAC1_4.VAL",
"14IDC:mir2Th.VAL",
"PA:14ID:A_SHTRS_CLOSED.VAL",
"ACIS:ShutterPermit",
"PA:14ID:A_SHTRS_CLOSED.VAL",
"14IDA:m5.VAL",
"14IDA:LA2000_SPEED",
"14IDB:DAC1_2.VAL",
"14IDB:DAC1_3.VAL",
"14IDB:xiaStatus.VAL",
"14IDB:DAC1_1.VAL",
"14IDB:B1Bi0.VAL",
]
for pv in PVs: print "%s: %r" % (pv,caget(pv))
<file_sep>"""Simple data base
Author: <NAME>
Date created: 2010-12-10
Date last modified: 2019-01-15
"""
from logging import debug
__version__ = "1.5.3" # colon in filenames
from thread import allocate_lock
lock = allocate_lock()
def dbset(name,value):
"""Store a value in the data base
value: any python built-in data type"""
dbput(name,repr(value))
def db(name,default_value=""):
"""Retrieve a value from the data base
Return value: any built-in Python data type"""
value = dbget(name)
dtype = type(default_value)
from numpy import nan,inf,array # for "eval"
from collections import OrderedDict # for "eval"
try: value = dtype(eval(value))
except: value = default_value
return value
def dbput(name,value):
"""Store a value in the data base
value: string"""
with lock: # Allow only one thread at a time in this critical section.
basename = name.split(".")[0]
resname = name[len(basename)+1:]
dbread(basename)
values = DB[basename]
if resname in values and values[resname] == value: return
DB[basename][resname] = value
dbsave(basename)
def dbget(name):
"""Retrieve a value from the data base
Return value: string, if not found: empty string"""
with lock: # Allow only one thread at a time in this critical section.
basename = name.split(".")[0]
resname = name[len(basename)+1:]
dbread(basename)
values = DB[basename]
if resname in values: return values[resname]
else: return ""
def dbdir(name):
"""List of entries names starting with 'name'"""
with lock: # Allow only one thread at a time in this critical section.
from os.path import isdir
keys = []
basename = name.split(".")[0]
pathname = normpath(settings_dir()+"/"+basename)
files = listdir(pathname) if isdir(pathname) else []
keys += [file.replace("_settings.py","") for file in files]
resname = name[len(basename)+1:]
dbread(basename)
keys += list(set([key.split(".")[0] for key in DB[basename].keys()]))
return keys
def listdir(pathname):
"""Directory content, minus "hidden" files"""
from os import listdir
filenames = listdir(pathname)
# Exclude "hidden" files.
filenames = [f for f in filenames if not f.startswith(".")]
return filenames
def dbread(basename):
from os.path import exists,getmtime
from time import time
from collections import OrderedDict
if not basename in DB: DB[basename] = OrderedDict()
settings_file = normpath(settings_dir()+"/"+basename+"_settings.py")
# Check only every N seconds to avoid excessive system load.
if settings_file in last_checked and \
time()-last_checked[settings_file] < 1.0: return
last_checked[settings_file] = time()
if not exists(settings_file):
##debug("Settings file %r not found" % settings_file)
return
if settings_file in timestamps and \
getmtime(settings_file) == timestamps[settings_file]: return
try: settings = file(settings_file).read()
except IOError: settings = ""
settings = settings.replace("\r","") # Convert DOS to UNIX
DB[basename] = OrderedDict()
values = DB[basename]
lines = settings.split("\n")
if len(lines) > 0 and lines[-1] == "": lines = lines[0:-1]
def process(entry):
if "=" in entry:
i = entry.index("=")
resname = entry[:i].strip(" ")
values[resname] = entry[i+1:].strip(" ")
entry = ""
for line in lines:
# Continuation of previous entry?
if entry == "": entry = entry = line
elif entry.endswith("\\"): entry += "\n"+line
elif line.startswith(" "): entry += "\n"+line
elif line.startswith("\t"): entry += "\n"+line
elif "=" not in line: entry += "\n"+line
else: process(entry); entry = line
process(entry)
timestamps[settings_file] = getmtime(settings_file)
def dbsave(basename):
from os.path import exists,getmtime,dirname,basename as file_basename
from os import makedirs,umask,chmod,remove,rename
from tempfile import NamedTemporaryFile
from time import time
if basename in DB:
values = DB[basename]
lines = [key+" = "+values[key] for key in values]
##lines.sort()
text = "\n".join(lines)
umask(0) # Make sure files and driectories are writable to all users.
settings_file = normpath(settings_dir()+"/"+basename+"_settings.py")
if not exists(dirname(settings_file)): makedirs(dirname(settings_file))
# Make sure that is a non-writeable file alreadt exists, is will be
# replaced by a writeable file.
tempfile = NamedTemporaryFile(delete=False,dir=dirname(settings_file),
prefix=file_basename(settings_file))
tempfile.write(text)
tempfile.close()
chmod(tempfile.name,0666)
if exists(settings_file): remove(settings_file)
rename(tempfile.name,settings_file)
timestamps[settings_file] = getmtime(settings_file)
last_checked[settings_file] = time()
def normpath(pathname):
"""Make sure no illegal characters are contained in the file name."""
from sys import platform
illegal_chars = ":?*"
for c in illegal_chars:
# Colon (:) may in the path after the drive letter.
if platform == "win32" and c == ":" and pathname[1:2] == ":":
pathname = pathname[0:2]+pathname[2:].replace(c,"")
else: pathname = pathname.replace(c,".")
return pathname
# Needed by "dbread" and "dbsave"
DB = {}
timestamps = {}
last_checked = {}
def settings_dir():
"""Pathname of the file used to store persistent parameters"""
from module_dir import module_dir
path = module_dir(settings_dir)+"/settings"
return path
if __name__ == '__main__': # for testing
from pdb import pm
import logging
logging.basicConfig(level=logging.DEBUG,format="%(asctime)s: %(message)s")
from time import time
print('print(dbget("LaueCrystallographyControl.GotoSaved.action"))')
print('dbset("LaueCrystallographyControl.time",time())')
<file_sep>#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
Author: <NAME>, <NAME>, <NAME>
Date created: 12/8/2016
Date last modified: 10/17/2017
2017-06-02 1.5 Adapted for 3-way injection port
2017-10-06 1.6 Friedrich, Using IOC
2017-10-17 1.7 Brian, Friedrich, refill_1, refill_3
Setup:
Start desktop shortcut "Centris Syringe IOC"
(Target: python cavro_centris_syringe_pump_IOC.py run_IOC
Start in: %LAUECOLLECT%)
"""
__version__ = "1.0"
from time import sleep,time
from logging import debug,info,warn,error
from thread import start_new_thread
from pdb import pm
from tempfile import gettempdir
# Assign default parameters.
class Cavro_centris_syringe_pump_SL(object):
"""Cavro Centris Syringe Pumps"""
def start_DL(self):
pass
if __name__ == "__main__":
import logging; logging.basicConfig(filename=gettempdir()+'/suringe_pump_SL.log', level=logging.DEBUG, format="%(asctime)s %(levelname)s: %(message)s")
server = Cavro_centris_syringe_pump_SL()
# p.write_read({4:"/1?20R\r"}) # query valve position
# p.write_read({1: "/1IR\r"}) # Move pump1 valve to Input
# p.write_read({2: "/1V0.3,1F\r"}) # Change speed to 0.3 uL/s
# sum(p.positions().values()[:2]) # Returns sum of first two values
<file_sep>#!/usr/bin/env python
"""Control panel for simulated beamline environment of APS 14-IDB
Author: <NAME>,
Date created: 2016-06-13
Date last modified: 2019-04-26
"""
from sim_id14 import sim_id14
from Panel import BasePanel,PropertyPanel,ButtonPanel,TogglePanel,TweakPanel
import wx
__version__ = "1.7" # Mirror benders, JJ1 slits, KB mirror, collimator
class SimID14Panel(BasePanel,sim_id14):
name = "sim_id14"
title = "14ID-B Simulator"
motors = [
"current","sbcurrent","U23","U27",
"FE_shutter_enabled",
"ID14A_shutter",
##"FE_shutter","FE_shutter_auto",
"Slit1H","Slit1V",
"HLC",
"mir1Th","MirrorV","mir1bender",
"mir2X1","mir2X2","mir2bender",
"ID14C_shutter",
##"safety_shutter","safety_shutter_auto",
"s1hg","s1ho","s1vg","s1vo",
"ChopX","ChopY",
"shg","sho","svg","svo",
"KB_Vpitch","KB_Vheight","KB_Vcurvature","KB_Vstripe",
"KB_Hpitch","KB_Hheight","KB_Hcurvature","KB_Hstripe",
"CollX","CollY",
"GonX","GonY","GonZ","Phi",
"DetZ",
"laser_safety_shutter",
##"laser_safety_shutter_open","laser_safety_shutter_auto",
"VNFilter",
]
standard_view = [eval("sim_id14."+motor+".description") for motor in motors]
layout = [[
eval("sim_id14."+motor+".description"),
[TweakPanel, [],{"name":motor+".value","digits":4,"width":60}],
[TogglePanel, [],{"name":motor+".EPICS_enabled","type":"Off/On","width":40}],
[PropertyPanel,[],{"name":motor+".prefix","width":120}]
] for motor in motors]
def __init__(self,parent=None):
BasePanel.__init__(self,
parent=parent,
name=self.name,
title=self.title,
layout=self.layout,
standard_view=self.standard_view,
label_width=170,
icon="BioCARS",
)
if __name__ == '__main__':
from pdb import pm # for debugging
##import logging; logging.basicConfig(level=logging.DEBUG)
if not hasattr(wx,"app"): wx.app = wx.App(redirect=False) # to initialize WX...
panel = SimID14Panel()
wx.app.MainLoop()
wx.App.Exit(wx.app)
<file_sep>"""
Find repeating patterns in sequences
<NAME>, Feb 6, 2016 - Feb 7, 2016
Reference:
Detecting a repeating cycle in a sequence of numbers
http://stackoverflow.com/questions/8672853/detecting-a-repeating-cycle-in-a-sequence-of-numbers-python
"""
__version__ = "1.0.2" # linear ranges
import re
from logging import debug,info,warn,error
# (.+ .+) will match at least two numbers (as many as possible) and place the
# result into capture group 1.
# ( \1)+ will match a space followed by the contents of capture group 1, at
# least once.
# (.+ .+) will originally match the entire string, but will give up
# characters off the end because ( \1)+ will fail, this backtracking will
# occur until (.+ .+) cannot match at the beginning of the string at which
# point the regex engine will move forward in the string and try again.
regex_parts = re.compile(r'(.+,.+)(,\1)+')
regex_parts = re.compile(r'(.+)([,+]\1)+')
def parts(string):
match = regex_parts.search(string)
if match:
begin,end = match.start(),match.start()+len(match.group(0))
part = match.group(1)
count = len(match.group(0)+",")/len(match.group(1)+",")
head,tail = string[0:begin],string[end:]
debug("head %r, part %r, count %r, tail %r" % (head,part,count,tail))
if head.endswith("["): head = head[:-1]
if head.endswith(","): head = head[:-1]
if len(head)>0 and head[-1] not in "+*[],": head = head+"]"
if head == "[]": head = ""
if head.endswith("]"): head = head+"+"
if tail == "]": tail = ""
if tail.startswith("]"): tail = tail[1:]
if tail.startswith(","): tail = tail[1:]
if len(tail)>0 and tail[0] not in "+*[],": tail = "["+tail
if tail == "[]": tail = ""
if tail.startswith("["): tail = "+"+tail
debug("head %r, part %r, count %r, tail %r" % (head,part,count,tail))
string = ""
if head: string += head
string += "["+part+"]*"+str(count)
if tail: string += tail
return string
regex_simplify1 = re.compile(r'([0-9]+)\*([0-9]+)')
def simplify1(string):
"""e.g. '2*2' -> '4'"""
match = regex_simplify1.search(string)
if match:
n,m = match.groups()
begin,end = match.start(),match.start()+len(match.group(0))
string = string[0:begin]+str(int(n)*int(m))+string[end:]
return string
regex_simplify2 = re.compile(r'\[([^\[\]]+)\]\*([0-9]+)\+\[\1\]')
def simplify2(string):
"""e.g. '[0]*4+[0]' -> '[0]*5'"""
match = regex_simplify2.search(string)
if match:
part,n = match.groups()
begin,end = match.start(),match.start()+len(match.group(0))
string = string[0:begin]+"["+part+"]*"+str(int(n)+1)+string[end:]
return string
regex_list = re.compile(r'(?<=\[)[0-9]+(,[0-9]+){2,}(?=\])')
def simplify3(string):
"""[1,2..4]+[6] -> [1,2..4,6]"""
string = string.replace("]+[",",")
return string
def mark_linear_range(string):
"""Replace stretches where the values chages linearly wirg "range(start,step,end)"""
match = regex_list.search(string)
if match:
begin,end = match.start(),match.start()+len(match.group(0))
list = match.group(0)
string = string[0:begin]+mark_linear_ranges(list)+string[end:]
return string
def mark_linear_ranges(string):
"""Replace stretches where the values chages linearly wirg "range(start,step,end)"""
values = eval(string)
ranges = linear_ranges(values)
debug("%s" % str(ranges).replace(" ","")[1:-1])
strings = []
for r in ranges:
if len(r) > 1:
if len(strings) > 0 and not "]" in strings[-1] and not ")" in strings[-1]:
strings[-1] += "]"
if len(r) == 1:
if len(strings) == 0 or "]" in strings[-1] or ")" in strings[-1]:
strings += ["[%r" % r[0]]
else: strings[-1] += ",%r" % r[0]
elif r[0] == r[-1]: strings += ["[%r]*%d" % (r[0],len(r))]
elif len(r) == 3: strings += "[%r,%r,%r]" % (r[0],r[1],r[2])
else:
start = r[0]; step = r[1]-r[0]; stop = r[-1]+1
strings += ["range(%r,%r,%r)"%(start,stop,step)]
if len(strings) > 0 and not "]" in strings[-1] and not ")" in strings[-1]:
strings[-1] += "]"
string = "+".join(strings)
return string
def linear_ranges(values):
"""Break of list of values into lists where the value changes linearly"""
ranges = []
def close(x,y): return abs(y-x) < 1e-6
for i in range(0,len(values)):
is_linear_before = i >= 2 and \
close(values[i]-values[i-1],values[i-1]-values[i-2])
is_linear_after = 1 <= i <= len(values)-2 and \
close(values[i]-values[i-1],values[i+1]-values[i])
if is_linear_before or \
(len(ranges) > 0 and len(ranges[-1]) == 1 and is_linear_after):
ranges[-1] += [values[i]]
else: ranges += [[values[i]]]
return ranges
regex_range = re.compile(r'range\(([0-9+]),([0-9+]),([0-9+])\)')
def replace_range_with_ellipse(string):
"""e.g. 'range(1,5,1)' -> '[1,2..4]'"""
match = regex_range.search(string)
if match:
start,stop,step = match.groups()
start,stop,step = eval(start),eval(stop),eval(step)
next = start+step
last = stop-step
begin,end = match.start(),match.start()+len(match.group(0))
string = string[0:begin]+"[%r,%r..%r]"%(start,next,last)+string[end:]
return string
regex_ellipse = re.compile(r'\[([0-9]),([0-9])\.\.([0-9])\]')
def replace_ellipse_with_range(string):
"""e.g. '[1,2..4]' -> 'range(1,5,1)'"""
match = regex_ellipse.search(string)
if match:
start,next,last = match.groups()
start,next,last = eval(start),eval(next),eval(last)
step = next-start
stop = last+step
begin,end = match.start(),match.start()+len(match.group(0))
string = string[0:begin]+"range(%r,%r,%r)"%(start,stop,step)+string[end:]
return string
def expand(string):
"""e.g. [0]*3+[1] -> [0,0,0,1]"""
string = str(flatten(eval(string))).replace(" ","")
return string
def flatten(l):
"""Make a simple list out of list of lists"""
flattened_list = iterate(flatten1,l)
return flattened_list
def flatten1(l):
"""Make a simple list out of list of lists"""
flattened_list = []
for x in l:
if type(x) == list: flattened_list += x
else: flattened_list += [x]
return flattened_list
def iterate(function,value):
"""Apply a function of a value repeatedly, until the value does not
change any more."""
new_value = function(value)
while new_value != value:
value = new_value
print("%s" % str(value).replace(" ",""))
new_value = function(value)
return value
if __name__ == "__main__":
values = [0,0,0,0,0,1,2,3,4,6,1,2,3,4,6,1,2,3,4,6,4,5,4]
string = str(values).replace(" ","")
##string = "0,0"
##match = regex_parts.search(string)
##if match: print("Found at pos %r: %r = repeat(%r)" % (match.start(),match.group(0),match.group(1)))
print("%s" % string)
##string = iterate(mark_linear_ranges,string)
string = iterate(parts,string)
string = iterate(simplify1,string)
string = iterate(simplify2,string)
string = mark_linear_range(string)
print("%s" % string)
string = iterate(simplify3,string)
string = iterate(replace_range_with_ellipse,string)
string = iterate(replace_ellipse_with_range,string)
string = expand(string)
print("%s" % string)
<file_sep>Ensemble.command = 'import Ensemble; Ensemble.run_server()'
WideFieldCamera.command = 'import GigE_camera_server; GigE_camera_server.run("WideFieldCamera")'
names = ['Ensemble', 'WideFieldCamera', 'Server']
Server.command = u'import GigE_camera_server; GigE_camera_server.run("MicroscopeCamera")'
Microscope Camera.command = u'import GigE_camera_server; GigE_camera_server.run("MicroscopeCamera")'
N = 19
1.label = u'Ensemble'
1.command = u'import Ensemble; Ensemble.run_server()'
2.label = u'WideField Camera'
2.command = u'import GigE_camera_server; GigE_camera_server.run("WideFieldCamera")'
3.command = u'import GigE_camera_server; GigE_camera_server.run("MicroscopeCamera")'
3.label = u'Microscope Camera'
4.label = 'Lightwave Temperature Controller DL'
4.command = 'from lightwave_temperature_controller_server import *; lightwave_temperature_controller_IOC.run()'
5.label = u'Centris Syringe IOC'
5.command = u'from cavro_centris_syringe_pump_IOC import *; syringe_pump_IOC.run()'
1.logfile_basename = u'Ensemble_IOC'
2.logfile_basename = u'WideFieldCamera_server'
3.logfile_basename = u'MicroscopeCamera_server'
4.logfile_basename = 'lightwave_temperature_controller_server '
5.logfile_basename = u'cavro_centris_syringe_pump_IOC'
1.value_code = u'ensemble.connected'
2.value_code = u'widefield_camera.state'
3.value_code = u'microscope_camera.state'
3.test_code = u'"offline" not in value'
2.test_code = u'"offline" not in value'
4.value_code = 'caget("NIH:LIGHTWAVE.VAL")'
4.test_code = u'value is not None and not isnan(value)'
1.test_code = u'value==1'
1.format_code = u'{0:"Device offline",1:"Online",nan:"IOC offline"}[value]'
4.format_code = u'"IOC offline" if value is None else "Device offline" if isnan(value) else "Online"'
5.value_code = u'volume[0].value'
5.format_code = u'"IOC offline" if value is None else "Device offline" if isnan(value) else "Online"'
5.test_code = u'not isnan(value)'
6.label = u'Lab Microscope'
6.command = u'import GigE_camera_server; GigE_camera_server.run("Microscope")'
6.logfile_basename = u'Microscope_server'
6.value_code = u'Camera("Microscope").state'
6.test_code = u'value and "offline" not in value'
7.label = u'Microfluidics Camera'
7.command = u'import GigE_camera_server; GigE_camera_server.run("MicrofluidicsCamera")'
7.logfile_basename = u'MicrofluidicsCamera_server'
7.value_code = u'Camera("MicrofluidicsCamera").state'
7.test_code = u'"offline" not in value'
8.label = u'Ramsey RF Generator'
8.command = u'from Ramsey_RF_generator import *; Ramsey_RF_IOC.run()'
8.value_code = u'caget("NIH:RF.VAL")'
8.logfile_basename = u'temperature_controller_IOC'
8.test_code = u'value is not None and not isnan(value)'
8.format_code = u'"IOC offline" if value is None else "Device offline" if isnan(value) else "Online"'
9.label = u'Test Bench Camera'
9.command = u'import GigE_camera_server; GigE_camera_server.run("TestBenchCamera")'
9.logfile_basename = u'TestBenchCamera_server'
9.value_code = u'Camera("TestBenchCamera").state'
9.test_code = u'"offline" not in value'
9.format_code = u'value'
6.format_code = u'value'
7.format_code = u'value'
10.label = 'Oasis Chiller DL'
10.command = u'from oasis_chiller import *; oasis_chiller_IOC.run()'
10.logfile_basename = u'oasis_chiller_IOC'
10.value_code = u'caget("NIH:CHILLER.RBV")'
10.format_code = u'"IOC offline" if value is None else "Device offline" if isnan(value) else "Online"'
10.test_code = u'value is not None and not isnan(value)'
11.label = u'Oasis Chiller Auto-tune'
11.command = u'from oasis_chiller_autotune import *; run()'
11.logfile_basename = u'oasis_chiller_autotune'
11.value_code = u'caget("NIH:CHILLER.AUTOTUNE")'
11.format_code = u'"Not active" if value is None else "Active"'
12.label = 'Optical Scattering Server '
12.command = 'from optical_scattering_server import optical_scattering_server; optical_scattering_server .run()'
12.logfile_basename = 'optical_scattering_server'
12.value_code = 'caget("NIH:OPTICAL_SCATTERING.MEAN")'
12.test_code = 'value is not None'
12.format_code = '"Server offline" if value is None else str(value)'
13.label = u'Hamilton Syringe Pump'
13.command = u'from syringe_pump import *; run_server()'
13.logfile_basename = u'syringe_pump'
13.value_code = u'caget("NIH:syringe_pump.V")'
11.test_code = u'value is not None'
13.format_code = u'"IOC offline" if value is None else "Device offline" if isnan(value) else "Online"'
13.test_code = u'value is not None and not isnan(value)'
14.label = u'Thermocouple IOC'
14.command = u'from omega_thermocouple import *; run_IOC()'
14.logfile_basename = u'omega_thermocouple'
14.value_code = u'caget("NIH:TC.VAL")'
14.test_code = u'value is not None and not isnan(value)'
14.format_code = u'"IOC offline" if value is None else "Device offline" if isnan(value) else "Online"'
15.command = 'from temperature_server_Friedrich import temperature_server; temperature_server.run()'
15.label = 'Temperature SL (Prototype, Friedrich)'
15.logfile_basename = 'temperature'
15.value_code = 'caget("NIH:TEMPERATURE.VAL")'
15.format_code = '"IOC offline" if value is None else "Device offline" if isnan(value) else "Online"'
15.test_code = 'value is not None and not isnan(value)'
16.command = 'from temperature_server_IOC import temperature_server_IOC; temperature_server_IOC.run();'
16.logfile_basename = 'temperature_server_IOC'
16.label = 'Temperature SL (Valentyn)'
16.value_code = 'caget("NIH:TEMP.VAL")'
16.format_code = '"IOC offline" if value is None else "Device offline" if isnan(value) else "Online"'
16.test_code = 'value is not None and not isnan(value)'
17.command = 'from configuration_server import *; configuration_server.run()'
17.label = 'Configuration Server'
17.logfile_basename = 'configuration_server'
17.value_code = 'caget("NIH:CONF.CONFIGURATION_NAMES")'
17.test_code = 'value is not None'
17.format_code = '"Not Running" if value is None else "Running"'
18.label = 'DI-245 Server'
18.command = 'from DI_245_DL import dev; dev.run();'
18.logfile_basename = 'DI_245_server'
18.value_code = 'caget("NIH:DI245.RUNNING")'
18.format_code = "str(value) == '1'"
18.test_code = 'value'
19.label = 'Rayonix Detector [new]'
19.command = 'from rayonix_detector_server import *; run()'
19.logfile_basename = 'rayonix_detector_server'
19.value_code = 'rayonix_detector_client.online'
19.format_code = '"Online" if value else "Offline"'<file_sep>#!/usr/bin/env python
"""
Monitors a counter and displays a time chart.
Author: <NAME>, NIH, 16 Jun 2011 - 30 Mar 2014
Modifier: <NAME>, Jan 30 2015
"""
from __future__ import with_statement,division
from numpy import *
from thread import start_new_thread
from instrumentation import *
from logging import debug
from normpath import normpath
__version__ = "1.3.7"
# Default settings
title = "Data Logger"
naverage = 1
default_logfile = "/Mirror/Femto/C/All Projects/APS/Experiments/2014.08/Logfiles/test.log"
default_logfile = "/Femto/C/All Projects/APS/Experiments/2014.11/Logfiles/Beamstop.log"
class intensity:
pass
intensity.value = 0
intensity.name = "intensity"
intensity.unit = "counts"
class x:
pass
x.value = 0
x.name = "x"
x.unit = "mm"
class y:
pass
y.value = 0
y.name = "y"
y.unit = "mm"
class I0_PIN:
pass
I0_PIN.value = 0
I0_PIN.name = "I0_PIN"
I0_PIN.unit = "nVs"
column_name = "x"
counter_name = column_name
waiting_time = 0.5 # delay between measurements
# Initialization
active = False # collecting data?
cancelled = False
def counter():
# Ttry if "counter_name" is a Python variable defined in "id14.py".
# If not, asssume counter name is an EPICS process variable
try:
counter = eval(counter_name)
return counter
except: pass
# from CA import PV
# return PV(counter_name)
def counter_value():
"""The current value of the counter"""
value = counter().value
#value = 0
try: return float(value)
except ValueError: return nan
except TypeError: return nan
def counter_unit():
"""The current value of the counter"""
if not hasattr(counter(),"unit"): return ""
unit = counter().unit
if hasattr(unit,"value"): unit = unit.value
if not isinstance(unit,basestring): return ""
return unit
def counter_description():
"""The current value of the counter"""
if not hasattr(counter(),"name"): return ""
name = counter().name
if hasattr(name,"value"): name = name.value
if not isinstance(name,basestring): return ""
return name
def measure():
from numpy import nan,isnan
from time import sleep
while not cancelled:
while active:
last_measurement = log.value[-1] if len(log.value) > 0 else nan
measurement = counter_value()
while measurement == last_measurement or isnan(measurement):
if not active: status("not active"); break
if measurement == last_measurement and not isnan(measurement):
status("Waiting for update...")
sleep(waiting_time)
measurement = counter_value()
if not active: status("not active"); break
status ("Measuring %s" % tostr(measurement))
#log.append(measurement) ## comment out by Cho
sleep(waiting_time)
sleep(waiting_time)
def watch_logfile():
"""Check whether logfile is beeing update and reload it if needed."""
from time import sleep
while not cancelled:
log.read_file()
sleep(2.5)
class Log(object):
"""Stores time-stamped data"""
def __init__(self):
self.filename = normpath(default_logfile)
self.loaded_filename = ""
self.timestamp = 0
self.T = zeros(0)
self.VALUE = zeros(0)
from thread import allocate_lock
self.lock = allocate_lock()
def append(self,value):
from time import time
from os import makedirs
from os.path import exists,dirname,getmtime
# A measurement that is a duplicate of the last is probably old.
self.read_file()
if len(self.VALUE) > 0 and value == self.VALUE[-1]: return
t = time()
self.T = concatenate((self.T,[t]))
self.VALUE = concatenate((self.VALUE,[value]))
if not exists(self.filename):
if not exists(dirname(self.filename)): makedirs(dirname(self.filename))
logfile = file(self.filename,"ab")
logfile.write("#date time\tvalue[%s]\n" % counter_unit())
logfile = file(self.filename,"ab")
logfile.write("%s\t%s\n" % (date_string(t),tostr(value)))
logfile.close()
self.timestamp = getmtime(self.filename)
##debug("updated log file: %.0f" % self.timestamp)
def read_file(self):
"Check log file for changes and reread it"
with self.lock: # Allow only one thread at a time inside this function.
from os.path import exists,getmtime
from table import table
if not exists(self.filename):
#print self.filename
##debug("file %r not found" % self.filename)
self.T,self.VALUE = zeros(0),zeros(0)
self.timestamp = 0
self.loaded_filename = ""
else:
current_timestamp = getmtime(self.filename)
if abs(current_timestamp - self.timestamp) > -1 or \
self.filename != self.loaded_filename:
if self.timestamp != 0:
dt = (current_timestamp - self.timestamp)
##debug ("log file changed by %g s" % dt)
debug("Reading %s" % self.filename)
status("Reading %s..." % self.filename)
try:
#print self.filename
logfile = table(self.filename,separator="\t")
#print logfile
self.T = array(map(timestamp,logfile.date_time))
#self.VALUE = logfile.value
self.VALUE = logfile[counter().name]
self.timestamp = current_timestamp
self.loaded_filename = self.filename
except Exception,details:
debug("%s unreadable: %s" % (self.filename,details))
if self.loaded_filename != self.filename:
self.T,self.VALUE = zeros(0),zeros(0)
self.timestamp = current_timestamp
self.loaded_filename = self.filename
status("Reading %s... done" % self.filename)
def get_t(self):
"""Timestamps"""
return self.T
t = property(get_t)
def get_value(self):
"""Recorded values"""
return self.VALUE
value = property(get_value)
import wx
class DataLogger (wx.Frame):
def __init__(self,name=""):
"""name: defines settings filename."""
if name == "": name = type(self).__name__
self.name = name
##debug("DataLogger: name: %r" % self.name)
wx.Frame.__init__(self,parent=None)
# Menus
self.title = title
menuBar = wx.MenuBar()
menu = wx.Menu()
menu.Append (101,"Logfile...\tCtrl+O",
"Where to store the timing history files to watch.")
self.Bind (wx.EVT_MENU,self.OnSelectLogfile,id=101)
menu.Append (121,"E&xit","Closes this window.")
self.Bind (wx.EVT_MENU,self.OnExit,id=121)
menuBar.Append (menu,"&File")
self.Bind(wx.EVT_CLOSE,self.OnExit)
menu = wx.Menu()
menu.Append (402,"&Options...","Parameters")
self.Bind (wx.EVT_MENU,self.OnOptions,id=402)
menuBar.Append (menu,"&Options")
menu = wx.Menu()
menu.Append (501,"&About...","Version information")
self.Bind (wx.EVT_MENU,self.OnAbout,id=501)
menuBar.Append (menu,"&Help")
self.SetMenuBar (menuBar)
# Controls
from matplotlib.figure import Figure
from matplotlib.backends.backend_wxagg import FigureCanvasWxAgg
self.figure = Figure(figsize=(4,3))
self.canvas = FigureCanvasWxAgg(self,-1,self.figure)
self.figure.subplots_adjust(bottom=0.2)
self.plot = self.figure.add_subplot(1,1,1)
self.active = wx.ToggleButton(self,label="Active")
self.Bind(wx.EVT_TOGGLEBUTTON,self.OnActive,self.active)
self.TimeFraction = wx.ScrollBar(self)
self.TimeFraction.SetScrollbar(0,200,1000,100,True)
# SetScrollbar(position,thumbSize,range,pageSize,refresh)
# [Arguments misnamed "orientation,position,thumbSize,range,refresh"
# in WxPython 2.9.1.1]
events = [wx.EVT_SCROLL_TOP,wx.EVT_SCROLL_BOTTOM,
wx.EVT_SCROLL_LINEUP,wx.EVT_SCROLL_LINEDOWN,
wx.EVT_SCROLL_PAGEUP,wx.EVT_SCROLL_PAGEDOWN,
wx.EVT_SCROLL_THUMBRELEASE]
for e in events: self.Bind(e,self.OnTimeFractionChanged,self.TimeFraction)
choices = ["10 s","30 s","1 min","2 min","5 min","10 min","30 min",
"1 h","2 h","6 h","12 h","1 d","2 d","5 d","10 d"]
style = wx.TE_PROCESS_ENTER
self.TimeWindow = wx.ComboBox(self,style=style,choices=choices)
self.Bind(wx.EVT_COMBOBOX,self.OnTimeWindowChanged,self.TimeWindow)
self.Bind(wx.EVT_TEXT_ENTER,self.OnTimeWindowChanged,self.TimeWindow)
self.CreateStatusBar()
# Layout
vbox = wx.BoxSizer(wx.VERTICAL)
vbox.Add(self.canvas,proportion=1,flag=wx.EXPAND)
hbox = wx.BoxSizer(wx.HORIZONTAL)
hbox.Add(self.active,proportion=0)
hbox.Add(self.TimeFraction,proportion=1,flag=wx.EXPAND)
vbox.Add(hbox,proportion=0,flag=wx.EXPAND)
hbox.Add(self.TimeWindow,proportion=0)
self.SetSizer(vbox)
self.Fit()
# Default settings.
self.time_window = 60 # seconds
self.max_value = nan
self.min_value = nan
self.waiting_time = 0.3
self.reject_outliers = False
self.outlier_cutoff = 2.5
self.show_statistics = True
self.average_count = 1
self.Size = 640,480
# Restore last saved settings.
self.settings = ["counter_name","Size","logfile",
"average_count","max_value","min_value","start_fraction","reject_outliers",
"outlier_cutoff","show_statistics","time_window"]
self.update_settings()
# Initialization
self.npoints = 0
self.Show()
self.update()
#start_new_thread (measure,())
start_new_thread (watch_logfile,())
def get_counter_name(self): return counter_name
def set_counter_name(self,new_counter_name):
global counter_name
counter_name = str(new_counter_name)
counter_name = property(get_counter_name,set_counter_name)
def get_logfile(self): return log.filename
def set_logfile(self,new_logfile):
log.filename = normpath(str(new_logfile))
logfile = property(get_logfile,set_logfile)
def get_average_count(self): return naverage
def set_average_count(self,value):
global naverage; naverage = max(1,int(value))
average_count = property(get_average_count,set_average_count)
def get_waiting_time(self): return waiting_time
def set_waiting_time(self,value):
global waiting_time; waiting_time = value
waiting_time = property(get_waiting_time,set_waiting_time)
def get_start_fraction(self):
position = self.TimeFraction.ThumbPosition
range = self.TimeFraction.Range
return position/range
def set_start_fraction(self,fraction):
fraction = max(0,min(fraction,1))
range = self.TimeFraction.Range
self.TimeFraction.ThumbPosition = rint(fraction*range)
start_fraction = property(get_start_fraction,set_start_fraction)
def get_end_fraction(self):
position = self.TimeFraction.ThumbPosition
size = self.TimeFraction.ThumbSize
end = position+size
range = self.TimeFraction.Range
return end/range
def set_end_fraction(self,fraction):
fraction = max(0,min(fraction,1))
range = self.TimeFraction.Range
size = self.TimeFraction.ThumbSize
self.TimeFraction.ThumbPosition = rint(fraction*range) - size
end_fraction = property(get_end_fraction,set_end_fraction)
def get_time_window(self):
value = seconds(self.TimeWindow.Value)
##debug("Read TimeWindow %r: %g s" % (self.TimeWindow.Value,value))
return value
def set_time_window(self,value):
self.TimeWindow.Value = time_string(value)
##debug("Set TimeWindow %g s: %r" % (value,self.TimeWindow.Value))
time_window = property(get_time_window,set_time_window)
def update(self,event=None):
# Do some work.
self.refresh()
# Relaunch yourself.
self.update_timer = wx.Timer(self)
self.Bind (wx.EVT_TIMER,self.update,self.update_timer)
self.update_timer.Start(1000,oneShot=True)
def refresh(self,event=None):
"Generate the plot"
# Update window title.
title = self.title+" - "+self.logfile
if self.Title != title: self.Title = title
# Update the chart.
if len(log.t) != self.npoints : self.refresh_chart()
self.npoints = len(log.t)
# Update status bar.
self.SetStatusText(status_text)
def UpdateTimeFraction(self):
"""Adjust the thumb size of the scroll bar"""
t,value = self.raw_data
if len(t) > 0: tmin,tmax = nanmin(t),nanmax(t)
else: tmin,tmax = nan,nan
range = self.TimeFraction.Range
size = self.TimeFraction.ThumbSize
position = self.TimeFraction.ThumbPosition
dt = tmax-tmin if tmax != tmin else 1
new_size = rint(clip(self.time_window/dt*range,1,range))
end = position+size
new_position = end - new_size
if new_position == position and new_size == size: return
pagesize = new_size
debug("new position %r, new size: %r" % (new_position,new_size))
self.TimeFraction.SetScrollbar(new_position,new_size,range,pagesize,True)
position = self.TimeFraction.ThumbPosition
size = self.TimeFraction.ThumbSize
##debug("position: %r, size: %r" % (position,size))
def refresh_chart(self):
# Generate a chart.
from pylab import setp,DateFormatter
t,value = self.data
#print "t = ", t
date = days(t)
self.figure.subplots_adjust(bottom=0.2)
self.plot = self.figure.add_subplot(1,1,1)
self.plot.clear()
if self.show_statistics and len(value) > 0:
unit = counter_unit()
def nanmean(x): return nansum(x)/sum(~isnan(x))
def nanstd(x): return std(x[~isnan(x)])
mean = nanmean(value)
sdev = nanstd(value)
min = nanmin(value)
max = nanmax(value)
text = "mean %.5f %s\n" % (mean,unit)
text += "sdev %.5f %s\n" % (sdev,unit)
text += "min %.5f %s\n" % (min,unit)
text += "max %.5f %s\n" % (max,unit)
text += "pkpk %.5f %s\n" % (max-min,unit)
self.plot.text(0.02,0.97,text,verticalalignment="top",fontsize="small",
transform=self.plot.transAxes)
# Annotate chart
t1,t2 = days(self.trange)
self.plot.plot((t1,t2),(mean,mean),"-",color=[1,0.2,0.2])
self.plot.plot((t1,t2),(mean+sdev,mean+sdev),"-",color=[1,0.6,0.6])
self.plot.plot((t1,t2),(mean-sdev,mean-sdev),"-",color=[1,0.6,0.6])
if not all(isnan(value)):
##debug("plotting %r,%r" % (date[0:5],value[0:5]))
self.plot.plot(date,value,'.',color=[0,0,1])
##else: debug("nothing plotted")
if len(t) > 0:
trange = self.tmax-self.tmin
if trange <= 5*60: date_format = "%H:%M:%S"
elif trange < 24*60*60: date_format = "%H:%M"
else: date_format = "%b %d %H:%M"
self.plot.xaxis.set_major_formatter(DateFormatter(date_format))
self.plot.set_xlabel("time")
self.plot.xaxis_date()
setp(self.plot.get_xticklabels(),rotation=90,fontsize=10)
label = counter_description()
if counter_unit(): label += "["+counter_unit()+"]"
self.plot.set_ylabel(label)
self.plot.grid()
if not isnan(self.min_value): self.plot.set_ylim(ymin=self.min_value)
if not isnan(self.max_value): self.plot.set_ylim(ymax=self.max_value)
if not isnan(self.tmin): self.plot.set_xlim(xmin=days(self.tmin))
if not isnan(self.tmax): self.plot.set_xlim(xmax=days(self.tmax))
self.canvas.draw()
self.UpdateTimeFraction()
def get_data(self):
"""Data points to be plotted
returns (t,value)
t: time stamp in seconds since 1 Jan 1970 00:00 UST
value: values"""
t,value = self.raw_data
value = array([float(x) for x in value])
valid = ~isnan(t) & ~isnan(value)
t,value = t[valid],value[valid]
# Average data.
if self.average_count > 1:
n = self.average_count
N = int(ceil(float(len(value))/n))
T,VALUE = zeros(N),zeros(N)
for i in range(0,N):
T[i] = average(t[i*n:(i+1)*n])
VALUE[i] = self.average(value[i*n:(i+1)*n])
t,value = T,VALUE
# Restrict the time range plotted according to the time window position
# control.
if len(t) > 0:
selected = (self.tmin <= t) & (t <= self.tmax)
t,value = t[selected],value[selected]
return t,value
data = property(get_data)
def get_trange(self):
"""Minimum and maximum of x axis, as pair of values"""
t,value = self.raw_data
f1,f2 = self.start_fraction,self.end_fraction
fc = (f1+f2)/2
##debug("range %r to %r" % (f1,f2))
if len(t) > 0:
tmin,tmax = nanmin(t),nanmax(t)
if fc < 0.5:
t1 = tmin + f1*(tmax-tmin)
t2 = t1 + self.time_window
if t2 > tmax: t2 = tmax
else:
t2 = tmin + f2*(tmax-tmin)
t1 = t2 - self.time_window
if t1 < tmin: t1 = tmin
else: t1,t2 = nan,nan
return array([t1,t2])
trange = property(get_trange)
def get_tmin(self): return self.trange[0]
tmin = property(get_tmin)
def get_tmax(self): return self.trange[1]
tmax = property(get_tmax)
def average(self,data):
if not self.reject_outliers: return average(data)
while True:
i = abs(data-average(data)) < self.outlier_cutoff*std(data)
if sum(i) == len(data): break
data = data[i]
return average(data)
def get_raw_data(self):
"""Data points to be plotted
returns (t,value)
t: time stamp in seconds since 1 Jan 1970 00:00 UST
value: values"""
t,value = log.t,log.value
n = min(len(t),len(value))
return t[:n],value[:n]
raw_data = property(get_raw_data)
def OnSelectLogfile(self,event):
"""Called from menu File/Watch Directory...
Let the user pick the directory which contains all the log files to watch.
"""
from os.path import basename,dirname
dlg = wx.FileDialog(self,"Select Logfile",
style=wx.SAVE,
defaultFile=basename(self.logfile),defaultDir=dirname(self.logfile),
wildcard="Text files (*.txt;*.log)|*.txt;*.log|"
"All Files (*.*)|*.*")
# ShowModal pops up a dialog box and returns control only after the user
# has selects OK or Cancel.
OK = (dlg.ShowModal() == wx.ID_OK)
dlg.Destroy()
if not OK: return
self.logfile = str(dlg.GetPath())
def OnExit(self,event):
"Called on File/Exit or when the windows's close button is clicked"
global active,cancelled
active = False
cancelled = True
self.Destroy()
def OnOptions(self,event):
"Change parameters controlling the centering procedure."
dlg = Options(self)
dlg.CenterOnParent()
dlg.Show()
def OnAbout(self,event):
"Called from the Help/About"
from os.path import basename
from inspect import getfile
filename = getfile(lambda x: None)
info = basename(filename)+" "+__version__+"\n"+__doc__
dlg = wx.MessageDialog(self,info,"About",wx.OK|wx.ICON_INFORMATION)
dlg.CenterOnParent()
dlg.ShowModal()
dlg.Destroy()
def OnTimeFractionChanged(self,event):
"""Called when time window position is changed"""
debug("Time fraction changed: %g" % self.start_fraction)
self.refresh_chart()
def OnTimeWindowChanged(self,event):
"""Called when time window width is changed"""
##debug("Time window changed: %r" % self.time_window)
self.time_window = self.time_window # normalizes displayed value
self.refresh_chart()
def OnActive(self,event):
"""called when 'Active' buttoin is toggled"""
global active
active = self.active.Value
def update_settings(self,event=None):
"""Monitors the settings file and reloads it if it is updated."""
from os.path import exists
from os import makedirs
if not hasattr(self,"settings_timestamp"): self.settings_timestamp = 0
if not hasattr(self,"saved_state"): self.saved_state = self.State
if mtime(self.settings_file()) != self.settings_timestamp:
if exists(self.settings_file()):
debug("reading %r" % self.settings_file())
self.State = file(self.settings_file()).read()
self.settings_timestamp = mtime(self.settings_file())
self.saved_state = self.State
elif self.saved_state != self.State or not exists(self.settings_file()):
if not exists(self.settings_dir()): makedirs(self.settings_dir())
debug("writing %r" % self.settings_file())
file(self.settings_file(),"wb").write(self.State)
self.settings_timestamp = mtime(self.settings_file())
self.saved_state = self.State
# Relaunch this procedure after 2 s
self.settings_timer = wx.Timer(self)
self.Bind (wx.EVT_TIMER,self.update_settings,self.settings_timer)
self.settings_timer.Start(2000,oneShot=True)
def GetState(self):
state = ""
for attr in self.settings:
line = attr+" = "+tostr(eval("self."+attr))
state += line+"\n"
return state
def SetState(self,state):
##debug("SetState %r" % state)
for line in state.split("\n"):
line = line.strip(" \n\r")
if line != "":
try: exec("self."+line)
except: debug("ignoring "+line); pass
if hasattr(self,"logfile"):
debug("logfile %r" % self.logfile)
self.logfile = normpath(self.logfile)
debug("logfile %r" % self.logfile)
State = property(GetState,SetState)
def settings_file(self):
"""pathname of the file used to store persistent parameters"""
return self.settings_dir()+"/"+self.name+"_settings.py"
def settings_dir(self):
"""pathname of the file used to store persistent parameters"""
from os.path import dirname
path = module_dir()+"/settings"
return path
class Options (wx.Dialog):
"Allows the use to configure camera properties"
def __init__ (self,parent):
wx.Dialog.__init__(self,parent,-1,"Options")
# Controls
style = wx.TE_PROCESS_ENTER
self.Counter = wx.TextCtrl (self,size=(80,-1),style=style)
self.Max = wx.TextCtrl (self,size=(80,-1),style=style)
self.Min = wx.TextCtrl (self,size=(80,-1),style=style)
self.ShowStatistics = wx.Choice (self,size=(80,-1),choices=["Yes","No"])
self.AverageCount = wx.TextCtrl (self,size=(80,-1),style=style)
self.RejectOutliers = wx.Choice (self,size=(80,-1),choices=["Yes","No"])
self.OutlierCutoff = wx.TextCtrl (self,size=(80,-1),style=style)
self.WaitingTime = wx.TextCtrl (self,size=(80,-1),style=style)
self.Bind (wx.EVT_TEXT_ENTER,self.OnEnter)
self.Bind (wx.EVT_CHOICE,self.OnEnter)
# Layout
layout = wx.BoxSizer()
grid = wx.FlexGridSizer (cols=2,hgap=5,vgap=5)
flag = wx.ALIGN_CENTER_VERTICAL
label = "Counter:"
grid.Add (wx.StaticText(self,label=label),flag=flag)
grid.Add (self.Counter,flag=flag)
label = "Vertical scale upper limit:"
grid.Add (wx.StaticText(self,label=label),flag=flag)
grid.Add (self.Max,flag=flag)
label = "Vertical scale lower limit:"
grid.Add (wx.StaticText(self,label=label),flag=flag)
grid.Add (self.Min,flag=flag)
label = "Show Statistics:"
grid.Add (wx.StaticText(self,label=label),flag=flag)
grid.Add (self.ShowStatistics,flag=flag)
label = "Average count:"
grid.Add (wx.StaticText(self,label=label),flag=flag)
grid.Add (self.AverageCount,flag=flag)
label = "Reject Outliers:"
grid.Add (wx.StaticText(self,label=label),flag=flag)
grid.Add (self.RejectOutliers,flag=flag)
label = "Outlier Cutoff:"
grid.Add (wx.StaticText(self,label=label),flag=flag)
grid.Add (self.OutlierCutoff,flag=flag)
label = "Waiting Time:"
grid.Add (wx.StaticText(self,label=label),flag=flag)
grid.Add (self.WaitingTime,flag=flag)
# Leave a 10-pixel wide space around the panel.
layout.Add (grid,flag=wx.EXPAND|wx.ALL,border=10)
self.SetSizer(layout)
self.Fit()
self.update()
def update(self):
self.Counter.Value = self.Parent.counter_name
self.Min.Value = tostr(self.Parent.min_value).replace("nan","auto")
self.Max.Value = tostr(self.Parent.max_value).replace("nan","auto")
self.ShowStatistics.StringSelection = "Yes" if self.Parent.show_statistics else "No"
self.AverageCount.Value = str(self.Parent.average_count)
self.RejectOutliers.StringSelection = "Yes" if self.Parent.reject_outliers else "No"
self.OutlierCutoff.Value = str(self.Parent.outlier_cutoff)
self.WaitingTime.Value = "%s s" % tostr(self.Parent.waiting_time)
def OnEnter(self,event):
if self.Parent.counter_name != self.Counter.Value:
self.Parent.counter_name = self.Counter.Value
log.read_file()
try: self.Parent.min_value = eval(self.Min.Value)
except: self.Parent.min_value = nan
try: self.Parent.max_value = eval(self.Max.Value)
except: self.Parent.max_value = nan
self.Parent.show_statistics = (self.ShowStatistics.StringSelection == "Yes")
try: self.Parent.average_count = int(eval(self.AverageCount.Value))
except: pass
self.Parent.reject_outliers = (self.RejectOutliers.StringSelection == "Yes")
try: self.Parent.outlier_cutoff = float(eval(self.OutlierCutoff.Value))
except: pass
try: self.Parent.waiting_time = eval(self.WaitingTime.Value.rstrip("s"))
except: pass
self.update()
self.Parent.refresh_chart()
def status(text):
"Display an informational message in the status bar"
global status_text
status_text = text
status_text = ""
def remote_shutter_state():
"""Tell the status of 'Remote Shutter' (in beamline frontend).
Return 'open' or 'closed'"""
from CA import caget
state = caget("PA:14ID:A_SHTRS_CLOSED.VAL")
if state == 1: return "closed"
if state == 0: return "open"
def timestamp(date_time):
"""Convert a date string to number of seconds til 1 Jan 1970."""
from time import strptime,mktime
return mktime(strptime(date_time,"%d-%b-%y %H:%M:%S.%f")) ###
def date_string(time):
"""Convert a time stamp in number of seconds til 1 Jan 1970 to a string"""
from time import strftime,localtime
return strftime("%d-%b-%y %H:%M:%S",localtime(time))
def days(seconds):
"""Convert a time stamp from seconds since 1 Jan 1970 0:00 UTC to days
since 1 Jan 1 AD 0:00 localtime
seconds: scalar or array"""
# Determine the offset, which his time zone and daylight saving time
# dependent.
t = nanmean(seconds)
from datetime import datetime; from pylab import date2num
offset = date2num(datetime.fromtimestamp(t)) - t/86400
return seconds/86400 + offset
def nanmean(x):
"""Average value of the array a, ignoring 'Not a Number' elements"""
if not hasattr(x,"__len__"): return x
x = asanyarray(x)
valid = ~isnan(x)
return sum(x[valid])/sum(valid)
def tostr(x):
"""Replacement for built-in function 'tostr'.
Fixes Microsoft quirk nan -> '1.#QNAN' or '1.#IND'. inf -> '1.#INF'"""
if issubclass(type(x),float):
if isnan(x): return "nan"
if isinf(x) and x>0: return "inf"
if isinf(x) and x<0: return "-inf"
return "%g" % x
return repr(x)
def module_dir():
"directory of the current module"
from os.path import dirname
module_dir = dirname(module_path())
if module_dir == "": module_dir = "."
return module_dir
def module_path():
"full pathname of the current module"
from sys import path
from os import getcwd
from os.path import basename,exists
from inspect import getmodulename,getfile
# 'getfile' retreives the source file name name compiled into the .pyc file.
pathname = getfile(lambda x: None)
if exists(pathname): return pathname
# The module might have been compiled on a different machine or in a
# different directory.
pathname = pathname.replace("\\","/")
filename = basename(pathname)
dirs = [dir for dir in [getcwd()]+path if exists(dir+"/"+filename)]
if len(dirs) == 0: debug("pathname of file %r not found" % filename)
dir = dirs[0] if len(dirs) > 0 else "."
pathname = dir+"/"+filename
return pathname
def module_name():
from inspect import getmodulename,getfile
return getmodulename(getfile(lambda x: None))
def mtime(filename):
"""Modication timestamp of a file, in seconds since 1 Jan 1970 12:00 AM GMT"""
from os.path import getmtime
try: return getmtime(filename)
except: return 0 # file does not exist
def time_string(t):
"""Convert time in seconds to text.
E.g. 1 to "1s", 60 to "1 min" """
t = float(t)
if isnan(t): return ""
if t < 60: return "%g s" % t
if t < 60*60: return "%.3g min" % (t/60)
if t < 24*60*60: return "%.3g h" % (t/(60*60))
return "%g d" % (t/(24*60*60))
def seconds(s):
"""Convert time string to number in unit of seconds.
E.g. "1 min" to 60"""
s = s.replace("s","")
s = s.replace("min","*60")
s = s.replace("h","*60*60")
s = s.replace("d","*24*60*60")
try: return float(eval(s))
except: return nan
def main():
global app,win
app = wx.App(redirect=False)
win = DataLogger(name=module_name())
app.MainLoop()
log = Log()
if __name__ == "__main__":
##import logging; logging.basicConfig(level=logging.DEBUG)
main()
##start_new_thread (main,()) # use for debugging
<file_sep>#!/bin/env python
"""Setup:
source ~schotte/Software/Test/setup_env.sh
"""
from xppdaq import xppdaq
from time import time
from logging import info,warn,debug
run_template = "exp=xppj1216:run=%d:smd:dir=/reg/d/ffb/xpp/xppj1216/xtc:live"
Nimages = 20
Nevents = Nimages*12
xppdaq.configure(Nevents)
xppdaq.begin(Nevents)
run_number = xppdaq.runnumber()
xppdaq.wait()
xppdaq.disconnect()
run = run_template % run_number
print("acqired run: %s" % run)
from datastream import datastream
start = time()
image_id = "%s:%d" % (run,0)
print("getting image %r" % image_id)
img = datastream.image(image_id)
while img is None: datastream.image(image_id)
print("%s\n%s"%(img.shape,img[0:2,0:2]))
print("waited for %.1f s to get first image." % ((time()-start)))
<file_sep>"""
Instrumentation of the 14-ID beamline
Author: <NAME>
Date created: 2007-12-08
Data last modified: 2019-05-31
"""
__version__ = "3.8" # rayonix_detector
from pdb import pm
from refill import time_to_next_refill
from undulator import undulator
from EPICS_motor import motor # EPICS-controlled motors
from xray_attenuator import xray_attenuator
from timing_system import timing_system
from timing_sequencer import timing_sequencer
from Ensemble_SAXS import Ensemble_SAXS,Sequence,Sequences
from agilent_scope import agilent_scope
from lecroy_scope import lecroy_scope
from variable_attenuator import variable_attenuator
from ms_shutter import ms_shutter
# Had to comment this out because the id14b20 computer could not load it???? RH
from oasis_chiller import chiller
from omega_thermocouple import thermocouple
from sample_translation import sample_stage
from syringe_pump import syringe_pump
from sample_illumination import illuminator_on
from xray_safety_shutters import xray_safety_shutters_open,\
xray_safety_shutters_enabled, xray_safety_shutters_auto_open
from laser_safety_shutter import laser_safety_shutter_open,\
laser_safety_shutter_auto_open
from LokToClock import LokToClock
from CA import PV,caget
from combination_motor import tilt
from GigE_camera_client import Camera
from cavro_centris_syringe_pump_IOC import volume,port
from sample_frozen import sample_frozen
from freeze_intervention import freeze_intervention
from configuration import configuration,configurations,config,configs
from collect import collect
from diagnostics import diagnostics
# Machine
ring_current = PV("S:SRcurrentAI.VAL")
bunch_current = PV("BNCHI:BunchCurrentAI.VAL")
# Undulators
U23 = undulator("ID14ds")
U27 = undulator("ID14us")
# Motors in ID14-C optics hutch
# white beam slits (at 28 m)
Slit1H = motor("14IDA:Slit1Hsize",name="Slit1H",readback="14IDA:Slit1Ht2.C",readback_slop=0.002)
Slit1V = motor("14IDA:Slit1Vsize",name="Slit1V",readback="14IDA:Slit1Vt2.C",readback_slop=0.002)
# Heat-load chopper
HLC = motor("14IDA:m5",name="HLC")
# Vertical deflecting mirror incidence angle in units of mrad
# resolution 0.4 urad (Resolution of indidivual motors 0.2 um, distance 1 m)
mir1Th = motor("14IDC:mir1Th",name="mir1Th")
# Vertical beamstearing control, piezo DAC voltage (0-10 V)
MirrorV = motor("14IDA:DAC1_4",name="MirrorV",readback="VAL")
mir1bender = motor("14IDC:m6",name="mir1bender")
# Horizontal deflecting mirror incidence angle in units of mrad
##mir2Th = motor("14IDC:mir2Th") # unreliable, tends to hang
# Mirror individual jacks (distance 1.045 m)
mir2X1 = motor("14IDC:m12",name="mir2X1") # H mirror X1-upstream
mir2X2 = motor("14IDC:m13",name="mir2X2") # H mirror X1-downstream
mir2Th = tilt(mir2X1,mir2X2,distance=1.045,name="mir2Th",unit="mrad")
MirrorH = mir2Th
mir2bender = motor("14IDC:m14",name="mir2bender")
# Motors in ID14-B end station
# Table horizontal pseudo motor.
TableX = motor("14IDB:table1",name="TableX",command="X",readback="EX")
# Table vertical pseudo motor.
TableY = motor("14IDB:table1",name="TableY",command="Y",readback="EY")
# JJ1 slits (upstream)
s1vg = motor("14IDC:m37",name="s1vg") # JJ1 y aperture (vertical gap)
s1vo = motor("14IDC:m38",name="s1vo") # JJ1 y translation
s1hg = motor("14IDC:m39",name="s1hg") # JJ1 x aperture (horizontal gap)
s1ho = motor("14IDC:m40",name="s1ho") # JJ1 x translation
# High-speed X-ray Chopper
ChopX = motor("14IDB:m1",name="ChopX")
ChopY = motor("14IDB:m2",name="ChopY")
# JJ2 slits (downstream)
shg = motor("14IDB:m25",name="shg") # JJ2 x aperture (horizontal gap)
sho = motor("14IDB:m26",name="sho") # JJ2 x offset
svg = motor("14IDB:m27",name="svg") # JJ2 y aperture (vertical gap)
svo = motor("14IDB:m28",name="svo") # JJ2 y offset
# KB mirror
KB_Vpitch = motor("14IDC:pm4",name="KB_Vpitch")
KB_Vheight = motor("14IDC:pm3",name="KB_Vheight")
KB_Vcurvature = motor("14IDC:pm1",name="KB_Vcurvature")
KB_Vstripe = motor("14IDC:m15",name="KB_Vstripe") # <NAME> 2018-10-04
KB_Hpitch = motor("14IDC:pm8",name="KB_Hpitch")
KB_Hheight = motor("14IDC:pm7",name="KB_Hheight")
KB_Hcurvature = motor("14IDC:pm5",name="KB_Hcurvature")
KB_Hstripe = motor("14IDC:m44",name="KB_Hstripe") # <NAME> 2018-10-04
# Collimator
CollX = motor("14IDB:m35",name="CollX")
CollY = motor("14IDB:m36",name="CollY")
# Goniometer
from diffractometer import diffractometer # configurable by DiffractometerPanel.py
# Goniometer rotation
Phi = motor("14IDB:m151",name="Phi")
# Goniometer translations
GonX = motor("14IDB:m152",name="GonX")
GonY = motor("14IDB:m153",name="GonY")
GonZ = motor("14IDB:m150",name="GonZ")
# Sample-to-detector distance
DetZ = motor("14IDB:m3",name="DetZ")
# PIN diode in front of CCD detector
DetX = motor("14IDB:m33",name="DetX")
DetY = motor("14IDB:m34",name="DetY",readback_slop=0.030,min_step=0.030)
# readback_slop: otherwise Thorlabs motor gets hung in "Moving" state
# min_step: otherwise Thorlabs motor gets hung in "Moving" state"
# Channel cut scan photon "Energy" pseudo-motor (moves Phi aind DetY)
E = motor('14IDB:Energy_CC',name="E")
Energy = E
# Laser transfer line periscope mirrors in laser lab
PeriscopeH = motor("14IDLL:m6",name="PeriscopeH")
PeriscopeV = motor("14IDLL:m7",name="PeriscopeV")
# Laser focus translation
LaserX = motor("14IDB:m30",name="LaserX")
LaserY = motor("14IDB:m42",name="LaserY")
LaserZ = motor("14IDB:m31",name="LaserZ")
# 6-GHz oscilloscope in ID14-B experiments hutch
id14b_scope = agilent_scope("id14b-scope.cars.aps.anl.gov")
# X-ray diagnostics oscilloscope in ID14-B experiments hutch
xray_scope = lecroy_scope(name='xray_scope',
default_ip_address_and_port='id14b-xscope.cars.aps.anl.gov:2000')
id14b_xscope = xray_scope # for backward compatibility
xscope = xray_scope # shortcut
# ps laser diagnostics oscilloscope in laser hutch
laser_scope = lecroy_scope(name='laser_scope',
default_ip_address_and_port='id14l-scope.cars.aps.anl.gov:2000')
id14l_scope = laser_scope # for backward compatibility
lscope = laser_scope # shortcut
# Diagnostics oscilloscope in ID14-B control hutch
diagnostics_scope = lecroy_scope(name='diagnostics_scope',
default_ip_address_and_port='id14b-wavesurfer.cars.aps.anl.gov:2000')
id14b_wavesurfer = diagnostics_scope # for backward compatibility
# Online diagnostics:
#
# Setup required:
# Agilent 6-GHz oscilloscope in X-ray hutch:
# C1 = MSM detector, C2 = photodiode, C3 damaged, C4 = MCP-PMT,
# AUX(back) = trigger
# The first measurement needs to be defined as Delta-Time(2,3) with
# rising edge on C2 and falling edge in C3.
# The timing skews of each channel need to be set such the measured
# time delay is 0 when the nominal time delay is zero.
# The second measurement needs defined as Area(3).
#
# LeCroy oscilloscope in Control Hutch:
# C1 = I0 PIN diode reverse-biased, 50 Ohm, C4 = trigger
#
# LeCroy oscilloscope in Laser Lab:
# The photodiode signal from the X-ray hutch needs to be connected to
# channel 4.
# The first measurement needs to be defined as P1:area(C4) with a gate
# of about 60 ns around the pulse (360 ns delay from the trigger).
actual_delay= id14b_scope.measurement(1)
xray_pulse = xray_scope.measurement(1)
xray_trace = xray_scope.channel(1)
laser_pulse = laser_scope.measurement(1)
laser_trace = laser_scope.channel(4)
# X-ray area detector
from rayonix_detector_continuous import rayonix_detector
from rayonix_detector_client import rayonix_detector as rayonix_detector_client
rayonix_detector = rayonix_detector_client
ccd = xray_detector = rayonix_detector
# Sample temperature
from temperature import temperature
# Laser beam attenuator wheel in 14-ID Laser Lab
VNFilter1 = motor("14IDLL:m8",name="VNFilter1",readback_slop=0.030,min_step=0.030)
# readback_slop: otherwise Thorlabs motor gets hung in "Moving" state
# min_step: otherwise Thorlabs motor gets hung in "Moving" state"
# This filter is mounted such that when the motor is homed (at 0) the
# attuation is minimal (OD 0.04) and increasing to 2.7 when the motor
# moves in positive direction.
trans1 = variable_attenuator(VNFilter1,motor_range=[15,295],OD_range=[0,2.66])
trans1.motor_min=0
trans1.OD_min=0
trans1.motor_max=315
trans1.OD_max=2.66
# Laser beam attenuator wheel in 14ID-B X-ray hutch
VNFilter2 = motor("14IDB:m32",name="VNFilter2",readback_slop=0.1,min_step=0.050)
# readback_slop [deg]" otherwise Thorlabs motor gets hung in "Moving" state
# min_step [deg]" otherwise Thorlabs motor gets hung in "Moving" state"
# This filter is mounted such that when the motor is homed (at 0) the
# attuation is minimal (OD 0.04) and increasing to 2.7 when the motor
# moves in positive direction.
# Based on measurements by <NAME> and <NAME>, made 11 Nov 2014
# Recalibrated by <NAME> and <NAME> 2018-10-28
trans2 = variable_attenuator(VNFilter2,motor_range=[5,285],OD_range=[0,2.66])
trans2.motor_min=0
trans2.OD_min=0
trans2.motor_max=300
trans2.OD_max=2.66
trans = trans1 # alias for "lauecollect"
VNFilter = VNFilter1 # alias for "lauecollect"
# Fast NIH Diffractometer, Aerotech "Ensemble" controller, <NAME>, 30 Jan 2013
from Ensemble import SampleX,SampleY,SampleZ,SamplePhi,PumpA,PumpB,msShut
from Ensemble_triggered_motion import triggered_motion
from Ensemble import ensemble_motors,ensemble
from Ensemble_SAXS_pp import Ensemble_SAXS
##from Alio_pp import Ensemble_SAXS # Added by RH 2018-10-04
# NIH Peristalitc pump, <NAME> Nov 12, 2014
from peristaltic_pump import PumpA,PumpB,peristaltic_pump
# Cameras
microscope_camera = Camera("MicroscopeCamera")
widefield_camera = Camera("WideFieldCamera")
# Optical Scattering server
#optical_scattering = #added <NAME> May 23, 2019
# Dummy for compatibility of XPP
class xray_detector_trigger(object):
class count(object): value = 0
# Configurations
import configuration_driver
for n in configuration_driver.configuration.configuration_names:
try: exec("%s = configuration(%r,globals=globals())" % (n,n))
except: pass
##BioCARS_methods_testing = configuration("BioCARS_methods_testing",globals=globals()) # <NAME> 2018-10-04
<file_sep>import sys; sys.path = ["//Femto/C/All Projects/Software/TWAX/Hyun Sun"] + sys.path
from pdb import pm
from lecroy_scope_waveform import read_waveform
import inspect; print inspect.getfile(read_waveform)
filename = "/Data/2014.11/WAXS/HbCN/HbCN1/HbCN1_27_10ms_on_xray.trc"
t,U = read_waveform(filename)
from pylab import *
i = 0
Nplot = 2
plot(t[i:i+Nplot].T,U[i:i+Nplot].T,".",ms=5,mew=0)
grid()
xlabel("t [s]")
ylabel("U [V]")
ylim(-4,4)
show()
<file_sep>XRayDetectorInserted.action = {
False: 'control.det_retracted = True',
True: 'control.det_inserted = True'}
XRayDetectorInserted.defaults = {
'Enabled': False, 'Label': 'Inserted [Withdrawn]'
}
XRayDetectorInserted.properties = {
'BackgroundColour': [
('green', 'control.det_inserted == True'),
('yellow', 'control.det_retracted == True'),
('red', 'control.det_inserted == control.det_retracted')
],
'Enabled': [(True, 'control.det_inserted in [True,False]')],
'Value': [
(True, 'control.det_inserted == True'),
(False, 'control.det_retracted == True')
],
'Label': [
('Inserted', 'control.det_inserted == True'),
('Retracted', 'control.det_retracted == True'),
('Insert', 'control.det_inserted == control.det_retracted')
]
}
GotoSaved.action = {True: 'control.centered = True'}
GotoSaved.defaults = {"Enabled":False}
GotoSaved.properties = {
'Label': [
("Go To Saved XYZ Position","control.centered == False"),
("At Saved XYZ Position","control.centered == True"),
],
'Enabled': 'control.centered == False and control.stage_online and not control.scanning',
'BackgroundColour': [
("red","control.stage_enabled == False"),
],
}
Save.action = {True: 'control.define_center()'}
Save.defaults = {"Enabled":False}
Save.properties = {
'Label': '"Save Current XYZ Position"',
'Enabled': 'control.centered == False and control.stage_online and not control.scanning',
}
Inserted.action = {
False: 'control.retracted = True',
True: 'control.inserted = True',
}
Inserted.defaults = {'Label': 'Insert/Retract'}
Inserted.properties = {
'BackgroundColour': [
('green', 'control.inserted == True'),
('yellow', 'control.retracted == True'),
],
'Enabled': 'not control.scanning',
'Value': [
(True, 'control.inserted == True'),
(False, 'control.retracted == True'),
],
'Label': [
('Inserted', 'control.inserted == True'),
('Retracted', 'control.retracted == True'),
('Insert', 'control.inserted == control.retracted'),
]
}
StepSize.value = 'control.image_scan.stepsize'
StepSize.scale = 1000
StepSize.format = '%g'
StepSize.properties = {'Enabled':'not control.scanning'}
HorizontalRange.value = 'control.image_scan.width'
HorizontalRange.scale = 1000
HorizontalRange.format = '%g'
HorizontalRange.properties = {'Enabled':'not control.scanning'}
VerticalRange.value = 'control.image_scan.height'
VerticalRange.scale = 1000
VerticalRange.format = '%g'
VerticalRange.properties = {'Enabled':'not control.scanning'}
StartRasterScan.action = {
True: 'control.scanning = True',
False:'control.scanning = False',
}
StartRasterScan.defaults = {"Enabled":False}
StartRasterScan.properties = {
"Label": [
("Start Raster Scan","not control.scanning"),
("Cancel Raster Scan","control.scanning"),
],
"Value": [
(False, "control.scanning == False"),
(True, "control.scanning == True"),
],
"Enabled": [
(True, "control.stage_online or control.scanning"),
],
"BackgroundColour": [
("red","control.stage_enabled == False"),
],
}
CrystalCoordinates.value = "control.crystal_coordinates"
Initialize.action = {True: 'control.init()'}
Initialize.properties = {'Enabled': 'control.pump_online'}
Flow.action = {
True: 'control.flowing = True',
False: 'control.flowing = False',
}
Flow.properties = {
'Enabled': 'control.pump_online',
'Value': 'control.flowing',
'Label': [
('Resume Flow','not control.flowing'),
('Suspend Flow','control.flowing'),
],
"BackgroundColour": [("green","control.flowing")],
}
Inject.action = {
True: 'control.injecting = True',
False: 'control.injecting = False',
}
Inject.properties = {
'Enabled': 'control.pump_online',
'Value': 'control.injecting',
'Label': '("Inject %s" if not control.injecting else "Cancel Inject %s") % control.inject_count'
}
MotherLiquorSyringeRefill.action = {
True: 'control.mother_liquor_refilling = True',
False: 'control.mother_liquor_refilling = False',
}
MotherLiquorSyringeRefill.properties = {
'Enabled': 'control.pump_online',
'Value': 'control.mother_liquor_refilling',
'Label': [
('Refill','not control.mother_liquor_refilling'),
('Cancel Refill','control.mother_liquor_refilling'),
],
}
MotherLiquorSyringeVolume.value = 'control.mother_liquor.value'
MotherLiquorSyringeVolume.properties = {'Enabled': 'control.pump_online'}
MotherLiquorSyringeStepsize.value = 'control.mother_liquor_dV'
MotherLiquorSyringeStepsize.properties = {'Enabled': 'True'}
CrystalLiquorSyringeRefill.action = {
True: 'control.crystal_liquor_refilling = True',
False: 'control.crystal_liquor_refilling = False',
}
CrystalLiquorSyringeRefill.properties = {
'Enabled': 'control.pump_online',
'Value': 'control.crystal_liquor_refilling',
'Label': [
('Refill','not control.crystal_liquor_refilling'),
('Cancel Refill','control.crystal_liquor_refilling'),
],
}
CrystalLiquorSyringeVolume.value = 'control.crystal_liquor.value'
CrystalLiquorSyringeVolume.properties = {'Enabled': 'control.pump_online'}
CrystalLiquorSyringeStepsize.value = 'control.crystal_liquor_dV'
CrystalLiquorSyringeStepsize.properties = {'Enabled': 'True'}
UpstreamPressure.value = 'control.upstream_pressure.value'
UpstreamPressure.format = '%.4f'
UpstreamPressure.properties = {'Enabled': 'True'}
DownstreamPressure.value = 'control.downstream_pressure.value'
DownstreamPressure.format = '%.4f'
DownstreamPressure.properties = {'Enabled': 'True'}
Image.properties = {
'Image': 'control.camera.RGB_array',
'ScaleFactor': '0.275',
'Mirror': 'True',
'Orientation': '0',
}
AcquireImage.properties = {'Enabled': 'True'}
ImageRootName.value = 'control.image_rootname'
ImageRootName.properties = {'Enabled': 'True'}
SaveImage.action = {True: 'control.save_image()'}
SaveImage.properties = {'Enabled': 'True'}
time = 1533775661.236139<file_sep>from socket import socket
from select import select
from time import sleep
def test():
global s
s=socket()
s.setblocking(False)
errno = s.connect_ex(("127.0.0.1",5064))
sel = select([s],[s],[s],0)
print errno,sel
sleep(1)
print select([s],[s],[s],0)
##>>> test()
##10035 ([], [], [])
##([], [], [<socket._socketobject object at 0x00CCEA08>])
##>>> test()
##10035 ([], [<socket._socketobject object at 0x00CCE9D0>], [])
##([], [<socket._socketobject object at 0x00CCE9D0>], [])
##>>> test()
##10035 ([], [], [])
##([], [], [<socket._socketobject object at 0x00CCEA08>])
if __name__ == "__main__":
print("test()")
<file_sep>"""
Remote control of thermoelectric chiller by Solid State Cooling Systems,
www.sscooling.com, via RS-323 interface
Model: Oasis 160
See: Oasis Thermoelectric Chiller Manual, Section 7 "Oasis RS-232
communication", p. 15-16
Settings: 9600 baud, 8 bits, parity none, stop bits 1, flow control none
DB09 connector pin 2 = TxD, 3 = RxD, 5 = Ground
The controller accepts binary commands and generates binary replies.
Commands are have the length of one to three bytes.
Replies have a length of either one or two bytes, depending on the command.
Command byte: bit 7: remote control active (1 = remote control,0 = local control)
bit 6 remote on/off (1 = Oasis running, 0 = Oasis in standby mode)
bit 5: communication direction (1 = write,0 = read)
bits 4-0: 00001: [1] Set-point temperature (followed by 2 bytes: temperature in C * 10)
00110: [6] Temperature low limit (followed by 2 bytes: temperature in C * 10)
00111: [7] Temperature high limit(followed by 2 bytes: temperature in C * 10)
01000: [8] Faults (followed by 1 byte)
01001: [9] Actual temperature (followed by 2 bytes: temperature in C * 10)
The 2-byte value is a 16-bit binary number enoding the temperature in units
of 0.1 degrees Celsius (range 0-400 for 0-40.0 C)
The fault byte is a bit map (0 = OK, 1 = Fault):
bit 0: Tank Level Low
bit 2: Temperature above alarm range
bit 4: RTD Fault
bit 5: Pump Fault
bit 7: Temperature below alarm range
Undocumented commands:
C6: Receive the lower limit. (should receive back C6 14 00)
E6 14 00: Set set point low limit to 2C
C7: Receive the upper limit. (should receive back C7 C2 01)
E7 C2 01: Set set point high limit to 45C
E-mail by <NAME> <<EMAIL>>, May 31, 2016,
"RE: Issue with Oasis 160 (S/N 8005853)"
Cabling:
"NIH-Instrumentation" MacBook Pro -> 3-port USB hub ->
"ICUSB232 SM3" UBS-Serial cable -> Oasis chiller
Setup to run IOC:
Windows 7 > Control Panel > Windows Firewall > Advanced Settings > Inbound Rules
> New Rule... > Port > TCP > Specific local ports > 5064-5070
> Allow the connection > When does the rule apply? Domain, Private, Public
> Name: EPICS CA IOC
Inbound Rules > python > General > Allow the connection
Inbound Rules > pythonw > General > Allow the connection
Authors: <NAME>, <NAME>, <NAME>
Date created: 2009-05-28
Date last modified: 2018-10-15 <NAME>
"""
from struct import pack,unpack
from numpy import nan,rint,isnan
from logging import error,warn,info,debug
import sys
if sys.version[0] == '3':
from _thread import allocate_lock
else:
from thread import allocate_lock
__lock__ = allocate_lock()
__version__ = "2.1" # fault code
class OasisChillerDriver(object):
"""Oasis thermoelectric chiller by Solid State Cooling Systems"""
name = "oasis_chiller"
timeout = 1.0
baudrate = 9600
id_query = "A"
id_reply_length = 3
wait_time = 0 # bewteen commands
last_reply_time = 0.0
last_command_execution_time = 0.0
# Make multithread safe
ser = None
def __init__(self):
pass
def init(self):
self.init_communications()
def close(self):
self.ser.close()
self.ser = None
def init_communications(self):
"""To do before communncating with the controller"""
from os.path import exists
from serial import Serial
import serial.tools.list_ports
if self.ser is not None:
try:
info("Checking whether device is still responsive...")
self.ser.write(self.id_query)
debug("%s: Sent %r" % (self.ser.name,self.id_query))
reply = self.read(count=self.id_reply_length)
if not self.id_reply_valid(reply):
debug("%s: %r: invalid reply %r" % (self.ser.name,self.id_query,reply))
info("%s: lost connection" % self.ser.name)
self.ser = None
else: info("Device is still responsive.")
except Exception as msg:
debug("%s: %s" % (Exception,msg))
self.ser = None
if self.ser is None:
devices = serial.tools.list_ports.comports()
debug('devices: %r' % devices)
for item in devices:
debug('device: %r' % item)
try:
ser = Serial(item.device,baudrate=self.baudrate)
ser.write(self.id_query)
debug("%s: Sent %r" % (ser.name,self.id_query))
reply = self.read(count=self.id_reply_length,ser=ser)
if self.id_reply_valid(reply):
self.ser = ser
info("Discovered device at %s based on reply %r" % (self.ser.name,reply))
break
except Exception as msg:
debug("%s: %s" % (Exception,msg))
if self.ser is not None: break
def query(self,command = None,count=1,ser = None):
"""Send a command to the controller and return the reply"""
from time import time
from time import sleep
if ser is None:
ser = self.ser
if ser is not None:
t1 = time()
self.write(command)
i = 0
while self.waiting(ser)[0] != count:
if i >int(self.timeout/0.015):
break
sleep(0.015)
i+=1
reply = self.read(ser = ser,count=count)
t2 = time()
self.last_command_execution_time = t2-t1
self.last_reply_time = time()
else:
reply = ''
return reply
def write(self,command,ser = None):
"""Send a command to the controller"""
if ser is None:
ser = self.ser
if ser is not None:
self.flush(ser = ser)
ser.write(command)
debug("%s: Sent %r" % (ser.name,command))
def read(self,count=None, ser = None):
"""Read a reply from the controller,
terminated with the given terminator string"""
from time import time
##debug("read count=%r,ser=%r" % (count,ser))
if ser is None:
ser = self.ser
if ser is not None:
#print("in wait:" + str(self.ser.inWaiting()))
debug("Trying to read %r bytes from %s..." % (count,ser.name))
ser.timeout = self.timeout
reply = ser.read(count)
debug("%s: Read %r" % (ser.name,reply))
self.last_reply_time = time()
else: reply = ""
return reply
def flush(self, ser = None):
if ser is not None:
ser.flushInput()
ser.flushOutput()
def waiting(self, ser = None):
if ser is None:
ser = self.ser
if ser is not None:
value = (driver.ser.in_waiting,driver.ser.out_waiting)
else:
value = None
return value
def id_reply_valid(self,reply):
valid = reply.startswith("A") and len(reply) == 3
debug("Reply %r valid? %r" % (reply,valid))
return valid
def get_nominal_temperature(self):
"""Temperature set point"""
debug("Getting nominal temperature...")
value = self.get_value(1)/10.
if not isnan(value): debug("Nominal temperature %r C" % value)
else: warn("Nominal temperature unreadable")
return value
def set_nominal_temperature(self,value): self.set_value(1,value*10)
nominal_temperature = property(get_nominal_temperature,set_nominal_temperature)
VAL = nominal_temperature
@property
def actual_temperature(self):
"""Temperature read value"""
debug("Getting actual temperature...")
value = self.get_value(9)/10.
if not isnan(value): debug("Actual temperature %r C" % value)
else: warn("Actual temperature unreadable")
return value
RBV = actual_temperature
def get_low_limit(self):
"""Not supported early firmware (serial number 1)"""
debug("Getting low limit...")
value = self.get_value(6)/10.
if not isnan(value): info("Low limit %r C" % value)
else: warn("Low limit unreadable (old firmware?)")
return value
def set_low_limit(self,value): self.set_value(6,value*10)
low_limit = property(get_low_limit,set_low_limit)
LLM = low_limit
def get_high_limit(self):
"""Not supported early firmware (serial number 1)"""
debug("Getting high limit...")
value = self.get_value(7)/10.
if not isnan(value): info("High limit %r C" % value)
else: warn("High limit unreadable (old firmware?)")
return value
def set_high_limit(self,value): self.set_value(7,value*10)
high_limit = property(get_high_limit,set_high_limit)
HLM = high_limit
def get_PID(self):
"""get PID parameters"""
from time import sleep
dic = {}
res_dic = {}
try:
dic['p1'] = ('\xd0',3)
except:
dic['p1'] = nan
try:
dic['i1'] = ('\xd1',3)
except:
dic['p1'] = nan
try:
dic['d1'] = ('\xd2',3)
except:
dic['p1'] = nan
try:
dic['p2'] = ('\xd3',3)
except:
dic['p1'] = nan
try:
dic['i2'] = ('\xd4',3)
except:
dic['p1'] = nan
try:
dic['d2'] = ('\xd5',3)
except:
dic['p1'] = nan
for key in dic.keys():
res = self.query(command = dic[key][0], count = dic[key][1])
if res is not nan:
res_dic[key] = unpack('H',res[1]+res[2])
else:
res = nan
sleep(0.1)
return res_dic
def set_factory_PID(self):
pid_dic = {}
#factory settings: good settings
pid_dic['p1'] = 90
pid_dic['i1'] = 32
pid_dic['d1'] = 2
pid_dic['p2'] = 50
pid_dic['i2'] = 35
pid_dic['d2'] = 3
dic = {}
dic['p1'] = '\xf0'
dic['i1'] = '\xf1'
dic['d1'] = '\xf2'
dic['p2'] = '\xf3'
dic['i2'] = '\xf4'
dic['d2'] = '\xf5'
for key in pid_dic.keys():
byte_temp = pack('h',round(pid_dic[key],0))
self.query(command = dic[key]+byte_temp,count = 1)
sleep(0.1)
def set_PID(self, pid_in = {}):
"""
sets PID parameters.
input as dictionary with keys p1,i1,d1,p2,i2,d2
"""
try:
dic = {}
dic['p1'] = '\xf0'
dic['i1'] = '\xf1'
dic['d1'] = '\xf2'
dic['p2'] = '\xf3'
dic['i2'] = '\xf4'
dic['d2'] = '\xf5'
for key in pid_in.keys():
byte_temp = pack('h',round(pid_in[key],0))
self.query(command = dic[key]+byte_temp,count = 1)
sleep(0.1)
except:
error('Oasis driver set_PID wrong input dictionary structure')
@property
def port_name(self):
"""Serial port name"""
if self.ser is None: value = ""
else: value = self.ser.name
return value
COMM = port_name
@property
def connected(self): return self.ser is not None
@property
def online(self):
if self.ser is None: self.init_communications()
online = self.ser is not None
if online: debug("Device online")
else: warn("Device offline")
return online
@property
def fault_code(self):
"""Report faults as number
bit 0: Tank Level Low
bit 2: Temperature above alarm range
bit 4: RTD Fault
bit 5: Pump Fault
bit 7: Temperature below alarm range
"""
from numpy import nan
debug("Getting faults...")
code = int("01001000",2)
command = pack('B',code)
reply = self.query(command,count=2)
fault_code = nan
# The reply is 0xC8 followed by a faults status byte.
if len(reply) != 2:
if len(reply)>0:
warn("%r: expecting 2-byte reply, got %r" % (command,reply))
elif self.connected:
warn("%r: expecting 2-byte reply, got no reply" % command)
else:
reply_code,fault_code = unpack('<BB',reply)
if reply_code != code:
warn("reply %r: expecting 0x%X(%s), got 0x%X(%s)" %
(reply,code,bin(code),reply_code,bin(reply_code)))
fault_code = nan
if fault_code == 2.0**7:
fault_code = 8
elif fault_code == 2.0**6:
fault_code = 7
elif fault_code == 2.0**5:
fault_code = 6
elif fault_code == 2.0**4:
fault_code = 5
elif fault_code == 2.0**3:
fault_code = 4
elif fault_code == 2.0**2:
fault_code = 3
elif fault_code == 2.0**1:
fault_code = 2
elif fault_code == 2.0**0:
fault_code = 1
elif fault_code == 0:
fault_code = 0
else:
fault_code = -1
debug("Fault code %s" % fault_code)
return fault_code
@property
def faults(self):
"""Report list of faults as string"""
debug("Getting faults...")
code = int("01001000",2)
command = pack('B',code)
reply = self.query(command,count=2)
faults = " "
# The reply is 0xC8 followed by a faults status byte.
if len(reply) != 2:
if len(reply)>0:
warn("%r: expecting 2-byte reply, got %r" % (command,reply))
elif self.connected:
warn("%r: expecting 2-byte reply, got no reply" % command)
else:
reply_code,bits = unpack('<BB',reply)
if reply_code != code:
warn("reply %r: expecting 0x%X(%s), got 0x%X(%s)" %
(reply,code,bin(code),reply_code,bin(reply_code)))
else:
fault_names = {0:"Tank Level Low",2:"Temperature above alarm range",
4:"RTD Fault",5:"Pump Fault",7:"Temperature below alarm range"}
faults = ""
for i in range(0,8):
if (bits >> i) & 1:
if i in fault_names: faults += fault_names[i]+", "
else: faults += str(i)+", "
faults = faults.strip(", ")
if faults == "": faults = "none"
debug("Faults %s" % faults)
return faults
def get_value(self,parameter_number):
"""Read a 16-bit value
parameter_number: 1-15 (1=set point, 6=low limit, 7=high limit, 9=coolant temp.)
"""
code = int("01000000",2) | parameter_number
command = pack('B',code)
reply = self.query(command = command,ser = self.ser,count=3)
# The reply is 0xC1 followed by 1 16-bit binary count on little-endian byte
# order. The count is the temperature in degrees Celsius, times 10.
if len(reply) != 3:
if len(reply)>0:
warn("%r: expecting 3-byte reply, got %r" % (command,reply))
elif self.connected:
warn("%r: expecting 3-byte reply, got no reply" % command)
return nan
reply_code,count = unpack('<BH',reply)
if reply_code != code:
warn("reply %r: expecting 0x%X(%s), got 0x%X(%s)" %
(reply,code,bin(code),reply_code,bin(reply_code)))
return nan
return count
def set_value(self,parameter_number,value):
"""Set a 16-bit value"""
code = int("01100000",2) | parameter_number
command = pack('<BH',code,int(rint(value)))
reply = self.query(command = command,ser = self.ser, count=1)
if len(reply) != 1:
warn("expecting 1, got %d bytes" % len(reply)); return
reply_code, = unpack('B',reply)
if reply_code != code: warn("expecting 0x%X, got 0x%X" % (code,reply_code))
driver = OasisChillerDriver()
if __name__ == "__main__": # for testing
import logging
from time import sleep, time
logging.basicConfig(level=logging.INFO,
format="%(asctime)s %(levelname)s: %(message)s")
self = driver #for debugging
<file_sep>"""
A propery object to be used inside a class
Author: <NAME>
Date created: 2018-11-01
Date last modified: 2019-03-06
"""
from logging import debug,warn,info,error
__version__ = "2.0.1" # debug messages
def thread_property(method):
"""A property representing an task to be run in background"""
name = method.__name__
thread_name = name+"_thread"
cancelled_name = name+"_cancelled"
def get_running(self):
thread = getattr(self,thread_name,None)
return thread is not None and thread.isAlive()
def set_running(self,running_requested):
running = get_running(self)
if running_requested and not running:
from threading import Thread
thread = Thread(target=run,args=(self,),name=thread_name)
thread.daemon = True
setattr(self,thread_name,thread)
setattr(self,cancelled_name,False)
thread.start()
if not running_requested and running:
setattr(self,cancelled_name,True)
def run(self):
debug("Starting %s..." % name)
method(self)
debug("%s finished" % name)
running = property(get_running,set_running)
return running
if __name__ == "__main__":
from pdb import pm
class Test(object):
@thread_property
def running(self):
from time import time,sleep
t0 = time()
while time()-t0 < 10 and not self.running_cancelled:
sleep(0.1)
test = Test()
print("test.running = True")
print("test.running")
print("test.running = False")
<file_sep>#!/usr/bin/env python
from CA import Record,caget,caput,cainfo
from numpy import *
from time import sleep,time
from logging import info
import logging; logging.basicConfig(level=logging.INFO)
array_test = Record("NIH:TEST")
ensemble = Record("NIH:ENSEMBLE")
def assign_element(record,name,index,value):
t0 = time()
x = getattr(record,name)
while x is None: x = getattr(record,name); sleep(0.1)
x[index] = value
setattr(record,name,x)
while not nan_equal(getattr(record,name),x): sleep(0.1)
info("%s.%s[%d]=%r: %.3f s" % (record,name,index,value,time()-t0))
def nan_equal(a,b):
"""Are two arrays containing nan identical, assuming nan == nan?"""
from numpy import asarray
from numpy.testing import assert_equal
a,b = asarray(a),asarray(b)
try: assert_equal(a,b)
except: return False
return True
print 'array_test.X'
print 'array_test.X = ones(len(test.X))'
print 'assign_element(test,"X",-1,-0.9)'
print 'assign_element(test,"Y",-1,-1)'
print 'assign_element(ensemble,"floating_point_registers",-1,-0.9)'
print 'assign_element(ensemble,"integer_registers",-1,-4)'
<file_sep>filename = '//mx340hs/data/anfinrud_1903/Archive/NIH.temperature_hutch.txt'<file_sep>CustomView = ['Image', 'Image filename', 'ROI width [mm]', 'Saturation level']
ROI_width = 4.0
TimeChart.time_window = 172800.0
auto_update = True
average_samples = 1
filename_filter = ''
history_filter = ''
history_length = 2000
log.filename = '//mx340hs/data/anfinrud_1707/Logfiles/xray_beam_stabilization-1.log'
saturation_level = 200
view = 'Custom'
x_ROI_center = 175.74
x_gain = 0.14285714285714285
x_nominal = 176.147
y_ROI_center = 173.8
y_nominal = 174.174<file_sep>title = 'Sequence Configuration'
nrows = 14
row_height = 40
motor_names = ['Ensemble_SAXS.acquisition_sequence', 'Ensemble_SAXS.sequence']
names = ['acquisition', 'idle']
motor_labels = ['acquisition', 'idle']
widths = [200, 200]
description_width = 100
line0.description = 'NIH:i1'
line1.description = 'NIH:i3'
line2.description = 'NIH:i5c1'
line3.description = 'NIH:i15'
line4.description = 'NIH:i24c1'
line5.description = 'NIH:i1_no_laser'
line6.description = 'NIH:TR-SAXS'
line0.Ensemble_SAXS.acquisition_sequence = 'enable=111'
line0.Ensemble_SAXS.sequence = 'enable=111'
line0.updated = '2019-06-01 07:12:06'
line1.Ensemble_SAXS.acquisition_sequence = 'enable=[011]*2+[111], circulate=[1]'
line1.Ensemble_SAXS.sequence = 'enable=[011]*2+[111]'
line1.updated = '2019-03-24 13:05:27'
line2.Ensemble_SAXS.acquisition_sequence = 'enable=[011]*4+[111], circulate=[0]*4+[1]'
line2.Ensemble_SAXS.sequence = 'enable=[011]*4+[111], circulate=[0]*4+[1]'
line2.updated = '18 Oct 21:30'
line3.Ensemble_SAXS.acquisition_sequence = 'enable=[011]*14+[111]'
line3.Ensemble_SAXS.sequence = 'enable=[011]*14+[111]'
line3.updated = '2019-02-01 02:15:34'
line4.Ensemble_SAXS.acquisition_sequence = 'enable=[011]*23+[111], circulate=[0]*23+[1]'
line4.Ensemble_SAXS.sequence = 'enable=[011]*23+[111], circulate=[0]*23+[1]'
line4.updated = '18 Oct 21:30'
line5.Ensemble_SAXS.acquisition_sequence = 'enable=101'
line5.Ensemble_SAXS.sequence = 'enable=101'
line5.updated = '18 Oct 22:06'
line6.Ensemble_SAXS.acquisition_sequence = 'enable=101,circulate=0'
line6.Ensemble_SAXS.sequence = 'enable=100'
line6.updated = '18 Oct 22:59'
command_row = 0
show_define_buttons = True
line7.description = 'NIH:Laser_on/off'
line7.updated = '26 Oct 01:51'
line7.Ensemble_SAXS.acquisition_sequence = 'enable=111'
line7.Ensemble_SAXS.sequence = 'enable=101'
line8.description = 'NIH:i1c1w9'
line8.Ensemble_SAXS.acquisition_sequence = 'enable=[111]+[000]*9, circulate=[1]*1+[0]*9'
show_stop_button = False
line8.Ensemble_SAXS.sequence = 'enable=[111]+[000]*9, circulate=[1]*1+[0]*9'
line8.updated = '31 Oct 21:58'
line9.description = 'Rayonix start'
line9.Ensemble_SAXS.acquisition_sequence = 'circulate=[0]'
line9.Ensemble_SAXS.sequence = 'circulate=[0]'
line10.Ensemble_SAXS.acquisition_sequence = 'enable=[111]+[101]*7, circulate=[1]+[0]*7'
line10.Ensemble_SAXS.sequence = 'enable=[111]+[101]*7, circulate=[1]+[0]*7'
line10.updated = '03 Nov 01:30'
line10.description = 'NIH:e8'
command_rows = [13]
line11.Ensemble_SAXS.acquisition_sequence = 'enable=[011]*3+[111]'
line11.updated = '2019-01-30 18:51:28'
line11.Ensemble_SAXS.sequence = 'enable=[011]*3+[111]'
line11.description = 'NIH:i4'
line12.Ensemble_SAXS.acquisition_sequence = 'enable=[011]*4+[111]'
line12.updated = '2019-03-17 00:19:42'
line12.Ensemble_SAXS.sequence = 'enable=[011]*4+[111]'
line12.description = 'NIH:i5'
line13.Ensemble_SAXS.acquisition_sequence = 'enable=[011]*1+[111], circulate=[1]'
line13.updated = '2019-06-01 22:16:39'
line13.Ensemble_SAXS.sequence = 'enable=[011]*1+[111]'
line13.description = 'NIH:i2'<file_sep>from ctypes import windll,byref,c_void_p,c_int,c_long,c_double,POINTER,ARRAY
filename = "EnsembleC.dll"
EnsembleC = windll.LoadLibrary(filename)
handles = POINTER(c_void_p)()
handle_count = c_int()
EnsembleC.EnsembleConnect(byref(handles),byref(handle_count))
assert handle_count.value == 1
handle = handles.contents
c_value = c_double()
EnsembleC.EnsembleRegisterDoubleGlobalRead(handle,c_int(0),byref(c_value))
value = c_value.value
value += 1
EnsembleC.EnsembleRegisterDoubleGlobalWrite(handle,c_int(0),c_double(value))
EnsembleC.EnsembleRegisterDoubleGlobalRead(handle,c_int(0),byref(c_value))
value = c_value.value
axis_number = 2 # 0=X,1=Y,2=Z,3=PHI
c_position = c_double()
PositionFeedback = 1
EnsembleC.EnsembleStatusGetItem(handle,c_int(axis_number),
c_int(PositionFeedback),byref(c_position))
position = c_position.value
position += 0.001
speed = 10.0
axis_mask = (1 << axis_number)
positions = ARRAY(c_double,1)(position)
speeds = ARRAY(c_double,1)(speed)
EnsembleC.EnsembleMotionMoveAbs(handle,c_int(axis_mask),positions,speeds)
<file_sep># -*- coding: utf-8 -*-
"""
Author: <NAME>, <NAME>, <NAME>
Date created: 12/8/2016
Date last modified: 10/17/2017
2017-06-02 1.5 Adapted for 3-way injection port
2017-10-06 1.6 Friedrich, Using IOC
2017-10-17 1.7 Brian, Friedrich, refill_1, refill_3
Setup:
Start desktop shortcut "Centris Syringe IOC"
(Target: python cavro_centris_syringe_pump_IOC.py run_IOC
Start in: %LAUECOLLECT%)
"""
__version__ = "1.7"
from time import sleep,time
from logging import debug,info,warn,error
from thread import start_new_thread
from pdb import pm
from tempfile import gettempdir
from cavro_centris_syringe_pump_IOC import volume,port as valve
volume1,volume2,volume3,volume4 = volume
valve1,valve2,valve3,valve4 = valve
# Assign default parameters.
Vol = {1:250,2:250,3:250,4:250} # Volumes of syringes.
Backlash = 100 # Backlash in increments.
V_prime = 25 # Volume needed to purge 2.3 m tubing (49 uL/m).
V_purge = 115 # Volume needed to purge 2.3 m tubing (49 uL/m).
V_inflate = 2 # Volume used to inflate tubing.
V_deflate = 2 # Volume used to deflate tubing.
V_clean = 4.0 # Volume used to advance dlivered xtal droplet
V_flush = 4.0 # Volume used to flush collapsible tubing.
V_injectX = 0.2 # Volume used to advance dlivered xtal droplet
V_injectM = 0.3 #Volume of mother liqour during inject
V_injectR = 0.2 # Volume desired for xtal delivery
V_droplet = 1 #Volume used to load droplets into cappilary
V_plug = 5 #Volume of fluorinert to remove protien from channels
S_pressure = 250 # Speed used to change pressure.
S_load = 50 # Speed used to load syringes.
S_prime = 20 # Speed used to prime capillaries.
S_flush = 68 # Speed used to flush collapsible tubing.
S_flow = 0.07 # Speed used to flow through collapsible tubing.
S_min = 0.002 # Minimum Speed available.
S_flowIX = 1.0 # Speed used for injection of xtals
S_flowIM = 0.5 #Speed of flow for injection cycle
S_flowRV = 0.75 #Speed of flow for reverse part of injection cycle
S_flowS1 = 0.05 #Speed used for small droplet generation
port = [1,2,3,4]
class PumpController(object):
def write_read(self, command_dict):
"""Writes commands to multiple pumps with pump ids and commands assembled in a dictionary.
Returns a dictionary of pump ids and their respective responses."""
from cavro_centris_syringe_pump_IOC import pump_controller
return pump_controller.write_read(command_dict)
def assign_pids(self):
"""Assigns pump id to each syringe pump according to dictionary; since
pump ids are written to non-volatile memory, need only execute once."""
self.write_read({1: "/1s0ZA1R\r",
2: "/1s0ZA2R\r",
3: "/1s0ZA3R\r",
4: "/1s0ZA4R\r"})
def syringe_setup(self):
"""Specifies the syringe volumes for each pump in the dictionary of
pumps. The command takes effect after power cycling the pumps, and
need only be executed once."""
# U93, U94, U90, U95 -> 50, 100, 250, 500 uL
self.write_read({1: "/1U90R\r",
2: "/1U90R\r",
3: "/1U90R\r",
4: "/1U90R\r"})
def move_abs(self,pid,position,speed=25):
"""Move plunger of pump[pid] to absolute position."""
if 0 <= position <= Vol[pid]:
self.write_read({pid: "".join(["/1J2V",str(speed),",1A",str(position),",1J0R\r"])})
else:
info('Position outside of absolute usable range: 0 <= position <= %r' % Vol[pid])
def move_rel(self,pid,position,speed=25):
"""Move plunger of pump[pid] to relative position."""
current = self.positions()[pid]
if 0 <= current + position <= Vol[pid]:
if position < 0:
position = abs(position)
self.write_read({pid: "".join(["/1J2V",str(speed),",1D",str(position),",1J0R\r"])})
else:
self.write_read({pid: "".join(["/1J2V",str(speed),",1P",str(position),",1J0R\r"])})
else:
info('Position outside of absolute usable range: 0 <= position <= %r' % Vol[pid])
def reset(self, *pid):
"""Performs a soft reset on pumps by passing pid number. if left blank, all pumps will soft reset."""
if len(pid) == 0:
pid = (1,2,3,4)
for i in pid:
self.write_read({pid: "/1!R\r" for pid in port})
def abort(self):
"""Terminates all pump motion and resets J to 0."""
self.write_read({pid: "/1TR\r" for pid in port})
self.write_read({pid: "/1J0R\r" for pid in port})
def init(self):
"""Initializes pumps, sets Backlash, loads syringes, and leaves valves set to "O"."""
t0 = time()
self.write_read({pid: "/1TR\r" for pid in port})
info("Executing init...")
info(" emptying syringes...")
self.write_read({1: "".join(["/1Y7,0,0IV",str(S_load),",1K",str(Backlash),"A0,1R\r"]),
2: "".join(["/1Z7,0,0IV",str(S_load),",1K",str(Backlash),"A0,1R\r"]),
3: "".join(["/1Y7,0,0IV",str(S_load),",1K",str(Backlash),"A0,1R\r"]),
4: "".join(["/1Z7,0,0IV",str(S_load),",1K",str(Backlash),"A0,1R\r"])})
while self.busy(1,2,3,4): sleep(0.1)
info(" filling syringes...")
self.write_read({1: "".join(["/1A",str(Vol[1]),",1R\r"]),
2: "".join(["/1A",str(Vol[2]),",1R\r"]),
3: "".join(["/1A",str(Vol[3]),",1R\r"]),
4: "".join(["/1A",str(Vol[4]),",1R\r"])})
while self.busy(1,2,3,4): sleep(0.1)
info(" emptying syringes...")
self.write_read({1: "".join(["/1A0,1R\r"]),
2: "".join(["/1A0,1R\r"]),
3: "".join(["/1A0,1R\r"]),
4: "".join(["/1A0,1R\r"])})
while self.busy(1,2,3,4): sleep(0.1)
info(" syringes are initialized, primed, and ready to load.")
info(" time to init (s): %r" % (time()-t0))
def prime(self):
"""Fills capillaries 1 with fluorinert and 3 with oil."""
t0 = time()
self.write_read({pid: "/1TR\r" for pid in port})
info("Executing purge...")
info(" filling capillary 1 with oil and 3 with mother liquor...")
self.write_read({1: "".join(["/1IV",str(S_load),",1A",str(Vol[1]),",1R\r"]),
3: "".join(["/1IV",str(S_load),",1A",str(Vol[3]),",1R\r"])})
while self.busy(1,3): sleep(0.1)
info(" purging lines...")
self.write_read({2: "/1BR\r"}) #Set pump2 valve to "B".
while self.busy(2): sleep(0.1)
self.write_read({1: "".join(["/1OV",str(S_prime),",1D",str(V_prime),",1R\r"]),
3: "".join(["/1OV",str(S_prime),",1D",str(V_prime),",1R\r"])})
i = -1
while self.busy(1,3):
i += 1
sleep(0.1)
if (i/20. == i/20): info("%r" % self.positions()) # every 2 s
info(" time to purge (s): %r" % (time()-t0))
self.refill()
def test_inject(self):
self.move_rel(3,-0.25,1)
self.move_rel(1,-0.25,1)
def pressure(self):
self.valve(2,port='O')
while self.busy(2): sleep(0.02)
self.write_read({2: "".join(["/1V",str(S_prime),",1P",str(V_prime),",1R\r"])})
while self.busy(2): sleep(0.1)
self.valve(2,port='B')
info("pressure down, valve 2 set to B...")
def pressure_old(self,strokes=-1):
"""Changes pressure using pump4."""
t0 = time()
info("Changing pressure...")
if strokes < 0:
for i in range(abs(strokes)):
self.write_read({2: "".join(["/1IV",str(S_pressure),",1A",str(Vol[4]),",1R\r"])})
while self.busy(2): sleep(0.1)
self.write_read({2: "".join(["/1OV",str(S_pressure),",1A",str(0),",1R\r"])})
while self.busy(2): sleep(0.1)
else:
for i in range(abs(strokes)):
self.write_read({2: "".join(["/1OV",str(S_pressure),",1A",str(Vol[4]),",1R\r"])})
while self.busy(2): sleep(0.1)
self.write_read({2: "".join(["/1IV",str(S_pressure),",1A",str(0),",1R\r"])})
while self.busy(2): sleep(0.1)
info(" time to change pressure (s): %r" % (time()-t0))
def flow(self,S = S_flow, pid = 1):
"""Starts flow."""
info("Executing flow...")
self.write_read({pid: "/1TR\r" for pid in port})
self.write_read({pid: "".join(["/1OV",str(S),",1A0,1R\r"])})
def run_flow(self,Speed = 0.25, pid = 1,N = 5):
for i in range(N):
self.flow(S = Speed, pid= pid)
while self.busy(pid): sleep(0.1)
self.fill(pid)
while self.busy(pid): sleep(0.1)
def injecttestN(self):
"""Assumes flow is active; increase flow from [1], while inject xtals using [4], Then increase flow speed
again, while retracting volume from inject. finish when resume normal flow [1]."""
t0 = time()
#info("Executing inject...")
self.write_read({1: "".join(["/1V",str(S_flowIX),",1F\r"]),
3: "".join(["/1V",str(S_flowIX),",1D",str(V_injectX+0.25),",1R\r"])})
while self.busy(3): sleep(0.02)
self.write_read({1: "".join(["/1V",str(S_flowIX),",1F\r"]),
3: "".join(["/1V",str(S_flowIM),",1P",str(V_injectM),",1R\r"])})
while self.busy(1,3): sleep(0.02)
self.write_read({1: "".join(["/1V",str(S_flow*5),",1F\r"])})
sleep (0.05)
self.write_read({1: "".join(["/1V",str(S_flow),",1F\r"])})
#info("time to swap flow source (s): %r" % (t1-t0))
info("time to inject (s): %r" % (time()-t0))
info("%r" % self.positions())
def injecttest(self):
"""Assumes flow is active; increase flow from [1], while inject xtals using [4], Then increase flow speed
again, while retracting volume from inject. finish when resume normal flow [1]."""
t0 = time()
#info("Executing inject...")
self.flush()
sleep(0.02)
self.write_read({1: "".join(["/1V",str(S_flowIX),",1F\r"]),
3: "".join(["/1V",str(S_flowIX),",1D",str(V_injectM),",1R\r"])})
while self.busy(1,3): sleep(0.02)
self.write_read({1: "".join(["/1V",str(S_flowIX),",1F\r"]),
3: "".join(["/1V",str(S_flowIM),",1P",str(V_injectM/2),",1R\r"])})
while self.busy(1,3): sleep(0.02)
self.write_read({1: "".join(["/1V",str(S_flow),",1F\r"])})
#info("time to swap flow source (s): %r" % (t1-t0))
info("time to inject (s): %r" % (time()-t0))
info("%r" % self.positions())
def inject(self):
"""Assumes flow is active; increase flow from [1], while inject xtals using [4], Then increase flow speed
again, while retracting volume from inject. finish when resume normal flow [1]."""
t0 = time()
#info("Executing inject...")
self.flush()
sleep(0.02)
self.write_read({1: "".join(["/1V",str(S_flowIM+0.5),",1F\r"]),
3: "".join(["/1V",str(S_flowIM),",1D",str(V_injectM+0.2),",1R\r"])})
while self.busy(3): sleep(0.02)
self.write_read({1: "".join(["/1V",str(S_flowIM*2),",1F\r"]),
3: "".join(["/1V",str(S_flowIM),",1P",str(V_injectM),",1R\r"])})
while self.busy(3): sleep(0.02)
self.write_read({1: "".join(["/1V",str(S_flow),",1F\r"])})
#info("time to swap flow source (s): %r" % (t1-t0))
info("time to inject (s): %r" % (time()-t0))
info("%r" % self.positions())
def reverse(self):
self.write_read({1: "".join(["/1V",str(S_flowIM),",1F\r"]),
3: "".join(["/1V",str(S_flowRV),",1P",str(V_injectX),",1R\r"])})
def injectN(self):
"""inject without flush."""
t0 = time()
#info("Executing inject...")
self.write_read({1: "".join(["/1V",str(S_flowIM/4),",1F\r"]),
3: "".join(["/1V",str(S_flowIM/2),",1D",str(V_injectR),",1R\r"])})
while self.busy(3): sleep(0.02)
self.write_read({1: "".join(["/1V",str(S_flowIM),",1F\r"]),
3: "".join(["/1V",str(S_flowIM/2),",1D",str(V_injectX),",1R\r"])})
while self.busy(3): sleep(0.02)
self.write_read({1: "".join(["/1V",str(S_flowIM),",1F\r"]),
3: "".join(["/1V",str(S_flowIM/4),",1P",str(V_injectX/2),",1R\r"])})
while self.busy(3): sleep(0.02)
self.write_read({1: "".join(["/1V",str(S_flow*4),",1F\r"])})
sleep (0.2)
self.write_read({1: "".join(["/1V",str(S_flow),",1F\r"])})
#info("time to swap flow source (s): %r" % (t1-t0))
info("time to inject (s): %r" % (time()-t0))
info("%r" % self.positions())
def clean(self):
"""injects cleaning solution and pressurizes from pump 4 to remove xtals."""
t0 = time()
info("Executing clean...")
self.abort()
self.valve(2,port = "I")
self.valve(4,port = "O")
while self.busy(2): sleep(0.02)
self.write_read({1: "".join(["/1V",str(S_flowIX),",1D",str(V_injectR),",1R\r"]),
3: "".join(["/1V",str(S_flowIM),",1P",str(V_injectX),",1R\r"])})
while self.busy(1,3): sleep(0.02)
self.write_read({4: "".join(["/1V",str(S_flush*2),",1D",str(V_clean),",1R\r"])})
while self.busy(4): sleep(0.02)
self.write_read({1: "".join(["/1V",str(S_flowRV),",1D",str(V_injectR),",1R\r"]),
3: "".join(["/1V",str(S_flowIM),",1D",str(V_injectM),",1R\r"])})
while self.busy(1,3): sleep(1.0)
self.valve(2,port = "B")
self.valve(4,port = "I")
while self.busy(2,4): sleep(0.02)
info("Initiating Flush...")
self.write_read({1: "".join(["/1V",str(S_flowIX*5),",1D",str(V_flush),",1R\r"])})
while self.busy(1): sleep(0.02)
info("Clean Sequence Finished, Resume Flow")
#info("time to swap flow source (s): %r" % (t1-t0))
info("time to clean (s): %r" % (time()-t0))
self.flow()
def xtal_grow1(self):
t0 = time()
info(" Initiating protein droplet generation")
self.write_read({1: "".join(["/1V",str(S_flowS1),",1D",str(V_droplet),",1R\r"]),
4: "".join(["/1V",str(S_flowS1),",1D",str(V_droplet),",1R\r"])})
while self.busy(1,4):
sleep(0.1)
info(" Sample loaded")
info("time to load (s): %r" % (time()-t0))
def xtal_grow2(self):
t0 = time()
info(" Initiating protein droplet generation")
self.write_read({1: "".join(["/1V",str(S_flowS1),",1D",str(V_droplet),",1R\r"]),
4: "".join(["/1V",str(S_flowS1),",1D",str(V_droplet),",1R\r"])})
while self.busy(1,4): sleep(0.1)
self.write_read({1: "".join(["/1V",str(S_flowRV),",1P",str(V_injectR),",1R\r"]),
4: "".join(["/1V",str(S_flowRV),",1P",str(V_injectR),",1R\r"])})
info(" Sample loaded")
info("time to load (s): %r" % (time()-t0))
def run(self):
"""executes a refill, flow, inject, flush, flow cycle"""
t0 = time()
info("%r" % self.positions())
info("executing run...")
self.flow(0.2)
sleep(3.0)
self.inject_new()
info("injecting xtals...")
sleep(8.0)
self.flush()
info("flushing xtals...")
info("resume flow...")
info("%r" % self.positions())
info("run time (s): %r" % (time()-t0))
def inject_old(self, V = V_injectX):
"""Assumes flow is active; slow flow from [1], inject using [3], then resume normal flow rate through [3]."""
t0 = time()
#info("Executing inject...")
info("%r" % self.positions())
self.write_read({1: "".join(["/1V",str(S_min),",1F\r"]),
4: "".join(["/1V",str(S_flow),",1D",str(V_injectX),",1R\r"])})
sleep(V/S_flow)
self.write_read({1: "".join(["/1V",str(S_flow),",1F\r"]),
4: "/1TR\r"})
#info("time to swap flow source (s): %r" % (t1-t0))
info("time to inject (s): %r" % (time()-t0))
info("%r" % self.positions())
def flush(self, V = V_flush, S = S_flush):
"""Stops flow, washes crystals out of tubing, then resumes flow."""
t0 = time()
info("Executing flush...")
self.write_read({1: "".join(["/1V",str(S),",1F\r"])})
sleep(V/float(S))
self.write_read({1: "".join(["/1V",str(S_min),",1F\r"])})
sleep(2)
self.write_read({1: "".join(["/1V",str(S_flow),",1F\r"])})
info("time to flush (s): %r" % (time()-t0))
def flush_1(self):
"""Stops flow, washes crystals out of tubing, then resumes flow."""
t0 = time()
info("Executing flush...")
#self.write_read({pid: "/1TR\r" for pid in port})
self.write_read({2: "/1OR\r"}) #Set pump2 valve to "O".
while self.busy(2): sleep(0.1)
#info(" filling capillary with water")
self.write_read({4: "".join(["/1V",str(S_flush),",1D",str(V_flush),",1R\r"])})
while self.busy(4): sleep(0.1)
self.write_read({2: "/1BR\r"}) #Set pump2 valve to "B".
while self.busy(2): sleep(0.1)
info("time to flush (s): %r" % (time()-t0))
#self.flow()
#sleep(1)
#self.inject()
def flush_2(self,N = 4):
"""Stops flow, washes crystals out of tubing, then resumes flow."""
t0 = time()
info("Executing flush...")
self.write_read({pid: "/1TR\r" for pid in port})
self.write_read({2: "/1OR\r"}) #Set pump2 valve to "O".
while self.busy(2): sleep(0.1)
info(" pulling back crystals in capillary 3")
self.write_read({1: "".join(["/1V",str(S_flush),",1D",str(V_injectX),",1R\r"]),
3: "".join(["/1V",str(S_flush),",1P",str(V_injectX),",1R\r"])})
while self.busy(1,3): sleep(0.1)
info(" filling capillary with water")
self.write_read({4: "".join(["/1V",str(S_flush),",1D",str(V_flush),",1R\r"])})
while self.busy(4): sleep(0.1)
info(" swishing water back and forth to dislodge/dissolve crystals")
for i in range(N):
self.write_read({1: "".join(["/1V",str(S_flush),",1D",str(V_flush),",1R\r"]),
4: "".join(["/1V",str(S_flush),",1P",str(V_flush),",1R\r"])})
while self.busy(1,4): sleep(0.1)
self.write_read({1: "".join(["/1V",str(S_flush),",1P",str(V_flush),",1R\r"]),
4: "".join(["/1V",str(S_flush),",1D",str(V_flush),",1R\r"])})
while self.busy(1,4): sleep(0.1)
info(" pushing crystals into capillary 2")
self.write_read({1: "".join(["/1V",str(S_flush),",1D",str(V_flush),",1R\r"]),
2: "".join(["/1V",str(S_flush),",1P",str(V_flush),",1R\r"])})
while self.busy(1,2): sleep(0.1)
self.write_read({2: "/1BR\r"}) #Set pump2 valve to "B".
while self.busy(2): sleep(0.1)
info(" pushing back crystals in capillary 3")
self.write_read({1: "".join(["/1V",str(S_flush),",1P",str(V_injectX),",1R\r"]),
3: "".join(["/1V",str(S_flush),",1D",str(V_injectX),",1R\r"])})
while self.busy(1,3): sleep(0.1)
info("time to flush (s): %r" % (time()-t0))
self.flow()
self.inject()
def refillN(self):
"""Loads syringe 1 and 3."""
t0=time()
info("Executing refill...")
self.write_read({pid: "/1TR\r" for pid in port})
self.write_read({3: "".join(["/1IV",str(S_load),",1A",str(Vol[4]),",1OR\r"]),
1: "".join(["/1IV",str(S_load),",1A",str(Vol[1]),",1OR\r"]),
4: "".join(["/1IV",str(S_load),",1A",str(Vol[1]),",1OR\r"])})
i = -1
while self.busy(1,3):
i += 1
sleep(0.1)
if (i/20. == i/20): info("%r" % self.positions()) # every 2 s
self.valve(2,port = "B")
self.valve(4,port = "I")
info(" time to refill (s): %r" % (time()-t0))
info("%r" % self.valve_read())
def degas(self):
"""increases upstream pressure to remove nucleated air bubbles."""
info("Degassing lines...")
self.valve(2, "O")
sleep(0.1)
self.flow(S=1.0)
sleep(3.0)
self.valve(2, "B")
sleep(0.1)
self.flow()
info("degassing complete, continue flow")
def refill_1(self):
"""Loads syringe 1 and restarts flow."""
t0=time()
info("Executing refill of pump 1...")
self.write_read({pid: "/1TR\r" for pid in port})
self.write_read({1: "".join(["/1IV",str(S_load),",1A",str(Vol[4]),",1OR\r"])})
i = -1
while self.busy(1):
i += 1
sleep(0.1)
if (i/20. == i/20): info("%r" % self.positions()) # every 2 s
self.valve(2,port = "B")
self.valve(4,port = "I")
info(" time to refill 1 (s): %r" % (time()-t0))
self.flow()
def refill_3(self):
"""Loads syringe 3."""
t0=time()
info("Executing refill of pump 3...")
self.write_read({3: "/1TR\r"})
self.write_read({3: "".join(["/1IV",str(S_load),",1A",str(Vol[4]),",1OR\r"])})
i = -1
while self.busy(3):
i += 1
sleep(0.1)
if (i/20. == i/20): info("%r" % self.positions()) # every 2 s
self.valve(2,port = "B")
self.valve(4,port = "I")
info(" time to refill 1 (s): %r" % (time()-t0))
def refill_all(self):
"""Loads syringe 1 and restarts flow."""
t0=time()
info("Executing refill...")
self.write_read({pid: "/1TR\r" for pid in port})
self.write_read({3: "".join(["/1IV",str(S_load),",1A",str(Vol[4]),",1OR\r"]),
1: "".join(["/1IV",str(S_load),",1A",str(Vol[1]),",1OR\r"]),
4: "".join(["/1IV",str(S_load),",1A",str(Vol[1]),",1OR\r"])})
i = -1
while self.busy(1,3):
i += 1
sleep(0.1)
if (i/20. == i/20): info("%r" % self.positions()) # every 2 s
self.valve(2,port = "B")
self.valve(4,port = "I")
info(" time to refill (s): %r" % (time()-t0))
self.flow()
def valve(self,pid,port = "I"):
"""Set port of pump[pid] to 'O', 'I', or 'B'."""
if port == 'i':
port = 'I'
elif port == 'o':
port = 'O'
elif port == 'b':
port = B
t0 = time()
self.write_read({pid: "".join(["/1",str(port),"R\r"])})
while self.busy(pid): sleep(0.1)
info("time to rotate valve (s): %r" % (time()-t0))
def empty(self):
"""Empty all syringes; switch all ports to B."""
self.write_read({1: "/1IV25,1A0,1R\r", 2: "/1IV25,1A0,1R\r",
3: "/1IV25,1A0,1R\r", 4: "/1IV25,1A0,1R\r"})
while self.busy(1, 2, 3, 4): sleep(0.1)
self.write_read({1: "/1BR\r", 2: "/1BR\r", 3: "/1BR\r", 4: "/1BR\r"})
def busy(self, *pids):
"""Returns True if any specified pump is busy. The query (?29) returns
the pump status, whose 4th byte is 1 or 0 (1 is busy)."""
from numpy import nan
reply = []
for pid in pids:
try:
reply.apend(self.write_read({pid: "/1?29\r"})[4])
except:
reply.append(nan)
return reply
def positions(self):
"""Queries positions of all pumps. Returns dict of pids to positions."""
reply = self.write_read({pid: "/1?18R\r" for pid in port})
return {pid: float(reply[pid][4:-3]) for pid in reply}
def valve_read(self,pids = []):
reply = []
"""Queries positions of all pumps. Returns dict of pids to positions."""
reply.append(self.write_read({pid: "/1?20R\r" for pid in port}))
return reply
def flow_old(self,S = S_flow):
"""Starts flow pfl changes flow speed on the fly."""
#self.write_read({1: "/1TR\r", 2: "/1TR\r"})
temp = self.positions()
info("%r" % temp)
if self.busy(1,2):
self.write_read({1: "".join(["/1V",str(S),",1F\r"]),
2: "".join(["/1V",str(S),",1F\r"])})
else:
V = min(temp[1],Vol[2]-temp[2])
self.write_read({1: "".join(["/1J1V",str(S),",1D",str(V),",1J0R\r"]),
2: "".join(["/1J1V",str(S),",1P",str(V),",1J0R\r"])})
def purge_12(self):
"""Purge bubbles from capillary using pumps (1,2) to displace 75 uL."""
self.write_read({pid: "/1TR\r" for pid in port})
temp = self.positions()
V = min(temp[1], Vol[2]-temp[2])
if V < 78: self.refill()
self.write_read({pid: "/1TR\r" for pid in port})
info(" purging...")
self.write_read({4: "/1OR\r"}) #Reposition #4 valve port before inflating.
while self.busy(4): sleep(0.1)
self.inflate(V_inflate)
while self.busy(2): sleep(0.1)
self.write_read({1: "".join(["/1J1V",str(S_prime),",1D",str(V_purge),",1J0R\r"]),
2: "".join(["/1J1V",str(S_prime),",1P",str(V_purge),",1J0R\r"])})
i = -1
while self.busy(1, 2):
i += 1
sleep(0.1)
if (i/20. == i/20): info("%r" % self.positions()) # every 2 s
self.refill()
def purge_32(self):
"""Purge bubbles from capillary using pumps (3,2) to displace 75 uL."""
self.write_read({pid: "/1TR\r" for pid in port})
temp = self.positions()
V = min(temp[3], Vol[2]-temp[2])
if V < 78: self.refill()
self.write_read({pid: "/1TR\r" for pid in port})
info(" purging...")
self.write_read({4: "/1OR\r"}) #Reposition #4 valve port before inflating.
while self.busy(4): sleep(0.1)
self.inflate(V_inflate)
while self.busy(2): sleep(0.1)
self.write_read({3: "".join(["/1J1V",str(S_prime),",1D",str(V_purge),",1J0R\r"]),
2: "".join(["/1J1V",str(S_prime),",1P",str(V_purge),",1J0R\r"])})
i = -1
while self.busy(2, 3):
i += 1
sleep(0.1)
if (i/20. == i/20): info("%r" % self.positions()) # every 2 s
self.refill()
def run_create_pressure(self,N):
start_new_thread(self.create_low_pressure,(N,))
def run_create_pressure_new(self,N):
start_new_thread(self.create_low_pressure_new,(N,))
def create_low_pressure_new(self,N):
from cavro_centris_syringe_pump_IOC import volume, port
for i in range(N):
port[1].value = 1
while port[1].moving: sleep(0.1)
volume[1].value = 250
while volume[1].moving: sleep(0.1)
port[1].value = 0
while port[1].moving: sleep(0.1)
volume[1].value = 0
while volume[1].moving: sleep(0.1)
def create_low_pressure(self, N = 2):
for i in range(N):
p.valve(2,'I')
while self.busy(2): sleep(0.1)
p.move_abs(2,250)
while self.busy(2): sleep(0.1)
p.valve(2,'O')
while self.busy(2): sleep(0.1)
p.move_abs(2,0)
while self.busy(2): sleep(0.1)
def fill(self, pid = 1):
while self.busy(pid): sleep(0.1)
p.valve(pid,'I')
p.move_abs(pid,250)
def prime_old(self):
"""Use after init; primes syringes and tubing (1,2) and (3,4) at S_load flow rate."""
info(" priming...")
self.write_read({pid: "/1TR\r" for pid in port})
self.write_read({4: "/1OR\r"})
while self.busy(4): sleep(0.1)
self.inflate(V_inflate)
while self.busy(2): sleep(0.1)
self.write_read({1: "".join(["/1J1V",str(S_load),",1D225,1J0R\r"]),
2: "".join(["/1J1V",str(S_load),",1P225,1J0R\r"]),
3: "".join(["/1J1V",str(S_load),",1D225,1J0R\r"]),
4: "".join(["/1J1V",str(S_load),",1P225,1JBR\r"])})
i = -1
while self.busy(1, 2, 3, 4):
i += 1
sleep(0.1)
if (i/20. == i/20): info("%r" % self.positions()) # every 2 s
self.refill()
def inflate(self, V = V_inflate):
"""Inflate tubing."""
self.write_read({1: "/1TR\r", 2: "/1TR\r"})
self.write_read({2: "".join(["/1J1V",str(S_flush),",1D",str(V),",1J0R\r"])})
while self.busy(2): sleep(0.1)
def reinject(self,V = V_flush):
"""Solution from pump 2 is rapidly pushed into the collapsible tubing;
then flow is continued."""
t0 = time()
self.write_read({pid: "/1TR\r" for pid in port})
self.write_read({4: "/1OR\r"})
while self.busy(4): sleep(0.1)
self.write_read({2: "".join(["/1V",str(S_flush),",1D",str(V),",1R\r"])})
while self.busy(2): sleep(0.1)
info("time to reinject (s): %r" % (time()-t0))
self.write_read({4: "/1BR\r"})
while self.busy(4): sleep(0.1)
self.flow()
if __name__ == "__main__":
import logging; logging.basicConfig(filename=gettempdir()+'/suringe_pump_DL.log',level=logging.INFO,format="%(levelname)s: %(message)s")
p = PumpController()
self = p # for debugging
print
print("p.init()")
print("p.flow()")
print("p.inject_new() # V = V_injectX")
print("p.flush() # V = V_flush, S = S_flush")
print("p.refillF()")
print("p.pressure() # strokes = -1")
print("p.positions()")
print("p.valve(2,'O') # pid, 'O', 'I', or 'B'")
print("p.valve_read()")
print("p.move_rel(3,-1,1) # pid,position,speed")
print("p.refill_1()")
print("p.refill_3()")
print("p.abort()")
# p.write_read({4:"/1?20R\r"}) # query valve position
# p.write_read({1: "/1IR\r"}) # Move pump1 valve to Input
# p.write_read({2: "/1V0.3,1F\r"}) # Change speed to 0.3 uL/s
# sum(p.positions().values()[:2]) # Returns sum of first two values
<file_sep>#!/bin/env python
"""Framework for an insturment server that comminitcates via
formatted text ASCII commands.
Author: <NAME>
Date created: 2016-01-18
Date last modified: 2019-06-01
"""
__version__ = "1.0.1" # issue: debug messages too long
from logging import debug,info,warn,error
import traceback
class TCP_Server(object):
name = "tcp_server"
from persistent_property import persistent_property
port = persistent_property("port",2222)
def __init__(self,
name=None,
globals=None,
locals=None,
idle_timeout=1,
idle_callback=None
):
"""
name: defines data base entry for number
globals: passed on to 'eval' or 'exec' when processing commands
locals: passed on to 'eval' or 'exec' when processing commands
idle_timeout: wait time for idle_callback in s
"""
if name: self.name = name
self.globals = globals
self.locals = locals
def reply(self,input):
"""Return a reply to a client process
command: string (without newline termination)
return value: string (without newline termination)"""
try:
value = eval(input,self.globals,self.locals)
reply = self.string(value)
except Exception,msg:
error_message_eval = "%s\n%s" % (msg,traceback.format_exc())
try:
exec(input,self.globals,self.locals)
info("Executed %.200r" % input)
reply = "\n"
except Exception,msg:
error_message_exec = "%s\n%s" % (msg,traceback.format_exc())
error(error_message_eval)
error(error_message_exec)
reply = error_message_eval+error_message_exec
return reply
def string(self,value):
"""Format python value as string for network stransmission"""
if isinstance(value,str) and len(value) > 1024: string = value
else: string = repr(value)+"\n"
return string
def get_running(self):
return getattr(self.server,"active",False)
def set_running(self,value):
if self.running != value:
if value: self.start()
else: self.stop()
running = property(get_running,set_running)
server = None
def start(self):
from threading import Thread
self.thread = Thread(target=self.run)
self.thread.start()
def stop(self):
if getattr(self.server,"active",False):
self.server.server_close()
self.server.active = False
def run(self):
try:
# make a threaded server, listen/handle clients forever
self.server = self.ThreadingTCPServer(("",self.port),self.ClientHandler)
self.server.active = True
info("%s: server version %s started, listening on port %d." % (self.name,__version__,self.port))
self.server.serve_forever()
except Exception,msg: info("%s: server: %s" % (self.name,msg))
info("%s: server shutting down" % self.name)
# By default, the "ThreadingTCPServer" class binds to the sever port
# without the option SO_REUSEADDR. The consequence of this is that
# when the server terminates you have to let 60 seconds pass, for the
# socket to leave to "CLOSED_WAIT" state before it can be restarted,
# otherwise the next bind call would generate the error
# 'Address already in use'.
# Setting allow_reuse_address to True makes "ThreadingTCPServer" use to
# SO_REUSEADDR option when calling "bind".
import SocketServer
class ThreadingTCPServer(SocketServer.ThreadingTCPServer):
allow_reuse_address = True
@property
def ClientHandler(self):
myself = self
import SocketServer
class ClientHandler(SocketServer.BaseRequestHandler):
def handle(self):
"""Called when a client connects. 'self.request' is the client socket"""
info("%s: accepted connection from %s" % (myself.name,self.client_address[0]))
import socket
input_queue = ""
while self.server.active:
# Commands from a client are not necessarily received as one packet
# but each command is terminated by a newline character.
# If 'recv' returns an empty string it means client closed the
# connection.
while input_queue.find("\n") == -1:
self.request.settimeout(1.0)
received = ""
while self.server.active:
try: received = self.request.recv(2*1024*1024)
except socket.timeout: continue
except Exception,msg:
error("%s: %s" % (myself.name,msg))
if received == "": info("%s: client disconnected" % myself.name)
break
if received == "": break
input_queue += received
if input_queue == "": break
if input_queue.find("\n") != -1:
end = input_queue.index("\n")
query = input_queue[0:end]
input_queue = input_queue[end+1:]
else: query = input_queue; input_queue = ""
query = query.strip("\r ")
debug("%s: evaluating query: %.200r" % (myself.name,query))
try: reply = myself.reply(query)
except Exception,msg: error("%s: %s" % (myself.name,msg)); reply = ""
if reply:
reply = reply.replace("\n","") # "\n" = end of reply
reply += "\n"
debug("%s: sending reply: %.200r" % (myself.name,reply))
self.request.sendall(reply)
info("%s: closing connection to %s" % (myself.name,self.client_address[0]))
self.request.close()
return ClientHandler
tcp_server = TCP_Server
if __name__ == "__main__":
import logging
logging.basicConfig(level=logging.DEBUG,
format="%(asctime)s %(levelname)s: %(message)s")
x = 1.2
self = TCP_Server("test",globals(),locals()) # for debugging
from tcp_client import query
print('self.port = %r' % self.port)
print('self.running = True')
print('query("localhost:%s","x")' % self.port)
<file_sep>from EPICS_serial_CA import Serial
port = Serial("14IDB:serial3") # loop back connector
string = "SET:TEMP 4.000\n"
port.query(string)
# generates reply 'SET:TEMP 4.000\nUT'
from CA import caput
encoded_string = repr(string)[1:-1]
##caput("14IDB:serial3.AOUT",encoded_string,wait=True)
caput('14IDB:serial3.AOUT','SET:TEMP 4.000\\n',wait=True)
<file_sep>#!/usr/bin/env python
"""
Software elulation of the BioCARS timing system to use at the NIH for testing.
<NAME>, 18 Sep 2014 - 18 Sep 2014
"""
__version__ = "1.0"
class Pulses(object):
"""Acquiation pulse count (software emulated)"""
from numpy import nan
start = nan
initial_count = 0
def get_value(self):
"""When read return the number of pulses remaining until the burst
ends. When set trigger a burst with the given number of pulses."""
from numpy import ceil,isnan
from time import time
if isnan(self.start): return 0
dt = time() - self.start
period = waitt.value
triggers_generated = int(ceil(dt/period))
count = max(self.initial_count - triggers_generated,0)
return count
def set_value(self,count):
from time import time
self.initial_count = count
self.start = time()
value = property(get_value,set_value)
pulses = Pulses()
class continuous_trigger:
"""Is continuous triggering enabled?"""
value = False
class tmode:
"""Trigger mode: 0 = continuous trigger, 1 = counted"""
value = False
class Waitt(object):
"""Waiting time between pulses"""
unit = "s"
stepsize = 1e-6
value = 0.024
min = 1e-6
max = 1000
from numpy import arange
choices = arange(0,1.05,0.05)
def next(self,value):
"""Closest allowed value to the given waitting time in s"""
from numpy import clip
value = clip(value,self.min,self.max)
return value
waitt = Waitt()
class transon:
"""Sample translation enabled?"""
value = False
class mson:
"""Millsecond X-ray shutter enabled?"""
value = False
class laseron:
"""Laser trigger enabled?"""
value = False
def toint(x):
"""Convert x to a floating point number.
If not convertible return zero"""
try: return int(x)
except: return 0
def tofloat(x):
"""Convert x to a floating point number.
If not convertible return 'Not a Number'"""
from numpy import nan
try: return float(x)
except: return nan
if __name__ == "__main__": # for testing
from time import sleep
print ""
<file_sep>vertical = True
nrows = 2
motor_names = [
'Slit1H.value',
'Slit1V.value',
'MirrorV.value',
'mir1bender',
'mir2Th.value',
'mir2bender.value',
's1hg.value',
'shg.value',
'svg.value',
'KB_Vpitch.value',
'KB_Vheight.value',
'KB_Vcurvature.value',
'KB_Hpitch.value',
'KB_Hheight.value',
'KB_Hcurvature.value',
'CollY.value',
]
motor_labels = [
'WhiteBS H [mm]',
'White BS V [mm]',
'V Mir Piezo [V]',
'V Mir Bend [mm]',
'H Mir Theta [mrad]',
'H Mir Bend [mrad]',
'JJ1 x aper [mm]',
'JJ2 x aper [mm]',
'JJ2 y aper [mm]',
'KB Vpitch [mm]',
'KB Vheight [mm]',
'KB Vcurv [mm]',
'KB Hpitch [mm]',
'KB Hheight [mm]',
'KB Hcurv [mm]',
'Pinhole Y [mm]',
]
formats = ['%.3f', '%.3f', '%.3f', '%.3f', '%.3f', '%.3f', '%.3f', '%.3f', '%.3f', '%.3f', '%.3f', '%.3f', '%.3f', '%.3f', '%.3f', '%.3f']
names = ['Slit1H', 'Slit1V']
title = 'Beamline Configurations'
description_width = 90
line0.description = 'Laue'
line1.description = 'SAXS/WAXS'
line0.updated = '2018-10-25 17:08:01'
line1.updated = '2019-03-19 13:15:22'
line0.Slit1H.value = 1.4986
line1.Slit1H.value = 0.898525
line0.Slit1V.value = 1.5
tolerance = [0.002, 0.002, 0.001, 0.001, 0.001, 0.001, 0.001, 0.001, 0.001, 0.001, 0.001, 0.001, 0.001, 0.001, 0.001, 0.001]
line1.Slit1V.value = 0.6
line1.MirrorV.value = 5.51
line1.mir1bender = 67.00000771
line1.mir2Th.value = 3.713
line1.mir2bender.value = 63.00003171000001
line1.s1hg.value = 1.0004000000000002
line1.shg.value = 0.15015
line1.svg.value = 0.070125
line1.KB_Vpitch.value = 3.7679340599999955
line1.KB_Vheight.value = 0.26522999999999985
line1.KB_Vcurvature.value = 8.79992
line1.KB_Hpitch.value = 3.7137414599999996
line1.KB_Hheight.value = 0.05020999999999898
line1.KB_Hcurvature.value = 11.799899999999997
line1.CollY.value = 8.796022388059697
line0.MirrorV.value = 4.8803818872691895
line0.mir1bender = 67.0
line0.mir2Th.value = 3.711437320574163
line0.mir2bender.value = 71.99995971000001
line0.s1hg.value = 0.20028333333333337
line0.shg.value = 0.40012500000000006
line0.svg.value = 0.070125
line0.KB_Vpitch.value = 3.8004496199999984
line0.KB_Vheight.value = 0.2909700000000002
line0.KB_Vcurvature.value = 14.000119999999999
line0.KB_Hpitch.value = 3.724579979999998
line0.KB_Hheight.value = 0.05003000000000002
line0.KB_Hcurvature.value = 12.799979999999998
line0.CollY.value = 5.818031483208959
widths = [100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100]
row_height = 20
show_stop_button = False
apply_button_label = 'Select'
define_button_label = 'Update'
command_row = 1
command_rows = [1]<file_sep>#!/bin/env python
"""Take a snapshot of sample using the Wide-filed camera image
<NAME>, APS, 8 Jul 2010 - 25 Oct 2014"""
__version__ = "2.2"
from GigE_camera import GigE_camera
from logging import debug
name = "WideFieldCamera"
# Under Linux, The Prosilica library requires administrative privileges
# to use multicast. Unless the calling prgram is registered in sudoers
# data base, 'use_multicast' needs to be set to False.
# If multicast is set to False, the image acquisition will fail if a
# another application acquires images from the beam profilter camera at
# the same time.
use_multicast = False
def camera_acquire_image():
"""Acquire a single image from the camera and return as PIL image.
This function is *NOT SAFE* to use for Python applications using network
communication ("Interrupted system call"), because loads the Prosilica
library."""
from time import time
from PIL import Image # Python Imaging Library
camera = GigE_camera(parameter("camera.IP_addr"),use_multicast=use_multicast)
camera.last_timestamp = 0
camera.start()
t = time()
while not camera.has_image or camera.timestamp == 0:
if time()-t > 2.0 and not "started" in camera.state:
log ("camera_acquire_image: image unreadable (%s)" % camera.state); break
if time()-t > 5.0:
log ("camera_acquire_image: image acquistion timed out (%s)" % camera.state); break
sleep(0.1)
camera.stop()
debug("get_image: read image with %dx%d pixels, %d bytes" %
(camera.width,camera.height,len(camera.rgb_data)))
image = Image.new('RGB',(camera.width,camera.height))
image.fromstring(camera.rgb_data)
image = rotated_image(image)
return image
def camera_save_image(filename):
"""Acquire a single image from the camera and save it as a file.
filename: the exension determines the image format, may be '.jpg',
'.png' or '.tif' or any other extension supported by the Python
Image Library (PIL)
This function is *NOT SAFE* to use for Python applications using network
communication ("Interrupted system call"), because loads the Prosilica
library."""
image = camera_acquire_image()
image.save(filename)
def camera_image_size():
"""Image width and height, without rotation applied.
This function is *NOT SAFE* to use for Python applications using network
communication ("Interrupted system call"), because loads the Prosilica
library."""
camera = GigE_camera(parameter("camera.IP_addr"))
width,height = camera.width,camera.height
orientation = parameter('Orientation',90) # in degrees counter-clockwise
if orientation == None: orienation = 0
orientation %= 360
if orientation == 90 or orientation == 270: width,height = height,width
return width,height
def subprocess(command):
"""Execute the given command in a subprocess.
The standard ouput of the command is returned as a string with trailing
newline.
If you need the result of the command, the command should contain a 'print'
statement. E.g. 'print get_center()'. Multiple commands can be
concatenated, separated by semicolons.
Functions that load the Prosilica library interfere with network
communication ("Interrupted system call").
Executing them in a subprocess makes it safe for applications that use
network communications to call them."""
from sys import executable as python
from subprocess import Popen,PIPE
from sys import stderr
command = "from %s import *; %s" % (modulename(),command)
for attempt in range(0,3):
try:
process = Popen([python,"-c",command],stdout=PIPE,stderr=PIPE,
universal_newlines=True)
break
except OSError,msg: # [Errno 513] Unknown error 513
log("subprocess: %s" % msg)
sleep(1)
output,error = process.communicate()
if "Traceback" in error: raise RuntimeError(repr(command)+"\n"+error)
if error: stderr.write(error)
return output
def save_image(filename):
"""Acquire a single image from the camera and save it as a file.
filename: the exension determines the image format, may be '.jpg',
'.png' or '.tif' or any other extensino supported by the Python Image
Library (PIL)
The Prosilica library is loaded in a subprocess."""
subprocess("camera_save_image(%r)" % filename)
##image = acquire_image()
##image.save(filename)
def acquire_image():
"""Acquire a single image from the camera and return it as PIL image.
If rotate = True, apply the same rotation as in the ImageViewer
application.
This function is safe to use from any Python application, because it does
not load the Prosilica library. The task is preformed in a subprocess
instead.
The Prosilica library is loaded in a subprocess."""
import Image
w,h = image_size()
image = Image.new('RGB',(w,h))
global image_data # for debugging
image_data = eval(subprocess("print repr(camera_acquire_image().tostring())"))
log("acquire_image: got %d bytes of image data from subprocess" % len(image_data))
if len(image_data) != w*h*3:
log("acquire_image: expecting %d, got %d bytes of image data" %
(w*h*3,len(image_data)))
if len(image_data) == w*h*3: image.fromstring(image_data)
else: log("acquire_image: image data corrupted, substituting blank image")
return image
def rotated_image(image):
"""Apply the same rotation as in the ImageViewer application."""
orientation = parameter('Orientation',90) # in degrees counter-clockwise
if orientation == None: orienation = 0
return image.rotate(orientation)
def image_size():
"""Image width and height, without rotation applied
This function is safe to use from any Python application, because it does
not load the Prosilica library. The task is performed in a subprocess
instead."""
return eval(subprocess("print camera_image_size()"))
def modulename():
"""Name of this Python module, without directory and extension,
as used for 'import'"""
from inspect import getmodulename,getfile
return getmodulename(getfile(lambda x:x))
def rotate((x,y)):
"""Apply the same rotation as in the ImageViewer application to the
cross-hair"""
orientation = parameter('Orientation',90) # in degrees counter-clockwise
if orientation == None: orienation = 0
w,h = image_size()
if orientation == 0: return (x,y)
if orientation == -90: return (h-y,x)
if orientation == 90: return (y,w-x)
if orientation == 180: return (w-x,h-y)
return (x,y)
def parameter(name,default_value=None):
"""Retreive a parameter used by the CameraViewer
application."""
settings = file(settings_file()).read()
for line in settings.split("\n"):
line = line.strip(" \n\r")
if len(line.split("=")) != 2: continue
keyword,value = line.split(" = ")
keyword = keyword.strip(" ")
if keyword == name: return eval(value)
return default_value
def settings_file():
"pathname of the file used to store persistent parameters"
return settings_dir()+"/"+name+"_settings.py"
def settings_dir():
"pathname of the file used to store persistent parameters"
path = module_dir()+"/settings"
return path
def module_dir():
"directory of the current module"
from os.path import dirname
module_dir = dirname(module_path())
if module_dir == "": module_dir = "."
return module_dir
def module_path():
"""Full pathname of the current module"""
from sys import path
from os import getcwd
from os.path import basename,exists
from inspect import getmodulename,getfile
from logging import warn
# 'getfile' retreives the source file name name compiled into the .pyc file.
pathname = getfile(lambda x: None)
if exists(pathname): return pathname
# The module might have been compiled on a different machine or in a
# different directory.
pathname = pathname.replace("\\","/")
filename = basename(pathname)
dirs = [dir for dir in [getcwd()]+path if exists(dir+"/"+filename)]
if len(dirs) == 0: warn("pathname of file %r not found" % filename)
dir = dirs[0] if len(dirs) > 0 else "."
pathname = dir+"/"+filename
return pathname
def log(message):
"""Append a message to the log file (/tmp/beam_profiler.log)"""
from tempfile import gettempdir
from time import strftime
from sys import stderr
timestamp = strftime("%d-%b-%y %H:%M:%S")
if len(message) == 0 or message[-1] != "\n": message += "\n"
stderr.write("%s: %s" % (timestamp,message))
logfile = gettempdir()+"/beam_profiler.log"
file(logfile,"a").write(timestamp+" "+message)
def sleep(seconds):
"""Return after for the specified number of seconds"""
# After load and initializing the PvAPI Python's built-in 'sleep' function
# stops working (returns too early). The is a replacement.
from time import sleep,time
t = t0 = time()
while t < t0+seconds: sleep(t0+seconds - t); t = time()
if __name__ == "__main__":
"""for testing"""
print 'save_image("test/test.png")'
<file_sep>"""
This is a utility to test the scan software without using any hardware.
<NAME>, NIH 13 Mar 2008
Run simuation:
app=wx.App(False)
data=rscan(sim_mot,-0.2,0.2,50,sim_det,plot=True)
COM(data)
FWHM(data),RMSD(data),CFWHM(data),COM(data)
"""
from scan import *
class simulated_motor(object):
"Simulates a motor in software without moving anything"
def __init__(self,name="dummy",speed=Inf,value=0):
object.__init__(self)
self.name = name
self.speed = speed
self.target_value = value
self.starting_value = value
self.move_started = time()
def get_value(self):
dt = time() - self.move_started
if isinf(self.speed): return self.target_value
if self.target_value >= self.starting_value:
return min(self.starting_value + dt*self.speed, self.target_value)
else:
return max(self.starting_value - dt*self.speed, self.target_value)
def set_value(self,value):
self.starting_value = self.value
self.target_value = value
self.move_started = time() # Record the time the last move was initiated.
value = property(get_value,set_value,doc="""Position of motor (user value)""")
def get_moving(self):
return (self.value != self.target_value)
moving = property(get_moving,doc="True if currently moving, False if done")
def wait(self):
"If the motor is moving, returns control after current move move is complete."
while self.moving: sleep(0.01)
class simulated_detector(object):
"""Simulates a detector. The detector reading is dependent on the
position of a simulates motor.
"""
def __init__(self,name="dummy",motor=simulated_motor(),center=0,FWHM=0.1):
object.__init__(self)
self.name = name
self.motor = motor
self.center = center
self.FWHM = FWHM
def get_value(self):
x = self.motor.value
cx = self.center
sx = self.FWHM / (2*sqrt(2*log(2)))
y = exp(-0.5*((x-cx)/sx)**2)
return y
value = property(fget=get_value,doc="simulates a measurement")
#sim_mot = simulated_motor("sim_mot",speed=0.2,value=69.0286)
sim_mot = simulated_motor("sim_mot",speed=Inf,value=0)
sim_det = simulated_detector("sim_det",motor=sim_mot,center=sim_mot.value,
FWHM=0.1)
# This is for testing, remove when done
# Needed for plot window:
if not "app" in globals(): app = wx.App(0)
<file_sep>list = 'ring_current, bunch_current, temperature'<file_sep>#!/usr/bin/env python
"""
Control panel
Author: <NAME>
Date created: 2018-10-26
Date last modified: 2018-10-26
"""
__version__ = "1.0"
from SavedPositionsPanel_2 import SavedPositionsPanel
if __name__ == '__main__':
from pdb import pm # for debugging
import logging # for debugging
from tempfile import gettempdir
logfile = gettempdir()+"/Methods_Configuration_Panel.log"
logging.basicConfig(level=logging.INFO,filename=logfile,
format="%(asctime)s %(levelname)s: %(message)s")
import wx
app = wx.App(redirect=False)
from instrumentation import * # -> globals()
panel = SavedPositionsPanel(name="method",globals=globals())
app.MainLoop()
<file_sep>filename = '//femto/C/All Projects/APS/Experiments/2019.05/Test/Archive/NIH.pressure_upstream.txt'<file_sep>"""Data Collection diagnostics
Author: <NAME>
Date created: 2018-10-27
Date last modified: 2019-05-31
"""
__version__ = "1.2" # issue: NaNs in log file, using interpolated average, ending time of last image
from logging import debug,info,warn,error
import traceback
class Diagnostics(object):
"""Data Collection diagnostics"""
from persistent_property import persistent_property
list = persistent_property("list","")
values = {}
images = {}
def get_running(self):
return self.monitoring_variables and self.monitoring_image_number
def set_running(self,value):
if value and not self.running: self.clear()
self.monitoring_variables = value
self.monitoring_image_number = value
running = property(get_running,set_running)
def started(self,image_number):
from numpy import nan
time = nan
if image_number in self.images: time = self.images[image_number].started
return time
def finished(self,image_number):
from numpy import nan
time = nan
if image_number in self.images: time = self.images[image_number].finished
return time
def is_finished(self,image_number):
from numpy import isfinite
return isfinite(self.finished(image_number))
def average_values(self,image_number):
values = [self.average_value(image_number,v) for v in self.variable_names]
return values
def interpolated_average_value(self,image_number,variable):
from numpy import nan,isfinite
v0 = nan
t0 = (self.started(image_number)+self.finished(image_number))/2
if isfinite(t0):
t,v = self.image_timed_samples(image_number,variable)
v0 = self.interpolate(t,v,t0)
return v0
average_value = interpolated_average_value
@staticmethod
def interpolate(t,v,t0):
from numpy import nan
v0 = nan
if len(v) > 1:
from scipy.interpolate import InterpolatedUnivariateSpline
f = InterpolatedUnivariateSpline(t,v,k=1)
v0 = f([t0])[0]
if len(v) == 1: v0 = v[0]
return v0
def image_timed_samples(self,image_number,variable):
from numpy import array,where
times,values = [],[]
if image_number in self.images and variable in self.values:
image = self.images[image_number]
t1,t2 = image.started,image.finished
t = array([sample.time for sample in self.values[variable]])
v = array([sample.value for sample in self.values[variable]])
i = list(where((t1 <= t) & (t <= t2))[0])
if len(i) < 1: i += list(where(t <= t1)[0][-1:])
if len(i) < 1: i += list(where(t >= t2)[0][0:1])
if len(i) < 2: i += list(where(t >= t2)[0][0:1])
times,values = t[i],v[i]
return times,values
def timed_samples(self,variable):
from numpy import array
t,v = [],[]
if variable in self.values:
t = array([sample.time for sample in self.values[variable]])
v = array([sample.value for sample in self.values[variable]])
return t,v
def samples(self,image_number,variable):
values = []
if image_number in self.images and variable in self.values:
image = self.images[image_number]
all_values = self.values[variable]
values = [tval.value for tval in all_values
if image.matches(tval.time)]
return values
@property
def image_numbers(self): return self.images.keys()
def clear(self):
self.values = {}
self.images = {}
@property
def variable_names(self):
names = self.list.replace(" ","").split(",")
return names
@property
def count(self): return len(self.variable_names)
@property
def vars(self):
vars = []
exec("from instrumentation import *") # -> eval
for variable_name in self.variable_names:
try: var = eval(variable_name)
except Exception,msg:
error("%r: %s" % (variable_name,msg))
from CA import PV
var = PV("")
vars += [var]
return vars
def get_monitoring_variables(self):
return self.__monitoring_variables__
def set_monitoring_variables(self,value):
if value:
for (variable_name,var) in zip(self.variable_names,self.vars):
var.monitor(self.handle_variables_update)
else:
for var in self.vars: var.monitor_clear()
self.__monitoring_variables__ = value
monitoring_variables = property(get_monitoring_variables,set_monitoring_variables)
__monitoring_variables__ = False
def handle_variables_update(self,PV_name,value,string_value):
from time import time
variable_name = ""
for (name,var) in zip(self.variable_names,self.vars):
if var.name == PV_name: variable_name = name
if variable_name:
if not variable_name in self.values: self.values[variable_name] = []
self.values[variable_name] += [self.timestamped_value(time(),value)]
def get_monitoring_image_number(self):
from timing_system import timing_system
monitoring_image_number = self.handle_image_number_update in timing_system.image_number.monitors
monitoring_acquiring = self.handle_acquiring_update in timing_system.acquiring.monitors
monitoring = monitoring_image_number and monitoring_acquiring
return monitoring
def set_monitoring_image_number(self,value):
from timing_system import timing_system
if value:
timing_system.image_number.monitor(self.handle_image_number_update)
timing_system.acquiring.monitor(self.handle_acquiring_update)
else:
timing_system.image_number.monitor_clear(self.handle_image_number_update)
timing_system.acquiring.monitor_clear(self.handle_acquiring_update)
monitoring_image_number = property(get_monitoring_image_number,set_monitoring_image_number)
def handle_image_number_update(self):
from time import time
t = time()
from timing_system import timing_system
i = timing_system.image_number.count
acquiring = timing_system.acquiring.count
if acquiring:
if not i in self.images: self.images[i] = self.interval()
self.images[i].started = t
from numpy import isfinite
if i-1 in self.images and \
(not isfinite(self.images[i-1].finished) or
not self.images[i-1].finished >= self.images[i-1].started):
self.images[i-1].finished = t
def handle_acquiring_update(self):
from time import time
t = time()
from timing_system import timing_system
i = timing_system.image_number.count
acquiring = timing_system.acquiring.count
if acquiring:
if not i in self.images: self.images[i] = self.interval()
self.images[i].started = t
if not acquiring:
from numpy import isfinite
if i-1 in self.images and \
(not isfinite(self.images[i-1].finished) or
not self.images[i-1].finished >= self.images[i-1].started):
self.images[i-1].finished = t
class timestamped_value(object):
def __init__(self,time,value):
self.time = time
self.value = value
def __repr__(self):
from time_string import date_time
return "(%s,%r)" % (date_time(self.time),self.value)
class interval(object):
from numpy import inf
def __init__(self,started=-inf,finished=inf):
self.started = started
self.finished = finished
def matches(self,time):
return self.started <= time <= self.finished
def __repr__(self):
from time_string import date_time
return "(%s,%s)" % (date_time(self.started),date_time(self.finished))
diagnostics = Diagnostics()
def nanmean(a):
from numpy import nansum,nan
if len(a) > 0: return nansum(a)/len(a)
else: return nan
if __name__ == '__main__':
from pdb import pm # for debugging
import logging # for debugging
logging.basicConfig(
level=logging.DEBUG,
format="%(asctime)s %(levelname)s %(module)s.%(funcName)s: %(message)s",
)
self = diagnostics # for debugging
from instrumentation import ring_current,bunch_current,temperature
variable = "ring_current"
##print("self.variable_names")
##print("self.running = True")
##print("self.running = False")
##print("self.values")
##print("self.image_numbers")
##print('self.average_values(self.image_numbers[2])')
from CA import camonitors
from timing_system import timing_system
print("self.monitoring_image_number = True")
print("timing_system.acquiring.count = 1")
print("timing_system.image_number.count += 1")
print("timing_system.acquiring.count = 0")
print("self.images")
print("camonitors(timing_system.image_number.PV_name)")
##print("camonitors(timing_system.acquiring.PV_name)")
<file_sep>VAL.filename = '//mx340hs/data/anfinrud_1906/Archive/S.SRcurrentAI.VAL.txt'<file_sep>local.viewer.CustomView = ['Title', 'Min. update time']
local.optics.CustomView = ['Nominal pixel size', 'Zoom levels']<file_sep>"""
Optical Freeze detector agent
Authors: <NAME>
Date created: 26 Feb 2018
Date last modified: 7 Mar 2018
Version: 1.5
-added retract -> iglobal =1 -> insert sequence that waits for previous one
to be executed first
"""
__version__ = "1.5"
from CAServer import casput,casdel
from CA import caget
from datetime import datetime
from logging import debug,info,warn,error
from thread import start_new_thread
import os
from Ensemble import ensemble
from time import sleep,time
from thread import start_new_thread
def freeze_intervention(filename = 'Freeze_Intervention.ab' ):
ensemble.auxiliary_task_filename = filename
if __name__ == "__main__":
print("freeze_intervention()")
<file_sep>#!/usr/bin/env python
"""
Timing System Simulator
Author: <NAME>
Date created: Oct 18, 2016
Date last modified: Oct 19, 2017
"""
__version__ = "1.0"
from tcp_server import tcp_server
class Timing_System_Simulator(tcp_server):
"""Timing System Simulator"""
name = "timing_system_simulator"
def reply(self,query):
"""Return a reply to a client process
command: string (without newline termination)
return value: string (without newline termination)"""
if query == "?": reply = "supported commands: ?, registers, parameters"
elif query == "registers": reply = "xosct,losct"
else: reply = "command %r not implemented" % query
return reply
timing_system_simulator = Timing_System_Simulator()
if __name__ == "__main__":
import logging
logging.basicConfig(level=logging.DEBUG,
format="%(asctime)s %(levelname)s: %(message)s")
self = timing_system_simulator # for debugging
from tcp_client import query
print('self.port = %r' % self.port)
print('self.server_running = True')
print('query("localhost:%s","registers")' % self.port)
<file_sep>#!/usr/bin/env python
"""Grapical User Interface for photocrystallography chip.
<NAME>, 18 Nov 2013 - 19 Nov 2013"""
import wx
from sample_translation_raster import grid
from instrumentation import SampleX,SampleY,SampleZ
__version__ = "1.0"
class SampleTranslationRasterPanel (wx.Frame):
"""Grapical User Interface for photocrystallography chip.
Author: <NAME>"""
def __init__(self):
""""""
wx.Frame.__init__(self,parent=None,title="Sample Translation Raster",
size=(410,460))
# Menus
menuBar = wx.MenuBar()
menu = wx.Menu()
menu.Append (121,"E&xit","Closes this window.")
self.Bind (wx.EVT_MENU,self.OnClose,id=121)
menuBar.Append (menu,"&File")
menu = wx.Menu()
menu.Append (402,"&Setup...","Parameters for sample alignment")
self.Bind (wx.EVT_MENU,self.OnSetup,id=402)
menuBar.Append (menu,"&More")
menu = wx.Menu()
menu.Append (501,"&About...","Version information")
self.Bind (wx.EVT_MENU,self.OnAbout,id=501)
menuBar.Append (menu,"&Help")
self.SetMenuBar (menuBar)
from ComboBox import ComboBox # A customized Combo Box control
self.panel = wx.Panel(self)
self.Image = Image(self.panel)
choices = ["1000","500","200","100","50","20","10","5","2","1"]
self.ScaleFactorControl = wx.ComboBox(self.panel,
choices=choices,size=(88,-1))##,style=wx.TE_PROCESS_ENTER)
self.ScaleFactorControl.Value = "%g" % self.Image.ScaleFactor
self.Bind (wx.EVT_COMBOBOX,self.OnChangeScaleFactor,self.ScaleFactorControl)
self.Bind (wx.EVT_TEXT,self.OnTypeScaleFactor,self.ScaleFactorControl)
self.PointerFunctionControl = wx.Choice(self.panel,
choices=["Info","Go to","Calibrate"],size=(88,-1))
self.Bind (wx.EVT_CHOICE,self.OnPointerFunction,
self.PointerFunctionControl)
self.CreateStatusBar()
# Layout
self.layout = wx.BoxSizer(wx.VERTICAL)
self.layout.Add (self.Image,proportion=1,flag=wx.EXPAND) # growable
self.Controls = wx.BoxSizer(wx.HORIZONTAL)
self.Controls.AddSpacer((5,5))
self.Controls.Add(self.ScaleFactorControl,flag=wx.ALIGN_CENTER)
self.Controls.AddSpacer((5,5))
self.Controls.Add(self.PointerFunctionControl,flag=wx.ALIGN_CENTER)
self.layout.Add (self.Controls,flag=wx.EXPAND)
self.panel.SetSizer(self.layout)
self.panel.Layout()
self.Bind(wx.EVT_CLOSE,self.OnClose)
self.Show()
# Restore last saved settings.
name = "SampleTranslationRaster"
self.config_file=wx.StandardPaths.Get().GetUserDataDir()+"/"+name+".py"
self.config = wx.FileConfig (localFilename=self.config_file)
state = self.config.Read('State')
if state:
try: self.State = eval(state)
except Exception,exception:
print "Restore failed: %s: %s" % (exception,state)
self.timer = wx.Timer(self)
self.Bind (wx.EVT_TIMER,self.update,self.timer)
self.timer.Start(1000,oneShot=True)
def update(self,event=None):
"""Periodocally called on timer"""
self.Image.Refresh()
self.timer = wx.Timer(self)
self.Bind (wx.EVT_TIMER,self.update,self.timer)
self.timer.Start(1000,oneShot=True)
def GetScaleFactor(self):
"""Current value of scale control as float"""
return self.Image.ScaleFactor
def SetScaleFactor(self,value):
self.Image.ScaleFactor = value
text = "%g" % value
if self.ScaleFactorControl.StringSelection != text:
self.ScaleFactorControl.StringSelection = text
ScaleFactor = property (GetScaleFactor,SetScaleFactor)
def OnChangeScaleFactor(self,event):
"""Callback for the ScaleFactor control"""
from numpy import isnan
##print("OnChangeScaleFactor")
##print("event.String %r" % event.String)
##print("ScaleFactorControl.StringSelection %r" % self.ScaleFactorControl.StringSelection)
##print("ScaleFactorControl.Value %r" % self.ScaleFactorControl.Value)
scale = tofloat(self.ScaleFactorControl.StringSelection)
if not isnan(scale): self.Image.ScaleFactor = scale
self.ScaleFactorControl.Value = "%g" % self.Image.ScaleFactor
def OnTypeScaleFactor(self,event):
"""Callback for the ScaleFactor control"""
from numpy import isnan
##print("OnTypeScaleFactor")
##print("event.String %r" % event.String)
##print("ScaleFactorControl.StringSelection %r" % self.ScaleFactorControl.StringSelection)
##print("ScaleFactorControl.Value %r" % self.ScaleFactorControl.Value)
# Due ot a bug on MacOSX, settings a callback on Enter crashes
# Python.
# As a work-around wait for SPACE instead to "enter" the current value.
if not event.String.endswith(" "): return
scale = tofloat(event.String)
##print("scale = %r" % scale)
if not isnan(scale): self.Image.ScaleFactor = scale
self.ScaleFactorControl.Value = "%g" % self.Image.ScaleFactor
self.ScaleFactorControl.StringSelection = "%g" % self.Image.ScaleFactor
def GetPointerFunction(self):
"""What happens at a mouse-click? type: string"""
return self.Image.PointerFunction
def SetPointerFunction(self,value):
self.Image.PointerFunction = value
self.PointerFunctionControl.StringSelection = value
PointerFunction = property (GetPointerFunction,SetPointerFunction)
def OnPointerFunction(self,event):
"""Callback for the PointerFunction control"""
self.Image.PointerFunction = self.PointerFunctionControl.StringSelection
def OnClose(self,event):
"""Clase the window and save settings"""
self.Show(False)
# Save settings for next time.
self.config.Write ('State',repr(self.State))
self.config.Flush()
app.ExitMainLoop() # for debugging
##self.Destroy()
def GetState(self):
"""The current settings of the window as dictionary"""
state = {}
state["Size"] = self.Size
state["Position"] = self.Position
state["ScaleFactor"] = self.ScaleFactor
state["PointerFunction"] = self.PointerFunction
state["Image.State"] = self.Image.State
return state
def SetState(self,state):
##print "MainWindow: restoring %r" % state
for key in state:
try: exec("self."+key+"="+repr(state[key]))
except Exception,msg: print("%s = %s: %s" % (key,state[key],msg))
State = property(GetState,SetState)
def OnSetup(self,event):
"""Change parameters controlling click-centering procedure"""
dlg = Setup(self)
dlg.CenterOnParent()
dlg.Show()
def OnAbout(self,event):
"""Show version info"""
info = self.__class__.__name__+" "+__version__+"\n"+__doc__
dlg = wx.MessageDialog(self,info,"About",wx.OK|wx.ICON_INFORMATION)
dlg.CenterOnParent()
dlg.ShowModal()
dlg.Destroy()
class Image(wx.ScrolledWindow):
scale_factor = 50.0
color = (100,100,100)
support_point_color = (255,0,0)
support_point_location_color = (0,0,255)
highlight_color = (255,255,0)
current_position_color = (0,255,0)
dotsize = 0.03 # in mm
x_axis = [0,0,1] # coordinate selector for horizontal direction in image
y_axis = [0,1,0] # coordinate selector for vertical direction in image
current = 0 # highlight this spot
PointerFunction = "Info"
def __init__(self,parent):
wx.ScrolledWindow.__init__(self,parent)
self.SetScrollRate(1,1)
self.Bind (wx.EVT_PAINT, self.OnPaint)
self.Bind (wx.EVT_ERASE_BACKGROUND, self.OnEraseBackground)
self.Bind (wx.EVT_SIZE, self.OnResize)
self.Bind (wx.EVT_LEFT_DOWN,self.OnLeftDown)
self.Bind (wx.EVT_KEY_DOWN,self.OnKey)
def OnPaint (self,event):
"""Called by WX whenever the contents of the window
needs re-rendering. E.g. when the window is brought to front,
uncovered, restored from minimized state."""
dc = wx.PaintDC(self)
# Needed to set the origin according to the scrollbar positions.
self.PrepareDC(dc)
# Display scroll bars if the window is smaller than the space needed.
w = self.ImageWidth * self.ScaleFactor
h = self.ImageHeight * self.ScaleFactor
self.VirtualSize = w,h
self.draw(dc)
def OnEraseBackground(self, event):
"""Overrides default background fill, avoiding flickering"""
def OnResize (self,event):
w = self.ImageWidth * self.ScaleFactor
h = self.ImageHeight * self.ScaleFactor
self.VirtualSize = w,h
self.Refresh()
def OnLeftDown(self,event):
"""Show information about the feature the mouse was clicked on"""
from numpy import argmin,sqrt,dot
xi,yi = event.Position
x,y = self.ScaledPosition(xi,yi)
XYZ = grid.xyz
if len(XYZ) > 0:
X,Y = dot(XYZ,self.x_axis),dot(XYZ,self.y_axis)
i = argmin(sqrt((x-X)**2+(y-Y)**2))
indices = tuple(grid.indices[i])
self.current = i
if self.PointerFunction == "Info":
xyz = grid.xyz[i]
elif self.PointerFunction == "Go to":
xyz = grid.xyz[i]
self.current_position = xyz
elif self.PointerFunction == "Calibrate":
xyz = self.current_position
if not grid.has_support_indices(indices):
##print("add %r,%r" % (indices,xyz))
grid.add_support_point(indices,xyz)
else: grid.remove_support_indices(indices)
x,y,z = xyz
text = "#%r %r" % (i+1,indices)
text += " %+.3f,%+.3f,%+.3f" % (x,y,z)
else:
self.current = 0
text = ""
self.Refresh()
self.Parent.Parent.SetStatusText(text)
def OnKey(self,event):
"""Navigate from spot to spot"""
##print("Key %r" % event.KeyCode)
from numpy import clip
n = len(grid.indices)
step = grid.n[-1]
if event.KeyCode == wx.WXK_LEFT:
print("left")
self.current = clip(self.current-1,0,n-1)
if event.KeyCode == wx.WXK_RIGHT:
print("right")
self.current = clip(self.current+1,0,n-1)
if event.KeyCode == wx.WXK_UP:
print("up")
self.current = clip(self.current-step,0,n-1)
if event.KeyCode == wx.WXK_DOWN:
print("down")
self.current = clip(self.current+step,0,n-1)
self.Refresh()
def get_current_position(self):
"""Current position (x,y,z)"""
return SampleX.value,SampleY.value,SampleZ.value
def set_current_position(self,xyz):
SampleX.value,SampleY.value,SampleZ.value = xyz
current_position = property(get_current_position,set_current_position)
def draw (self,dc):
"""This function is responsible for drawing the contents of the window.
"""
from numpy import dot,isnan,array,where,all
gc = wx.GraphicsContext.Create(dc)
x,y,z = grid.xyz.T
s = self.ScaleFactor
ox,oy = self.Offset
gc.Scale(s,s)
gc.Translate(ox,oy)
d = self.dotsize
gc.SetBrush(wx.TRANSPARENT_BRUSH)
gc.SetPen (wx.Pen(self.color,d/4))
xyz = grid.xyz
XY = array(zip(dot(xyz,self.x_axis),dot(xyz,self.y_axis)))
for x,y in XY: gc.DrawRectangle(x-d/2,y-d/2,d,d)
# Show support point location.
gc.SetPen (wx.Pen(self.support_point_location_color,d/4))
xyz = grid.support_xyz
X,Y = dot(xyz,self.x_axis),dot(xyz,self.y_axis)
for (x,y) in zip(X,Y):
gc.DrawRectangle(x-d/2,y-d/2,d,d)
# Highlight support points in grid.
indices = grid.indices
ns = []
for si in grid.support_indices:
if any(all(indices==si,axis=1)): ns += [where(all(indices==si,axis=1))[0][0]]
gc.SetPen (wx.Pen(self.support_point_color,d/4))
for x,y in XY[ns]: gc.DrawRectangle(x-d/2,y-d/2,d,d)
# Highlight current point.
if len(grid.xyz) > 0:
from numpy import clip
i = clip(self.current,0,len(grid.xyz)-1)
xyz = grid.xyz[i]
gc.SetPen (wx.Pen(self.highlight_color,d/8))
x,y = dot(xyz,self.x_axis),dot(xyz,self.y_axis)
d2 = d/2
gc.DrawRectangle(x-d2/2,y-d2/2,d2,d2)
# Show current position
xyz = self.current_position
if not any(isnan(xyz)):
gc.SetPen (wx.Pen(self.current_position_color,d/8))
x,y = dot(xyz,self.x_axis),dot(xyz,self.y_axis)
d2 = d/2
gc.DrawRectangle(x-d2/2,y-d2/2,d2,d2)
def ScaledPosition(self,x,y):
"""x,y: pixel coordinates
Return value: real (x,y) coordinates in mm"""
xu,yu = self.CalcUnscrolledPosition(x,y)
s = self.ScaleFactor
ox,oy = self.Offset
xs,ys = xu/s-ox,yu/s-oy
return xs,ys
@property
def Offset(self):
"""For drawing, in mm"""
x,y,z = grid.xyz.T
w,h = max(z)-min(z),max(y)-min(y)
ox,oy = -min(z)+w*0.025,-min(y)+h*0.025
return ox,oy
@property
def ImageWidth(self):
"""in mm"""
x,y,z = grid.xyz.T
width = max(z)-min(z)
return width
@property
def ImageHeight(self):
"""in mm"""
x,y,z = grid.xyz.T
height = max(y)-min(y)
return height
def GetScaleFactor(self):
return self.scale_factor
def SetScaleFactor(self,value):
self.scale_factor = value
self.Refresh()
ScaleFactor = property(GetScaleFactor,SetScaleFactor)
def GetState(self):
"""The current settings of the window as dictionary"""
state = {}
state["ScaleFactor"] = self.ScaleFactor
state["PointerFunction"] = self.PointerFunction
state["current"] = self.current
return state
def SetState(self,state):
for key in state:
try: exec("self."+key+"="+repr(state[key]))
except Exception,msg: print("%s = %s: %s" % (key,state[key],msg))
State = property(GetState,SetState)
class Setup (wx.Dialog):
"""Allows the use to configure camera properties"""
def __init__ (self,parent):
from TextCtrl import TextCtrl
wx.Dialog.__init__(self,parent,-1,"Setup")
# Controls
style = wx.TE_PROCESS_ENTER
self.N = TextCtrl (self,size=(160,-1),style=style)
self.Origin = TextCtrl (self,size=(160,-1),style=style)
self.BaseVectors = TextCtrl (self,size=(160,80),style=style)
self.Bind (wx.EVT_TEXT_ENTER,self.OnEnter)
# Layout
layout = wx.BoxSizer()
grid = wx.FlexGridSizer (cols=2,hgap=5,vgap=5)
flag = wx.ALIGN_CENTER_VERTICAL
label = "Number:"
grid.Add (wx.StaticText(self,label=label),flag=flag)
grid.Add (self.N,flag=flag)
label = "Origen:"
grid.Add (wx.StaticText(self,label=label),flag=flag)
grid.Add (self.Origin,flag=flag)
label = "Base vectors:"
grid.Add (wx.StaticText(self,label=label),flag=flag)
grid.Add (self.BaseVectors,flag=flag)
# Leave a 10-pixel wide space around the panel.
layout.Add (grid,flag=wx.EXPAND|wx.ALL,border=10)
self.SetSizer(layout)
self.Fit()
self.update()
def update(self,Event=0):
"""Update the controls from the parameters"""
self.N.Value = ",".join([str(n) for n in grid.n])
def format(v): return "%+.3f,%+.3f,%+.3f" % tuple(v)
self.Origin.Value = format(grid.origin)
self.BaseVectors.Value = "\n".join([format(b) for b in grid.base_vectors])
def OnEnter(self,event):
"""Update the parameters from the controls"""
from numpy import asarray
t = self.N.Value
t = t.replace("x",",")
try: grid.n = asarray(eval(t))
except Exception,msg: print("%r: %r" % (t,msg))
t = self.Origin.Value
try: grid.origin = asarray(eval(t))
except Exception,msg: print("%r: %r" % (t,msg))
t = self.BaseVectors.Value
t = t.replace("\r","\n")
try: grid.base_vectors = asarray([eval(v) for v in t.split("\n")])
except Exception,msg: print("%r: %r" % (v,msg))
##print("grid.n = %r" % n)
##print("grid.origin = %r" % origin)
##print("grid.base_vectors = %r" % base_vectors)
self.update()
def tofloat(x):
from numpy import nan
try: return float(x)
except: return nan
if __name__ == '__main__': # for testing
from pdb import pm
app = wx.PySimpleApp(redirect=False) # Needed to initialize WX library
window = SampleTranslationRasterPanel()
app.MainLoop()
self = window # for debugging
<file_sep>#!/bin/env python
"""Setup: source /reg/g/psdm/etc/ana_env.sh
Open a port to psana via SSh Tunneling.
ssh -Nx -L localhost:12322:psana1508:12322 psdev &
"""
from time import time
import zmq
##run = "exp=xpptut15:run=240:smd"
run = "exp=xppj1216:run=10:smd:dir=/reg/d/ffb/xpp/xppj1216/xtc:live"
context = zmq.Context()
client = context.socket(zmq.PAIR)
client.connect("tcp://127.0.01:12322") # requires SSH Tunnel
start = time()
for i in range(0,20):
image_id = "%s:%d" % (run,i)
print "sending %r" % image_id
client.send_pyobj(image_id)
arr = client.recv_pyobj()
if arr is not None: print arr.shape,'\n',arr[0:2,0:2]
else: print "None"
print 20/(time()-start), 'Hz'
<file_sep>baudrate.value = 56700
port_name.value = 'COM3'<file_sep>title = 'BioCARS Methods Testing'
motor_names = ['high_speed_chopper_modes.value', 'heat_load_chopper_modes.value', 'Ensemble_SAXS.mode', 'Ensemble_SAXS.passes']
names = ['high_speed_chopper_mode', 'heat_load_chopper_mode', 'Ensemble_mode', 'passes_per_image']
motor_labels = ['HS Chopper', 'HL Chopper', 'ALIO Mode', 'Passes per image']
formats = ['%s', '%s', '%s', '%d']
line0.high_speed_chopper_modes.value = 'C-1'
line0.heat_load_chopper_modes.value = u'82-1.5'
line0.Ensemble_SAXS.mode = u'Laue-5Hz'
line0.Ensemble_SAXS.passes = 1
line0.updated = '21 Sep 10:53'
line0.description = 'Laue-5Hz'
command_row = 0<file_sep>#!/bin/env python
"""
Acquire a series of images using the XPP Rayonix detector with the
LCLS data acquisition system and a server running on a "mond" node
Setup:
source ~schotte/Software/Lauecollect/setup_env.sh
"""
from xppdaq import xppdaq
from time import time
from time import sleep
from logging import info,warn,debug
import logging; logging.basicConfig(level=logging.DEBUG)
from rayonix_detector_XPP_client import daq_images
Nimages = 20
Nevents = (Nimages+1)*12 # Sometimes the last image is not recorded.
info("DAQ begin...")
xppdaq.begin(Nevents)
images = daq_images.get(Nimages+1)[:Nimages]
info("waiting for DAQ to finish...")
xppdaq.wait()
info("DAQ finished...")
xppdaq.disconnect()
info("disconnect from DAQ ...")
<file_sep>#!/usr/bin/env python
"""Timing System Simulator
Author: <NAME>
Date created: Oct 19, 2016
Date last modified: Oct 19, 2017
"""
from timing_system_simulator import timing_system_simulator
t = timing_system_simulator
from Panel import BasePanel,PropertyPanel,ButtonPanel,TogglePanel,TweakPanel
import wx
from numpy import inf
__version__ = "1.0"
class TimingSystemSimulatorPanel(BasePanel):
name = "TimingSystemSimulatorPanel"
title = "Timing System Simulator"
icon = "timing-system"
standard_view = [
"TCP server",
"TCP port",
]
parameters = [
[[TogglePanel, "TCP server",t,"server_running"],{"type":"Offline/Online","refresh_period":1.0}],
[[PropertyPanel,"TCP port",t,"port"],{"choices":[2000,2001,2002,2003],"refresh_period":1.0}],
]
def __init__(self,parent=None):
BasePanel.__init__(self,
parent=parent,
name=self.name,
title=self.title,
icon=self.icon,
parameters=self.parameters,
standard_view=self.standard_view,
label_width=90,
refresh=False,
live=False,
)
self.Bind(wx.EVT_CLOSE,self.OnClose)
def OnClose(self,event=None):
t.server_running = False
self.Destroy()
##if hasattr(wx,"app"): wx.app.Exit()
if __name__ == '__main__':
from pdb import pm # for debugging
import logging
from tempfile import gettempdir
import rayonix_detector_simulator
logfile = gettempdir()+"/TimingSystemSimulatorPanel.log"
logging.basicConfig(level=logging.DEBUG,
format="%(asctime)s (levelname)s: %(message)s",
filename=logfile,
)
if not hasattr(wx,"app"): wx.app = wx.App(redirect=False) # initialize WX
panel = RayonixDetectorSimulatorPanel()
wx.app.MainLoop()
<file_sep>#!/bin/env python
"""
CA robustness test
July 7 2018
"""
__version__ = "1.0.2"
def diff_time_stamp(self):
from CA import camonitor
dic = {}
def monitor_PVS(pv):
from numpy import nan
from CA import caget
from time import sleep
dic[pv] = (0,0)
while True:
sleep(0.5)
value = caget(pv)
if type(value) == None or value == nan:
print('WARNING: %r IS %r' % (pv,value))
dic[pv] = (dic[pv][0],dic[pv][1]+1)
else:
dic[pv] = (dic[pv][0]+1,dic[pv][1])
def add_thread_PV(pv):
from thread import start_new_thread
start_new_thread(monitor_PVS,(pv,))
# Run the main program
if __name__ == "__main__":
from thread import start_new_thread
add_thread_PV('BNCHI.BunchCurrentAI.VAL')
add_thread_PV('NIH:TEMP.P')
add_thread_PV('NIH:TEMP.I')
add_thread_PV('NIH:SAMPLE_FROZEN_OPT_RGB.MEAN')
add_thread_PV('NIH:SAMPLE_FROZEN_OPT_RGB.STDEV')
add_thread_PV('NIH:CHILLER.VAL')
add_thread_PV('NIH:TEMP.VAL')
add_thread_PV('NIH:CHILLER.RBV')
add_thread_PV('NIH:TEMP.RBV')
<file_sep>ip_address = 'pico5.cars.aps.anl.gov:8100'
refresh_interval = 10.0<file_sep>#!/usr/bin/env python
"""Simple TCP/IP communication with a server.
<NAME>, Nov 6, 2016 - Aug 28, 2017
"""
__version__ = "1.3" # (ip_address,port) -> ip_address_and_port
from logging import debug,info,warn,error
connections = {}
timeout = 5.0
def send(ip_address_and_port,command):
"""Send a command that does not generate a reply.
ip_address_and_port: e.g. '192.168.3.11:2001'
command: string, will by '\n' terminated"""
query(ip_address_and_port,command,count=0)
write = send
def query(ip_address_and_port,command,terminator="\n",count=None):
"""Send a command that generates a reply.
ip_address_and_port: e.g. '192.168.3.11:2001'
command: string, will by '\n' terminated
count: if given, number of bytes to read as reply, overrides terminator
Return value: reply
"""
with lock(ip_address_and_port):
import socket # for exception
if not command.endswith("\n"): command += "\n"
reply = ""
for attempt in range(0,2):
if attempt > 0: warn("query %r, retrying..." % command)
try:
c = connection(ip_address_and_port)
if c is None: break
# Clear input queue
c.settimeout(1e-6)
discard = ""
while True:
try:
discard += c.recv(65536)
c.settimeout(0.1)
except socket.timeout: break
if len(discard) > 0:
warn("query %r, ignoring unexpected reply (%d bytes)" %
(command,len(discard)))
c.settimeout(3)
c.sendall(command)
reply = ""
if count is not None:
disconnected = False
while len(reply) < count:
r = c.recv(count-len(reply))
reply += r
if len(r) == 0: disconnected = True; break
if len(reply) > count:
warn("query %r, count=%d: discarding %d bytes" %
(command,count,len(reply)-count))
reply = reply[0:count]
if disconnected: warn("disconnected"); continue
elif terminator:
while not terminator in reply:
r = c.recv(65536)
reply += r
if len(r) == 0: break
if len(r) == 0: warn("disconnected"); continue
except socket.error,msg:
warn("query %r, error %s" % (command,msg))
if ip_address_and_port in connections:
debug("resetting connection to %s" % ip_address_and_port)
del connections[ip_address_and_port]
continue
break
##if count is not None: debug("query %r, count=%d, got %d bytes" % (command,count,len(reply)))
##elif terminator: debug("query %r, %.23r" % (command,reply))
return reply
def disconnect(ip_address_and_port):
"""Make sure no connection is open to the specified port.
ip_address_and_port: e.g. '192.168.3.11:2001'
"""
with lock(ip_address_and_port):
if ip_address_and_port in connections:
debug("disconnecting %s" % ip_address_and_port)
del connections[ip_address_and_port]
def connected(ip_address_and_port):
"""Is server online?
ip_address_and_port: e.g. '192.168.3.11:2001'
"""
with lock(ip_address_and_port):
connected = connection(ip_address_and_port) is not None
return connected
def connection(ip_address_and_port):
"""Cached IP socket connection"""
from thread import start_new_thread
from time import time,sleep
if not ip_address_and_port in connecting:
connecting[ip_address_and_port] = False
if not connection_alive(ip_address_and_port):
if not ip_address_and_port in first_attempt:
first_attempt[ip_address_and_port] = time()
if not connecting[ip_address_and_port]:
connecting[ip_address_and_port] = True
start_new_thread(connect,(ip_address_and_port,))
while not connection_alive(ip_address_and_port):
sleep(0.010)
if time()-first_attempt[ip_address_and_port] > 1.0: break
if connection_alive(ip_address_and_port) and ip_address_and_port in connections:
# reset timeout
if ip_address_and_port in first_attempt:
del first_attempt[ip_address_and_port]
connection = connections[ip_address_and_port]
else: connection = None
return connection
def connect(ip_address_and_port):
"""Establish IP socket connection"""
import socket
if not connection_alive(ip_address_and_port):
if ip_address_and_port in connections:
warn("tcp client: %s: reconnecting" % ip_address_and_port)
connection = socket.socket()
connection.settimeout(timeout)
connection.setsockopt(socket.SOL_SOCKET,socket.SO_KEEPALIVE,1)
try: # MacOS, Linux?
TCP_KEEPALIVE = 0x10 # idle time
TCP_KEEPINTVL = 0x101
TCP_KEEPCNT = 0x102
connection.setsockopt(socket.IPPROTO_TCP,TCP_KEEPALIVE,3)
connection.setsockopt(socket.IPPROTO_TCP,TCP_KEEPINTVL,3)
connection.setsockopt(socket.IPPROTO_TCP,TCP_KEEPCNT,1)
except: pass
try: # Windows
connection.ioctl(socket.SIO_KEEPALIVE_VALS,(1,1000,1000))
except: pass
##debug("tcp client: %s connecting" % ip_address_and_port)
ip_address,port = ip_address_and_port.split(":")
port = int(port)
try: connection.connect((ip_address,port))
except socket.error,m:
warn("tcp client: %s: connect: %s" % (ip_address_and_port,m))
connection = None
if connection:
##debug("tcp client: %s: connected" % ip_address_and_port)
connection.settimeout(timeout)
connections[ip_address_and_port] = connection
elif ip_address_and_port in connections:
del connections[ip_address_and_port]
connecting[ip_address_and_port] = False
def connection_alive(ip_address_and_port):
"""Is socket in usable state?"""
import socket
if not ip_address_and_port in connections: return False
c = connections[ip_address_and_port]
try: c.getpeername()
except socket.error,m:
warn("tcp client: %s alive? peername: %s"%(ip_address_and_port,m));
return False
timeout = c.gettimeout()
c.settimeout(0.000001)
try:
if len(c.recv(1)) == 0:
warn("tcp client: %s alive?disconnected"% ip_address_and_port );
return False
except socket.timeout: pass
except socket.error,m:
warn("tcp client: %s alive? recv: %s"%(ip_address_and_port,m));
return False
c.settimeout(timeout)
try: c.send("")
except socket.error,m:
warn("tcp client: %s alive? send: %s"%(ip_address_and_port,m));
return False
return True
def lock(ip_address_and_port):
"""A per-connection thread synchronization lock
ip_address_and_port: e.g. '192.168.3.11:2001'
"""
from thread import allocate_lock
if not ip_address_and_port in locks:
locks[ip_address_and_port] = allocate_lock()
lock = locks[ip_address_and_port]
return lock
locks = {}
first_attempt = {}
connecting = {}
if __name__ == "__main__":
from pdb import pm
import logging
from time import time
ip_address_and_port = "pico25.niddk.nih.gov:2000"
print('connected("localhost:2222")')
print('connected("mx340hs.cars.aps.anl.gov:2222")')
print('connected("172.16.17.32:2000")')
print('connected("pico25.niddk.nih.gov:2000")')
print('query("pico25.niddk.nih.gov:2000","registers")')
ip_address = '192.168.3.11:2002'; command = "frame_count"; terminator="\n";count=None
reply = query(ip_address,command,terminator,count)
logging.basicConfig(level=logging.DEBUG,
format="%(asctime)s %(levelname)s: %(message)s")
debug("?")
<file_sep>"""
One-dimensional scans
<NAME>, APS, Mar 12, 2008 - Jul 23, 2015
<NAME>, APS, Feb 28, 2018 - July 4, 2018
Run simuation:
from sim_scan import *
data=rscan(sim_taby,-0.2,0.2,20,sim_flux)
COM(data)
app=wx.App(False)
Plot(data)
Run electronic test:
tmode.value = 1
trigger="pulses.value=1;sleep(0.1)"
data=rscan (sim_taby,-0.2,0.2,10,xray_pulse,trigger=trigger)
Center the laser beam:
data=rscan (LaserZ,-1,1,50,laser_pulse,plot=True)
data=rscan (LaserX,-0.4,0.4,40,laser_pulse,plot=True)
Tweak the optical table with single X-ray pulses:
tmode.value = 1
trigger="pulses.value=1;sleep(0.1)"
data=rscan (TableY,-0.05,0.05,10,xray_pulse,trigger=trigger,plot=True)
COM(data)
Measure the X-ray beam profile:
data=rscan (sx,-0.25,0.25,50,xray_pulse,plot=True)
data=read_xy("J:\\anfinrud_0803\\Scans\\2008.03.14 X-ray Y proj 2.txt")
FWHM(data),COM(data),CFWHM(data)
Feb 28 2018 <NAME>
version 1.6 - Added analysis of the slit scan.
slit_scan_analysis_1d(data)
This code takes "data", takes derivative and fits it with 2 gaussians.
The initial parameters for the fit are taken:
amplitudes: max/min values
positions: max/min argument
width: 200 um <- I ahve tested with 56 um as well. It always finds nice fit.
version 1.7 - March 1 2018 Valentyn
added compensation for the pulse fluctions
in the X-Ray hutch Lecroy ps laser ch4 area
(search for Valentyn March 1 2018)
Later commented it out since it wasn't doing much(this line added on July 4 2018)
version 1.8 -July 4 2018 Valentyn
this used to be scan.py filename
added save image to a file
added comments section to scan_and_analyse_1d function
function slit_scan_analysis_1d scans motor A between two different
limits with defined step.
"""
from Plot import Plot
from numpy import sqrt,isnan
from time import time
from sleep import sleep
from logging import debug,info,warn,error
__version__ = "1.8"
def rscan(motors,begins,ends,nsteps,counters=[],averaging_time=0,logfile=None,
trigger=None,plot=False,verbose=True,data=None):
"""
Performs a relative scan around the current position.
This moves 'motor' from the current position - 'begin' to
the current position + 'end' in 'nsteps' steps, while
reading 'counters' each time the motor stops.
The number of scan points acquired is nsteps+1.
The motor returns to the initial position after the scan is complete.
If 'averaging_time' (in seconds) is given the motor stops for the given
time at each scan point, while the counter result is averaged.
'counters' can be either a single counter or list of counters (in square
backets).
'trigger' is a python command to be executed before each scan point.
If 'plot' is True the scan data is dsiplayed a curve in a graphocs window
during the scan.
If 'verbose' is True scan data is printed in the terminal window during
the scan.
If 'data' is given, this list is used to store the scan result, rather than
creating a new one.
nm - number of motors
nc - number of counters
"""
if not isinstance(motors,list): motors = [motors]
nm = len(motors)
if not isinstance(begins,list): begins = [begins]
while len(begins) < nm: begins.append(begins[-1])
for i in range(0,nm): begins[i] = float(begins[i])
if not isinstance(ends,list): ends = [ends]
while len(ends) < nm: ends.append(ends[-1])
for i in range(0,nm): ends[i] = float(ends[i])
nsteps = int(round(nsteps))
if not isinstance(counters,list): counters = [counters]
nc = len(counters)
steps = range(0,nm)
for i in range(0,nm):
steps[i] = (ends[i]-begins[i])/nsteps
if logfile != None:
logfile = file(logfile,"w")
if data == None:
data = []
return_data = True
else:
while len(data) > 0: data.pop()
return_data = False
cancelled = False
# Record initial motor positions.
starting_positions = range(0,nm)
for i in range(0,nm): starting_positions[i] = motors[i].value
if x_method == 'linear':
scan_vector = linear_vector(motors,starting_positions,begins,ends,nsteps)
elif x_method == 'nonlinear'::
scan_vector = nonlinear_vector(motors,starting_positions,begins,ends,nsteps)
# Write scan header.
line = "#"
for i in range(0,nm):
if hasattr(motors[i],"name"): line += motors[i].name
else: line += "pos"
if hasattr(motors[i],"unit") and motors[i].unit != "": line += "/"+motors[i].unit
line += "\t"
for i in range(0,nc):
if hasattr(counters[i],"name"): line += counters[i].name
else: line += "\tcount"
if hasattr(counters[i],"unit") and counters[i].unit != "":
line += "/"+counters[i].unit
line += "\t"
line.strip("\t")
if verbose: print line
if logfile != None: logfile.write(line+"\n"); logfile.flush()
# Open plot window.
if plot: StartMyMainLoop(); plot_data.append([[0,0],[1,1]])
positions = range(0,nm); counts = range(0,nc)
try:
for j in range (0,nsteps+1):
try:
# Move motors
for i in range(0,nm):
if x_method == 'linear' or x_method == 'nonlinear:
motors[i].value = scan_vector[i][j]# scan vector for motor i
else:
motors[i].value = starting_positions[i] + begins[i]+steps[i]*j
# Wait for motors to stop
while 1:
moving = False
for i in range(0,nm):
if hasattr(motors[i],"moving"): moving = moving or motors[i].moving
if not moving: break
sleep(0.03)
for i in range(0,nm): positions[i] = motors[i].value
# Acquire scan point
if averaging_time == 0:
if trigger: exec(trigger)
for i in range(0,nc): counts[i] = counters[i].value#/laser_scope.measurement(1).value
# line above March 1, 2018 Valentyn added /laser_scope.measurement(1).value
else:
for i in range(0,nc):
if hasattr(counters[i],"count_time"): counters[i].count_time = averaging_time; #laser_scope.measurement(1).count_time = averaging_time;
for i in range(0,nc):
if hasattr(counters[i],"start"): counters[i].start(); #laser_scope.measurement(1).start() # line above March 1, 2018 Valentyn added
if trigger: exec(trigger)
sleep(averaging_time)
for i in range(0,nc):
if hasattr(counters[i],"stop"): counters[i].stop(); #laser_scope.measurement(1).stop() # line above March 1, 2018 Valentyn added
for i in range(0,nc):
if hasattr(counters[i],"average"): counts[i] = counters[i].average#/laser_scope.measurement(1).average
# line above March 1, 2018 Valentyn added /laser_scope.measurement(1).average
else: counts[i] = counters[i].value
# Write scan record
line = ""
for i in range(0,nm): line += str(positions[i])+"\t"
for i in range(0,nc): line += str(counts[i])+"\t"
line.strip("\t")
if verbose: print line
if logfile != None: logfile.write(line+"\n"); logfile.flush()
# Skip 'Not a Number' values (problems with plotting)
skip = False
for val in positions+counts:
if isnan(val): skip = True
if not skip: data.append(positions+counts)
# Update plot window
if plot: plot_data[-1] = data+[]
except KeyboardInterrupt: cancelled = True; break
# Return motors to the starting positions
for i in range(0,nm): motors[i].value = starting_positions[i]
# Wait for motors to stop
while not cancelled:
try:
moving = False
for i in range(0,nm):
if hasattr(motors[i],"moving"): moving = moving or motors[i].moving
if not moving: break
sleep(0.01)
except KeyboardInterrupt: break
# Restart the counter after than scan is done (useful for oscilloscope-based counters)
for i in range(0,nc):
if hasattr(counters[i],"start"): counters[i].start(); laser_scope.measurement(1).start()
if return_data: return data
except KeyboardInterrupt:
info("Returning motors to the starting positions.")
for i in range(0,nm): motors[i].value = starting_positions[i]
finally:
info("Returning motors to the starting positions.")
for i in range(0,nm): motors[i].value = starting_positions[i]
def linear_vector(motors,starting_positions,begins,ends,nsteps):
"""creates a linear scan vector"""
from numpy import arange
if not isinstance(starting_positions,list): starting_positions = [starting_positions]
if not isinstance(begins,list): begins = [begins]
if not isinstance(ends,list): ends = [ends]
if not isinstance(nsteps,list): nsteps = [nsteps]
if not isinstance(motors,list): motors = [motors]
steps = []
scan_vector = []
nm = len(motors)
for i in range(0,nm):
steps.append((1.0*ends[i]-1.0*begins[i])/(1.0*nsteps[i]))
#scan_vector.append([])
#for j in range (0,nsteps[i]+1):
scan_vector.append(arange(begins[i],ends[i],steps[i]))#starting_positions[i] + begins[i]+steps[i]*j)
return scan_vector
def nonlinear_vector(motors,starting_positions,width,nsteps):
"""creates a error function type of scan vector"""
from numpy import arange
from numpy import concatenate
if not isinstance(starting_positions,list): starting_positions = [starting_positions]
if not isinstance(width,list): width = [width]
if not isinstance(nsteps,list): nsteps = [nsteps]
if not isinstance(motors,list): motors = [motors]
a1=range(len(motors))
a2=range(len(motors))
x1=range(len(motors))
x2=range(len(motors))
w1=range(len(motors))
w2 =range(len(motors))
linear=range(len(motors))
ends =range(len(motors))
begins =range(len(motors))
steps= range(len(motors))
for i in range(len(motors)):
a1[i] = -1
a2[i] = -1
x1[i] = starting_positions[i] - width[i]/2.0
x2[i] = starting_positions[i] + width[i]/2.0
w1[i] = 2
w2[i] = 2
begins[i] = starting_positions[i]-width[i]
ends[i] = starting_positions[i]+width[i]
steps[i] = (2*width[i])/(1.0*nsteps[i])
print(x1,x2,begins,ends,steps)
scan_vector = []
nm = len(motors)
for i in range(0,nm):
x = arange(begins[i],ends[i],steps[i])
x_0125 = x.shape[0]/8
x_0250 = x.shape[0]/4
x_0375 = x.shape[0]*3/8
x_050 = x.shape[0]/2
x_0625 = x.shape[0]*5/8
x_075 = x.shape[0]*3/4
x_0875 = x.shape[0]*7/8
x_1 = x.shape[0]-1
x1 = arange(x[0],x[x_0125],steps[i]*4)
x2 = arange(x[x_0125],x[x_0375],steps[i]/2)
x3 = arange(x[x_0375],x[x_0625],steps[i]*4)
x4 = arange(x[x_0625],x[x_0875],steps[i]/2)
x5 = arange(x[x_0875],x[x_1],steps[i]*4)
y_erf = concatenate((x1,x2,x3,x4,x5))
scan_vector.append(list(y_erf))
return y_erf
def test_erf_vs_lin():
from matplotlib import pyplot as plt
erf_v = erf_vector(1,0,5,100)
lin_v = linear_vector(1,0,-15,15,100)[0]
plt.plot(erf_v)
plt.plot(lin_v)
plt.show()
def plot_erf_correction(x1,x2):
from matplotlib import pyplot as plt
from numpy import arange
x = arange(-3,3,0.04)
y1 = 1*x
summ = abs(x2)+abs(x1)
y = erf(x,-0.10*summ,(summ*3*(x2-x1))/(summ),x1,0,-(summ*3*(x2-x1))/(summ),x2,0) + 0;
plt.plot(x,y+y1,'o');
x = arange(-3,3,0.02)
y1 = 1*x;
plt.plot(x,y1,'o');plt.show()
def peakinfo(data):
"Generate a report about peak wdith and position"
return "FWHM %.3f mm at %.3f mm, COM %.3f mm, peak %.2g at %.3f mm" %\
(FWHM(data),CFWHM(data),COM(data),peak(data),peakpos(data))
def peak(data):
"""Returns the maximum y of a curve given as list of [x,y] values"""
return max(yvals(data))
def pkpk(data):
"""Returns peak to peak difference of the y values of a curve given as
list of [x,y] values"""
return max(yvals(data))-min(yvals(data))
def peakpos(data):
"""Returns the x value of the maximum curve given as list of [x,y] values"""
x = xvals(data); y = yvals(data); n = len(data)
if n < 1: return NaN
x_at_ymax = x[0]; ymax = y[0]
for i in range (0,n):
if data[i][1] > ymax: x_at_ymax = x[i]; ymax = y[i]
return x_at_ymax
def COM(data):
"""Calculates the center of mass of the positive peak of a curve
given as list of [x,y] values"""
data = subtract_baseline(data)
x = xvals(data); y = yvals(data); n = len(data)
# Subtract baseline
y0 = min(y)
for i in range (0,n): y[i] -= y0
sumxy = 0
for i in range (0,n): sumxy += x[i]*y[i]
return sumxy/sum(y)
def RMSD(data):
"""Calculates root mean square deviation width of the positive peak of
a curve given as list of [x,y] values"""
data = subtract_baseline(data)
x0 = COM(data)
x = xvals(data); y = yvals(data); n = len(data)
sumx2 = 0
for i in range (0,n): sumx2 += y[i]*(x[i]-x0)**2
return sqrt(sumx2/sum(y))
def FWHM(data):
"""Calculates full-width at half-maximum of a positive peak of a curve
given as list of [x,y] values"""
x = xvals(data); y = yvals(data); n = len(data)
HM = (min(y)+max(y))/2
for i in range (0,n):
if y[i]>HM: break
x1 = interpolate_x((x[i-1],y[i-1]),(x[i],y[i]),HM)
r = range(0,n); r.reverse()
for i in r:
if y[i]>HM: break
x2 = interpolate_x((x[i+1],y[i+1]),(x[i],y[i]),HM)
return abs(x2-x1)
def CFWHM(data):
"""Calculates the center of the full width half of the positive peak of
a curve given as list of [x,y] values"""
x = xvals(data); y = yvals(data); n = len(data)
HM = (min(y)+max(y))/2
for i in range (0,n):
if y[i]>HM: break
x1 = interpolate_x((x[i-1],y[i-1]),(x[i],y[i]),HM)
r = range(0,n); r.reverse()
for i in r:
if y[i]>HM: break
x2 = interpolate_x((x[i+1],y[i+1]),(x[i],y[i]),HM)
return (x2+x1)/2.
def remove_NaN(data):
"""Filters out 'Not a Number' values from a list of [x,y] values"""
x = xvals(data); y = yvals(data); n = len(data)
data2 = []
for i in range (0,n):
if not isnan(x[i]) and not isnan(y[i]): data2.append([x[i],y[i]])
return data2
def subtract_baseline(data):
"""Returns baseline-ccorrects a curve given as list of [x,y] values"""
x = xvals(data); y = yvals(data); n = len(data)
y0 = min(y)
for i in range (0,n): y[i] -= y0
return zip(x,y)
def interpolate_x((x1,y1),(x2,y2),y):
"Linear interpolation between two points"
# In case result is undefined, midpoint is as good as any value.
if y1==y2: return (x1+x2)/2.
x = x1+(x2-x1)*(y-y1)/float(y2-y1)
#print "interpolate_x [%g,%g,%g][%g,%g,%g]" % (x1,x,x2,y1,y,y2)
return x
def xvals(xy_data):
"xy_data = list of (x,y)-tuples. Returns list of x values only."
xvals = []
for i in range (0,len(xy_data)): xvals.append(xy_data[i][0])
return xvals
def yvals(xy_data):
"xy_data = list of (x,y)-tuples. Returns list of y values only."
yvals = []
for i in range (0,len(xy_data)): yvals.append(xy_data[i][1])
return yvals
def print_xy(xy_data):
"Displays (x,y) tuples as two columns"
for i in range(0,len(xy_data)): print "%g\t%g" % (xy_data[i][0],xy_data[i][1])
def save_xy(xy_data,filename, directory = ""):
"Write (x,y) tuples as two-column tab separated ASCII file."
output = file(filename,"w")
for i in range(0,len(xy_data)):
output.write("%g\t%g\n" % (xy_data[i][0],xy_data[i][1]))
def read_xy(filename):
"""Reads two two-column ASCII file and returns as list of floating point
[x,y] pairs"""
data = []
infile = file(filename)
line = infile.readline()
while line != '':
try:
cols = line.split()
x = float(cols[0]); y = float(cols[1])
data.append([x,y])
except ValueError: pass
line = infile.readline()
return data
def timescan(counters=[],waiting_time=1,averaging_time=0,total_time=1e1000,
logfile=None):
"""Monitor a counter or list of counters at a regular time interval.
If "waiting_time" is not specified that interval is 1 second.
"counters" can be either a single counter or list of counters (in square backets).
If "total_time" is given, the scan is ended after the specified number of seconds.
Otherwise, it is ended on keyboard interrupt (Control-C).
"""
if not isinstance(counters,list): counters = [counters]
nc = len(counters)
if logfile != None: logfile = file(logfile,"w")
# Write scan header
line = "#date\ttime/s\t"
for i in range(0,nc):
if hasattr(counters[i],"name"): line += counters[i].name
else: line += "\tcount"
if hasattr(counters[i],"unit") and counters[i].unit != "":
line += "/"+counters[i].unit
line += "\t"
line.strip("\t")
#print line # commented on Feb 28 2018, Valentyn
if logfile != None: logfile.write(line+"\n"); logfile.flush()
counts = range(0,nc)
n = 0
start = time()
while time() < start + total_time:
try:
t = time()
# Acquire scan point
if averaging_time == 0:
for i in range(0,nc): counts[i] = counters[i].value
else:
for i in range(0,nc):
if hasattr(counters[i],"count_time"): counters[i].count_time = averaging_time
for i in range(0,nc):
if hasattr(counters[i],"start"): counters[i].start()
sleep(averaging_time)
for i in range(0,nc):
if hasattr(counters[i],"stop"): counters[i].stop()
for i in range(0,nc):
if hasattr(counters[i],"average"): counts[i] = counters[i].average
else: counts[i] = counters[i].value
# Write scan record
line = datestring(t)+"\t"+str(t-start)+"\t"
for i in range(0,nc): line += str(counts[i])+"\t"
line.strip("\t")
print line
if logfile != None: logfile.write(line+"\n"); logfile.flush()
n = n+1
dt = n*waiting_time - (time()-start)
while dt>0:
sleep (min(dt,0.1))
dt = n*waiting_time - (time()-start)
except KeyboardInterrupt: break
def datestring(seconds):
from datetime import datetime
date = str(datetime.fromtimestamp(seconds))
return date[:-3] # omit microsconds
def StartMyMainLoop():
import wx
import threading
if not hasattr(wx,"MainLoopThread") or not wx.MainLoopThread.isAlive():
wx.MainLoopThread = threading.Thread(target=MyMainLoop,name="MyMainLoop")
if not wx.MainLoopThread.isAlive():
wx.MainLoopThread = threading.Thread(target=MyMainLoop,name="MyMainLoop")
wx.MainLoopThread.start()
def MyMainLoop():
import wx
from time import sleep
if not hasattr(wx,"app"): wx.app = wx.App(False)
evtloop = wx.GUIEventLoop()
wx.EventLoop.SetActive(evtloop)
while True:
while evtloop.Pending(): evtloop.Dispatch()
evtloop.ProcessIdle()
update_plots()
sleep(0.1)
def gauss(x,a1,x01,fwhm1,a2,x02,fwhm2):
from numpy import exp
return a1 * exp(-(x-x01)**2 / (2*(fwhm1/2.355)**2)) + a2 * exp(-(x-x02)**2 / (2*(fwhm2/2.355)**2))
def erf(x,a,b1,x01,y01,b2,x02,y02):
from scipy import special
return (a/2)*special.erf(b1*(x-x01)) + y01 + (a/2)*special.erf(-b2*(x-x02)) + y02
def slit_scan_analysis_1d(xy_data, plot = False, img_filename = '', comments = ''):
from numpy import asarray, gradient
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
from numpy import exp, argmin, argmax, where, max, min
arr = asarray(xy_data) #create numpy array
x = arr[:,0]
y = arr[:,1]
y_max = max(y)
y_min_l = y[0]
y_min_r = y[-1]
r_idx = where(y > y_max/2.0)[0][-1]
l_idx = where(y > y_max/2.0)[0][0]
print(l_idx,r_idx)
popt_data,pcov_data = curve_fit(erf,x,y, p0 = [y_max,1,x[l_idx],y_min_l,1,x[r_idx],y_min_r])
#print popt_data,pcov_data
grad_y = gradient(y)
popt, pcov = curve_fit(gauss,x,grad_y, p0 = [max(grad_y), x[argmax(grad_y)] , 0.2, min(grad_y), x[argmin(grad_y)] , 0.2])
print('---from error function fit---')
erf_fwhm1 = 2.335/(sqrt(2)*popt_data[1])
erf_fwhm2 = 2.335/(sqrt(2)*popt_data[4])
print('FWHM_1 = ' + str(round(1000*erf_fwhm1,1)) + ' um'
+ ' and FWHM_2= ' + str(round(1000*erf_fwhm2,1)) + ' um' + ' and average of '
+ str(round(1000*(0.5*erf_fwhm1+0.5*erf_fwhm2),1)) + ' um' )
print('center1 = ' + str(round(popt_data[2],3)) + ' mm' + ' and center2 = '
+ str(round(popt_data[5],3)) + ' mm' + ' and center at '
+ str(round(0.5*popt_data[2]+0.5*popt_data[5],3)) + ' mm')
print('---From gaussians fit---')
print('FWHM_1 = ' + str(round(1000*popt[2],1)) + ' um' + ' and FWHM_2= ' + str(round(popt[5]*1000,1)) + ' um' + ' and average of ' + str(round(1000*(0.5*popt[2]+0.5*popt[5]),1)) + ' um' )
print('center1 = ' + str(round(popt[1],3)) + ' mm' + ' and center2 = ' + str(round(popt[4],3)) + ' mm' + ' and center at ' + str(round(0.5*popt[4]+0.5*popt[1],3)) + ' mm')
plt.figure(1)
plt.subplot(211)
plt.plot(x,y)
plt.plot(x,erf(x,*popt_data), linewidth = 2)
plt.xticks([])
plt.title('max intensity = %r' % round(max(y),5) + ' FWHM(um) = (%r,%r) \n and center at %r mm' % (round(1000*erf_fwhm1,1) ,round(1000*erf_fwhm2,1),round(0.5*popt_data[2]+0.5*popt_data[5],3)) )
plt.subplot(212)
plt.plot(x,grad_y,'o')
plt.plot(x,gauss(x,*popt), linewidth = 2)
plt.title('FWHM_1 = ' + str(round(1000*popt[2],1))+ ' um' + ' and FWHM_2 = ' + str(round(popt[5]*1000,1)) + ' um'+
'\n and center at' + str(round(0.5*popt[4]+0.5*popt[1],3)) + ' mm' +
' comments:' + comments)
try:
plt.savefig(img_filename, dpi = 300)
except:
print('couldn"t save image to %r' %img_filename)
if plot:
plt.show()
def scan_and_analyse(axis = 'GonZ', filename = '/Laser Z scan-3', plot = False, comments = 'no comments'):
"""
filename is a local filename in the folder dir.
"""
if axis == 'GonZ':
data = rscan(GonZ,-0.5,+0.5,40,xray_pulse,1.0, plot=True)
elif axis == 'GonY':
data = rscan(GonY,-2.8,+2.8,100,xray_pulse,1.0, plot=True)
elif axis == 'GonX':
data = rscan(GonX,-4,+4,100,xray_pulse,1.0, plot=True)
logfile = dir + filename
try:
save_xy(data,logfile+'.txt')
except:
print("couldn't save to a file")
try:
slit_scan_analysis_1d(data, plot = plot, img_filename = logfile + '.png', comments = comments)
except:
print(traceback.format_exc())
print("couldn't plot and analyse")
print('Comments: %r' % comments)
return data
plots = []
plot_data = []
def update_plots():
import wx
while len(plots) < len(plot_data): plots.append(Plot())
for plot,data in zip(plots,plot_data):
try:
if plot.data != data: plot.data = data; plot.update()
except wx.PyDeadObjectError: pass
def scan_LaserY(from_value = 0, to_value = 0,steps = 0):
"""
"""
from instrumentation import * # Beamline instrumentation motors
data_lst = []
for i in range(6):
LaserY.value = -4.34 + 0.1*i
data = scan_and_analyse(axis = "GonZ", filename = "/Laser Z scan -4.34-> -3.74 - "+str(i), plot = False, comments = "laserY = "+str(-4.34 - 0.1*i)+"mm telescope = 2mm")
data_lst.append(data)
return data_lst
if __name__ == "__main__": # This is for testing, remove when done
import logging
logging.basicConfig(level=logging.INFO,format="%(levelname)s: %(message)s")
from instrumentation import * # Beamline instrumentation motors
import os
import matplotlib.pyplot as plt
dir = '/net/mx340hs/data/anfinrud_1810/Scans/2018.10.30 ns laser beam profile/'
logfile = dir+"/Laser Z scan-1.txt"
if not os.path.exists(dir):
print("directory didn't exist, creating (%r)" % dir)
os.mkdir(dir)
else:
print('directory %r exists' % dir)
print('erf = erf_vector(1,-10,10,10)')
print('dir = %r' %(dir))
print('logfile = %r' %logfile)
print('data = rscan(GonZ,-0.4,+0.4,160,xray_pulse,1.0,plot=True)')
print('data = rscan(GonY,-2,+2,160,xray_pulse,1.0,plot=True)')
print('data = rscan(GonX,-2,+2,40,xray_pulse,1.0,plot=True)')
print('save_xy(data,%r)' % logfile)
print('data = read_xy(' + logfile + ')')
print('"FWHM %.3f @ %.3f" % (FWHM(data),CFWHM(data))')
print('slit_scan_analysis_1d(data, plot = True) #run analysis and plot the result')
print('data = scan_and_analyse(axis = "GonZ", filename = "/Laser Z scan-6", plot = False, comments = "laserY = -3.9099mm")')
<file_sep>"""<NAME>, 14 Nov 2014 - 14 Nov 2014"""
__version__ = "1.0"
import sys
def module_dir(object):
"""directory of the current module"""
from os.path import dirname
module_dir = dirname(module_path(object))
##module_dir = module_dir.replace("\\","/")
if module_dir == "": module_dir = "."
return module_dir
def module_path(object):
"""full pathname of the current module"""
if sys.version_info[0] ==3:
from normpath3 import normpath
else:
from normpath import normpath
global MODULE_PATH
if "MODULE_PATH" in globals(): return MODULE_PATH
from sys import path
from os import getcwd
from os.path import basename,exists
from inspect import getmodulename,getfile
# 'getfile' retreives the source file name name compiled into the .pyc file.
try: pathname = getfile(object)
except: pathname = getfile(lambda x:x)
##print("module_path: pathname: %r" % pathname)
if not exists(pathname):
# The module might have been compiled on a different machine or in a
# different directory.
pathname = pathname.replace("\\","/")
filename = basename(pathname)
##print("module_path: filename: %r" % filename)
dirs = [dir for dir in [getcwd()]+path if exists(dir+"/"+filename)]
if len(dirs) == 0: print("pathname of file %r not found" % filename)
dir = dirs[0] if len(dirs) > 0 else "."
pathname = dir+"/"+filename
##print("module_path: pathname: %r" % pathname)
pathname = normpath(pathname)
MODULE_PATH = pathname
return pathname
if __name__ == "__main__":
print("module_path(module_dir)")
print("module_dir(module_dir)")
<file_sep>filename = '/data/anfinrud_1203/Data/Laue/PYP/PYP-H2/PYP-H2.log'
lines = file(filename).readlines()
column_headers = lines[18]
line1 = lines[19]
line2 = lines[20]
NF = [line.count("\t") for line in lines[18:]]
<file_sep>port = COM3
stabilization_nsamples = 5
stabilization_threshold = 0.05
temperature.moving_timeout = 15.0
temperature.timeout = 180
temperature.tolerance = 0.5<file_sep>Ensemble.ip_address = 'nih-instrumentation.cars.aps.anl.gov:2000'
GigE_camera.MicroscopeCamera.camera.IP_addr = 'id14b-prosilica1.cars.aps.anl.gov'
GigE_camera.MicroscopeCamera.ip_address = 'nih-instrumentation.cars.aps.anl.gov:2002'
GigE_camera.WideFieldCamera.camera.IP_addr = 'id14b-prosilica2.cars.aps.anl.gov'
GigE_camera.WideFieldCamera.ip_address = 'nih-instrumentation.cars.aps.anl.gov:2001'
GigE_camera.WidefieldCamera.camera.IP_addr = 'id14b-prosilica2.cars.aps.anl.gov'
GigE_camera.WidefieldCamera.ip_address = '172.16.31.10:2001'
MicroscopeCamera.ImageWindow.Center = (680.0, 512.0)
MicroscopeCamera.Mirror = True
MicroscopeCamera.NominalPixelSize = 0.000526
MicroscopeCamera.Orientation = 0
MicroscopeCamera.camera.IP_addr = 'id14b-prosilica1.cars.aps.anl.gov'
MicroscopeCamera.x_scale = -1.0
MicroscopeCamera.y_scale = 1.0
MicroscopeCamera.z_scale = -1.0
WideFieldCamera.ImageWindow.Center = (656.0, 508.0)
WideFieldCamera.Mirror = False
WideFieldCamera.NominalPixelSize = 0.00465
WideFieldCamera.Orientation = 0
WideFieldCamera.camera.IP_addr = 'id14b-prosilica2.cars.aps.anl.gov'
WideFieldCamera.x_scale = -1.0
WideFieldCamera.y_scale = 1.0
WideFieldCamera.z_scale = -1.0
laser_scope.ip_address = 'id14l-scope.cars.aps.anl.gov:2000'
rayonix_detector.ip_address = 'mx340hs.cars.aps.anl.gov:2222'
sample.phi_motor_name = 'SamplePhi'
sample.phi_scale = 1.0
sample.rotation_center = (-0.32668, -0.6098)
sample.x_motor_name = 'SampleX'
sample.x_scale = 1.0
sample.xy_rotating = True
sample.y_motor_name = 'SampleY'
sample.y_scale = 1.0
sample.z_motor_name = 'SampleZ'
sample.z_scale = 1.0
timing_system.ip_address = 'id14timing2.cars.aps.anl.gov:2000'
xray_scope.ip_address = 'id14b-xscope.cars.aps.anl.gov:2000'
timing_system.ip_address_and_port = 'id14timing2.cars.aps.anl.gov:2002'
timing_system.prefix = 'NIH:TIMING.'<file_sep>import sys
sys.path = ["../TWAX/Philip","../TReX/Python","../TWAX/Friedrich"] + sys.path
from dataset import Dataset
parameter_file = \
"/net/id14bxf/data/anfinrud_1110/Analysis/WAXS/Friedrich/parameters.twax"
dataset = Dataset(parameter_file)
logfile = dataset.combined_logfile
t = logfile["timestamp"]
I0 = logfile["x-ray"]
I = logfile["bunch-current[mA]"]
import matplotlib
matplotlib.use('PDF') # on ID14B6, default is "WxAgg", which is broken.
from pylab import *
from matplotlib.backends.backend_pdf import PdfPages
if True:
PDF_file = PdfPages(dataset.analysis_root+"/beamline_stability.pdf")
fig = figure(figsize=(7.5,3))
fig.subplots_adjust(bottom=0.25,top=0.97,left=0.075,right=0.97)
from datetime import datetime
date = array([date2num(datetime.fromtimestamp(x)) for x in t])
plot(date,I0,".",ms=1)
gca().xaxis_date()
formatter = DateFormatter('%a %d %Hh')
gca().xaxis.set_major_formatter(formatter)
xticks(rotation=90,fontsize=8)
grid()
ylim(0,1.2)
yticks(fontsize=8)
ylabel("X-ray I0 [norm.]",fontsize=8)
PDF_file.savefig(fig)
fig = figure(figsize=(7.5,3))
fig.subplots_adjust(bottom=0.25,top=0.97,left=0.075,right=0.97)
from datetime import datetime
date = array([date2num(datetime.fromtimestamp(x)) for x in t])
plot(date,I,".",ms=1)
gca().xaxis_date()
formatter = DateFormatter('%a %d %Hh')
gca().xaxis.set_major_formatter(formatter)
xticks(rotation=90,fontsize=8)
grid()
ylim(ymin=0,ymax=max(I)*1.2)
yticks(fontsize=8)
ylabel("bunch current [mA]",fontsize=8)
PDF_file.savefig(fig)
fig = figure(figsize=(7.5,3))
fig.subplots_adjust(bottom=0.25,top=0.97,left=0.075,right=0.97)
plot(date,I0/(I/average(I)),".",ms=1)
gca().xaxis_date()
formatter = DateFormatter('%a %d %Hh')
gca().xaxis.set_major_formatter(formatter)
xticks(rotation=90,fontsize=8)
grid()
ylim(0,1.2)
yticks(fontsize=8)
ylabel("X-ray I0 scaled by bunch current",fontsize=8)
PDF_file.savefig(fig)
PDF_file.close()
<file_sep>__version__ = "2.0.1"
if __name__ == "__main__":
from pdb import pm # for debugging
from timing_system import *
from Ensemble_SAXS import Ensemble_SAXS
from numpy import arange,vectorize
from time import time # for timing
from numpy import *
import logging
logging.basicConfig(level=logging.DEBUG,format="%(asctime)s: %(message)s")
##import timing_system; timing_system.DEBUG = True
print 'timing_system.ip_address = %r' % timing_system.ip_address
@vectorize
def round(x,n): return float(("%."+str(n)+"g") % x)
waitt = 2.0 # seconds
waitt = rint(waitt*hscf)/hscf
eps = 1e-6
timepoints = round(10**arange(-9,-2+eps,0.25),3)
laser_modes = [1] # [0,1] = off/on
delays = array([x for x in timepoints for l in laser_modes])
laser_on = laser_modes*len(timepoints)
xray_on = [1]*len(laser_modes)*len(timepoints)
N = len(delays)
n = rint(waitt*hscf)
hsc_delay = -hscd.offset # assume hscd.value ~ 0 (with small adjustments)
margin = 1/hscf - hsc_delay
xosct_delay = waitt - margin # # X-ray timing determined by high-speed chopper
xosct_delays = array([xosct_delay]*len(laser_modes)*len(timepoints))
pst_delays = xosct_delays-delays
xosct_fine_delays = xosct_delays % (1/hscf)
xosct_coarse_delays = floor(xosct_delays / (1/hscf)).astype(int)
pst_fine_delays = pst_delays % (1/hscf)
pst_coarse_delays = floor(pst_delays / (1/hscf)).astype(int)
xosct_delay_count = rint(xosct_fine_delays/(0.5/bcf)).astype(int)
pst_delay_count = rint(pst_fine_delays/(0.5/bcf)).astype(int)
xosct_coarse_delays += arange(0,N)*n
pst_coarse_delays += arange(0,N)*n
xosct_enable = zeros((N*n),int); xosct_enable[xosct_coarse_delays] = 1
pst_enable = zeros((N*n),int); pst_enable[pst_coarse_delays] = laser_on
xosct_delay_counts = repeat(xosct_delay_count,n)
pst_delay_counts = repeat(pst_delay_count,n)
variables,value_lists = [],[]
variables += [timing_system.xosct_enable]; value_lists += [xosct_enable]
variables += [timing_system.xosct_delay]; value_lists += [xosct_delay_counts]
variables += [timing_system.pst_enable]; value_lists += [pst_enable]
variables += [timing_system.pst_delay]; value_lists += [pst_delay_counts]
for l in value_lists: l += [0] # After last image, turn everything off.
data = sequencer_stream(variables,value_lists)
print 'timing_sequencer.set_sequence(variables,value_lists,100)'
print 'timing_sequencer.add_sequence(variables,value_lists,100)'
print 'timing_sequencer.enabled'
print 'timing_sequencer.running'
print 'timing_sequencer.queue'
print 'timing_sequencer.clear_queue()'
print 'timing_sequencer.abort()'
print 'timing_system.xosct_enable.count = 0'
<file_sep>"""
Author: <NAME>
Date created: 11/3/2017
Date last modified: 11/3/2017
"""
__version__ = "1.0"
import lauecollect,id14
from logging import debug,info,warn,error
if __name__ == "__main__":
from pdb import pm
import logging
logging.basicConfig(level=logging.DEBUG,
format="%(asctime)s %(levelname)s: %(message)s")
##from IPython.extensions.autoreload import superreload
from autoreload import superreload
import autoreload
print("print autoreload.dependencies(id14)")
print("superreload(id14)")
print("superreload(lauecollect)")
<file_sep>"""
"""
from serial import Serial
port = Serial("COM5")
s = ""
for i in range(0,255):
port.write(chr(i))
s += port.read(1)
<file_sep>prefix = '14IDB:m152'
description = 'Alio X'
target = -0.1059375
EPICS_enabled = True<file_sep>title = 'Delay Configuration'
motor_labels = ['list of delays']
names = ['delay_configuration']
motor_names = ['collect.delay_configuration']
line0.description = 'NIH:H-1_ps'
line1.description = 'NIH:H-56_ps'
line0.collect.delay_configuration = 'delays=pairs(-10us, lin_series(-100ps, 75ps, 25ps)+sorted(log_series(100ps, 1us, steps_per_decade=4)+[75ns, 133ns]))'
line1.collect.delay_configuration = 'hsc=CH-56, pp=Flythru-48, seq=NIH:i1, delays=pairs(-10us, [-10.1us]+log_series(316ns, 178ms, steps_per_decade=4))'
line0.updated = '28 Jan 09:48'
line1.updated = '09 Oct 14:07'
widths = [500]
row_height = 40
description_width = 140
nrows = 18
line2.collect.delay_configuration = 'delays=pairs(-10us, sorted(log_series(10ns, 563ns, steps_per_decade=4)+[75ns, 133ns]))'
line3.collect.delay_configuration = 'delays=pairs(-10us, [-10.1us]+log_series(316ns, 178ms, steps_per_decade=4))'
line2.description = 'NIH:H-1_ns'
line5.collect.delay_configuration = 'hsc=H-56, pp=Flythru-48, seq=NIH:i1, delays=pairs(-10us, log_series(10ms, 178ms, steps_per_decade=4))'
line4.collect.delay_configuration = 'delays=log_series(1ms, 75ms, steps_per_decade=4)'
line7.collect.delay_configuration = u'delays=[[(pp=Period-48, enable=010)]*5, (image=0, pp=Period-144, enable=100), (264+1*144, enable=101), [(image=0, enable=100)]*2, (264+4*144, enable=101), (image=0, enable=100)*4, (264+9*144, enable=101), (image=0, enable=100)*8, (264+18*144, enable=101), (image=0, enable=100)*16, (264+35*144, enable=101), (image=0, enable=100)*32, (264+68*144, enable=101)]'
line6.collect.delay_configuration = u'hsc=H-56, pp=Flythru-4, seq=NIH:i1, delays=[-10us, -10us, (264, enable=101, circulate=0), 528, 792, 1056, (-10us, enable=111, circulate=1), -10us]'
line3.description = 'NIH:H-56_ns'
line4.description = 'NIH:CW-longtime'
line5.description = 'NIH:H-56_LT'
line6.description = 'NIH:H-56_Exotic_ps'
line7.description = 'BioCARS:TR-LT'
line2.updated = '04 Nov 16:55'
line6.updated = '09 Oct 20:30'
line7.updated = '09 Oct 20:30'
line5.updated = '09 Oct 20:30'
line3.updated = '04 Nov 10:18'
command_row = 9
show_apply_buttons = True
apply_button_label = 'Select'
define_button_label = 'Update'
show_define_buttons = True
show_stop_button = False
line8.description = 'NIH:H-1-ps-56-sb'
line8.updated = '23 Oct 19:24'
line8.collect.delay_configuration = 'hsc=CH-1, seq=NIH:i1, delays=pairs(-10us, lin_series(-100ps, 75ps, 25ps)+sorted(log_series(100ps, 10us, steps_per_decade=4)+[75ns, 133ns])), hsc=CH-56, delays=pairs(-10us,log_series(10us, 178ms, steps_per_decade=4))'
line9.description = 'NIH:single_timepoint'
line9.collect.delay_configuration = 'delays=[-10us, 10us]'
line10.description = 'NIH:H-56_-10us'
line10.collect.delay_configuration = 'delays = [-10us]'
line11.collect.delay_configuration = 'delays=[(delay=-10us,circulate=1), -10us, -10us, (delay=-10us,laser=1), 264, 2*264,3*264,4*264,5*264,6*264,7*264,8*264]'
line11.updated = '03 Nov 13:32'
line11.description = 'NIH:TR-LT_Exotic'
line12.collect.delay_configuration = 'delays=[(-10us,image=0, enable=111,circulate=1), (-10us, image=1, enable=101,circulate=0), (264, enable=101), (2*264, enable=101),(3*264, enable=101),(4*264, enable=101),(5*264, enable=101),(6*264, enable=101),(7*264, enable=101)]'
line12.updated = '03 Nov 10:56'
line12.description = 'NIH:TR-LT_Exotic2'
line13.description = 'NIH:TR-LT_Exotic3'
line13.collect.delay_configuration = 'delays=[(-10us,circulate=1), -10us, -10us, (-10us,laser=1), 264, 2*264,3*264,4*264,5*264,6*264,7*264,8*264]'
command_rows = [17]
line14.description = 'UCSF:T-jump\t'
line14.collect.delay_configuration = 'delays=pairs(-10us, log_series(562ns, 1ms, steps_per_decade=8))'
line14.updated = '04 Nov 01:15'
line15.description = 'NIH:H-1_ns_linear'
line15.collect.delay_configuration = 'delays=pairs(-10us, lin_series(50ns, 550ns, 25ns))'
line15.updated = '2019-03-25 05:24:39'
multiple_selections = False
line16.collect.delay_configuration = 'delays=[-10.1us]+log_series(1us, 1ms, steps_per_decade=1)'
line16.updated = '2019-02-04 11:39:16'
line16.description = 'Rob test'
line17.collect.delay_configuration = 'delays=pairs(-10us, [-10.1us, 0]+log_series(562ns, 10ms, steps_per_decade=4))'
line17.updated = '2019-06-01 08:19:55'
line17.description = 'NIH:S-7'<file_sep>ip_address = 'id14b4.cars.aps.anl.gov:2223'<file_sep>#!/bin/bash
dir=`dirname "$0"`
python "$dir/syringe_pump.py" run_server
<file_sep>self.insert_sample().running = False
self.insert_sample().timeout_start = 1559568346.443381
cancelled = False
timeout_period = 10
timeout_start = 1559569685.139272
x = 0.263365334794732
y = 0.548708348754011
self.retract_sample().running = False
self.retract_sample().timeout_start = 1559569686.983505
self.pump_turn_off().running = False
self.pump_turn_off().timeout_start = 1549250188.466
action = 'extract sample'
extract_step = u'-510'
load_step = u'1000'
circulate_step = u'2000'
self.pump_turn_on().running = False
self.pump_turn_on().timeout_start = 1549250842.22<file_sep>"""Caching of Channel Access
Author: <NAME>
Date created: 2018-10-24
Date last modified: 2019-05-26
"""
__version__ = "2.0" # preserve data types
from logging import debug,info,warn,error
from cache import Cache
def caget_cached(PV_name):
"""Value of Channel Access (CA) Process Variable (PV)"""
from CA import caget,camonitor
camonitor(PV_name,callback=CA_cache_update)
value = caget(PV_name,timeout=0)
if value is None:
if cache_exists(PV_name): value = cache_get(PV_name)
if value is None: value = caget(PV_name)
if value is None: warn("Failed to get PV %r" % PV_name)
return value
def CA_cache_update(PV_name,value,formatted_value):
"""Handle Process Variable (PV) update"""
if not cache_exists(PV_name) or value != cache_get(PV_name):
##debug("%s=%s" % (PV_name,value))
cache_set(PV_name,value)
cache = Cache("CA")
def cache_set(PV_name,value):
cache.set(PV_name+".py",repr(value))
def cache_get(PV_name):
cache_value = cache.get(PV_name+".py")
try: value = eval(cache_value)
except: value = None
return value
def cache_exists(PV_name):
return cache.exists(PV_name+".py")
if __name__ == "__main__":
from pdb import pm # for debugging
import logging # for debugging
from time import time # for timing
logging.basicConfig(
level=logging.DEBUG,
format="%(asctime)s %(levelname)s %(module)s.%(funcName)s: %(message)s",
)
PV_name = "NIH:CONF.CONFIGURATION_NAMES"
from CA import caget
print('caget(PV_name)')
print('caget_cached(PV_name)')
print('cache_get(PV_name)')
<file_sep>"""Delay line linearity characterization
<NAME>, Jul 22, 2015 - Jul 31, 2015
Setup:
Ramsay-100B RF Generator, 351.93398 MHz +10 dBm -> FPGA RF IN
FPGA 1: X-scope trig -> CH1, DC50, 500 mV/div
FPGA 13: ps L oscill -> DC block -> 90-MHz low-pass -> CH2, DC50, 500 mV/div
Timebase 5 ns/div
Measurement P1 CH2, time@level, Absulute, 0, Slope Pos, Gate Start 4.5 div, Stop 5.5 div
FPGA Frequency: 41 Hz
"""
__version__ = "4.0.1"
from instrumentation import lecroy_scope,timing_system
from Ensemble_SAXS_pp import Ensemble_SAXS
from scan import timescan as tscan
from sleep import sleep
scope = lecroy_scope()
delay = scope.measurement(1)
def timescan():
tscan(delay,averaging_time=2.0,logfile="logfiles/delay.log")
if __name__ == "__main__":
print('timing_system.ip_address = %r' % timing_system.ip_address)
print('scope.ip_address = %r' % scope.ip_address)
print('Ensemble_SAXS.resync()')
print('timescan()')
<file_sep>"""
Author: <NAME>
Date created: 2018-01-25
Date last modified: 2018-01-25
"""
__version__ = "0.0"
from logging import debug,info,warn,error
class monitor(object):
"""For Linux and MacOS
Is compatible with Windows XP, but has poor performance:
"Failed to import read_directory_changes. Fall back to polling"
"""
def __init__(self,directory,handler,*args,**kwargs):
"""directory: pathname
handler: routine to be called
"""
self.directory = directory
self.handler = handler
self.args = args
self.kwargs = kwargs
##self.monitoring = True
def __repr__(self):
return "monitor(%r,%r,%r,%r)" % \
(self.directory,self.handler,self.args,self.kwargs)
def __eq__(self,other):
return (self.directory == other.directory and
self.handler == other.handler and
self.args == other.args and
self.kwargs == other.kwargs)
def get_monitoring(self): return getattr(self,self.monitoring_property)
def set_monitoring(self,value): setattr(self,self.monitoring_property,value)
monitoring = property(get_monitoring,set_monitoring)
@property
def monitoring_property(self):
from sys import platform
return "monitoring_win32" if platform == "win32" else "monitoring_posix"
def get_monitoring_posix(self):
"""Watching trace directory for new files?"""
return hasattr(self,"observer") and self.observer.is_alive()
def set_monitoring_posix(self,value):
if bool(value) != self.monitoring_posix:
if bool(value) == True:
# https://stackoverflow.com/questions/18599339/python-watchdog-monitoring-file-for-changes
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
class MyHandler(FileSystemEventHandler):
def on_modified(handler,event):
self.handler(*self.args,**self.kwargs)
event_handler = MyHandler()
self.observer = Observer()
self.observer.schedule(event_handler,path=self.directory,recursive=False)
self.observer.start()
if bool(value) == False:
if hasattr(self,"observer"): self.observer.stop()
monitoring_posix = property(get_monitoring_posix,set_monitoring_posix)
from thread_property import thread_property
@thread_property
def monitoring_win32(self):
"""Watch trace directory for new files
(Windows only)"""
while not self.monitoring_win32_cancelled:
from os.path import exists
from time import sleep
if not exists(self.directory): sleep(1)
else:
# watchdog: "Failed to import read_directory_changes. Fall back to polling"
# http://code.activestate.com/recipes/156178-watching-a-directory-under-win32/
import win32file,win32event,win32con
change_handle = win32file.FindFirstChangeNotification(directory,0,
win32con.FILE_NOTIFY_CHANGE_FILE_NAME)
try:
while self.monitoring_win32_cancelled:
result = win32event.WaitForSingleObject(change_handle, 500)
if result == win32con.WAIT_OBJECT_0:
self.handler(*self.args,**self.kwargs)
win32file.FindNextChangeNotification(change_handle)
finally: win32file.FindCloseChangeNotification(change_handle)
def directory_monitor(directory,handler,*args,**kwargs):
new_monitor = monitor(directory,handler,*args,**kwargs)
if not new_monitor in monitors:
monitors.append(new_monitor)
new_monitor.monitoring = True
def directory_monitor_clear(directory,handler,*args,**kwargs):
monitor_to_remove = monitor(directory,handler,*args,**kwargs)
for old_monitor in monitors:
if old_monitor == monitor_to_remove: old_monitor.monitoring = False
while monitor_to_remove in monitors: monitors.remove(monitor_to_remove)
def directory_monitors(directory):
return [monitor.handler for monitor in monitors if monitor.directory == directory]
monitors = []
if __name__ == "__main__":
from pdb import pm
directory = "/net/mx340hs/data/tmp"
##directory = "/tmp"
def handle_change(directory): warn("%r changed" % directory)
print('monitors.append(monitor(directory,handle_change,directory))')
print('directory_monitor(directory,handle_change,directory)')
print('directory_monitor_clear(directory,handle_change,directory)')
print('directory_monitors(directory)')
<file_sep>#!/bin/bash
localdir=`dirname "$0"`
cd "${localdir}"
iconutil -c icns core.iconset
<file_sep>"""Author: <NAME>,
Date created: Oct 21, 2015
Date last modified: Jun 6, 2018
"""
__version__ = "5.4.1" # resume
from pdb import pm # for debugging
from timing_system import timing_system
from timing_sequence import timing_sequencer
from time import sleep,time
from numpy import *
import logging
from tempfile import gettempdir
logfile = None ##gettempdir()+"/lauecollect_debug.log"
logging.basicConfig(level=logging.DEBUG,format="%(asctime)s: %(message)s",
filename=logfile)
timepoints = [
100e-12,178e-12,316e-12,562e-12,
1e-9,1.78e-9,3.16e-9,5.62e-9,
10e-9,17.8e-9,31.6e-9,56.2e-9,
100e-9,178e-9,316e-9,562e-9,
1e-6,1.78e-6,3.16e-6,5.62e-6,
10e-6,17.8e-6,31.6e-6,56.2e-6,
100e-6,178e-6,316e-6,562e-6,
1e-3,1.78e-3,3.16e-3,5.62e-3,
10e-3,17.8e-3,31.6e-3,
32*timing_system.hsct,64*timing_system.hsct,128*timing_system.hsct
]
timepoints=timepoints[:]
laser_mode = [0,1]
npulses = 1
delays = array([t for t in timepoints for l in laser_mode])
laser_on = array([l for t in timepoints for l in laser_mode])
image_numbers = arange(1,len(delays)+1)
npulses = [1 if l else 1 for l in laser_on]
waitt = [984*timing_system.hsct if l else 984*timing_system.hsct for l in laser_on]
burst_waitt = [t*n for (t,n) in zip(waitt,npulses)]
ms_on = [1 if l else 1 for l in laser_on]
# for debugging
##laser_on = delays = lxd = nsq_on = s3_on = None
self = timing_sequencer
##image_numbers = array([62,64,66,68,70])
##delays = delays[image_numbers-1]
##laser_ons = laser_ons[image_numbers-1]
##npulses = npulses[image_numbers-1]
def update():
timing_sequencer.acquire(delays=delays,laser_on=laser_on,
npulses=npulses,waitt=waitt,burst_waitt=burst_waitt,
image_numbers=image_numbers,
ms_on=ms_on)
def start():
update()
timing_system.image_number.value = 0
timing_system.pass_number.value = 0
timing_system.pulses.value = 0
timing_sequencer.queue_sequence_count = 0
timing_sequencer.queue_repeat_count = 0
timing_sequencer.queue_active = True
def cancel():
timing_sequencer.queue_active = False
def resume():
update()
timing_sequencer.queue_active = True
print("timing_system.ip_address = %r" % timing_system.ip_address)
##print("timing_sequencer.cache_enabled = %r" % timing_sequencer.cache_enabled)
print("")
print("timing_sequencer.running = True")
print("update()")
print("start()")
print("cancel()")
print("resume()")
<file_sep>1.code = 'float(value) > 10'
1.enabled = False
1.format = u'"%.3f mA" % value'
1.label = 'Storage ring'
1.value = 'caget("S:SRcurrentAI.VAL")'
2.code = 'float(value) < 10.75'
2.enabled = False
2.format = '"%.3f mm" % value'
2.label = 'Insertion device U23'
2.value = 'caget("ID14ds:Gap.VAL")'
3.code = u'15.84 < float(value) < 15.86'
3.enabled = False
3.format = u'"%.3f mm" % value'
3.label = u'Insertion device U27'
3.value = u'caget("ID14us:Gap.VAL")'
4.code = 'int(value)'
4.enabled = False
4.format = '{0:"CLOSED",1:"OPEN"}[value]'
4.label = 'Frontend shutter 14IDA'
4.value = 'caget("PA:14ID:STA_A_FES_OPEN_PL.VAL")'
5.code = 'int(value)'
5.enabled = False
5.format = '{0:"CLOSED",1:"OPEN"}[value]'
5.label = 'Station shutter 14IDC'
5.value = 'caget("PA:14ID:STA_B_SCS_OPEN_PL.VAL")'
6.code = '-8e-6 < value < +8e-6'
6.enabled = False
6.format = '"%+.3f us" % (value/1e-6)'
6.label = 'Heatload chopper phase error'
6.value = u'timing_system.hlcad.value - timing_system.hlcnd.value'
7.code = 'value == 1'
7.enabled = False
7.format = '{0:"off",1:"green",2:"red",3:"orange"}[value]'
7.label = 'Heatload chopper FPGA status LED'
7.value = 'timing_system.hlcled.count'
8.code = u'int(value) == 0'
8.enabled = False
8.format = u'{1:"Closed",0:"Open"}[value]'
8.label = u'Laser Safety Shutter'
8.value = u'caget("14IDB:B1Bi0.VAL")'
9.enabled = False
9.format = u'"Online" if value else "Offline"'
9.label = u'Timing System'
9.value = u'timing_system.online'
10.label = u'Lok-to-Clock'
10.enabled = False
10.code = u'int(value)'
10.format = u'"Unlocked" if value==0 else "Locked" if value==1 else "Offline"'
10.value = u'LokToClock.locked'
11.code = 'int(value) == 0'
11.enabled = False
11.format = u'"OK" if value==0 else "Fault" if value==1 else "unknown"'
11.label = 'Ensemble status'
11.value = 'ensemble.fault'
12.code = u'value == "SAXS-WAXS_PVT.ab"'
12.enabled = False
12.format = u'value if value else "Not running"'
12.label = u'SAXS/WAXS Ensemble program'
12.value = u'ensemble.program_filename'
13.value = u'ensemble.program_filename'
13.label = u'Laue Ensemble program'
13.code = u'value in ["ms-shutter.ab","PVT_Fly-thru.ab"]'
13.format = u'value'
13.enabled = False
14.enabled = False
14.format = u'"Online" if value else "Offline"'
14.label = u'X-ray detector'
14.value = u'xray_detector.online'
15.label = u'Sample frozen?'
15.value = u'sample_frozen.diffraction_spots'
15.format = u'"%s spots" % value'
15.enabled = False
15.code = u'value < 20'
N = 16
16.label = u'Freeze intervention'
16.value = u'freeze_intervention.active'
16.format = u'"Active" if value else "Not active"'
16.code = u'value == False'
16.enabled = True<file_sep>#!/usr/bin/env python
"""
Author: <NAME>
Date created: 2018-10-09
Date last modified: 2019-06-01
"""
__version__ = "1.15.2" # issue: logging hung waiting for one image
from logging import debug,info,warn,error
import traceback
class Collect(object):
"""Data collection"""
cancelled = False
from persistent_property import persistent_property
delay_configuration = persistent_property("delay","")
power_configuration = persistent_property("power","power(T0=1.0, N_per_decade=4, N_power=6, reverse=False)")
temperatures = persistent_property("temperatures","ramp(low=-18,high=120,step=0.5,hold=10,repeat=3)")
temperature_wait = persistent_property("temperature_wait",0)
temperature_idle = persistent_property("temperature_idle",22.0)
basename = persistent_property("basename","test")
xray_image_extension = persistent_property("xray_image_extension","mccd")
description = persistent_property("description","[Add description here]")
logfile_basename = persistent_property("logfile_basename","test")
directory_string = persistent_property("directory","//femto-data/C/Data")
variables = ["Delay","Laser_on","Temperature","Repeat","Power","Scan_Motor"]
collection_order = persistent_property("collection_order","")
finish_series = persistent_property("finish_series",False)
finish_series_variable = persistent_property("finish_series_variable","Temperature")
scan_points = persistent_property("scan_points","")
scan_return = persistent_property("scan_return",0)
scan_relative = persistent_property("scan_relative",0)
scan_motor_name = persistent_property("scan_motor","")
scan_origin = persistent_property("scan_origin",0.0)
detector_configuration = persistent_property("detector_configuration","")
def get_directory(self):
from normpath import normpath
return normpath(self.directory_string)
def set_directory(self,value): self.directory_string = value
directory = property(get_directory,set_directory)
@property
def collection_pass_count(self):
"""Into how many passes does the data collection need to be broken up?"""
count = 1
for i,variable in enumerate(self.collection_variables):
wait = self.variable_wait(variable)
N = len(self.variable_values(i))
if wait or count > 1: count *= N
return count
@property
def collection_passes(self):
"""List of integers, 0,1,...collection_pass_count-1"""
from numpy import unique
collection_passes = unique(self.collection_pass[~self.all_acquired])
return collection_passes
@property
def all_acquired(self):
"""Aquired status for each scan point in the dataset"""
return self.acquired(range(0,self.n))
def acquired(self,i):
"""Aquired status for given each scan point"""
from exists import exist_files
acquired = exist_files(self.xray_image_filenames[i])
return acquired
@property
def collection_pass(self):
"""To which collection pass does each scan point in the dataset belong?"""
from numpy import arange
i = arange(0,self.n)
pass_length = self.n/self.collection_pass_count
collection_pass = i/pass_length
return collection_pass
def collection_pass_ranges(self,collection_pass):
"""Pairs of starting and ending scan point numbers (range 0,,,n-1)"""
ranges = self.ranges(self.collection_pass_i(collection_pass))
return ranges
@staticmethod
def ranges(i):
from numpy import asarray,where,diff,concatenate
i = asarray(i)
gaps = where(diff(i)>1)[0]
firsts = [0] if len(i)>0 else []
lasts = [len(i)-1] if len(i)>0 else []
firsts = concatenate((firsts,gaps+1))
lasts = concatenate((gaps,lasts))
ranges = [(i[first],i[last]) for (first,last) in zip(firsts,lasts)]
return ranges
def collection_pass_i(self,collection_pass):
"""Image numbers of a collection pass
collection_pass: 0,1,... collection_pass_count-1"""
from numpy import arange
pass_length = self.n/self.collection_pass_count
first = pass_length*collection_pass
i = arange(first,first+pass_length)
i = i[~self.acquired(i)]
return i
@property
def collection_first_i(self):
first,last = self.collection_first_range
return first
@property
def collection_first_range(self):
from numpy import nan
first,last = nan,nan
collection_passes = self.collection_passes
for collection_pass in self.collection_passes:
for (first,last) in self.collection_pass_ranges(collection_pass):
break
break
return first,last
def collection_pass_first_i(self,collection_pass):
"""First image number of a collection pass
collection_pass: 0,1,... collection_pass_count-1"""
pass_length = self.n/self.collection_pass_count
first = pass_length*collection_pass
return first
def collection_pass_last_i(self,collection_pass):
"""Last image number of a collection pass
collection_pass: 0,1,...collection_pass_count-1"""
last = self.collection_pass_first_i(collection_pass+1)-1
return last
def set_collection_variables(self,i,wait=False):
"""i: range 0 to self.n"""
values = self.collection_variable_values(i)
variables = self.collection_variables
for variable,value in zip(variables,values):
self.variable_set(variable,value)
if wait: self.wait_for_collection_variables()
def wait_for_collection_variables(self):
"""i: range 0 to self.n"""
from time import sleep
variables = self.collection_variables
while any([self.variable_changing(var) for var in variables]):
if self.cancelled: break
self.actual(self.collection_variable_changing_report)
sleep(0.2)
@property
def collection_variable_changing_report(self):
message = ""
for variable in self.collection_variables:
if self.variable_changing(variable):
value = self.variable_value(variable)
formatted_value = self.variable_formatted_value(variable,value)
message += "%s=%s, " % (variable,formatted_value)
message = message.strip(", ")
return message
def collection_variables_dataset_start(self):
"""To be done at the beginning of the data collection"""
for variable in self.collection_variables:
if variable == "Scan_Motor":
self.scan_origin = self.variable_command_value(variable)
def collection_variables_dataset_stop(self):
"""To be done at the end of the data collection"""
for variable in self.collection_variables:
if variable == "Temperature":
self.variable_set(variable,self.temperature_idle)
if variable == "Scan_Motor":
if self.scan_return:
self.variable_set(variable,self.scan_origin)
collection_values = {}
def collection_variables_start(self):
self.collection_values = {}
for variable,values in zip(self.collection_variables,self.collection_variable_all_values):
if variable == "Repeat": continue
if variable == "Temperature": continue
self.collection_values[variable] = values
from timing_system import timing_system
for variable in self.collection_values:
timing_system.image_number.monitor(self.collection_variables_handle_image_number_update,variable)
def collection_variables_stop(self):
from timing_system import timing_system
for variable in self.collection_values:
timing_system.image_number.monitor_clear(self.collection_variables_handle_image_number_update,variable)
self.collection_values = {}
def collection_variables_handle_image_number_update(self,variable):
from timing_system import timing_system
i = timing_system.image_number.count
collection_values = dict(self.collection_values)
if variable in collection_values:
if 0 <= i < len(collection_values[variable]):
value = collection_values[variable][i]
debug("Image %r: Setting collection variable %s=%r..." % (i,variable,value))
self.variable_set(variable,value)
debug("Image %r: Setting collection variable %s=%r done" % (i,variable,value))
def variable_value(self,variable):
"""Current read-back value"""
from numpy import nan
value = nan
if variable == "Temperature":
from instrumentation import temperature
value = temperature.value
if variable == "Power":
from instrumentation import trans2
value = trans2.value
if variable == "Scan_Motor":
return self.scan_motor.value
return value
def variable_command_value(self,variable):
"""Nominal value"""
from numpy import nan
value = nan
if variable == "Temperature":
from instrumentation import temperature
value = temperature.command_value
if variable == "Power":
from instrumentation import trans2
value = trans2.value # has no attribute 'command_value'
if variable == "Scan_Motor":
return self.scan_motor.command_value
return value
def variable_set(self,variable,value):
if variable != "Repeat":
formatted_value = self.variable_formatted_value(variable,value)
self.actual("%s=%s" % (variable,formatted_value))
if variable == "Temperature":
from instrumentation import temperature
if temperature.command_value != value:
temperature.command_value = value
self.temperature_changed = True
if variable == "Power":
from instrumentation import trans2
trans2.value = value
if variable == "Scan_Motor":
self.scan_motor.value = value
def variable_changing(self,variable):
changing = False
if variable == "Temperature":
from instrumentation import temperature
changing = temperature.moving or self.temperature_changed
if variable == "Power":
from instrumentation import trans2
changing = trans2.moving
if variable == "Scan_Motor":
changing = self.scan_motor.moving
return changing
# The "moving" property does not update immediately.
# As a workaraound keep track of the last change and wait for 2s
# before consulting the "moving" property.
temperature_last_changed = 0
def get_temperature_changed(self):
from time import time
return time() - self.temperature_last_changed < 5.0
def set_temperature_changed(self,value):
from time import time
if value: self.temperature_last_changed = time()
temperature_changed = property(get_temperature_changed,set_temperature_changed)
def collection_variable_values(self,i):
"""i: range 0 to self.n"""
values = []
for j,n in enumerate(self.collection_variable_indices(i)):
values += [self.variable_values(j)[n]]
return values
def collection_all_values(self,variable):
"""variable: e.g. 'Temperature'"""
values = []
if variable in self.collection_variables:
i = self.collection_variables.index(variable)
values = self.collection_variable_all_values[i]
return values
@property
def collection_variable_all_values(self):
from numpy import array,repeat,tile,vstack
values_list = []
for (i,variable) in enumerate(self.collection_variables):
values_list += [self.variable_values(i)]
all_values = array([values_list[0]])
for values in values_list[1:]:
all_values = vstack([
tile(all_values,len(values)),
repeat(values,len(all_values[0])),
])
return all_values
@property
def collection_variable_count(self):
"""How many nested loops?"""
return len(self.collection_variables)
def collection_variable_indices(self,i):
"""List of integers of length self.collection_variable_count
range 0 to self.collection_variable_counts
i: range 0 to self.n"""
indices = []
for n in self.collection_variable_counts:
indices += [i % n]
i /= n
return indices
@property
def collection_variable_counts(self):
"""Number of scan points for each nested loop"""
counts = []
for i in range(0,self.collection_variable_count):
counts += [len(self.variable_values(i))]
return counts
@property
def n(self):
"""Number of scan points in a dataset"""
n = 1
for i in self.collection_variable_counts: n *= i
return n
@property
def collection_variables(self):
variables = []
for variable in self.collection_variables_with_options:
if "=" in variable: variable = variable.split("=")[0]
variables += [variable]
return variables
@property
def collection_variables_with_options(self):
"""e.g. 'Laser_on=[0,1]', 'Repeat=16' """
from expand_sequence import split_list
variables = split_list(self.collection_order.replace(" ",""))
return variables
def variable_values(self,i):
"""i range 0 to len(collection_variables)"""
# For choices encoded in the "collection_order" string
# e.g. Repeat=16, Laser_on=[0,1]
variable = self.collection_variables[i]
if variable == "Repeat": values = range(0,self.repeat_count(i))
elif variable == "Laser_on": values = self.laser_on_list(i)
else: values = self.variable_choices(variable)
return values
def variable_choices(self,variable):
# For choices encoded outside the "collection_order" string
# in searate tables.
if variable == "Temperature": choices = self.temperature_list
elif variable == "Power": choices = self.power_list
elif variable == "Scan_Motor": choices = self.scan_point_list
elif variable == "Delay": choices = self.delay_sequences
else: choices = []
return choices
def variable_wait(self,variable):
"""Suspend collection while changing this variable?"""
if variable == "Temperature": wait = self.temperature_wait
elif variable == "Power": wait = True
elif variable == "Scan_Motor": wait = False
else: wait = False
return wait
def variable_formatted_value(self,variable,value):
from time_string import time_string
text = str(value)
if variable == "Delay": text = time_string(value.nom_delay)
if variable == "Temperature": text = "%.3fC" % value
if variable == "Laser_on": text = "on" if value else "off"
if variable == "Power": text = "%.4f" % value
if variable == "Scan_Motor": text = "%.04f" % value
if variable == "Repeat": text = "%02d" % (value+1)
return text
def repeat_count(self,i):
"""i: collection variable number 0...len(collection_variables)"""
count = 0
variables = self.collection_variables_with_options
if 0 <= i <= len(variables):
variable = variables[i]
if variable.startswith("Repeat="):
count_string = variable.split("=")[-1]
try: count = int(eval(count_string))
except Exception,msg:
error("%s: %s: %s: %s: expecting int" %
(collection_order,variable,count_string,msg))
return count
def laser_on_list(self,i):
"""i: collection variable number 0...len(collection_variables)"""
values = [1]
variables = self.collection_variables_with_options
if 0 <= i <= len(variables):
variable = variables[i]
if variable.startswith("Laser_on="):
values_string = variable.split("=")[-1]
try: values = eval(values_string)
except Exception,msg:
error("%s: %s: %s: %s: expecting int" %
(collection_order,variable,values_string,msg))
return values
@property
def delay_list(self):
delay_list = [s.nom_delay for s in self.delay_sequences]
return delay_list
@property
def delay_sequences(self):
from expand_sequence import delay_sequences
from Ensemble_SAXS_pp import Sequence
sequences = Sequence()
expr = self.delay_configuration
if expr:
try: expr = delay_sequences(expr)
except Exception,msg:
error("delay_sequences: %r: %s\n%s" % (expr,msg,traceback.format_exc()))
expr = ""
if expr:
try: sequences = eval(expr)
except Exception,msg:
error("%s: %s\n%s" % (expr,msg,traceback.format_exc()))
sequences = self.as_list(sequences)
return sequences
@property
def temperature_list(self):
"""List of temperature setpoints for dataset"""
values = self.expand_sequence(self.temperatures)
return values
def temperature_start(self):
if "Temperature" in self.collection_variables and \
self.variable_wait("Temperature") == False:
self.actual("Temperature start...")
from linear_ranges import linear_ranges
image_numbers,temperatures = \
linear_ranges(self.collection_all_values("Temperature"))
times = image_numbers * self.image_acquisition_time
from instrumentation import temperature
self.actual("Temperature uploading ramp...")
temperature.time_points = list(times)
temperature.temp_points = list(temperatures)
self.actual("Temperature started")
def temperature_stop(self):
if "Temperature" in self.collection_variables and \
self.variable_wait("Temperature") == False:
self.actual("Temperature stop...")
from instrumentation import temperature
temperature.time_points = []
temperature.temp_points = []
self.actual("Temperature stopped")
@property
def pass_acquisition_time(self):
sequences = self.sequences
N = sequences[0].period if len(sequences) > 0 else 0
##T = sequences[0].tick_period()
from timing_system import timing_system
T = timing_system.hsct
t = N * T
return t
@property
def image_acquisition_time(self):
sequences = self.sequences
N = sum([sequence.period for sequence in sequences])
##T = sequences[0].tick_period()
from timing_system import timing_system
T = timing_system.hsct
t = N * T
return t
@property
def temperature_count(self):
"""List of temperature setpoints for dataset"""
return len(self.temperature_list)
@property
def power_list(self):
values = self.expand_sequence(self.power_configuration)
return values
@property
def scan_point_list(self):
"""List of positions of *scan_motor* for dataset"""
from expand_sequence import expand_sequence
from numpy import array
values = self.expand_sequence(self.scan_points)
values = array(values)
if self.scan_relative: values += self.scan_origin
return values
@staticmethod
def expand(expr):
values = []
from expand_sequence import expand
if expr:
try: expr = expand(expr)
except Exception,msg:
error("expand_sequence: %r: %s\n%s" % (expr,msg,traceback.format_exc()))
expr = ""
if expr:
try: values = eval(expr)
except Exception,msg:
error("%s: %s\n%s" % (expr,msg,traceback.format_exc()))
values = Collect.as_list(values)
return values
@staticmethod
def expand_sequence(expr):
values = []
from expand_sequence import expand_sequence
if expr:
try: expr = expand_sequence(expr)
except Exception,msg:
error("expand_sequence: %r: %s\n%s" % (expr,msg,traceback.format_exc()))
expr = ""
if expr:
try: values = eval(expr)
except Exception,msg:
error("%s: %s\n%s" % (expr,msg,traceback.format_exc()))
values = Collect.as_list(values)
return values
@staticmethod
def as_list(value):
if not hasattr("__len__",value) or isinstance(value,str):
value = [value]
return value
@property
def scan_motor(self):
exec("from instrumentation import *")
return eval(self.scan_motor_name)
@property
def detector_names(self):
"""e.g. 'xray_detector', 'xray_scope', 'laser_scope'"""
from expand_sequence import split_list
names = split_list(self.detector_configuration.replace(" ",""))
return names
@property
def info_message(self):
if self.dataset_complete: message = "Dataset complete"
elif self.current > self.n: message = "Collection completed"
else:
i = self.current if self.acquiring else self.collection_first_i
message = "%s %s of %s" % (self.scan_point_name,i+1,self.n)
if i < self.n: message += ": "+self.scan_point_filename(i)
message = message[0:1].upper()+message[1:]
return message
status_message = ""
actual_message = ""
def acquisition_status(self,i):
"""Progress Message"""
message = "Acquiring %s %d of %d" % (self.scan_point_name,i+1,self.n)
message += ": "+self.scan_point_filename(i)
values = self.collection_variable_values(i)
variables = self.collection_variables
for variable,value in zip(variables,values):
formatted_value = self.variable_formatted_value(variable,value)
message += ", %s %s" % (variable,formatted_value)
return message
@property
def scan_point_name(self):
name = "scan point"
if "xray_detector" in self.detector_names: name = "image"
return name
def scan_point_filename(self,i):
self.file_basename(i)
if "xray_detector" in self.detector_names:
from os.path import basename
name = basename(self.xray_image_filename(i))
elif "xray_scope" in self.detector_names:
##filenames = self.xray_scope_trace_filenames
name = self.file_basename(i)
else: name = self.file_basename(i)
return name
@property
def current(self):
"""Current image number"""
from timing_system import timing_system
current = timing_system.image_number.count
return current
@property
def acquiring(self):
"""Timing system currently in 'acquiring' state'?"""
from timing_system import timing_system
acquiring = timing_system.acquiring.count
return acquiring
@property
def dataset_complete(self):
from exists import exist_files
filenames = self.xray_image_filenames
dataset_complete = all(exist_files(filenames))
return dataset_complete
@property
def dataset_started(self):
started = \
len(self.xray_images_collected) > 0 or \
len(self.xray_scope_traces_collected) > 0 or \
len(self.laser_scope_traces_collected) > 0 or \
sum(self.logfile_has_entries(self.xray_image_filenames)) > 0
return started
from thread_property import thread_property
erasing_dataset = thread_property("erase_dataset")
def erase_dataset(self):
self.actual("Erasing Dataset...")
for i,filename in enumerate(self.xray_images_collected):
self.actual("Erasing X-ray image %r" % (i+1))
if self.cancelled: break
self.remove(filename)
for i,filename in enumerate(self.xray_scope_traces_collected):
self.actual("Erasing X-ray scope trace %r" % (i+1))
if self.cancelled: break
self.remove(filename)
for i,filename in enumerate(self.laser_scope_traces_collected):
self.actual("Erasing Laser scope trace %r" % (i+1))
if self.cancelled: break
self.remove(filename)
filenames = self.xray_image_filenames
if sum(self.logfile_has_entries(filenames)) > 0:
self.actual("Cleaning Logfile...")
self.logfile_delete_filenames(filenames)
self.actual("Dataset erased")
@staticmethod
def remove(filename):
from os import remove
try: remove(filename)
except Exception,msg: warn("remove %r: %s" % (filename,msg))
@property
def xray_images_collected(self):
from exists import exist_files
filenames = self.xray_image_filenames
xray_images_collected = filenames[exist_files(filenames)]
return xray_images_collected
@property
def xray_scope_traces_collected(self):
from exists import exist_files
filenames = self.xray_scope_trace_filenames
filenames = filenames[exist_files(filenames)]
return filenames
@property
def xray_scope_all_traces_collected(self):
from exists import exist_files
filenames = self.xray_scope_all_trace_filenames
filenames = filenames[exist_files(filenames)]
return filenames
@property
def laser_scope_traces_collected(self):
from exists import exist_files
filenames = self.laser_scope_trace_filenames
filenames = filenames[exist_files(filenames)]
return filenames
def status(self,message):
if message: info(message)
self.status_message = message
def actual(self,message):
if message: info(message)
self.actual_message = message
from thread_property import thread_property
collecting_dataset = collecting = thread_property("collect_dataset")
def collect_dataset(self):
self.status("Collection started")
self.collection_variables_dataset_start()
# for temperature equilibration
self.set_collection_variables(self.collection_first_i,wait=False)
self.timing_system_start()
self.timing_system_setup()
self.xray_detector_start()
self.xray_scope_start()
self.laser_scope_start()
self.diagnostics_start()
self.logging_start()
self.temperature_start()
self.collection_variables_start()
self.update_status_start()
for collection_pass in self.collection_passes:
if self.cancelled: break
for (first,last) in self.collection_pass_ranges(collection_pass):
if self.cancelled: break
self.timing_system_setup(first,last)
self.set_collection_variables(first,wait=True)
self.acquisition_start()
for i in range(first,last+1):
if self.cancelled: break
self.acquire(i)
self.status("Collection suspended")
self.play_sound()
self.update_status_stop()
self.collection_variables_stop()
self.temperature_stop()
self.diagnostics_stop()
self.timing_system_stop()
self.collection_variables_dataset_stop()
self.sleep(5)
self.logging_stop()
self.laser_scope_stop()
self.xray_scope_stop()
self.sleep(5)
self.xray_detector_stop()
self.status("Collection ended")
def update_status_start(self):
from timing_system import timing_system
timing_system.image_number.monitor(self.update_status_handle_image_number_update)
def update_status_stop(self):
from timing_system import timing_system
timing_system.image_number.monitor_clear(self.update_status_handle_image_number_update)
def update_status_handle_image_number_update(self):
from timing_system import timing_system
i = timing_system.image_number.count
##debug("image_number %r" % i)
self.status(self.acquisition_status(i))
def acquire(self,i):
"""Acquire one scan point"""
self.status(self.acquisition_status(i))
self.wait_for(i)
def wait_for(self,i):
"""Follow the data collection for one image"""
from time import sleep
while not self.completed(i) and not self.cancelled: sleep(0.02)
def completed(self,i):
from timing_sequence import timing_sequencer
if self.current > i: completed = True
elif not timing_sequencer.queue_active: completed = True
else: completed = False
if completed: debug("Completed %r" % i)
return completed
from thread_property import thread_property
generating_packets = thread_property("generate_packets")
def generate_packets(self):
self.actual("Generating packets: started")
self.sequencer_packets
self.actual("Generating packets: done")
@property
def sequencer_packets(self):
"""Generate the binary packets for the Piano Player timing sequencer"""
packets = []
sequences = self.sequences
for i,sequence in enumerate(sequences):
if self.cancelled: break
##self.actual("Checking packets: %d/%d" % (i+1,len(sequences)))
if not sequence.is_cached:
self.actual("Generating packets: %d/%d" % (i+1,len(sequences)))
packets += [sequence.data]
return packets
def sequence_properites(self,property_name):
"""property_name:
laser_on
delay
nom_delay
pump_on
following_pump_on
"""
properties = [getattr(s,property_name) for s in self.sequences]
return properties
@property
def sequences(self):
from Ensemble_SAXS_pp import Sequences
# Update "following_delay" properties
sequences = Sequences(sequences=self.sequences_simple)[:]
return sequences
@property
def sequences_simple(self):
from Ensemble_SAXS_pp import Sequences
sequences = Sequences(acquiring=1,image_number_inc=0)[:]
sequences[-1].image_number_inc = 1
for i,variable in enumerate(self.sequence_variables):
choices = self.variable_values(i)
values = self.repeat(choices,len(sequences))
sequences = self.tile(sequences,len(choices))
for s,value in zip(sequences,values):
if variable == "Laser_on":
# Selectively turn the laser OFF if ON in the sequence
# configuration, however do not turn in ON if OFF by
# default.
s.laser_on &= value
if variable == "Delay": s.update(value)
return sequences
@property
def sequence_variables(self):
"""Which variable changes are handled by the timing sequence?"""
sequence_variables = []
for i,variable in enumerate(self.collection_variables):
if self.variable_wait(variable): break
else: sequence_variables += [variable]
while len(sequence_variables) > 0 and sequence_variables[-1] not in ["Delay","Laser_on"]:
sequence_variables = sequence_variables[:-1]
return sequence_variables
@staticmethod
def tile(list,n):
"""tile([1,2,3],2) -> [1,2,3,1,2,3]"""
from copy import deepcopy
new_list = []
for i in range(0,n):
for elem in list: new_list.append(deepcopy(elem))
return new_list
@staticmethod
def repeat(list,n):
"""tile([1,2,3],2) -> [1,1,2,2,3,3]"""
from copy import deepcopy
new_list = []
for elem in list:
for i in range(0,n): new_list.append(deepcopy(elem))
return new_list
@staticmethod
def as_list(x):
if not hasattr(x,"__len__") or isinstance(x,str): x = [x]
return x
@property
def xray_images_per_sequence_queue(self):
"""How many X-ray images per repeating sequece pattern?"""
xray_images = sum([s.xdet_on for s in self.sequences])
return xray_images
@property
def sequences_per_xray_image(self):
"""How many single timining sequences (=packets) per X-ray image"""
sequences = self.sequences
xray_images = sum([s.xdet_on for s in sequences])
sequences_per_xray_image = len(sequences)/xray_images
return sequences_per_xray_image
@property
def sequences_per_xray_image2(self):
"""Periodic repeating pattern
How many single timining sequences (=packets) per X-ray image"""
xdet_on = [s.xdet_on for s in self.sequences]
return xdet_on
def timing_system_start(self):
self.actual("Timing system start...")
from timing_sequence import timing_sequencer
timing_sequencer.set_queue_sequences(self.sequences)
self.actual("Timing system started")
def timing_system_stop(self):
self.actual("Timing system stop...")
from timing_sequence import timing_sequencer
# Leave acquistion mode at the next sequence_count (fast).
timing_sequencer.next_queue_sequence_count = -1
timing_sequencer.queue_active = False
self.actual("Timing system stopped")
def timing_system_setup(self,first=None,last=None):
self.actual("Timing system setup...")
if first is None or last is None:
first,last = self.collection_first_range
N = self.xray_images_per_sequence_queue
from timing_sequence import timing_sequencer
timing_sequencer.queue_active = False
from numpy import isnan
if not isnan(first):
timing_sequencer.queue_repeat_count = first/N
if not isnan(last):
timing_sequencer.queue_max_repeat_count = (last+1)/N
# Switch from idle to acquistion mode only when sequence_count = 0.
timing_sequencer.next_queue_sequence_count = 0
timing_sequencer.queue_sequence_count = 0
from timing_system import timing_system
timing_system.image_number.count = first
timing_system.xdet_acq_count.count = first
timing_system.pass_number.count = 0
timing_system.pulses.count = 0
Ntrace = self.sequences_per_xray_image
timing_system.xosct_acq_count.count = first * Ntrace
timing_system.losct_acq_count.count = first * Ntrace
self.actual("Timing system setup complete")
def acquisition_start(self):
self.timing_system_acquisition_start()
def timing_system_acquisition_start(self):
self.actual("Timing system acquisition start...")
from timing_sequence import timing_sequencer
timing_sequencer.queue_active = True
from time import sleep
while not timing_sequencer.queue_active and not self.cancelled:
self.actual("Timing system acquisition start: sequence count %s"
% timing_sequencer.current_queue_sequence_count)
sleep(0.1)
self.actual("Timing system acquisition started")
def xray_detector_start(self):
if "xray_detector" in self.detector_names:
filenames = self.xray_image_filenames
self.actual("X-ray detector acqisition start...")
from instrumentation import xray_detector
image_numbers = range(1,self.n+1)
xray_detector.acquire_images(image_numbers,filenames)
self.actual("X-ray detector acqisition started")
def xray_detector_stop(self):
if "xray_detector" in self.detector_names:
self.actual("X-ray detector acqisition stop...")
from instrumentation import xray_detector
xray_detector.cancel_acquisition()
self.actual("X-ray detector acqisition stopped")
def xray_scope_start(self):
if "xray_scope" in self.detector_names:
filenames = self.xray_scope_trace_filenames
self.actual("X-ray Scope Start...")
from instrumentation import xray_scope
filename_dict = dict([(i+1,f) for (i,f) in enumerate(filenames)])
xray_scope.trace_filenames = filename_dict
xray_scope.trace_acquisition_running = True
xray_scope.filenames = list(self.xray_scope_trace_filenames)
xray_scope.times = list(self.xray_scope_trace_times)
self.actual("X-ray Scope Started")
def xray_scope_stop(self):
if "xray_scope" in self.detector_names:
self.actual("X-ray Scope Stop...")
from instrumentation import xray_scope
xray_scope.trace_acquisition_running = False
xray_scope.trace_filenames = {}
self.actual("X-ray Scope Stopped")
def laser_scope_start(self):
if "laser_scope" in self.detector_names:
filenames = self.laser_scope_trace_filenames
self.actual("Laser Scope Start...")
filename_dict = dict([(i+1,f) for (i,f) in enumerate(filenames)])
from instrumentation import laser_scope
laser_scope.trace_filenames = filename_dict
laser_scope.times = self.laser_scope_trace_times
laser_scope.trace_acquisition_running = True
self.actual("Laser Scope Started")
def laser_scope_stop(self):
if "laser_scope" in self.detector_names:
self.actual("Laser Scope Stop...")
from instrumentation import laser_scope
laser_scope.trace_acquisition_running = False
laser_scope.trace_filenames = {}
self.actual("Laser Scope Stopped")
@property
def xray_scope_trace_times(self):
from numpy import arange
N = self.n * self.sequences_per_xray_image
trace_numbers = arange(0,N)
times = (trace_numbers+1) * self.image_acquisition_time
return times
@property
def xray_scope_trace_filenames(self):
from numpy import array,chararray,repeat,tile
filenames = self.file_basenames
N = self.sequences_per_xray_image
suff = array(["_%02d" % (i+1) for i in range(0,N)]).view(chararray)
filenames = repeat(filenames,len(suff))+tile(suff,len(filenames))
filenames = self.directory+"/xray_traces/"+filenames+".trc"
return filenames
@property
def xray_scope_all_trace_filenames(self):
"""Filenames including channel suffix if mutiple traces were collected"""
filenames = self.xray_scope_trace_filenames
trace_sources = self.xray_scope_trace_sources
if len(trace_sources) > 1:
from numpy import repeat,tile
filenames = filenames.replace(".trc","")
filenames = repeat(filenames,len(trace_sources))+\
"_"+tile(trace_sources,len(filenames))
filenames = filenames+".trc"
return filenames
@property
def xray_scope_trace_sources(self):
trace_sources = [""]
if "xray_scope" in self.detector_names:
from instrumentation import xray_scope
trace_sources = xray_scope.trace_sources
from numpy import array
trace_sources = array(trace_sources)
return trace_sources
laser_scope_trace_times = xray_scope_trace_times
@property
def laser_scope_trace_filenames(self):
filenames = self.xray_scope_trace_filenames
filenames = filenames.replace("/xray_traces/","/laser_traces/")
return filenames
@property
def missing_xray_scope_trace_filenames(self):
filenames = self.xray_scope_trace_filenames
from exists import exist_files
missing = filenames[~exist_files(filenames)]
return missing
def xray_image_filename(self,i):
ext = "."+self.xray_image_extension.strip(".")
filename = self.directory+"/xray_images/"+self.file_basename(i)+ext
return filename
@property
def xray_image_filenames(self):
ext = "."+self.xray_image_extension.strip(".")
filenames = self.directory+"/xray_images/"+self.file_basenames+ext
return filenames
def file_basename(self,i):
filename = self.basename
filename += "_"+"%04d" % (i+1)
values = self.collection_variable_values(i)
variables = self.collection_variables
for variable,value in zip(variables,values):
text = self.variable_formatted_value(variable,value)
filename += "_"+text
return filename
@property
def file_basenames(self):
"""numpy chararray"""
from numpy import array,chararray,repeat,tile
suffixes = []
for (i,variable) in enumerate(self.collection_variables):
vals = self.variable_values(i)
suff = ["_"+self.variable_formatted_value(variable,val) for val in vals]
suff = array(suff).view(chararray)
suffixes += [suff]
names = array([""]).view(chararray)
for suff in suffixes:
names = tile(names,len(suff)) + repeat(suff,len(names))
serial = ["_%04d" % (i+1) for i in range(0,len(names))]
serial = array(serial).view(chararray)
names = self.basename + serial + names
return names
def diagnostics_start(self):
from diagnostics import diagnostics
diagnostics.running = True
self.actual("Diagnostics Started")
def diagnostics_stop(self):
from diagnostics import diagnostics
diagnostics.running = False
self.actual("Diagnostics Stopped")
def logging_start(self): self.logging = True
def logging_stop(self): self.logging = False
from thread_property_2 import thread_property
@thread_property
def logging(self):
self.actual("Logging Started")
from diagnostics import diagnostics
self.logged = {}
while not self.logging_cancelled:
for i in range(0,self.n):
if not i in self.logged and diagnostics.is_finished(i):
self.logfile_update(i)
self.logged[i] = True
self.sleep(1)
self.actual("Logging Stopped")
def logfile_update(self,i):
"""Add image information to the end of the data collection log file"""
self.logfile_add_line(self.logfile_entry(i))
def logfile_add_line(self,line):
with self.logfile_lock:
from os.path import exists
if not exists(self.logfile_name): self.initialize_logfile()
filenames = line.split("\t")[3:4]
self.logfile_delete_filenames(filenames)
file(self.logfile_name,"a").write(line)
from thread import allocate_lock
logfile_lock = allocate_lock()
def logfile_entry(self,i):
from time import time
from time_string import date_time
from diagnostics import diagnostics
from numpy import isnan,isfinite
from os.path import basename
started = diagnostics.started(i)
finished = diagnostics.finished(i)
timestamp = finished if isfinite(finished) else time()
line = []
line += [date_time(timestamp)]
line += [date_time(started)]
line += [date_time(finished)]
line += [basename(self.xray_image_filename(i))]
values = self.collection_variable_values(i)
values += diagnostics.average_values(i)
for value in values: line += [str(value)]
line = "\t".join(line)+"\n"
return line
def initialize_logfile(self):
from os.path import exists,dirname; from os import makedirs
from diagnostics import diagnostics
filename = self.logfile_name
dir = dirname(filename)
try: makedirs(dir)
except Exception,msg:
if not exists(dir): error("%s: %s" % (dir,msg))
header = "# Data collection log file generated by collect "+\
__version__+"\n"
header += "# Description: "+self.description+"\n"
labels = []
labels += ["date time"]
labels += ["started"]
labels += ["finished"]
labels += ["file"]
labels += self.collection_variables
labels += diagnostics.variable_names
header += "#"+"\t".join(labels)+"\n"
log = file(filename,"w").write(header)
@property
def logfile_name(self):
return self.directory+"/"+self.logfile_basename
def logfile_has_entries(self,image_filenames):
"""Is there an entry for this image in the log file?
image_filenames: filenames of images (with or without directory)
"""
from os.path import basename
from numpy import array
entries = self.logfile_entries
return array([basename(f) in entries for f in image_filenames])
def logfile_has_entry(self,image_filename):
"""Is there an entry for this image in the log file?
image_filename: filename of image (with or without directory)
"""
return self.logfile_has_entries([image_filename])[0]
@property
def logfile_entries(self):
"""Is there an entry for this image in the log file?
"""
filenames = []
try: log = file(self.logfile_name)
except: log = None
if log:
lines = log.read().split("\n")
# 'split' makes the last line an empty line.
if lines and lines[-1] == "": lines.pop(-1)
for line in lines:
if line.startswith("#"): continue # Ignore comment lines.
fields = line.split("\t")
if len(fields)>3: filenames += [fields[3]]
return filenames
def logfile_timestamp(self,filename):
"""When was this image file or scope trace acquired?
Return value: seconds since 1970-01-01 00:00:00 UTC"""
date_time = self.logfile_timestamp_string(filename)
from time_string import timestamp
from numpy import nan
seconds = timestamp(date_time) if date_time else nan
return seconds
def logfile_timestamp_string(self,filename):
"""When was this image file or scope trace acquired?
Return value: string, format 1970-01-01 00:00:00"""
line = self.logfile_line(filename)
fields = line.split("\t")
date_time = fields[2] if len(fields)>2 else ""
if date_time == "": date_time = fields[0] if len(fields)>0 else ""
return date_time
def logfile_line(self,filename):
"""Entry for this image or scope trace in the log file
image_filename: basename of image filename (without directory)
"""
from os.path import splitext
file_basename = self.file_basename_of_filename(filename)
entry = ""
filenames = []
try: log = file(self.logfile_name)
except: log = None
if log:
lines = log.read().split("\n")
# 'split' makes the last line an empty line.
if lines and lines[-1] == "": lines.pop(-1)
for line in lines:
if line.startswith("#"): continue # Ignore comment lines.
fields = line.split("\t")
entry_filename = fields[3] if len(fields)>3 else ""
entry_basename = splitext(entry_filename)[0]
if entry_basename == file_basename: entry = line
return entry
def file_basename_of_filename(self,filename):
"""E.g. 'Sample-1_0001_01_01_C1.trc' -> 'Sample-1_0001_01'"""
from os.path import basename,splitext
file_basename = basename(filename)
file_basename,ext = splitext(file_basename)
if ext.endswith("trc"):
suffixes = ["_C%d" % (i+1) for i in range(0,4)]
for suffix in suffixes:
if file_basename.endswith(suffix):
file_basename = file_basename[0:-len(suffix)]
break
suffixes = ["_%02d" % (i+1) for i in range(0,20)]
for suffix in suffixes:
if file_basename.endswith(suffix):
file_basename = file_basename[0:-len(suffix)]
break
return file_basename
def logfile_delete_scan_point(self,i):
"""Make sure that there are no duplicate entries in the
data collection logfile, in the case an image is recollected.
i: 0 to self.n-1
"""
filename = self.xray_image_filename(i)
logfile_delete_filename([filename])
def logfile_delete_filenames(self,image_filenames):
"""Make sure that there are no duplicate entries in the
data collection logfile, in the case an image is recollected.
image_filename: basename of image filename (without directory)
"""
from os.path import basename
image_filenames = [basename(f) for f in image_filenames]
try: log = file(self.logfile_name)
except: log = None
if log:
lines = log.read().split("\n")
# 'split' makes the last line an empty line.
if lines and lines[-1] == "": lines.pop(-1)
output_lines = list(lines)
# Remove matching lines.
for line in lines:
if line.startswith("#"): continue # Ignore comment lines.
fields = line.split("\t")
if len(fields)>3 and fields[3] in image_filenames:
output_lines.remove(line)
# Update the log file if needed.
if output_lines != lines:
log = file(self.logfile_name,"w")
for line in output_lines: log.write(line+"\n")
def sleep(self,delay):
"""Interruptible delay"""
from time import time,sleep
t = time()
while time()-t < delay and not self.cancelled: sleep(0.050)
def exec_delayed(self,time,command):
"""Execute a command on background after a certain delay
time: seconds
command: string, executable Python code"""
from thread import start_new_thread
start_new_thread(self.exec_delayed_thread,(time,command))
def exec_delayed_thread(self,time,command):
"""Execute a command after a certain delay
time: seconds
command: string, executable Python code"""
from time import sleep
sleep(time)
exec(command)
def play_sound(self):
from sound import play_sound
if not self.cancelled: play_sound("ding")
collect = Collect()
def basenames(filenames):
from os.path import basename
from numpy import array,chararray
basenames = [basename(f) for f in filenames]
basenames = array(basenames).view(chararray)
return basenames
if __name__ == '__main__':
from pdb import pm # for debugging
from time import time # for timing
import logging # for debugging
logging.basicConfig(
level=logging.DEBUG,
format=
"%(asctime)s "
"%(levelname)s "
"%(module)s"
".%(funcName)s"
", line %(lineno)d"
": %(message)s"
)
self = collect # for debugging
##from Ensemble_SAXS_pp import Sequence,Sequences
##print('collect.scan_points')
##print('self.scan_point_list')
##print("self.power_configuration")
##print('self.collection_order')
##print('self.collection_variables')
##print('self.collection_variable_counts')
##print('self.temperatures')
##print('self.temperature_list')
##print('self.collection_all_values("Temperature")')
##from linear_ranges import linear_ranges
##print('linear_ranges(self.collection_all_values("Temperature"))')
##from instrumentation import temperature
##print('temperature.time_points,temperature.temp_points')
##print('')
##print('self.temperature_list')
##print('self.scan_point_list')
##print('self.power_list')
##print('')
##print('self.delay_configuration')
##print('self.delay_sequences')
##print('self.delay_list')
##print('self.sequence_properites("laser_on")')
##print('self.sequence_properites("delay")')
##print('self.sequence_properites("nom_delay")')
##print('self.sequence_properites("pump_on")')
##print('self.sequence_properites("following_pump_on")')
##print('self.directory')
##print('self.n')
##print('self.sequences_simple')
##print('self.sequences')
##print('Sequences(sequences=self.sequences)')
##print(r'print self.sequences[0].description.replace(",","\n")')
##print('')
##print('self.xray_image_filename(0)')
##print('self.file_basenames')
##print('self.xray_image_filenames')
##print('self.xray_scope_trace_filenames')
##print('len(self.xray_scope_trace_filenames)')
##print('len(self.missing_xray_scope_trace_filenames)')
##print('for f in basenames(self.missing_xray_scope_trace_filenames): print f')
##print('self.collection_pass_count')
##print('self.collection_passes')
##print('self.collection_pass_ranges(self.collection_passes[0])')
##print('self.collection_first_i')
print('')
print('self.generate_packets()')
print('')
##print('self.collection_variables_dataset_start()')
##print('self.set_collection_variables(0)')
print('self.timing_system_start()')
print('self.timing_system_setup()')
print('self.xray_detector_start()')
##print('self.xray_scope_start()')
##print('self.laser_scope_start()')
##print('self.diagnostics_start()')
##print('self.logging_start()')
##print('self.temperature_start()')
##print('self.collection_variables_start()')
##print('self.update_status_start()')
print('')
##print('self.acquisition_start()')
print('self.timing_system_acquisition_start()')
print('')
##print('self.update_status_stop()')
##print('self.collection_variables_stop()')
##print('self.temperature_stop()')
##print('self.logging_stop()')
##print('self.diagnostics_stop()')
##print('self.xray_scope_stop()')
##print('self.laser_scope_stop()')
print('self.xray_detector_stop()')
print('self.timing_system_stop()')
##print('self.collection_variables_dataset_stop()')
print('')
##print('self.generating_packets = True')
##print('self.collect_dataset()')
print('self.collecting_dataset = True')
##print('self.erasing_dataset = True')
##print('sum(self.logfile_has_entries(self.xray_image_filenames))')
##print('self.logfile_delete_filenames(self.xray_image_filenames)')
print('')
from instrumentation import rayonix_detector
print('rayonix_detector.image_numbers[0:10]')
print('rayonix_detector.filenames[0:2]')
<file_sep>"""
wxPython: TextCtrl doesn't ever receive focus when inside a panel inside
another panel inside a frame
http://stackoverflow.com/questions/10048564/wxpython-textctrl-doesnt-ever-receive-focus-when-inside-a-panel-inside-another
So I have the following code set up to demonstrate the problem:
"""
import wx
class testPanel(wx.Panel):
def __init__(self, parent):
super(testPanel, self).__init__(parent)
self.hsizer = wx.BoxSizer(wx.HORIZONTAL)
self.txt = wx.TextCtrl(self, style=wx.TE_MULTILINE)
self.hsizer.Add(self.txt, proportion=1,
flag=wx.EXPAND)
self.SetSizer(self.hsizer)
self.hsizer.Fit(self)
self.Show(True)
class testFrame(wx.Frame):
def __init__(self, parent):
super(testFrame, self).__init__(parent)
self.mainPanel = wx.Panel(self)
self.vsizer = wx.BoxSizer(wx.VERTICAL)
##self.txt1 = testPanel(self)
##self.txt2 = testPanel(self)
# Use:
self.txt1 = testPanel(self.mainPanel)
self.txt2 = testPanel(self.mainPanel)
# and they will get focus.
self.vsizer.Add(self.txt1, proportion=1,
flag=wx.EXPAND)
self.vsizer.Add(self.txt2, proportion=1,
flag=wx.EXPAND)
self.mainPanel.SetSizer(self.vsizer)
self.vsizer.Fit(self.mainPanel)
self.mainSizer = wx.BoxSizer(wx.HORIZONTAL)
self.mainSizer.Add(self.mainPanel, proportion=1,
flag=wx.EXPAND)
self.SetSizer(self.mainSizer)
self.mainSizer.Fit(self)
self.Show(True)
app = wx.PySimpleApp()
frame = testFrame(None)
frame.Show(True)
app.MainLoop()
<file_sep>#!/bin/bash -l
# The -l (login) option makes sure that the environment is the same as for
# an interactive shell.
localdir=`dirname "$0"`
dir=`cd "${localdir}/../../../../../.."; pwd`
exec python "$dir/Collect_Panel.py" >> ~/Library/Logs/Python.log 2>&1
<file_sep>#!/bin/env python
"""
Acquire a series of images using the XPP Rayonix detector with the
LCLS data acquisition system and a server running on a "mond" node
Setup:
source ~schotte/Software/Lauecollect/setup_env.sh
DAQ Control: check Sync Sequence 3 - Target State: Allocate
(if grayed out: daq.diconnect())
xpphome -> LSLS tab -> Event Sequencer -> Event Code Sequence 3 -> Start
ssh daq-xpp-mon05
ssh daq-xpp-mon06
~xppopr/experiments/xppj1216/software/start_zmqsend.sh:
source /reg/d/iocCommon/All/xpp_env.sh
export TIME=`date +%s`
export NAME="zmqsend.$HOSTNAME.$TIME"
source /reg/g/psdm/etc/ana_env.sh
$PROCSERV --logfile /tmp/$NAME --name zmqsend 40000 ./zmqsend.cmd
~xppopr/experiments/xppj1216/software/start_zmqsend.sh:
source /reg/g/psdm/etc/ana_env.sh
`which mpirun` -n 12 python /reg/neh/home/cpo/ipsana/xppj1216/zmqpub.py
Monitor status of servers:
telnet daq-xpp-mon05 40000
telnet daq-xpp-mon06 40000
Control-X, Control-R to restart
Author: <NAME>, Jan 26, 2016 - Feb 1, 2016
"""
from time import time
import zmq
from logging import error,warn,info,debug
from numpy import nan,argsort,array
from threading import Thread
from os.path import basename
from thread import start_new_thread
__version__ = "1.0.2" # multiple command port number
class DAQImages(object):
context = zmq.Context()
socket = context.socket(zmq.SUB)
servers = ["daq-xpp-mon05","daq-xpp-mon06"]
ports = range(12300,12300+12)
cmd_ports = range(12399,12399+5)
for server in servers:
for port in ports: socket.connect("tcp://%s:%d" % (server,port))
socket.setsockopt(zmq.SUBSCRIBE, 'rayonix')
socket.setsockopt(zmq.RCVTIMEO,1000) # ms
cancelled = False
completed = False
def __init__(self):
self.cmd_socket = self.context.socket(zmq.PUB)
for port in self.cmd_ports:
try: self.cmd_socket.bind("tcp://*:%s" % port); break
except zmq.ZMQError: pass # Address already in use
def get(self,nimages):
"""nimages: number of images to retreive"""
images = []; fiducials = []
for i in range(0,nimages):
try:
topic = self.socket.recv()
except Exception,msg:
error("Rayonix shmem: Image %2d/%d: recv: %s" % (i+1,nimages,msg))
break
fiducial = self.socket.recv_pyobj()
image = self.socket.recv_pyobj()
t = "Rayonix shmem: Image %d/%d %r: %d" % (i+1,nimages,image.shape,fiducial)
if len(fiducials)>0: t += " (%+g)" % (fiducial-fiducials[-1])
info(t)
images.append(image); fiducials.append(fiducial)
# The images are not guaranteed to be received in the order acquired.
# Sort the images by "fiducials" timestamp.
order = argsort(fiducials)
images = [images[i] for i in order]
return images
def save_images(self,filenames):
"""Receive a series images from a server running on the
"mond" nodes and save them as TIFF files.
filename: list of absolute pathnames
Returns immediately. Cancel with "abort".
"""
self.completed = False
start_new_thread(self.__save_images__,(filenames,))
def __save_images__(self,filenames):
"""Receive a series images from a server running on the
"mond" nodes and save them as TIFF files.
filename: list of absolute pathnames
Returns after the requested nuumber of images have been received or
a timeout (1 s) has occured.
"""
self.cancelled = False
self.completed = False
nimages = len(filenames)
images = []; fiducials = []; threads = []
for i in range(0,nimages):
if self.cancelled:
info("Rayonix shmem: Image reception cancelled.")
break
try:
topic = self.socket.recv()
except Exception,msg:
error("Image %d/%d: recv: %s" % (i+1,nimages,msg))
break
fiducial = self.socket.recv_pyobj()
image = self.socket.recv_pyobj()
t = "Image %2d/%d %r: %d" % (i+1,nimages,image.shape,fiducial)
if len(fiducials)>0: t += " (%+g)" % (fiducial-fiducials[-1])
info(t)
images.append(image); fiducials.append(fiducial)
thread = Thread(target=save_image,args=(image,filenames[i]))
thread.start()
threads.append(thread)
debug("Rayonix shmem: Waiting for all images to be saved...")
for thread in threads: thread.join()
debug("Rayonix shmem: All images saved.")
# The images are not guaranteed to be received in the order acquired.
# Sort the images by "fiducials" timestamp.
# The "fiducial" timestamp in a 17-bit counter running at 360 Hz.
# It wraps back to 0 from 131039, exactly every 364 seconds.
##fiducials = array(fiducials)
period = 131040
if len(fiducials)>0 and max(fiducials)-min(fiducials) > period/2:
fiducials[fiducials<period/2] += period
order = argsort(fiducials)
if not all(sorted(order) == order):
debug("Rayonix shmem: Resorting images...")
temp_names = [f+".tmp" for f in filenames]
for f,t in zip(filenames,temp_names): move(f,t)
temp_names = [temp_names[i] for i in order]
for t,f in zip(temp_names,filenames): move(t,f)
debug("Rayonix shmem: Images resorted...")
self.completed = True
def abort(self):
"""Cancel series acquisition"""
info("Cancelling image reception...")
self.cancelled = True
__bin_factor__ = 4
def get_bin_factor(self):
"""binning: integer, e.g. 1,2,4,8"""
return self.__bin_factor__
def set_bin_factor(self,binning):
"""binning: integer, e.g. 1,2,4,8"""
debug("Rayonix shmem: bin factor %s" % binning)
self.cmd_socket.send("cmd",zmq.SNDMORE)
self.cmd_socket.send_pyobj(binning)
self.__bin_factor__ = binning
bin_factor = property(get_bin_factor,set_bin_factor)
daq_shmem_client = DAQImages()
def move(src,dest):
"""Rename of move a file or a different directory, overwriting an exising
file"""
from os.path import basename,exists
from os import rename,remove
try:
if exists(dest): remove(dest)
rename(src,dest)
except OSError,msg: warn("Failed to move %r to %r: %s" % (src,dest,msg))
def save_image(image,filename):
from numimage import numimage
##debug("Saving image %r..." % basename(filename))
numimage(image).save(filename,"MCCD")
##debug("Image saved %r" % basename(filename))
if __name__ == "__main__":
import logging
logging.basicConfig(level=logging.DEBUG,format="%(asctime)s: %(message)s")
print("images = daq_shmem_client.get(20)")
print("daq_shmem_client.bin_factor = 4")
<file_sep>from math import sqrt
phi = (sqrt(5)+1)/2
div = 0.65
def series(n):
x = [0.,1.]
for i in range(3,n+1): insert1(x)
return x
def insert1(x):
n = len(x)
x.sort()
dx = [x[i+1]-x[i] for i in range(0,n-1)]
i = dx.index(max(dx))
gap = x[i+1]-x[i]
x.insert(i+1,x[i]+gap*div)
def max_ratio(x):
n = len(x)
x.sort()
dx = [x[i+1]-x[i] for i in range(0,n-1)]
dx.sort()
return dx[n-2]/dx[0]
print [max_ratio(series(i)) for i in range(3,11)]
<file_sep>"""
Rayonix CCD X-ray detector
<NAME>
Date created: 2019-05-31
Date last modified: 2019-06-02
"""
__version__ = "2.0.2" # current_temp_filename, ip_address_choices
from logging import debug,info,warn,error
from tcp_client import tcp_client_object
class Rayonix_Detector(tcp_client_object):
"""Rayonix MX series X-ray Detector"""
name = "rayonix_detector_client"
from tcp_client import tcp_property
online = tcp_property("online",False)
acquiring = tcp_property("acquiring",False)
last_image_number = tcp_property("last_image_number",0)
current_image_basename = tcp_property("current_image_basename","")
nimages = tcp_property("nimages",0)
last_filename = tcp_property("last_filename","")
bin_factor = tcp_property("bin_factor",0)
scratch_directory = tcp_property("scratch_directory","")
nimages_to_keep = tcp_property("nimages_to_keep",0)
detector_ip_address = tcp_property("ip_address","")
timing_mode = tcp_property("timing_mode","")
timing_modes = tcp_property("timing_modes","")
ADXV_live_image = tcp_property("ADXV_live_image",False)
live_image = tcp_property("live_image",False)
limit_files_enabled = tcp_property("limit_files_enabled",True)
auto_start = tcp_property("auto_start",False)
image_numbers = tcp_property("image_numbers",[])
filenames = tcp_property("filenames",[])
xdet_trig_counts = tcp_property("xdet_trig_counts",{})
acquiring = tcp_property("acquiring",False)
trigger_monitoring = tcp_property("trigger_monitoring",False)
saving_images = tcp_property("saving_images",False)
current_temp_filename = tcp_property("current_temp_filename","")
current_image_filename = tcp_property("current_image_filename","")
ip_address_choices = [
"localhost:2223",
"id14b4.cars.aps.anl.gov:2223",
"pico5.cars.aps.anl.gov:2223",
"pico5.niddk.nih.gov:2223",
"pico8.niddk.nih.gov:2223",
"pico20.niddk.nih.gov:2223",
]
detector_ip_address_choices = [
"mx340hs.cars.aps.anl.gov:2222",
"pico5.cars.aps.anl.gov:2222",
"localhost:2222",
"pico5.niddk.nih.gov:2222",
"pico8.niddk.nih.gov:2222",
"pico20.niddk.nih.gov:2222",
]
def acquire_images(self,image_numbers,filenames):
"""Save a series of images
image_numbers: 0-based, matching timing system's 'image_number''"""
image_numbers = list(image_numbers)
filenames = list(filenames)
debug("image_numbers = %.200r" % image_numbers)
self.image_numbers = image_numbers
debug("filenames = %.200r" % filenames)
self.filenames = filenames
self.xdet_trig_counts = {}
self.acquiring = True
self.trigger_monitoring = True
self.saving_images = True
def cancel_acquisition(self):
"""Undo 'acquire_images', stop saving images"""
self.image_numbers = []
self.filenames = []
self.trigger_monitoring = False
rayonix_detector = Rayonix_Detector()
if __name__ == "__main__": # for debugging
from pdb import pm
import logging
logging.basicConfig(
level=logging.DEBUG,
format=
"%(asctime)s "
"%(levelname)s "
"%(funcName)s"
", line %(lineno)d"
": %(message)s"
)
self = rayonix_detector
print("self.ip_address = %r" % self.ip_address)
print("")
print("self.online")
print("self.acquiring")
print("self.last_image_number")
print("self.current_image_basename")
print("self.nimages")
print("self.last_filename")
print("self.bin_factor")
print("self.scratch_directory")
print("self.nimages_to_keep = 999")
print("self.detector_ip_address")
print("self.timing_mode")
print("self.ADXV_live_image")
print("self.live_image")
print("self.limit_files_enabled")
print("self.auto_start")
print("")
print("self.image_numbers")
print("self.filenames[0:5]")
print("self.xdet_trig_counts")
print("self.trigger_monitoring")
print("self.saving_images")
<file_sep>#!/usr/bin/env python
"""Control panel to save and recall motor positions.
Author: <NAME>
Date created: 2010-12-13
Date last modified: 2018-02-01
"""
__version__ = "3.6.1" # Scrolled panel
from logging import debug,info,warn,error
import traceback
import wx
from numpy import ndarray,isnan
# Turn off IEEE-754 warnings in numpy 1.6+ ("invalid value encountered in...")
import numpy; numpy.seterr(invalid="ignore",divide="ignore")
class SavedPositionsPanel(wx.Frame):
"""Control panel to save and recall motor positions"""
icon = "Tool"
name = "SavedPositionsPanel"
from setting import setting
size = setting("size",(600,800))
def __init__(self,configuration=None,name=None,globals=None,locals=None,
parent=None,title=None):
"""
configuration: object of type "configuration" from "configuration.py"
name: name of configuration, e.g. "alio_diffractometer_saved_positions",
"timing_modes"
globals: When using "name=...", dictionary onctaining available motor
objects.
e.g. "from instrumentation import *" populates the global names space,
globals=globals() to make these available inside the SavedPositionsPanel
title: overrides user-configurable title (for backward compatibility)
"""
self.cache = {}
self.locals = locals
self.globals = globals
if configuration is not None: self.configuration = configuration
elif name is not None:
from configuration import configuration
self.configuration = configuration(name,globals=globals,locals=locals)
else: raise RuntimeError("SavedPositionsPanel requires 'configuration' or 'name'")
if title is not None: self.configuration.title = title
if name is not None: self.name = name
wx.Frame.__init__(self,parent=parent,size=self.size)
# Icon
from Icon import SetIcon
SetIcon(self,self.icon)
self.layout()
##self.Fit()
debug("Size=%r" % (self.Size,))
self.Show()
self.Bind(wx.EVT_SIZE,self.OnResize)
# Make sure "on_input" is called only after "update_settings".
# Call the "on_input" routine whenever the user presses Enter.
self.Bind (wx.EVT_TEXT_ENTER,self.on_input)
# Periodically update the displayed fields.
self.timer = wx.Timer(self)
self.Bind (wx.EVT_TIMER,self.OnTimer)
self.timer.Start(5000,oneShot=True)
from threading import Thread
self.update_thread = Thread(target=self.keep_updated)
self.update_thread.daemon = True
self.update_thread.start()
def OnResize(self,event):
event.Skip()
self.size = tuple(self.Size)
def OnTimer(self,event=None):
"""Called periodically every second triggered by a timer"""
##debug("Started %r" % self.configuration.name)
import traceback
try: self.update_module()
except Exception,msg: error("%s\n%s" % (msg,traceback.format_exc()))
try: self.update_layout()
except Exception,msg: error("%s\n%s" % (msg,traceback.format_exc()))
try: self.update_date()
except Exception,msg: error("%s\n%s" % (msg,traceback.format_exc()))
self.timer.Start(5000,oneShot=True) # Need to restart the Timer
##debug("Finished %r" % self.configuration.name)
def keep_updated(self):
while True:
try:
self.check_for_updates()
self.delay()
except wx.PyDeadObjectError: break
def delay(self):
from time import sleep
sleep(1)
def check_for_updates(self):
##debug("Started %r" % self.configuration.name)
names = []
names += ["title"]
names += ["description"]
names += ["matching_description"]
names += ["closest_descriptions"]
names += ["command_description"]
names += ["command_rows"]
names += ["matching_rows"]
names += ["closest_rows"]
for j in range(0,self.configuration.n_motors):
names += ["current_positions[%d]" % j]
names += ["motor_labels[%d]" % j]
names += ["formats[%d]" % j]
for i in range(0,self.configuration.nrows):
names += ["descriptions[%d]" % i]
names += ["updated[%d]" % i]
for i in range(0,self.configuration.nrows):
for j in range(0,self.configuration.n_motors):
names += ["positions[%d][%d]" % (j,i)]
for i in range(0,self.configuration.nrows):
for j in range(0,self.configuration.n_motors):
names += ["matches(%d,%d)" % (i,j)]
from collections import OrderedDict
changes = OrderedDict()
for name in names:
code = "self.configuration."+name
try: value = eval(code)
except Exception,msg:
error("%r: %s\n%s" % (code,msg,traceback.format_exc()))
value = None
if value is not None:
from same import same
if name not in self.cache or not same(value,self.cache[name]):
changes[name] = value
self.cache.update(changes)
if changes:
debug("%s: changes: %.400r" % (self.configuration.name,changes))
myEVT_UPDATE = wx.NewEventType()
EVT_UPDATE = wx.PyEventBinder(myEVT_UPDATE,1)
self.Bind(EVT_UPDATE,self.OnUpdate)
event = self.UpdateEvent(myEVT_UPDATE,value=changes)
wx.PostEvent(self,event)
##debug("Finished %r" % self.configuration.name)
class UpdateEvent(wx.PyCommandEvent):
"""Event to signal that a value changed"""
def __init__(self,etype,eid=-1,value=""):
wx.PyCommandEvent.__init__(self,etype,eid)
self.value = value
def OnUpdate(self,event):
changes = event.value
self.update(changes)
@property
def menu_bar(self):
"""MenuBar object"""
# Menus
menuBar = wx.MenuBar()
# Edit
menu = wx.Menu()
menu.Append(wx.ID_CUT,"Cu&t\tCtrl+X","selection to clipboard")
menu.Append(wx.ID_COPY,"&Copy\tCtrl+C","selection to clipboard")
menu.Append(wx.ID_PASTE,"&Paste\tCtrl+V","clipboard to selection")
menu.Append(wx.ID_DELETE,"&Delete\tDel","clear selection")
menu.Append(wx.ID_SELECTALL,"Select &All\tCtrl+A")
menuBar.Append(menu,"&Edit")
# View
self.ViewMenu = wx.Menu()
for i in range(0,len(self.configuration.motor_labels)):
self.ViewMenu.AppendCheckItem(100+i,self.configuration.motor_labels[i])
self.ViewMenu.AppendSeparator()
menuBar.Append (self.ViewMenu,"&View")
# More
menu = wx.Menu()
menu.Append (201,"Configure this Panel...")
menu.Append (202,"Modes/Configurations Panel...")
menuBar.Append (menu,"&More")
# Help
menu = wx.Menu()
menu.Append (wx.ID_ABOUT,"About...","Show version number")
menuBar.Append (menu,"&Help")
# Callbacks
for i in range(0,len(self.configuration.motor_labels)):
self.Bind(wx.EVT_MENU,self.OnView,id=100+i)
self.Bind(wx.EVT_MENU_OPEN,self.OnOpenView)
self.Bind(wx.EVT_MENU,self.OnConfiguration,id=201)
self.Bind(wx.EVT_MENU,self.OnConfigurations,id=202)
self.Bind(wx.EVT_MENU,self.OnAbout,id=wx.ID_ABOUT)
return menuBar
date_width = 160
@property
def ControlPanel(self):
# Controls and Layout
import wx.lib.scrolledpanel
panel = wx.lib.scrolledpanel.ScrolledPanel(self)
##panel = wx.Panel(self)
panel.vertical = self.configuration.vertical
def flip(i,j): return (j,i) if panel.vertical else (i,j)
# Leave a 5 pixel wide border.
border_box = wx.BoxSizer(wx.VERTICAL)
# Labels
grid = panel.grid = wx.GridBagSizer(1,1)
flag = wx.ALIGN_CENTRE_VERTICAL|wx.ALIGN_CENTRE_HORIZONTAL|wx.ALL
style = wx.TE_PROCESS_ENTER
if not panel.vertical: style |= wx.TE_MULTILINE
left,center,right = wx.ALIGN_LEFT,wx.ALIGN_CENTER_HORIZONTAL,wx.ALIGN_RIGHT
row_height = self.configuration.row_height
# Labels
header_flag = wx.ALIGN_CENTRE_VERTICAL|wx.ALIGN_CENTRE_HORIZONTAL|wx.ALL|wx.ALIGN_TOP|wx.EXPAND
width = self.configuration.description_width
if panel.vertical: width = -1
panel.DescriptionLabel = wx.Button(panel,label="Name",size=(width,row_height))
panel.DescriptionLabel.Enabled = False
grid.Add(panel.DescriptionLabel,flip(0,1),flag=header_flag)
width = 100
if panel.vertical: width = -1
panel.DateLabel = wx.Button(panel,label="Updated",size=(width,row_height))
panel.DateLabel.Enabled = False
grid.Add(panel.DateLabel,flip(0,2),flag=header_flag)
panel.PositionLabels = []
for i in range(0,self.configuration.n_motors):
label = self.configuration.motor_labels[i]
width = self.configuration.widths[i]
if panel.vertical: width = -1
button = wx.Button(panel,label=label,size=(width,row_height),
id=300+i*100+98)
button.Enabled = self.configuration.is_configuration(i)
self.Bind(wx.EVT_BUTTON,self.OnShowConfiguration,button)
grid.Add(button,flip(0,i+3),flag=header_flag)
panel.PositionLabels += [button]
# Controls
from EditableControls import TextCtrl
panel.Descriptions = ndarray(self.configuration.nrows,object)
for i in range(0,self.configuration.nrows):
width = self.configuration.description_width
if panel.vertical: width = self.configuration.description_width
align = center if panel.vertical else left
panel.Descriptions[i] = TextCtrl(panel,size=(width,row_height),
style=style|align,id=100+i)
grid.Add(panel.Descriptions[i],flip(i+1,1),flag=flag)
self.NormalBackgroundColour = panel.Descriptions[0].BackgroundColour
panel.Dates = ndarray(self.configuration.nrows,object)
for i in range(0,self.configuration.nrows):
width = self.date_width
if panel.vertical: width = self.configuration.description_width
panel.Dates[i] = TextCtrl(panel,size=(width,row_height),style=style,id=200+i)
grid.Add(panel.Dates[i],flip(i+1,2),flag=flag)
panel.Positions = ndarray((self.configuration.nrows,self.configuration.n_motors),object)
for i in range(0,self.configuration.nrows):
for j in range(0,self.configuration.n_motors):
width = self.configuration.widths[j]
align = right if self.configuration.is_numeric(j) else left
panel.Positions[i,j] = TextCtrl(panel,size=(width,row_height),
style=style|align,id=300+j*100+i)
panel.Positions[i,j].BackgroundColour = panel.BackgroundColour
grid.Add(panel.Positions[i,j],flip(i+1,j+3),flag=flag|wx.EXPAND)
header_flag = wx.ALIGN_CENTRE_VERTICAL|wx.ALIGN_CENTRE_HORIZONTAL|wx.ALL|wx.ALIGN_TOP|wx.EXPAND
panel.SelectButtons = []
height = panel.Descriptions[0].Size[1]
for i in range(0,self.configuration.nrows):
label = self.configuration.apply_button_label
width = int(20+6.5*len(label)) if len(label) <= 10 else -1
if panel.vertical: width = self.configuration.description_width
button = wx.ToggleButton(panel,label=label,size=(width,height),id=i)
button.Shown = self.configuration.show_apply_buttons
grid.Add(button,flip(i+1,0),flag=flag)
self.Bind(wx.EVT_TOGGLEBUTTON,self.OnSelect,button)
panel.SelectButtons += [button]
panel.DefineButtons = []
height = panel.Descriptions[0].Size[1]
for i in range(0,self.configuration.nrows):
label = self.configuration.define_button_label
width = 20+7*len(label) if len(label) <= 10 else -1
if panel.vertical: width = self.configuration.description_width
button = wx.Button(panel,label=label,size=(width,height),id=100+i)
button.Shown = self.configuration.show_define_buttons
grid.Add(button,flip(i+1,self.configuration.n_motors+3),flag=flag)
self.Bind(wx.EVT_BUTTON,self.define_setting,button)
panel.DefineButtons += [button]
# Current values
width = panel.SelectButtons[0].Size[0] if len(panel.SelectButtons) > 0 else -1
if panel.vertical: width = self.configuration.description_width
label = wx.StaticText(panel,label="Current",size=(width,row_height))
label.Shown = self.configuration.show_apply_buttons
grid.Add(label,flip(self.configuration.nrows+1,0),flag=flag)
width = self.configuration.description_width
align = center if panel.vertical else left
panel.CurrentDescription = TextCtrl(panel,size=(width,row_height),
style=style|align,id=100+99)
panel.CurrentDescription.BackgroundColour = panel.BackgroundColour
grid.Add(panel.CurrentDescription,flip(self.configuration.nrows+1,1),flag=flag)
width = self.date_width
if panel.vertical: width = self.configuration.description_width
panel.CurrentDate = TextCtrl(panel,size=(width,row_height),style=style,id=200+99)
panel.CurrentDate.BackgroundColour = panel.BackgroundColour
panel.CurrentDate.Enabled = True
grid.Add(panel.CurrentDate,flip(self.configuration.nrows+1,2),flag=flag)
panel.CurrentPositions = ndarray(self.configuration.n_motors,object)
for i in range(0,self.configuration.n_motors):
width = self.configuration.widths[i]
align = right if self.configuration.is_numeric(i) else left
panel.CurrentPositions[i] = TextCtrl(panel,size=(width,row_height),
style=style|align,id=300+i*100+99)
panel.CurrentPositions[i].BackgroundColour = panel.BackgroundColour
grid.Add(panel.CurrentPositions[i],flip(self.configuration.nrows+1,i+3),flag=flag)
border_box.Add (grid,flag=wx.ALL|wx.EXPAND,border=5)
panel.StopButton = wx.Button(panel,label="Stop")
panel.StopButton.Shown = self.configuration.show_stop_button
self.Bind(wx.EVT_BUTTON,self.stop,panel.StopButton)
border_box.Add (panel.StopButton,flag=wx.ALL|wx.ALIGN_CENTRE_HORIZONTAL,border=2)
panel.SetSizer(border_box)
panel.SetupScrolling()
##panel.Fit()
return panel
def layout(self):
menu_bar = self.menu_bar
old_menu_bar = self.MenuBar
self.MenuBar = menu_bar
if old_menu_bar: old_menu_bar.Destroy()
panel = self.ControlPanel
if hasattr(self,"panel"): self.panel.Destroy()
self.panel = panel
##self.Fit()
self.update()
def update_module(self):
from os.path import getmtime
import SavedPositionsPanel_2 as module
##info("Checking file %r..." % module.__file__)
if not hasattr(module,"__timestamp__"):
module.__timestamp__ = getmtime(module.__file__)
if getmtime(module.__file__) != module.__timestamp__:
module.__timestamp__ = getmtime(module.__file__)
reload(module)
info('Reloaded module (version %s)' % module.__version__)
self.__class__ = module.SavedPositionsPanel
self.layout()
@property
def update_needed(self):
"""Has the configuration has changed?"""
update_needed = False
nrows = len(self.panel.Descriptions)
if nrows != self.configuration.nrows: update_needed = True
n_motors = self.panel.Positions.shape[1]
if n_motors != self.configuration.n_motors: update_needed = True
widths = []
for i in range(0,self.panel.Positions.shape[1]):
widths += [self.panel.Positions[0][i].Size[0] if i<len(self.panel.Positions[0]) else 0]
if widths != self.configuration.widths: update_needed = True
description_width = self.panel.Descriptions[0].Size[0] if len(self.panel.Descriptions)>0 else 0
if description_width != self.configuration.description_width: update_needed = True
row_height = self.panel.Descriptions[0].Size[1] if len(self.panel.Descriptions)>0 else 0
if row_height != self.configuration.row_height: update_needed = True
show_apply_buttons = self.panel.SelectButtons[0].Shown if len(self.panel.SelectButtons)>0 else False
if show_apply_buttons != self.configuration.show_apply_buttons: update_needed = True
apply_button_label = self.panel.SelectButtons[0].Label if len(self.panel.SelectButtons)>0 else ""
if apply_button_label != self.configuration.apply_button_label: update_needed = True
show_define_buttons = self.panel.DefineButtons[0].Shown if len(self.panel.DefineButtons)>0 else False
if show_define_buttons != self.configuration.show_define_buttons: update_needed = True
define_button_label = self.panel.DefineButtons[0].Label if len(self.panel.DefineButtons)>0 else ""
if define_button_label != self.configuration.define_button_label: update_needed = True
show_stop_button = self.panel.StopButton.Shown
if show_stop_button != self.configuration.show_stop_button: update_needed = True
vertical = self.panel.vertical
if vertical != self.configuration.vertical: update_needed = True
if update_needed: debug("update_needed: %r" % update_needed)
return update_needed
def update_layout(self):
"""Update the number of rows or columns if the configuration has changed"""
if self.update_needed: self.layout()
def update_date(self):
self.panel.CurrentDate.Value = self.configuration.current_timestamp
def update(self,changes={}):
"""Update the panel"""
debug("Started %r" % self.configuration.name)
from numpy import nan
self.Title = self.cache.get("title","")
for i in range(0,self.configuration.n_motors):
value = self.cache.get("motor_labels[%d]"%i,"")
self.panel.PositionLabels[i].Label = value
for i in range(0,self.configuration.nrows):
value = self.cache.get("descriptions[%d]"%i,"")
self.panel.Descriptions[i].Value = value
value = self.cache.get("updated[%d]"%i,"")
self.panel.Dates[i].Value = value
for i in range(0,self.configuration.nrows):
for j in range(0,self.configuration.n_motors):
##if "positions[%d][%d]"%(j,i) in changes or "formats[%d]"%j in changes:
value = self.cache.get("positions[%d][%d]"%(j,i),nan)
format = self.cache.get("formats[%d]"%j,"%s")
self.panel.Positions[i,j].Value = tostr(value,format)
# Update current description, date, motor positions
for i in range(0,self.configuration.n_motors):
##if "current_positions[%d]"%i in changes or "formats[%d]"%i in changes:
value = self.cache.get("current_positions[%d]"%i,nan)
format = self.cache.get("formats[%d]"%i,"%s")
self.panel.CurrentPositions[i].Value = tostr(value,format)
description = self.cache.get("description","")
self.panel.CurrentDescription.Value = description
# Highlight the current settings
matching_description = self.cache.get("matching_description","")
closest_descriptions = self.cache.get("closest_descriptions","")
command_description = self.cache.get("command_description","")
matching_rows = self.cache.get("matching_rows",[])
closest_rows = self.cache.get("closest_rows",[])
command_rows = self.cache.get("command_rows",[])
for i in range(0,self.configuration.nrows):
selected = (i in command_rows)
self.panel.SelectButtons[i].Value = \
selected if self.configuration.multiple_selections else False
if selected:
color = self.matching_color if i in matching_rows else self.close_color
else: color = self.NormalBackgroundColour
self.panel.SelectButtons[i].BackgroundColour = color
if i in matching_rows or i in closest_rows:
if i in matching_rows: color = self.matching_color
elif i in closest_rows: color = self.close_color
self.panel.Descriptions[i].BackgroundColour = color
self.panel.Dates[i].BackgroundColour = color
for j in range(0,self.configuration.n_motors):
matches = self.cache.get("matches(%d,%d)"%(i,j),False)
color = self.matching_color if matches else self.close_color
self.panel.Positions[i,j].BackgroundColour = color
elif i in command_rows:
color = self.close_color
self.panel.Descriptions[i].BackgroundColour = color
self.panel.Dates[i].BackgroundColour = color
for j in range(0,len(self.configuration.motors)):
name = "current_positions[%d]" % j
position = self.cache[name] if name in self.cache else nan
matches = self.configuration.matches(i,j,position)
color = self.close_color if matches else self.command_color
self.panel.Positions[i,j].BackgroundColour = color
else:
color = self.NormalBackgroundColour
self.panel.Descriptions[i].BackgroundColour = color
self.panel.Dates[i].BackgroundColour = color
for j in range(0,len(self.configuration.motors)):
self.panel.Positions[i,j].BackgroundColour = color
debug("Finished %r" % self.configuration.name)
matching_color = wx.Colour(0,180,0)
close_color = wx.Colour(255,200,0)
command_color = wx.Colour(255,128,128)
def on_input(self,event):
"""This is called when the use switches between fields and controls
using Tab or the mouse, or presses Enter in a text entry. This does
necessarily indicate that any value was changed. But it is a good
opportunity the process any changes."""
Id = event.Id
info("event.Id=%r" % event.Id)
nrows = self.panel.Descriptions.shape[0]
for i in range(0,nrows):
if self.panel.Descriptions[i].Id == Id:
text = self.panel.Descriptions[i].Value
info("%r.descriptions[%r] = %r" % (self.configuration,i,text))
self.configuration.descriptions[i] = text
if self.panel.Dates[i].Id == Id:
text = self.panel.Dates[i].Value
info("%r.updated[%r] = %r" % (self.configuration,i,text))
self.configuration.updated[i] = text
for j in range(0,len(self.configuration.positions)):
if self.panel.Positions[i,j].Id == Id:
text = self.panel.Positions[i,j].Value
try: value = motor_position(text,self.configuration.formats[j])
except Exception,msg:
warn("%r,%r: %s: %s" % (i,j,text,msg))
continue
info("%r.positions[%r][%r] = %r" % (self.configuration,j,i,value))
self.configuration.positions[j][i] = value
if self.panel.CurrentDescription.Id == Id:
value = self.panel.CurrentDescription.Value
info("%r.value = %r" % (self.configuration,value))
self.configuration.value = value
for j in range(0,len(self.configuration.positions)):
if self.panel.CurrentPositions[j].Id == Id:
text = self.panel.CurrentPositions[j].Value
try: value = motor_position(text,self.configuration.formats[j])
except Exception,msg:
warn("%r: %s: %s" % (j,text,msg))
continue
info("%r.current_positions[%r] = %r" % (self.configuration,j,value))
self.configuration.current_positions[j] = value
def OnShowConfiguration(self,event):
"""Display the configuration panel for this configuration"""
Id = event.Id
##info("event.Id=%r" % event.Id)
for i in range(0,self.configuration.n_motors):
if self.panel.PositionLabels[i].Id == Id:
name = self.configuration.configuration_name(i)
info("Showing configration %r" % name)
show_panel(name)
def OnSelect(self,event):
"""Handle row select"""
##info("event.Id=%r" % event.Id)
row = event.Id
selected = event.IsChecked()
info("Select row %r,%r" % (row,selected))
if self.configuration.multiple_selections:
rows = self.configuration.command_rows
if not selected and row in rows: rows.remove(row)
if selected and not row in rows: rows.append(row)
else: rows = [row]
info("rows = %r" % rows)
self.configuration.command_rows = rows
self.configuration.applying = True
if not self.configuration.multiple_selections:
# Make the toggle button behave like a command button
button = event.EventObject
button.Value = False
def define_setting(self,event):
"""Copy the current motor settings in the row of the 'Set" button
that was pressed."""
info("event.Id=%r" % event.Id)
row = event.Id-100 # Row number of "Set" button pressed
info("self.configuration.define(%r)" % row)
self.configuration.define(row)
def stop(self,event):
"""To cancel any move should one hit the wrong button by mistake"""
self.configuration.stop()
from persistent_property import persistent_property
__show__ = persistent_property("show",[])
def get_show(self):
"""Which columns to show? list of boolean"""
show = self.__show__
while len(show) < len(self.configuration.motor_labels): show += [True]
return show
def set_show(self,value): self.__show__ = value
show = property(get_show,set_show)
def OnOpenView(self,event):
"""Called if the "View" menu is selected"""
for i in range(0,len(self.configuration.motor_labels)):
self.ViewMenu.Check(100+i,self.show[i])
def OnView(self,event):
"""Called if one of the items of the "View" menu is selected"""
i = event.Id-100
self.show[i] = not self.show[i]
self.panel.Sizer.Fit(self)
# To do: update panel
def OnConfiguration(self,event):
show_configuration(self.configuration.name)
def OnConfigurations(self,event):
show_configurations()
def OnAbout(self,event):
"""Show panel with additional parameters"""
from os.path import basename
from inspect import getfile,getmodule
from os.path import getmtime
from datetime import datetime
filename = getfile(type(self))
info = basename(filename)+" "+getmodule(type(self)).__version__
info += "\n\n"+getmodule(type(self)).__doc__
dlg = wx.MessageDialog(self,info,"About",wx.OK|wx.ICON_INFORMATION)
dlg.CenterOnParent()
dlg.ShowModal()
dlg.Destroy()
from Panel import BasePanel,PropertyPanel,TogglePanel,TweakPanel
class ConfigurationPanel(BasePanel):
name = "configuration"
title = "Configuration"
standard_view = [
"Rows",
"Title",
"Mnemonic",
"Python code",
"Column mnemonics",
"Column labels",
"Column widths",
"Column formats",
"Tolerances",
"Name width",
"Row height",
"Apply buttons",
"Apply button label",
"Update buttons",
"Update button label",
"Stop button",
"Go To",
"Vertical",
"Multiple Selections",
]
def __init__(self,parent=None,configuration=None,name=None,
globals=None,locals=None):
if configuration is not None: self.configuration = configuration
elif name is not None:
from configuration import configuration
self.configuration = configuration(name,globals=globals,locals=locals)
else: raise RuntimeError("SavedPositionsPanel requires 'configuration' or 'name'")
parameters = [
[[PropertyPanel,"Rows",self.configuration,"nrows"],{}],
[[PropertyPanel,"Title",self.configuration,"title"],{}],
[[PropertyPanel,"Mnemonic",self.configuration,"name"],{}],
[[PropertyPanel,"Python code",self.configuration,"motor_names"],{}],
[[PropertyPanel,"Column mnemonics",self.configuration,"names"],{}],
[[PropertyPanel,"Column labels",self.configuration,"motor_labels"],{}],
[[PropertyPanel,"Column widths",self.configuration,"widths"],{}],
[[PropertyPanel,"Column formats",self.configuration,"formats"],{}],
[[PropertyPanel,"Tolerances",self.configuration,"tolerance"],{}],
[[PropertyPanel,"Name width",self.configuration,"description_width"],{}],
[[PropertyPanel,"Row height",self.configuration,"row_height"],{}],
[[PropertyPanel,"Apply buttons",self.configuration,"show_apply_buttons"],{}],
[[PropertyPanel,"Apply button label",self.configuration,"apply_button_label"],{}],
[[PropertyPanel,"Update buttons",self.configuration,"show_define_buttons"],{}],
[[PropertyPanel,"Update button label",self.configuration,"define_button_label"],{}],
[[PropertyPanel,"Stop button",self.configuration,"show_stop_button"],{}],
[[PropertyPanel,"Go To",self.configuration,"serial"],{"type":"All motors at once/One motor at a time (left to right)"}],
[[PropertyPanel,"Vertical",self.configuration,"vertical"],{}],
[[PropertyPanel,"Multiple Selections",self.configuration,"multiple_selections"],{}],
]
from numpy import inf
BasePanel.__init__(self,
parent=parent,
name=self.name,
title=self.title,
parameters=parameters,
standard_view=self.standard_view,
subname=True,
label_width=130,
width=250,
refresh_period=1.0,
)
class ConfigurationsPanel(wx.Frame):
"""Control panel to show all configurations"""
icon = "Tool"
title = "Modes/Configurations"
def __init__(self,parent=None):
wx.Frame.__init__(self,parent=parent)
self.configure = False
self.layout()
self.Show()
# Periodically update the displayed fields.
self.timer = wx.Timer(self)
self.Bind (wx.EVT_TIMER,self.OnTimer)
self.timer.Start(1000,oneShot=True)
def OnTimer(self,event=None):
"""Called periodically every second triggered by a timer"""
import traceback
try: self.refresh_layout()
except Exception,msg: error("%s" % msg); traceback.print_exc()
self.timer.Start(1000,oneShot=True) # Need to restart the Timer
def update_layout(self):
"""Update the number of rows or columns if the configuration has changed"""
self.layout()
def refresh_layout(self):
"""Update the number of rows or columns if the configuration has changed"""
if self.update_needed: self.layout()
@property
def update_needed(self):
update_needed = False
labels = [self.label(i) for i in range(0,self.count) if self.show_in_list(i)]
button_labels = [button.Label for button in self.panel.buttons]
if labels != button_labels: update_needed = True
if update_needed: debug("update_needed")
return update_needed
def layout(self):
self.Title = self.title
from Icon import SetIcon
SetIcon(self,self.icon)
if not self.MenuBar: self.MenuBar = self.menu_bar
panel = self.ControlPanel
if hasattr(self,"panel"): self.panel.Destroy()
self.panel = panel
self.Fit()
@property
def ControlPanel(self):
# Controls and Layout
panel = wx.Panel(self)
##sizer = wx.BoxSizer(wx.VERTICAL)
sizer = wx.GridBagSizer(1,1)
flag = wx.ALIGN_CENTRE_VERTICAL|wx.ALL|wx.EXPAND
buttons = []
j = 0
for i in range(0,self.count):
if self.show_in_list(i):
button = wx.Button(panel,label=self.label(i),id=i)
button.Shown = self.show_in_list(i)
##sizer.Add(button,flag=flag)
sizer.Add(button,(j,0),flag=flag)
j += 1
buttons += [button]
panel.buttons = buttons
panel.SetSizer(sizer)
panel.Fit()
self.Bind(wx.EVT_BUTTON,self.show)
return panel
@property
def menu_bar(self):
"""MenuBar object"""
# Menus
menuBar = wx.MenuBar()
# View
self.ViewMenu = wx.Menu()
for i in range(0,self.count):
self.ViewMenu.AppendCheckItem(100+i,self.label(i))
self.ViewMenu.AppendSeparator()
menuBar.Append (self.ViewMenu,"&View")
# More
self.MoreMenu = wx.Menu()
self.MoreMenu.AppendCheckItem(201,"Configure this Panel")
menuBar.Append (self.MoreMenu,"&More")
# Help
menu = wx.Menu()
menu.Append (wx.ID_ABOUT,"About...","Show version number")
menuBar.Append (menu,"&Help")
# Callbacks
self.Bind(wx.EVT_MENU_OPEN,self.OnOpenView)
for i in range(0,self.count):
self.Bind(wx.EVT_MENU,self.OnView,id=100+i)
self.Bind(wx.EVT_MENU,self.OnConfigure,id=201)
self.Bind(wx.EVT_MENU,self.OnAbout,id=wx.ID_ABOUT)
return menuBar
def OnOpenView(self,event):
"""Called if the "View" menu is selected"""
for i in range(0,self.count):
self.ViewMenu.Check(100+i,self.show_in_list(i))
self.MoreMenu.Check(201,self.configure)
def OnView(self,event):
"""Called if one of the items of the "View" menu is selected"""
i = event.Id-100
self.set_show_in_list(i,not self.show_in_list(i))
self.layout()
def OnConfigure(self,event):
self.configure = not self.configure
self.layout
def OnAbout(self,event):
"""Show panel with additional parameters"""
from os.path import basename
from inspect import getfile,getmodule
from os.path import getmtime
from datetime import datetime
filename = getfile(type(self))
info = basename(filename)+" "+getmodule(type(self)).__version__
info += "\n\n"+getmodule(type(self)).__doc__
dlg = wx.MessageDialog(self,info,"About",wx.OK|wx.ICON_INFORMATION)
dlg.CenterOnParent()
dlg.ShowModal()
dlg.Destroy()
def show(self,event):
"""Display control panel"""
##info("event.Id=%r" % event.Id)
from configuration import configuration
name = configuration.configuration_names[event.Id]
info("name=%r" % name)
show_panel(name)
@property
def count(self):
from configuration import configuration
return len(configuration.configurations)
def label(self,i):
from configuration import configuration
return configuration.configurations[i].title
def show_in_list(self,i):
from configuration import configuration
return configuration.configurations[i].show_in_list
def set_show_in_list(self,i,value):
from configuration import configuration
configuration.configurations[i].show_in_list = value
def tostr(x,format="%g"):
"""Converts a number to a string.
This is needed to handle "not a number" and infinity properly.
Under Windows, 'str()','repr()' and '%' format 'nan' as '-1.#IND' and 'inf'
as '1.#INF', which is inconsistent with Linux ('inf' and 'nan').
"""
from numpy import isnan,isinf
from time_string import time_string
try:
if isnan(x): return ""
elif isinf(x) and x>0: return "inf"
elif isinf(x) and x<0: return "-inf"
elif "time" in format:
precision = format.split(".")[-1][0]
try: precision = int(precision)
except: precision = 3
return time_string(x,precision)
else: return format % x
except TypeError: return str(x)
def motor_position(s,format="%g"):
"""Convert string to float and return 'not a number' if not possiple"""
from time_string import seconds
from numpy import nan
if "time" in format: value = seconds(s)
elif "s" in format: value = s # "%s" -> keep as string
else:
try: value = float(eval(s))
except Exception: value = nan
return value
def show_panel(name):
##exec("from instrumentation import *") # -> locals()
##SavedPositionsPanel(name=name,globals=globals(),locals=locals())
from start import start
start("SavedPositionsPanel_2","SavedPositionsPanel(name=%r,globals=globals(),locals=locals())" % name)
def show_configuration(name):
##exec("from instrumentation import *") # -> locals()
##ConfigurationPanel(name=self.configuration.name,globals=self.globals,locals=self.locals)
from start import start
start("SavedPositionsPanel_2","ConfigurationPanel(name=%r,globals=globals(),locals=locals())" % name)
def show_configurations():
##ConfigurationsPanel()
from start import start
start("SavedPositionsPanel_2","ConfigurationsPanel()")
if __name__ == '__main__':
from pdb import pm # for debugging
from redirect import redirect
format="%(asctime)s %(levelname)s %(module)s.%(funcName)s: %(message)s"
redirect("SavedPositionsPanel_2",format=format)
import autoreload
name = ""
##name = "sequence_modes"
##name = "beamline_configuration"
##name = "high_speed_chopper_modes"
##name = "Julich_chopper_modes"
##name = "timing_modes"
##name = "delay_configuration"
##name = "power_configuration"
##name = "detector_configuration"
name = "method"
# Allow commandline argument to specifiy which configuration to use.
from sys import argv
if len(argv) >= 2: name = argv[1]
if not hasattr(wx,"app"): wx.app = wx.App(redirect=False)
exec("from instrumentation import *") # -> globals()
##from instrumentation import * # -> globals()
##t = timing_sequencer # shortcut
if name: SavedPositionsPanel(name=name,globals=globals(),locals=locals())
else: ConfigurationsPanel()
wx.app.MainLoop()
<file_sep>"""Instruct the ADXV image display application to display a live image during
data collection
Author: <NAME>
Date created: 2017-06-28
Date last modified: 2019-06-02
"""
__version__ = "1.0"
from logging import debug,info,warn,error
class ADXV_Live_Image(object):
name = "ADXV_live_image"
from persistent_property import persistent_property
ip_address = persistent_property("ip_address","id14b4.cars.aps.anl.gov:8100")
ip_address_choices = [
"id14b4.cars.aps.anl.gov:8100",
"pico5.cars.aps.anl.gov:8100",
]
refresh_interval = persistent_property("refresh_interval",1.0)
refresh_interval_choices = [0.25,0.5,1,2,5,10,30,60]
last_refresh_time = 0.0
from thread_property_2 import thread_property
@thread_property
def live_image(self):
"""Display a live image"""
while not self.live_image_cancelled:
self.update_live_image()
self.live_image_wait_for_next_update()
self.connected = False
def live_image_wait_for_next_update(self):
from time import sleep,time
next_refresh_time = self.last_refresh_time + self.refresh_interval
while time() < next_refresh_time and self.live_image:
wait_time = min(max(next_refresh_time-time(),0),0.25)
sleep(wait_time)
next_refresh_time = self.last_refresh_time + self.refresh_interval
live_image_filename = ""
def update_live_image(self):
"""Display a live image"""
filename = self.image_filename
if filename and filename != self.live_image_filename:
self.show_image(filename)
def show_image(self,filename):
"""Tell ADSV to display an image"""
if filename:
from tcp_client import query,connected
from time import time
query(self.ip_address,"load_image %s" % filename,count=0)
self.is_connected = connected(self.ip_address)
if self.is_connected:
self.live_image_filename = filename
self.last_refresh_time = time()
else:
from tcp_client import disconnect
disconnect(self.ip_address)
self.is_connected = False
self.live_image_filename = ""
@property
def image_filename(self):
from instrumentation import rayonix_detector
filename = rayonix_detector.current_temp_filename
return filename
is_connected = False
def get_connected(self):
return self.is_connected
def set_connected(self,value):
if bool(value) == False:
from tcp_client import disconnect
disconnect(self.ip_address)
self.is_connected = False
if bool(value) == True:
from tcp_client import connect
connect(self.ip_address)
self.is_connected = True
connected = property(get_connected,set_connected)
online = connected
ADXV_live_image = ADXV_Live_Image()
def show_image(filename):
from thread import start_new_thread
start_new_thread(ADXV_live_image.show_image,(filename,))
if __name__ == "__main__":
from pdb import pm
import logging
logging.basicConfig(level=logging.DEBUG,format="%(asctime)s: %(message)s")
self = ADXV_live_image
print('ADXV_live_image.ip_address = %r' % ADXV_live_image.ip_address)
print('ADXV_live_image.refresh_interval = %r' % ADXV_live_image.refresh_interval)
print('')
print('ADXV_live_image.live_image = True')
print('ADXV_live_image.update_live_image()')
from instrumentation import rayonix_detector
print('show_image(rayonix_detector.current_temp_filename)')
<file_sep>EPICS_enabled = True
description = 'Laser atten. X-Ray hutch'
prefix = '14IDB:m32'<file_sep>#!/bin/env python
# AMO data collection
# 4/3/2011 RH
# To Do
# 82.3 Hz? Need to force open shutter. EPICS control?
# Could copy function update_bkg_image() to close shutter.
# Use 11 bunch. 41Hz.
from id14 import *
from time import sleep, time, strftime
from epics import caget,caput,PV
# This will overwrite old images
#base_filename="test_file_"
#base_filename="CF3Br_last_14keV_"
base_filename="nogas_last_14keV_"
# Number of pulses per image
num_pulses=25000
extension=".mccd"
directory="/data/young_1103/CF3Br/" # Need to create manually
images=1 #How many images to collect
# Log to file
filename_log=directory+base_filename+".log"
f = open(filename_log,'w')
#EPICS PV's
p1_mean=PV('14IDB:waveSurfer:P1:mean.VAL')
p1_sdev=PV('14IDB:waveSurfer:P1:sdev.VAL')
p2_mean=PV('14IDB:waveSurfer:P2:mean.VAL')
p2_sdev=PV('14IDB:waveSurfer:P2:sdev.VAL')
p1_num=PV('14IDB:waveSurfer:P1:num.VAL')
p1_read=PV('14IDB:waveSurfer:P1:read.PROC')
p2_read=PV('14IDB:waveSurfer:P2:read.PROC')
Wave_Clear=PV('14IDB:waveSurfer:clearSweeps.PROC')
f.write("BackgroundDate BackgroundTime Filename FileDate FileTime Pulses I0_mean I0_sdev BS_mean BS_sdev Triggers\n")
# Readout detector.
for image in range(1,(images+1)):
Wave_Clear.value=1
back_time=strftime("%Y-%m-%d %H:%M:%S")
print "Reading background "+back_time
ccd.read_bkg() # Read background
ccd.start() # Start integrating
pulses.value=num_pulses
# tmode.value=0 # Continous
# sleep(exposure_time)
# tmode.value=1 # Counted
while(pulses.value > 0): sleep(0.5)
filename=directory+base_filename+str(image)+extension
read_msg=filename+" "+strftime("%Y-%m-%d %H:%M:%S")
print read_msg
ccd.readout(filename)
p1_read.value=1
p2_read.value=1
sleep(5) # time to readout detector
f.write(back_time+" "+read_msg+" "+str(num_pulses)+" "+str(p1_mean.value)+" "+str(p1_sdev.value)+" "+str(p2_mean.value)+" "+str(p2_sdev.value)+" "+str(p1_num.value)+"\n")
sleep(1)
f.close()
<file_sep>"""This is to switch between hardware configurations for the synchroneous
sample translation.
<NAME> Mar 24, 2014 - Sep 19,2014
version 1.1"""
# Uncomment the appropriate line to change configurations
from sample_translation_Ensemble import *
##from sample_translation_soloist import *
<file_sep>CustomView = ['Data']
view = 'Custom'<file_sep>Size = (512, 748)
ScaleFactor = 0.33
ZoomLevel = 1.0
Orientation = -90
Mirror = True
NominalPixelSize = 0.002325
filename = ''
ImageWindow.Center = (680, 512)
ImageWindow.ViewportCenter = (1.1904, 1.5774772727272726)
ImageWindow.crosshair_color = (255, 0, 255)
ImageWindow.boxsize = (0.1, 0.06)
ImageWindow.box_color = (128, 128, 255)
ImageWindow.show_box = False
ImageWindow.Scale = [[0.062775, -0.5417249999999999], [0.9044249999999999, -0.5324249999999999]]
ImageWindow.show_scale = False
ImageWindow.scale_color = (255, 0, 255)
ImageWindow.crosshair_size = (0.05, 0.05)
ImageWindow.show_crosshair = True
ImageWindow.show_profile = False
ImageWindow.show_FWHM = False
ImageWindow.show_center = False
ImageWindow.calculate_section = False
ImageWindow.profile_color = (255, 0, 255)
ImageWindow.FWHM_color = (0, 0, 255)
ImageWindow.center_color = (0, 0, 255)
ImageWindow.ROI = [[-0.299925, -0.5905499999999999], [0.3999, 0.19529999999999997]]
ImageWindow.ROI_color = (255, 255, 0)
ImageWindow.show_saturated_pixels = False
ImageWindow.mask_bad_pixels = False
ImageWindow.saturation_threshold = 233
ImageWindow.saturated_color = (255, 0, 0)
ImageWindow.linearity_correction = False
ImageWindow.bad_pixel_threshold = 233
ImageWindow.bad_pixel_color = (30, 30, 30)
ImageWindow.show_grid = False
ImageWindow.grid_type = u'xy'
ImageWindow.grid_color = (98, 98, 98)
ImageWindow.grid_x_spacing = 0.1
ImageWindow.grid_x_offset = 0.0
ImageWindow.grid_y_spacing = 1.0
ImageWindow.grid_y_offset = 0.0
camera.use_multicast = False
camera.IP_addr = u'id14b-prosilica1.cars.aps.anl.gov'
<file_sep>#!/usr/bin/env python
"""High-speed diffractometer.
<NAME>, 8 Dec 2015 - 8 Dec 2015"""
__version__ = "1.0"
import wx
from MotorPanel import MotorWindow
# Needed to initialize WX library
if not "app" in globals(): app = wx.App(redirect=False)
from instrumentation import ChopX,ChopY
window = MotorWindow([ChopX,ChopY],
title="High-Speed Chopper")
app.MainLoop()
<file_sep>title = 'Microscope [advanced] (-30 deg)'<file_sep>from psana import *
ds = DataSource('exp=xpptut15:run=240')
det = Detector('rayonix',ds.env())
for nevent,evt in enumerate(ds.events()):
img = det.raw_data(evt)
break
import matplotlib.pyplot as plt
plt.imshow(img,vmin=-2,vmax=2)
plt.show()
<file_sep>"The basic infrastructure for maintaining a vxi-11 protocol connection to a remote device"
_rcsid="vxi_11.py,v 1.6 2003/05/30 13:29:23 mendenhall Release-20050805"
import rpc
from rpc import TCPClient, RawTCPClient
import exceptions
import struct
import traceback
import time
import weakref
import sys
import select
try:
import threading
threads=1
except:
threads=0
connection_dict={}
def close_all_connections():
"disconnect and close out all vxi_11 connections created here, even if their object references have been lost"
for wobj in connection_dict.keys():
name, wconn=connection_dict[wobj]
conn=wconn() #dereference weak ref
if conn is not None:
try:
conn.disconnect()
except:
conn.log_exception("***vxi_11.close_all_connections exception: ")
else:
del connection_dict[wobj] #how did this happen?
class Junk_OneWayAbortClient(RawTCPClient):
"""OneWayAbortClient allows one to handle the strange, one-way abort rpc from an Agilent E5810.
Really, it doesn't even do a one-way transmission... it loses aborts, so this is history """
def do_call(self):
call = self.packer.get_buf()
rpc.sendrecord(self.sock, call)
self.unpacker.reset('\0\0\0\0') #put a valid return value into the unpacker
class VXI_11_Error(IOError):
vxi_11_errors={
0:"No error", 1:"Syntax error", 3:"Device not accessible",
4:"Invalid link identifier", 5:"Parameter error", 6:"Channel not established",
8:"Operation not supported", 9:"Out of resources", 11:"Device locked by another link",
12:"No lock held by this link", 15:"IO Timeout", 17:"IO Error", 21:"Invalid Address",
23:"Abort", 29:"Channel already established" ,
"eof": "Cut off packet received in rpc.recvfrag()",
"sync":"stream sync lost",
"notconnected": "Device not connected"}
def identify_vxi_11_error(self, error):
if self.vxi_11_errors.has_key(error):
return `error`+": "+self.vxi_11_errors[error]
else:
return `error`+": Unknown error code"
def __init__(self, code, **other_info):
self.code=code
self.message=self.identify_vxi_11_error(code)
self.other_info=other_info
def __repr__(self):
if self.other_info:
return self.message+": "+str(self.other_info)
else:
return self.message
def __str__(self):
return self.__repr__()
class VXI_11_Device_Not_Connected(VXI_11_Error):
def __init__(self):
VXI_11_Error.__init__(self,'notconnected')
class VXI_11_Device_Not_Locked(VXI_11_Error):
pass
class VXI_11_Transient_Error(VXI_11_Error): #exceptions having to do with multiple use which might get better
pass
class VXI_11_Timeout(VXI_11_Transient_Error):
pass
class VXI_11_Locked_Elsewhere(VXI_11_Transient_Error):
pass
class VXI_11_Stream_Sync_Lost(VXI_11_Transient_Error):
def __init__(self, code, bytes):
VXI_11_Transient_Error.__init__(self, code)
self.other_info="bytes vacuumed = %d" % bytes
class VXI_11_RPC_EOF(VXI_11_Transient_Error):
pass
_VXI_11_enumerated_exceptions={ #common, correctable exceptions
15:VXI_11_Timeout,
11:VXI_11_Locked_Elsewhere,
12:VXI_11_Device_Not_Locked
}
class vxi_11_connection:
"""vxi_11_connection implements handling of devices compliant with vxi11.1-vxi11.3 protocols, with which
the user should have some familiarity"""
debug_info=0
debug_error=1
debug_warning=2
debug_all=3
debug_level=debug_error
OneWayAbort=0 #by default, this class uses two-way aborts, per official vxi-11 standard
def _list_packer(self, args):
l=map(None, self.pack_type_list, args) # combine lists
for packer, data in l:
packer(data)
def _list_unpacker(self):
return [func() for func in self.unpack_type_list]
def _link_xdr_defs(self, channel):
"self.link_xdr_defs() creates dictionaries of functions for packing and unpacking the various data types"
p=channel.packer
u=channel.unpacker
xdr_packer_defs={
"write": (p.pack_int, p.pack_int, p.pack_int, p.pack_int, p.pack_opaque),
"read": (p.pack_int, p.pack_int, p.pack_int, p.pack_int, p.pack_int, p.pack_int),
"create_link": (p.pack_int, p.pack_bool, p.pack_uint, p.pack_string),
"generic": (p.pack_int, p.pack_int, p.pack_int, p.pack_int),
"lock": (p.pack_int, p.pack_int, p.pack_int),
"id": (p.pack_int,)
}
xdr_unpacker_defs={
"write": (u.unpack_int, u.unpack_int),
"read": (u.unpack_int, u.unpack_int, u.unpack_opaque),
"create_link": (u.unpack_int, u.unpack_int, u.unpack_uint, u.unpack_uint),
"read_stb":(u.unpack_int, u.unpack_int),
"error": (u.unpack_int,)
}
return xdr_packer_defs, xdr_unpacker_defs
def _setup_core_packing(self, pack, unpack):
self.pack_type_list, self.unpack_type_list=self._core_packers[pack],self._core_unpackers[unpack]
def post_init(self):
pass
def simple_log_error(self, message, level=debug_error, file=None):
if level <= self.debug_level:
if file is None:
file=sys.stderr
print >> file, self.device_name, message
def fancy_log_error(self, message, level=debug_error, file=None):
if level <= self.debug_level:
message=str(message).strip()
level_str=("**INFO*****", "**ERROR****", "**WARNING**", "**DEBUG****")[level]
if file is None:
file=sys.stderr
print >> file, time.asctime().strip(), '\t', level_str, '\t', self.shortname, '\t', \
message.replace('\n','\n\t** ').replace('\r','\n\t** ')
def log_error(self, message, level=debug_error, file=None):
"override log_error() for sending messages to special places or formatting differently"
self.fancy_log_error(message, level, file)
def log_traceback(self, main_message='', file=None):
exlist=traceback.format_exception(*sys.exc_info())
s=main_message+'\n'
for i in exlist:
s=s+i
self.log_error(s, self.debug_error, file)
def log_info(self, message, file=None):
self.log_error(message, self.debug_info, file)
def log_warning(self, message, file=None):
self.log_error(message, self.debug_warning, file)
def log_debug(self, message, file=None):
self.log_error(message, self.debug_all, file)
def log_exception(self, main_message='', file=None):
self.log_error(main_message+traceback.format_exception_only(*(sys.exc_info()[:2]))[0], self.debug_error, file)
def __init__(self, host='127.0.0.1', device="inst0", timeout=1000, raise_on_err=None, device_name="Network Device", shortname=None,
portmap_proxy_host=None, portmap_proxy_port=rpc.PMAP_PORT):
self.raise_on_err=raise_on_err
self.lid=None
self.timeout=timeout
self.device_name=device_name
self.device_sicl_name=device
self.host=host
self.portmap_proxy_host=portmap_proxy_host
self.portmap_proxy_port=portmap_proxy_port
self.core=None
self.abortChannel=None
self.mux=None #default is no multiplexer active
if shortname is None:
self.shortname=device_name.strip().replace(' ','').replace('\t','')
else:
self.shortname=shortname.strip().replace(' ','').replace('\t','')
if threads:
self.threadlock=threading.RLock()
try:
self.reconnect()
except VXI_11_Transient_Error:
self.log_exception("Initial connect failed... retry later")
def setup_mux(self, mux=None, global_name=None):
self.mux=mux
self.global_mux_name=global_name
def command(self, id, pack, unpack, arglist, ignore_connect=0):
if not (ignore_connect or self.connected):
raise VXI_11_Device_Not_Connected
self._setup_core_packing(pack, unpack)
try:
result= self.core.make_call(id, arglist, self._list_packer, self._list_unpacker)
except (RuntimeError, EOFError):
#RuntimeError is thrown by recvfrag if the xid is off... it means we lost data in the pipe
#EOFError is thrown if the packet isn't full length, as usually happens when ther is garbage in the pipe read as a length
#so vacuum out the socket, and raise a transient error
rlist=1
ntotal=0
while(rlist):
rlist, wlist, xlist=select.select([self.core.sock],[],[], 1.0)
if rlist:
ntotal+=len(self.core.sock.recv(10000) )#get some data from it
raise VXI_11_Stream_Sync_Lost("sync", ntotal)
err=result[0]
if err and self.raise_on_err:
e=_VXI_11_enumerated_exceptions #common, correctable exceptions
if e.has_key(err):
raise e[err](err) #raise these exceptions explicitly
else:
raise VXI_11_Error(err) #raise generic VXI_11 exception
return result
def do_timeouts(self, timeout, lock_timeout, channel=None):
if channel is None:
channel=self.core
flags=0
if timeout is None:
timeout=self.timeout
if not lock_timeout and hasattr(self,"default_lock_timeout"):
lock_timeout=self.default_lock_timeout
if lock_timeout:
flags |= 1 # append waitlock bit
if channel:
channel.select_timeout_seconds=1.5*max(timeout, lock_timeout)/1000.0 #convert ms to sec, and be generous on hard timeout
return flags, timeout, lock_timeout
def reconnect(self): #recreate a broken connection
"""reconnect() creates or recreates our main connection. Useful in __init__ and in complete communications breakdowns.
If it throws a VXI_11_Transient_Error, the connection exists, but the check_idn() handshake or post_init() failed."""
self.connected=0
if self.core:
self.core.close() #if this is a reconnect, break old connection the hard way
if self.abortChannel:
self.abortChannel.close()
self.core=rpc.TCPClient(self.host, 395183, 1,
portmap_proxy_host=self.portmap_proxy_host,
portmap_proxy_port=self.portmap_proxy_port)
self._core_packers, self._core_unpackers=self._link_xdr_defs(self.core) #construct xdr data type definitions for the core
err, self.lid, self.abortPort, self.maxRecvSize=self.command(
10, "create_link","create_link", (0, 0, self.timeout, self.device_sicl_name), ignore_connect=1) #execute create_link
if err: #at this stage, we always raise exceptions since there isn't any way to bail out or retry reasonably
raise VXI_11_Error(err)
self.maxRecvSize=min(self.maxRecvSize, 1048576) #never transfer more than 1MB at a shot
if self.OneWayAbort:
#self.abort_channel=OneWayAbortClient(self.host, 395184, 1, self.abortPort)
self.abort_channel=rpc.RawUDPClient(self.host, 395184, 1, self.abortPort)
else:
self.abort_channel=RawTCPClient(self.host, 395184, 1, self.abortPort)
connection_dict[self.lid]=(self.device_name, weakref.ref(self))
self.locklevel=0
self.connected=1
self.check_idn()
self.post_init()
def abort(self):
self.abort_channel.select_timeout_seconds=self.timeout/1000.0 #convert to seconds
try:
err=self.abort_channel.make_call(1, self.lid, self.abort_channel.packer.pack_int, self.abort_channel.unpacker.unpack_int) #abort
except EOFError:
raise VXI_11_RPC_EOF("eof")
if err and self.raise_on_err:
raise VXI_11_Error( err)
return err
def disconnect(self):
if self.connected:
try:
err, =self.command(23, "id", "error", (self.lid,)) #execute destroy_link
except:
self.log_traceback() #if we can't close nicely, we'll close anyway
self.connected=0
del connection_dict[self.lid]
self.lid=None
self.core.close()
self.abort_channel.close()
del self.core, self.abort_channel
self.core=None
self.abortChannel=None
def __del__(self):
if self.lid is not None:
self.raise_on_err=0 #no exceptions here from simple errors
try:
self.abort()
except VXI_11_Error:
pass
try:
self.disconnect()
except VXI_11_Error:
pass
def write(self, data, timeout=None, lock_timeout=0):
"""err, bytes_sent=write(data [, timeout] [,lock_timeout]) sends data to device. See do_timeouts() for
semantics of timeout and lock_timeout"""
flags, timeout, lock_timeout=self.do_timeouts(timeout, lock_timeout)
base=0
end=len(data)
while base<end:
n=end-base
if n>self.maxRecvSize:
xfer=self.maxRecvSize
else:
xfer=n
flags |= 8 #write end on last byte
err, count=self.command(11, "write", "write", (self.lid, timeout, lock_timeout, flags, data[base:base+xfer]))
if err: break
base+=count
return err, base
def read(self, timeout=None, lock_timeout=0, count=None, termChar=None):
"""err, reason, result=read([timeout] [,lock_timeout] [,count] [,termChar]) reads up to count bytes from the device,
ending on count, EOI or termChar (if specified). See do_timeouts() for semantics of the timeouts."""
flags, timeout, lock_timeout=self.do_timeouts(timeout, lock_timeout)
if termChar is not None:
flags |= 128 # append termchrset bit
act_term=termChar
else:
act_term=0
accumdata=""
reason=0
err=0
accumlen=0
while ( (not err) and (not (reason & 4) ) and
( (count is None) or (accumlen < count)) and
( (termChar is None) or (accumdata[-1] != termChar)) ): #wait for END flag or count or matching terminator char
readcount=self.maxRecvSize/2
if count is not None:
readcount=min(readcount, count-accumlen)
err, reason, data = self.command(12, "read","read", (self.lid, readcount, timeout, lock_timeout, flags, act_term))
accumdata+=data
accumlen+=len(data)
#print err, reason, len(data), len(accumdata)
return err, reason, accumdata
def generic(self, code, timeout, lock_timeout):
flags, timeout, lock_timeout=self.do_timeouts(timeout, lock_timeout)
err, = self.command(code, "generic", "error", (self.lid, flags, timeout, lock_timeout))
return err
def trigger(self, timeout=None, lock_timeout=0):
return self.generic(14, timeout, lock_timeout)
def clear(self, timeout=None, lock_timeout=0):
return self.generic(15, timeout, lock_timeout)
def remote(self, timeout=None, lock_timeout=0):
return self.generic(16, timeout, lock_timeout)
def local(self, timeout=None, lock_timeout=0):
return self.generic(17, timeout, lock_timeout)
def read_status_byte(self, timeout=None, lock_timeout=0):
flags, timeout, lock_timeout=self.do_timeouts(timeout, lock_timeout)
err, status = self.command(13, "generic","read_stb", (self.lid, flags, timeout, lock_timeout))
return err, status
def lock(self, lock_timeout=0):
"lock() acquires a lock on a device and the threadlock. If it fails it leaves the connection cleanly unlocked"
err=0
if threads:
self.threadlock.acquire()
if self.locklevel==0:
flags, timeout, lock_timeout=self.do_timeouts(0, lock_timeout)
try:
if self.mux: self.mux.lock_connection(self.global_mux_name)
try:
err, = self.command(18, "lock","error", (self.lid, flags, lock_timeout))
except:
if self.mux: self.mux.unlock_connection(self.global_mux_name)
raise
except:
if threads:
self.threadlock.release()
raise
if err:
if threads:
self.threadlock.release()
else:
self.locklevel+=1
return err
def is_locked(self):
return self.locklevel > 0
def unlock(self, priority=0):
"""unlock(priority=0) unwinds one level of locking, and if the level is zero, really unlocks the device.
Calls to lock() and unlock() should be matched. If there is a danger that they are not, due to bad
exception handling, unlock_completely() should be used as a final cleanup for a series of operations.
Setting priority to non-zero will bias the apparent last-used time in a multiplexer (if one is used),
so setting priority to -10 will effectively mark this channel least-recently-used, while setting it to
+2 will post-date the last-used time 2 seconds, so for the next 2 seconds, the device will be hard to kick
out of the channel cache (but not impossible).
"""
self.locklevel-=1
assert self.locklevel>=0, "Too many unlocks on device: "+self.device_name
err=0
try:
if self.locklevel==0:
try:
err, = self.command(19, "id", "error", (self.lid, ))
finally:
if self.mux:
self.mux.unlock_connection(self.global_mux_name, priority) #this cannot fail, no try needed (??)
elif priority and self.mux:
#even on a non-final unlock, a request for changed priority is always remembered
self.mux.adjust_priority(self.global_mux_name, priority)
finally:
if threads:
self.threadlock.release()
return err
def unlock_completely(self, priority=0):
"unlock_completely() forces an unwind of any locks all the way back to zero for error cleanup. Only exceptions thrown are fatal."
if threads:
self.threadlock.acquire() #make sure we have the threadlock before we try a (possibly failing) full lock
try:
self.lock() #just to be safe, we should already hold one level of lock!
except VXI_11_Locked_Elsewhere:
pass #this is often called on error cleanup when we don't already have a lock, and we don't really care if we can't get it
except VXI_11_Error:
self.log_exception("Unexpected trouble locking in unlock_completely(): ")
if threads:
self.threadlock._RLock__count += (1-self.threadlock._RLock__count)
#unwind to single lock the fast way, and make sure this variable really existed, to shield against internal changes
self.locklevel=1 #unwind our own counter, too
try:
self.unlock(priority)
except VXI_11_Device_Not_Locked:
pass #if we couldn't lock above, we will probably get another exception here, and don't care
except VXI_11_Transient_Error:
self.log_exception("Unexpected trouble unlocking in unlock_completely(): ")
except VXI_11_Error:
self.log_exception("Unexpected trouble unlocking in unlock_completely(): ")
raise
def transaction(self, data, count=None, lock_timeout=0):
"""err, reason, result=transaction(data, [, count] [,lock_timeout]) sends data and waits for a response.
It is guaranteed to leave the lock level at its original value on exit,
unless KeyboardInterrupt breaks the normal flow. If count isn't provided, there is no limit to how much data will be accepted.
See do_timeouts() for semantics on lock_timeout."""
self.lock(lock_timeout)
reason=None
result=None
try:
err, write_count = self.write(data)
if not err:
err, reason, result = self.read(count=count)
finally:
self.unlock()
return err, reason, result
def check_idn(self):
'check_idn() executes "*idn?" and aborts if the result does not start with self.idn_head'
if hasattr(self,"idn"):
return #already done
if hasattr(self,"idn_head") and self.idn_head is not None:
self.lock()
try:
self.clear()
err, reason, idn = self.transaction("*idn?")
finally:
self.unlock()
check=idn.find(self.idn_head)
self.idn=idn.strip() #save for future reference info
if check:
self.disconnect()
assert check==0, "Wrong device type! expecting: "+self.idn_head+"... got: "+self.idn
else:
self.idn="Device *idn? not checked!"
import copy
class device_thread:
Thread=threading.Thread #by default, use canonical threads
def __init__(self, connection, main_sleep=1.0, name="Device"):
self.running=0
self.main_sleep=main_sleep
self.__thread=None
self.__name=copy.copy(name) #make a new copy to avoid a possible circular reference
self.__wait_event=threading.Event()
self.set_connection(connection)
def set_connection(self, connection):
#keep only a weak reference, so the thread cannot prevent the device from being deleted
#such deletion creates an error when the thread tries to run, but that's OK
#this allows the device_thread to be used as a clean mix-in class to a vxi_11 connection
self.__weak_connection=weakref.ref(connection)
def connection(self):
return self.__weak_connection() #dereference weak reference
def handle_lock_error(self):
"handle_lock_error can be overridden to count failures and do something if there are too many"
self.connection().log_exception(self.name+": Error while locking device")
def onepass(self):
connection=self.connection()
try:
connection.lock()
except VXI_11_Transient_Error:
self.handle_lock_error()
return
try:
self.get_data()
except:
connection.log_traceback('Uncaught exception in get_data()')
try:
connection.clear()
except:
connection.log_exception('failed to clear connection after error')
self.run=0
connection.unlock()
def monitor(self):
self.connection().log_info("Monitor loop entered")
while(self.run):
try:
self.onepass()
self.__wait_event.wait(self.main_sleep) #wait until timeout or we are cancelled
except KeyboardInterrupt:
self.connection().log_error("Keyboard Interrupt... terminating")
self.run=0
except:
self.connection().log_traceback()
self.run=0
self.running=0
self.connection().unlock_completely()
def run_thread(self):
if not self.running: #if it's already running, just keep it up.
self.run=1
self.__thread=self.Thread(target=self.monitor, name=self.__name)
self.__wait_event.clear() #make sure we don't fall through immediately
self.__thread.start()
self.running=1
def get_monitor_thread(self):
return self.__thread
def stop_thread(self):
if self.running:
self.run=0
self.__wait_event.set() #cancel any waiting
<file_sep>#!/usr/bin/env python
"""
Control panel for variable laser attenuator
<NAME>, APS, 8 Jun 2009 - 16 Nov 2014
"""
__version__ = "1.1"
import wx
from LaserAttenuatorPanel import LaserAttenuatorPanel
from id14 import trans1
wx.app = wx.App(redirect=False) # Needed to initialize WX library
panel = LaserAttenuatorPanel(trans1,title="Laser Attenuator [in Laser Lab]")
wx.app.MainLoop()
<file_sep>#!/usr/bin/env python
"""Controls when data collection is suspended, in case the X-ray beam is
down
Author: <NAME>, <NAME>
Date created: 2017-11-13
Date modified: 2019-06-01
"""
__version__ = "1.2.1" # newline at last line
from logging import debug,info,warn,error
import traceback
from servers import servers
import wx, wx3_compatibility
from EditableControls import TextCtrl,ComboBox
class ServersPanel(wx.Frame):
name = "ServersPanel"
from setting import setting
from collections import OrderedDict as odict
AllView = range(0,20)
CustomView = setting("CustomView",range(0,20))
views = odict([("All","AllView"),("Custom","CustomView")])
view = setting("view","All")
attributes = "Nrunning",
refresh_period = 10.0 # s
def __init__(self,parent=None,title="IOCs & Servers"):
wx.Frame.__init__(self,parent=parent,title=title)
from Icon import SetIcon
SetIcon(self,"Server")
# Controls
self.panel = wx.Panel(self)
self.controls = []
# Menus
menuBar = wx.MenuBar()
self.ViewMenu = wx.Menu()
for i in range(0,len(self.views)):
self.ViewMenu.AppendCheckItem(10+i,self.views.keys()[i])
self.ViewMenu.AppendSeparator()
menuBar.Append (self.ViewMenu,"&View")
self.SetupMenu = wx.Menu()
self.SetupMenu.AppendCheckItem(200,"Setup")
self.SetupMenu.AppendSeparator()
self.SetupMenu.Append(201,"Add Line")
self.SetupMenu.Append(202,"Remove Line")
menuBar.Append(self.SetupMenu,"&More")
menu = wx.Menu()
menu.Append(wx.ID_ABOUT,"About...")
menuBar.Append(menu,"&Help")
self.SetMenuBar(menuBar)
# Callbacks
self.Bind(wx.EVT_MENU_OPEN,self.OnOpenView)
for i in range(0,len(self.views)):
self.Bind(wx.EVT_MENU,self.OnSelectView,id=10+i)
self.Bind(wx.EVT_MENU,self.OnSetup,id=200)
self.Bind(wx.EVT_MENU,self.OnAdd,id=201)
self.Bind(wx.EVT_MENU,self.OnRemove,id=202)
self.Bind(wx.EVT_MENU,self.OnAbout,id=wx.ID_ABOUT)
self.Bind(wx.EVT_CLOSE,self.OnClose)
# Layout
self.sizer = wx.BoxSizer(wx.VERTICAL)
self.panel.SetSizer(self.sizer)
self.update_controls()
self.Show()
# Refresh
from numpy import nan
self.values = {}
self.old_values = {}
self.Bind(wx.EVT_TIMER,self.OnUpdate)
from threading import Thread
self.thread = Thread(target=self.keep_updated,name=self.name)
self.thread.daemon = True
self.thread.start()
def keep_updated(self):
"""Periodically refresh the displayed settings."""
from time import time,sleep
while True:
try:
t0 = time()
while time() < t0+self.refresh_period: sleep(0.5)
if self.Shown:
self.update_data()
if self.data_changed:
event = wx.PyCommandEvent(wx.EVT_TIMER.typeId,self.Id)
# call OnUpdate in GUI thread
wx.PostEvent(self.EventHandler,event)
except wx.PyDeadObjectError: break
def refresh(self):
"""Force update"""
from threading import Thread
self.thread = Thread(target=self.refresh_background,name=self.name+".refresh")
self.thread.daemon = True
self.thread.start()
def refresh_background(self):
"""Force update"""
self.update_data()
if self.data_changed:
event = wx.PyCommandEvent(wx.EVT_TIMER.typeId,self.Id)
wx.PostEvent(self.EventHandler,event) # call OnUpdate in GUI thread
def update_data(self):
"""Retreive status information"""
self.old_values = dict(self.values) # make a copy
for n in self.attributes:
try: self.values[n] = getattr(servers,n)
except Exception,msg: error("%s\n%s" % (msg,traceback.format_exc()))
@property
def data_changed(self):
"""Did the last 'update_data' change the data to be plotted?"""
changed = (self.values != self.old_values)
return changed
def OnUpdate(self,event):
"""Periodically refresh the displayed settings."""
self.refresh_status()
def refresh_status(self,event=None):
"""Update title to show whether all checks passed"""
if "Nrunning" in self.values:
text = "%r of %r running locally" % (self.values["Nrunning"],servers.N)
self.Title = self.Title.split(":")[0]+": %s" % text
def update_controls(self):
if len(self.controls) != servers.N:
for control in self.controls: control.Destroy()
##self.sizer.DeleteWindows() # not compatible with wx 4.0
self.controls = []
for i in range(servers.N):
self.controls += [ServerControl(self.panel,i)]
for i in range(0,len(self.controls)):
self.sizer.Add(self.controls[i],flag=wx.ALL|wx.EXPAND,proportion=1)
setup = self.SetupMenu.IsChecked(200)
for control in self.controls: control.setup = setup
self.panel.Sizer.Fit(self)
if not self.view in self.views: self.view = self.views.keys()[0]
self.View = getattr(self,self.views[self.view])
def get_View(self):
"""Which control to show? List of 0-based integers"""
view = [i for (i,c) in enumerate(self.controls) if c.Shown]
return view
def set_View(self,value):
currently_shown = [c.Shown for c in self.controls]
shown = [False]*len(self.controls)
for i in value:
if i < len(shown): shown[i] = True
if shown != currently_shown:
for i in range(0,len(self.controls)):
self.controls[i].Shown = shown[i]
self.panel.Sizer.Fit(self)
View = property(get_View,set_View)
def OnOpenView(self,event):
"""Called if the "View" menu is selected"""
for i in range(0,len(self.views)):
self.ViewMenu.Check(10+i,self.views.keys()[i] == self.view)
for i in range(0,len(self.controls)):
try: self.ViewMenu.Remove(100+i)
except Exception,msg: warn("ViewMenu.Remove(%d): %s" % (100+i,msg))
title = self.controls[i].Title
if title == "": title = "Untitled %d" % (i+1)
ID = 100+i
self.ViewMenu.AppendCheckItem(ID,title)
self.ViewMenu.Check(ID,self.controls[i].Shown)
self.ViewMenu.Enable(ID,self.view != "All")
self.Bind(wx.EVT_MENU,self.OnView,id=100+i)
def OnSelectView(self,event):
"""Called if the view is toogled between 'All' and 'Custome'
from the 'View ' menu."""
n = event.Id-10
self.view = self.views.keys()[n]
self.View = getattr(self,self.views.values()[n])
def OnView(self,event):
"""Called if one of the items of the "View" menu is checked or
unchecked."""
n = event.Id-100
self.controls[n].Shown = event.IsChecked()
self.panel.Sizer.Fit(self)
setattr(self,self.views[self.view],self.View) # save modified view
def OnSetup(self,event):
"""Enable 'setup' mode, allowing the panel to be configured"""
setup = self.SetupMenu.IsChecked(200)
for control in self.controls: control.setup = setup
self.panel.Sizer.Fit(self)
def OnAdd(self,event):
servers.N += 1
self.update_controls()
def OnRemove(self,event):
if servers.N > 0: servers.N -= 1
self.update_controls()
def OnAbout(self,event):
"""Show panel with additional parameters"""
from os.path import basename
from inspect import getfile
from os.path import getmtime
from datetime import datetime
filename = getfile(lambda x: None)
info = basename(filename)+" "+__version__
import servers as module
filename = getfile(module)
if hasattr(module,"__source_timestamp__"):
timestamp = module.__source_timestamp__
filename = filename.replace(".pyc",".py")
else: timestamp = getmtime(getfile(module))
info += "\n"+basename(filename)+" "+module.__version__
info += " ("+str(datetime.fromtimestamp(timestamp))+")"
info += "\nwx "+wx.__version__
info += "\n\n"+__doc__
dlg = wx.MessageDialog(self,info,"About",wx.OK|wx.ICON_INFORMATION)
dlg.CenterOnParent()
dlg.ShowModal()
dlg.Destroy()
def OnClose(self,event):
"""Called when the windows's close button is clicked"""
self.Destroy()
class ServerControl(wx.Panel):
name = "ServersControl"
attributes = "label","running","OK","test_code_OK","formatted_value",
refresh_period = 1.0
def __init__(self,parent,n,shown=False):
self.values = {
"label":"",
"running":False,
"formatted_value":"",
"OK":True,
"test_code_OK":False
}
self.old_values = {}
wx.Panel.__init__(self,parent)
self.Shown = shown
self.Title = "Test %d" % n
self.n = n
self.myEnabled = wx.CheckBox(self,size=(470,-1))
from wx.lib.buttons import GenButton
self.State = GenButton(self,size=(25,20))
self.Setup = wx.Button(self,size=(60,-1),label="More...")
self.Setup.Shown = False
self.Log = wx.Button(self,size=(50,-1),label="Log...")
self.Bind(wx.EVT_CHECKBOX,self.OnEnable,self.myEnabled)
self.Bind(wx.EVT_BUTTON,self.OnState,self.State)
self.Bind(wx.EVT_BUTTON,self.OnSetup,self.Setup)
self.Bind(wx.EVT_BUTTON,self.OnLog,self.Log)
# Layout
self.layout = wx.BoxSizer(wx.HORIZONTAL)
flag = wx.ALL|wx.ALIGN_CENTER_VERTICAL|wx.EXPAND
self.layout.Add(self.myEnabled,flag=flag,proportion=1)
self.layout.Add(self.State,flag=flag)
self.layout.Add(self.Setup,flag=flag)
self.layout.Add(self.Log,flag=flag)
# Leave a 10 pixel wide border.
self.box = wx.BoxSizer(wx.VERTICAL)
self.box.Add(self.layout,flag=wx.ALL,border=5)
self.SetSizer(self.box)
self.Fit()
self.refresh_label()
# Periodically refresh the displayed settings.
self.Bind(wx.EVT_TIMER,self.OnUpdate)
from threading import Thread
self.thread = Thread(target=self.keep_updated,name=self.name)
self.thread.daemon = True
self.thread.start()
@property
def server(self): return servers[self.n]
def keep_updated(self):
"""Periodically refresh the displayed settings."""
from time import time,sleep
while True:
try:
t0 = time()
if self.Shown:
##debug("ServerControl %s: Shown: %r" % (self.n,self.Shown))
self.update_data()
if self.data_changed:
event = wx.PyCommandEvent(wx.EVT_TIMER.typeId,self.Id)
# call OnUpdate in GUI thread
wx.PostEvent(self.EventHandler,event)
while time() < t0+self.refresh_period: sleep(0.5)
except wx.PyDeadObjectError: break
def OnUpdate(self,event):
"""Periodically refresh the displayed settings."""
self.refresh_status()
def refresh(self):
"""Force update"""
from threading import Thread
self.thread = Thread(target=self.refresh_background,
name=self.name+".refresh")
self.thread.daemon = True
self.thread.start()
def refresh_background(self):
"""Force update"""
self.update_data()
if self.data_changed:
event = wx.PyCommandEvent(wx.EVT_TIMER.typeId,self.Id)
wx.PostEvent(self.EventHandler,event) # call OnUpdate in GUI thread
def update_data(self):
"""Retreive status information"""
self.old_values = dict(self.values) # make a copy
for n in self.attributes:
try: self.values[n] = getattr(self.server,n)
except Exception,msg: error("%s\n%s" % (msg,traceback.format_exc()))
@property
def data_changed(self):
"""Did the last 'update_data' change the data to be plotted?"""
changed = (self.values != self.old_values)
return changed
def refresh_label(self,event=None):
"""Update the controls with current values"""
self.Title = self.server.label
self.myEnabled.Value = self.server.enabled
self.myEnabled.Label = self.server.label
def refresh_status(self,event=None):
"""Update the controls with current values"""
label = self.values["label"]
running = self.values["running"]
self.Title = label
self.myEnabled.Value = running
red = (255,0,0)
green = (0,255,0)
gray = (180,180,180)
self.myEnabled.Label = "%s: %s" % (label,self.values["formatted_value"])
color = green if self.values["OK"] else red
if not self.values["test_code_OK"]: color = gray
self.State.BackgroundColour = color
self.State.ForegroundColour = color
self.State.Refresh() # work-around for a GenButton bug in Windows
def OnEnable(self,event):
value = event.IsChecked()
try: self.server.running = value
except Exception,msg: error("%r\n%r" % (msg,traceback.format_exc()))
self.refresh()
def get_setup(self):
"""'Setup' mode enabled? (Allows reconfiguring parameters)"""
value = self.Setup.Shown
return value
def set_setup(self,value):
self.Setup.Shown = value
self.Layout()
self.Fit()
setup = property(get_setup,set_setup)
def OnState(self,event):
"""Start/Stop server"""
try: self.server.running = not self.server.running
except Exception,msg: error("%r\n%r" % (msg,traceback.format_exc()))
self.refresh()
def OnSetup(self,event):
"""Bring up configuration panel"""
dlg = SetupPanel(self,self.n)
dlg.CenterOnParent()
dlg.Show()
def OnLog(self,event):
"""Bring up configuration panel"""
dlg = LogPanel(self,self.n)
dlg.CenterOnParent()
dlg.Show()
class SetupPanel(wx.Frame):
def __init__(self,parent,n):
self.n = n
wx.Frame.__init__(self,parent=parent,title="Setup")
from Icon import SetIcon
SetIcon(self,"Server")
self.panel = wx.Panel(self)
# Controls
style = wx.TE_PROCESS_ENTER
self.myLabel = TextCtrl(self.panel,size=(320,-1),style=style)
self.Command = TextCtrl(self.panel,size=(320,-1),style=style)
self.LogfileBasename = TextCtrl(self.panel,size=(320,-1),style=style)
self.Value = TextCtrl(self.panel,size=(320,-1),style=style)
self.Format = TextCtrl(self.panel,size=(320,-1),style=style)
self.Test = TextCtrl(self.panel,size=(320,-1),style=style)
# Callbacks
self.Bind(wx.EVT_TEXT_ENTER,self.OnLabel,self.myLabel)
self.Bind(wx.EVT_TEXT_ENTER,self.OnCommand,self.Command)
self.Bind(wx.EVT_TEXT_ENTER,self.OnLogfileBasename,self.LogfileBasename)
self.Bind(wx.EVT_TEXT_ENTER,self.OnValue,self.Value)
self.Bind(wx.EVT_TEXT_ENTER,self.OnFormat,self.Format)
self.Bind(wx.EVT_TEXT_ENTER,self.OnTest,self.Test)
self.Bind(wx.EVT_SIZE,self.OnResize)
# Layout
self.layout = wx.BoxSizer()
grid = wx.FlexGridSizer(cols=2,hgap=5,vgap=5)
flag = wx.ALIGN_CENTER_VERTICAL|wx.ALL|wx.EXPAND
label = "Name:"
grid.Add(wx.StaticText(self.panel,label=label),flag=flag)
grid.Add(self.myLabel,flag=flag,proportion=1)
label = "Command:"
grid.Add(wx.StaticText(self.panel,label=label),flag=flag)
grid.Add(self.Command,flag=flag,proportion=1)
label = "Logfile basename:"
grid.Add(wx.StaticText(self.panel,label=label),flag=flag)
grid.Add(self.LogfileBasename,flag=flag,proportion=1)
label = "Value:"
grid.Add(wx.StaticText(self.panel,label=label),flag=flag)
grid.Add(self.Value,flag=flag,proportion=1)
label = "Format:"
grid.Add(wx.StaticText(self.panel,label=label),flag=flag)
grid.Add(self.Format,flag=flag,proportion=1)
label = "Test:"
grid.Add(wx.StaticText(self.panel,label=label),flag=flag)
grid.Add(self.Test,flag=flag,proportion=1)
# Leave a 10-pixel wide space around the panel.
self.layout.Add(grid,flag=wx.EXPAND|wx.ALL,proportion=1,border=10)
self.panel.SetSizer(self.layout)
self.panel.Fit()
self.Fit()
# Intialization
self.refresh()
@property
def server(self): return servers[self.n]
def refresh(self,Event=0):
self.myLabel.Value = self.server.label
self.Command.Value = self.server.command
self.LogfileBasename.Value = self.server.logfile_basename
self.Value.Value = self.server.value_code
self.Format.Value = self.server.format_code
self.Test.Value = self.server.test_code
def OnLabel(self,event):
self.server.label = self.myLabel.Value
self.refresh()
def OnCommand(self,event):
self.server.command = self.Command.Value
self.refresh()
def OnLogfileBasename(self,event):
self.server.logfile_basename = self.LogfileBasename.Value
self.refresh()
def OnValue(self,event):
self.server.value_code = self.Value.Value
self.refresh()
def OnFormat(self,event):
self.server.format_code = self.Format.Value
self.refresh()
def OnTest(self,event):
self.server.test_code = self.Test.Value
self.refresh()
def OnResize(self,event):
"""Rearange contents to fit best into new size"""
self.panel.Fit()
event.Skip()
class LogPanel(wx.Frame):
name = "LogPanel"
attributes = "log","label"
refresh_period = 1.0
levels = ["DEBUG","INFO","WARNING","ERROR"]
from persistent_property import persistent_property
level = persistent_property("level","DEBUG")
def __init__(self,parent,n):
self.n = n
wx.Frame.__init__(self,parent=parent,title="Log",size=(640,240))
from Icon import SetIcon
SetIcon(self,"Server")
self.panel = wx.Panel(self)
# Controls
from EditableControls import TextCtrl,ComboBox
style = wx.TE_PROCESS_ENTER|wx.TE_MULTILINE|wx.TE_DONTWRAP
self.Log = TextCtrl(self.panel,size=(-1,-1),style=style)
self.Log.Font = wx.Font(pointSize=10,family=wx.TELETYPE,style=wx.NORMAL,
weight=wx.NORMAL)
self.Clear = wx.Button(self.panel,size=(-1,-1),label="Clear Log")
self.Level = ComboBox(self.panel,size=(-1,-1),choices=self.levels)
# Callbacks
self.Bind(wx.EVT_TEXT_ENTER,self.OnLog,self.Log)
self.Bind(wx.EVT_BUTTON,self.OnClear,self.Clear)
self.Bind(wx.EVT_COMBOBOX,self.OnLevel,self.Level)
self.Bind(wx.EVT_TEXT_ENTER,self.OnLevel,self.Level)
# Layout
self.layout = wx.BoxSizer(wx.VERTICAL)
self.layout.Add(self.Log,flag=wx.ALL|wx.EXPAND,proportion=1,border=2)
self.controls = wx.BoxSizer(wx.HORIZONTAL)
self.layout.Add(self.controls,flag=wx.ALL|wx.EXPAND,proportion=0,border=2)
self.controls.Add(self.Clear,flag=wx.ALL|wx.EXPAND,proportion=0,border=2)
self.controls.Add(self.Level,flag=wx.ALL|wx.EXPAND,proportion=0,border=2)
self.panel.SetSizer(self.layout)
self.Layout()
# Periodically refresh the displayed settings.
self.values = {}
self.Bind(wx.EVT_TIMER,self.OnUpdate)
from threading import Thread
self.thread = Thread(target=self.keep_updated,name=self.name)
self.thread.daemon = True
self.thread.start()
def keep_updated(self):
"""Periodically refresh the displayed settings."""
from time import time,sleep
while True:
try:
t0 = time()
if self.Shown:
self.update_data()
if self.data_changed:
event = wx.PyCommandEvent(wx.EVT_TIMER.typeId,self.Id)
# call OnUpdate in GUI thread
wx.PostEvent(self.EventHandler,event)
while time() < t0+self.refresh_period: sleep(0.5)
except wx.PyDeadObjectError: break
def OnUpdate(self,event):
"""Periodically refresh the displayed settings."""
self.refresh_status()
def refresh(self):
"""Force update"""
from threading import Thread
self.thread = Thread(target=self.refresh_background,
name=self.name+".refresh")
self.thread.daemon = True
self.thread.start()
def refresh_background(self):
"""Force update"""
self.update_data()
if self.data_changed:
event = wx.PyCommandEvent(wx.EVT_TIMER.typeId,self.Id)
wx.PostEvent(self.EventHandler,event) # call OnUpdate in GUI thread
def update_data(self):
"""Retreive status information"""
self.old_values = dict(self.values) # make a copy
for n in self.attributes:
try: self.values[n] = getattr(self.server,n)
except Exception,msg: error("%s\n%s" % (msg,traceback.format_exc()))
@property
def data_changed(self):
"""Did the last 'update_data' change the data to be plotted?"""
changed = (self.values != self.old_values)
return changed
@property
def server(self): return servers[self.n]
def refresh_status(self):
if "label" in self.values:
self.Title = "Log: "+self.values["label"]
if "log" in self.values:
text = self.values["log"]
text = self.filter(text)
text = last_lines(text)
self.Log.Value = text
# Scroll to the end
self.Log.ShowPosition(self.Log.LastPosition)
self.Level.StringSelection = self.level
def OnLog(self,event):
self.server.log = self.Log.Value
self.refresh()
def OnClear(self,event):
self.server.log = ""
self.refresh()
def OnLevel(self,event):
self.level = self.Level.StringSelection
self.refresh_status()
def filter(self,text):
words_to_filter = []
if self.level in self.levels:
i = self.levels.index(self.level)
words_to_filter = self.levels[0:i]
debug("level: %r, filtering %r" % (self.level,words_to_filter))
if words_to_filter:
lines = text.splitlines()
for word in words_to_filter:
lines = [line for line in lines if not word in line]
text = "\n".join(lines)+"\n"
return text
def last_lines(text,max_line_count=1000):
line_count = text.count("\n")
if line_count > max_line_count:
text = text[-160*max_line_count:]
lines = text.splitlines()
lines = lines[-max_line_count-2:][1:]
text = "\n".join(lines)+"\n"
debug("Reduced line count from from %r to %r" % (line_count,text.count("\n")))
return text
if __name__ == '__main__':
from pdb import pm
import autoreload
import logging
from tempfile import gettempdir
logging.basicConfig(level=logging.DEBUG,format="%(asctime)s: %(message)s",
filename=gettempdir()+"/ServersPanel.log")
# Needed to initialize WX library
if not "app" in globals(): app = wx.App(redirect=False)
window = ServersPanel()
app.MainLoop()
<file_sep>filename = '//mx340hs/data/anfinrud_1903/Archive/NIH.pressure_downstream.txt'<file_sep>#!/usr/bin/env python
"""Control panel to save and motor positions.
<NAME> 13 Dec 2010 - 6 Jul 2017"""
__version__ = "1.3.7" # fixed settings lost bug
import wx
from EditableControls import TextCtrl
from numpy import ndarray,isnan
from DB import dbput,dbget
# Turn off IEEE-754 warnings in numpy 1.6+ ("invalid value encountered in...")
import numpy; numpy.seterr(invalid="ignore",divide="ignore")
class SavedPositionsPanel (wx.Frame):
"""Control panel to save and recall goniometer X,Y,Z and Phi settings."""
def __init__(self,parent=None,
title="Goniometer Saved Positions",
name = "goniometer_saved",
motors = [],
motor_names = [],
formats = [],
nrows = 8):
"""
name: basename of settings file
"""
wx.Frame.__init__(self,parent=parent,title=title)
self.name = name
self.motors = motors
self.motor_names = motor_names
self.formats = formats
for i in range(len(self.motor_names),len(self.motors)):
self.motor_names += [self.motors[i].name]
while len(self.formats) < len(self.motors): self.formats += ["%+6.3f"]
panel = wx.Panel(self)
# Leave a 5 pixel wide border.
border_box = wx.BoxSizer(wx.VERTICAL)
# Controls
# Labels
flag = wx.ALIGN_CENTRE_VERTICAL|wx.ALL
grid = wx.GridBagSizer(1,1)
labels = ["","Description","Updated"]
for i in range(len(self.motors)):
labels += ["%s\n[%s]" % (self.motor_names[i],self.motors[i].unit)]
self.Labels = ndarray(len(labels),object)
for i in range(0,len(labels)):
self.Labels[i] = wx.StaticText(panel,label=labels[i],style=wx.ALIGN_CENTRE)
grid.Add(self.Labels[i],(0,i),flag=flag)
# Settings
style = wx.TE_PROCESS_ENTER
self.Descriptions = ndarray(nrows,object)
for i in range(0,nrows):
self.Descriptions[i] = TextCtrl(panel,size=(200,-1),style=style)
grid.Add(self.Descriptions[i],(i+1,1),flag=flag)
self.NormalBackgroundColour = self.Descriptions[0].BackgroundColour
self.Dates = ndarray(nrows,object)
for i in range(0,nrows):
self.Dates[i] = TextCtrl(panel,size=(100,-1),style=style)
grid.Add(self.Dates[i],(i+1,2),flag=flag)
self.Positions = ndarray((nrows,len(self.motors)),object)
for i in range(0,nrows):
for j in range(0,len(self.motors)):
width = max(75,self.Labels[j+3].GetSize()[0]+5)
self.Positions[i,j] = TextCtrl(panel,size=(width,-1),style=style)
grid.Add(self.Positions[i,j],(i+1,j+3),flag=flag)
# Current positions
label = wx.StaticText(panel)
grid.Add(label,(nrows+1,1),flag=flag)
label.Label = "Current value:"
# 'Go To' Buttons
height = self.Descriptions[0].GetSize()[1]
for i in range(0,nrows):
button = wx.Button(panel,label="Go To",size=(60,height),id=i)
grid.Add(button,(i+1,0),flag=flag)
self.Bind(wx.EVT_BUTTON,self.goto_setting,button)
# 'Set' Buttons
height = self.Descriptions[0].GetSize()[1]
for i in range(0,nrows):
button = wx.Button(panel,label="Set",size=(45,height),id=100+i)
grid.Add(button,(i+1,len(self.motors)+3),flag=flag)
self.Bind(wx.EVT_BUTTON,self.define_setting,button)
self.Current = ndarray(len(motors),object)
for i in range(0,len(self.motors)):
self.Current[i] = wx.StaticText(panel)
grid.Add(self.Current[i],(nrows+1,i+3),flag=flag)
border_box.Add (grid,flag=wx.ALL,border=5)
button = wx.Button(panel,label="Stop")
self.Bind(wx.EVT_BUTTON,self.stop,button)
border_box.Add (button,flag=wx.ALL|wx.ALIGN_CENTRE_HORIZONTAL,border=5)
panel.SetSizer(border_box)
panel.Fit()
self.Fit()
self.Show()
self.update_settings()
# Make sure "on_input" is called only after "update_settings".
# Call the "on_input" routine whenever the user presses Enter.
self.Bind (wx.EVT_TEXT_ENTER,self.on_input)
# Call the "on_input" routine whenever the user navigates between
# fields, using Enter, Tab or the mouse
self.Bind (wx.EVT_CHILD_FOCUS,self.on_child_focus)
# Periodically update the displayed fields.
self.timer = wx.Timer(self)
self.Bind (wx.EVT_TIMER,self.OnTimer)
self.timer.Start(1000,oneShot=True)
def OnTimer(self,event=None):
"Called periodically every second triggered by a timer"
self.update_settings()
self.update()
self.timer.Start(1000,oneShot=True) # Need to restart the Timer
def on_input(self, event):
"""This is called when the use switches between feilds and controls
using Tab or the mouse, or presses Enter in a text entry. This does
necessarily indicate that any value was changed. But it is a good
opportunity the process any changes."""
self.save_settings()
def on_child_focus(self,event):
"""Called whenever the user navigates between fields, using Enter,
Tab or the mouse.
This routine simply calls 'on_input' and the passes the event on to the
default handler. I did not bind the CHILD_FOCUS to 'on_input' directly
because the other events 'on_input' handles (TEXT_ENTER,COMBOBOX)
must not be passed on to a default event handler."""
self.on_input(event)
# The default event handler needs to receive the event too, otherwise
# the focus would not change.
event.Skip()
def update(self):
"""Update motor positions"""
from numpy import zeros,array,average,sqrt,nanargmin
for i in range(0,len(self.motors)):
position = self.motors[i].value
self.Current[i].Label = tostr(self.motors[i].value,self.formats[i])
# Highlight the current settings
nrows = self.Descriptions.shape[0]
values = zeros((nrows,len(self.motors)))
for i in range(0,nrows):
for j in range(0,len(self.motors)):
values[i,j] = tofloat(self.Positions[i,j].Value)
positions = array([motor.value for motor in self.motors])
tolerance = array([getattr(motor,"readback_slop",0)
for motor in self.motors])
# Find the row that matches the actual settings
matches = zeros(nrows,bool)
for i in range(0,nrows):
matches[i] = all(abs(values[i,:] - positions) < tolerance)
# Find the row the is closest to the actual settings
dist = zeros(nrows)
for i in range(0,nrows):
dist[i] = sqrt(average((values[i,:] - positions)**2))
try: closest = nanargmin(dist)
except ValueError: closest = 0
##print "closest",closest
# Update the colors
for i in range(0,nrows):
if matches[i]: color = wx.Colour(150,150,255)
elif i == closest: color = wx.Colour(200,200,255)
else: color = self.NormalBackgroundColour
self.Descriptions[i].BackgroundColour = color
self.Dates[i].BackgroundColour = color
for j in range(0,len(self.motors)):
self.Positions[i,j].BackgroundColour = color
def update_settings(self):
"""Reload saved settings from the settings file"""
nrows = self.Descriptions.shape[0]
for i in range(0,nrows):
text = dbget("%s.line%d.description" % (self.name,i))
self.Descriptions[i].Value = text
text = dbget("%s.line%d.updated" % (self.name,i))
self.Dates[i].Value = text
for j in range(0,len(self.motors)):
value = dbget("%s.line%d.%s" % (self.name,i,self.motor_names[j]))
self.Positions[i,j].Value = value
def save_settings(self):
nrows = self.Descriptions.shape[0]
for i in range(0,nrows):
text = self.Descriptions[i].Value
dbput("%s.line%d.description" % (self.name,i),text)
text = self.Dates[i].Value
dbput("%s.line%d.updated" % (self.name,i),text)
for j in range(0,len(self.motors)):
value = self.Positions[i,j].Value
resname = "%s.line%d.%s" % (self.name,i,self.motor_names[j])
dbput(resname,value)
def goto_setting(self,event):
"""Moved the motor to the settings in the row of the 'Go To'
button that was pressed pressed."""
i = event.GetId() # Row number of "Go To" button pressed
for j in range(0,len(self.motors)):
try:
value = float(self.Positions[i,j].Value)
##print "%s.value = %r" % (self.motor_names[j],value)
self.motors[j].value = value
except ValueError: pass
def define_setting(self,event):
"""Copy the current motor settings in the row of the 'Set" button
that was pressed."""
i = event.GetId()-100 # Row number of "Set" button pressed
for j in range(0,len(self.motors)):
value = tostr(self.motors[j].command_value,self.formats[j])
self.Positions[i,j].Value = value
from time import strftime
date = strftime("%d %b %H:%M")
self.Dates[i].Value = date
self.save_settings()
def stop(self,event):
"""To cancel any move should one hit the wrong button by mistake"""
for j in range(0,len(self.motors)): self.motors[j].stop()
def tostr(x,format="%g"):
"""Converts a number to a string.
This is needed to handle "not a number" and infinity properly.
Under Windows, 'str()','repr()' and '%' format 'nan' as '-1.#IND' and 'inf'
as '1.#INF', which is inconsistent with Linux ('inf' and 'nan').
"""
from numpy import isnan,isinf
try:
if isnan(x): return "nan"
if isinf(x) and x>0: return "inf"
if isinf(x) and x<0: return "-inf"
return format % x
except TypeError: return str(x)
def tofloat(s):
"""Convert string to float and return 'not a number' in case of """
from numpy import nan
try: return float(s)
except Exception: return nan
if __name__ == '__main__':
from id14 import SampleX,SampleY,SampleZ,SamplePhi
# Needed to initialize WX library
if not hasattr(wx,"app"): wx.app = wx.App(redirect=False)
panel = SavedPositionsPanel(
title="Goniometer Saved Positions",
name="goniometer_saved",
motors=[SampleX,SampleY,SampleZ,SamplePhi],
motor_names=["SampleX","SampleY","SampleZ","SamplePhi"],
formats = ["%+6.3f","%+6.3f","%+6.3f","%+8.3f"],
nrows=8)
wx.app.MainLoop()
<file_sep>Size = (702, 629)
Position = (141, 30)
ScaleFactor = 0.5
ZoomLevel = 1.0
Orientation = 0
Mirror = True
NominalPixelSize = 0.000526
filename = '/usr/local/DurbinPix/surface4.jpg'
ImageWindow.Center = (680.0, 512.0)
ImageWindow.ViewportCenter = (0.35768, 0.269312)
ImageWindow.crosshair_color = (0, 255, 0)
ImageWindow.boxsize = (0.03, 0.03)
ImageWindow.box_color = (0, 0, 255)
ImageWindow.show_box = False
ImageWindow.Scale = [[-0.008416, 0.023143999999999998], [0.014728, 0.069432]]
ImageWindow.show_scale = False
ImageWindow.scale_color = (255, 0, 0)
ImageWindow.crosshair_size = (0.03, 0.03)
ImageWindow.show_crosshair = True
ImageWindow.show_profile = True
ImageWindow.show_FWHM = True
ImageWindow.show_center = False
ImageWindow.calculate_section = False
ImageWindow.profile_color = wx.Colour(255, 0, 255, 255)
ImageWindow.FWHM_color = (255, 255, 0)
ImageWindow.center_color = wx.Colour(0, 0, 255, 255)
ImageWindow.ROI = [[-0.127292, 0.100992], [0.118876, -0.088368]]
ImageWindow.ROI_color = wx.Colour(255, 255, 0, 255)
ImageWindow.show_saturated_pixels = False
ImageWindow.mask_bad_pixels = False
ImageWindow.saturation_threshold = 233
ImageWindow.saturated_color = (255, 0, 0)
ImageWindow.linearity_correction = False
ImageWindow.bad_pixel_threshold = 233
ImageWindow.bad_pixel_color = (0, 0, 0)
ImageWindow.show_grid = False
ImageWindow.grid_type = u'y'
ImageWindow.grid_color = (82, 82, 82)
ImageWindow.grid_x_spacing = 0.055
ImageWindow.grid_x_offset = 0.020543749999997925
ImageWindow.grid_y_spacing = 0.05
ImageWindow.grid_y_offset = 0.0
camera.use_multicast = True
camera.IP_addr = u'id14b-prosilica1.cars.aps.anl.gov'
show_alignment_controls = True
show_edge_controls = False
stepsize = 0.005
camera_angle = -30.0
x_scale = -1
y_scale = 1
z_scale = -1.0
phi_stepsize = 90.0
auto_rotate = False
<file_sep>#!/usr/bin/env python
"""
Grapical User Interface for FPGA Timing System.
Author: <NAME>
Date created: 2018-12-04
Date last modified: 2019-03-26
"""
__version__ = "1.3" # using timing_system.prefixes for choices
from logging import debug,info,warn,error
import wx
class Timing_Setup_Panel(wx.Frame):
title = "Timing System Setup"
icon = "timing-system"
def __init__(self,parent=None,name="TimingPanel"):
wx.Frame.__init__(self,parent=parent,title=self.title)
self.name = name
panel = wx.Panel(self)
from Icon import SetIcon
SetIcon(self,self.icon)
# Controls
from EditableControls import ComboBox
style = wx.TE_PROCESS_ENTER
width = 160
self.Prefix = ComboBox(panel,style=style,size=(width,-1))
self.Address = wx.TextCtrl(panel,style=wx.TE_READONLY,size=(width,-1))
self.Address.Enabled = False
# Callbacks
self.Bind (wx.EVT_TEXT_ENTER,self.OnEnterPrefix,self.Prefix)
self.Bind (wx.EVT_COMBOBOX ,self.OnEnterPrefix,self.Prefix)
self.Bind (wx.EVT_CLOSE ,self.OnClose)
# Layout
layout = wx.GridBagSizer(1,1)
a = wx.ALIGN_CENTRE_VERTICAL
e = wx.EXPAND
row = 0
label = wx.StaticText(panel,label="EPICS Record:")
layout.Add (label,(row,0),flag=a)
layout.Add (self.Prefix,(row,1),flag=a|e)
row += 1
label = wx.StaticText(panel,label="IP Address (auto detect):")
layout.Add (label,(row,0),flag=a)
layout.Add (self.Address,(row,1),flag=a|e)
# Leave a 5-pixel wide border.
box = wx.BoxSizer(wx.VERTICAL)
box.Add (layout,flag=wx.ALL,border=5)
panel.SetSizer(box)
panel.Fit()
self.Fit()
self.Show()
self.refresh()
def OnEnterPrefix(self,event):
"""Called if EPICS record prefix is changed"""
from timing_system import timing_system
timing_system.prefix = self.Prefix.Value
self.refresh()
def OnRefresh(self,event=None):
self.refresh()
def refresh(self,event=None):
"""Update the controles and indicators with current values"""
if self.Shown:
from timing_system import timing_system
self.Prefix.Value = timing_system.prefix
self.Prefix.Items = timing_system.prefixes
self.Address.Value = timing_system.ip_address
self.timer = wx.Timer(self)
self.Bind(wx.EVT_TIMER,self.refresh,self.timer)
self.timer.Start(1000,oneShot=True)
def OnClose(self,event):
self.Shown = False
##self.Destroy() # might crash under Windows
wx.CallLater(2000,self.Destroy)
SetupPanel = Timing_Setup_Panel # for backward compatibility
if __name__ == '__main__':
from pdb import pm # for debugging
from tempfile import gettempdir
logfile = gettempdir()+"/Timing_Setup_Panel.log"
import logging # for debugging
logging.basicConfig(
level=logging.DEBUG,
filename=logfile,
format="%(asctime)s %(levelname)s: %(message)s",
)
app = wx.App(redirect=False)
panel = Timing_Setup_Panel()
app.MainLoop()
<file_sep>line0.Center X = +0.000
line0.Center Y = +0.000
line0.Center Z = +0.000
line0.Phi = nan
line0.SamplePhi = -0.000
line0.SampleX = +0.049
line0.SampleY = +0.500
line0.SampleZ = -0.799
line0.description = SAXS/WAXS Sample Cell (middle) 2
line0.updated = 03 Feb 22:38
line1.Center X = +0.000
line1.Center Y = +0.000
line1.Center Z = +0.000
line1.Phi =
line1.SamplePhi = -0.000
line1.SampleX = +0.575
line1.SampleY = -0.774
line1.SampleZ = +0.378
line1.description = Laue Sample Cell
line1.updated = 11 Oct 18:01
line10.Center X = -0.767
line10.Center Y = -0.064
line10.Center Z = -1.381
line10.SamplePhi = -35.000
line10.SampleX = +0.428
line10.SampleY = +0.328
line10.SampleZ = -1.738
line10.description = Alignment Tool #1 Laser (-35 wide field)
line10.updated = 31 Jan 12:27
line11.Center X = -0.767
line11.Center Y = -0.064
line11.Center Z = -1.381
line11.SamplePhi = -30.000
line11.SampleX = -0.863
line11.SampleY = +0.173
line11.SampleZ = +1.235
line11.description = Alignment Tool #1 Tip (-30)
line11.updated = 25 Feb 21:20
line12.Center X = -0.767
line12.Center Y = -0.064
line12.Center Z = -1.381
line12.SamplePhi = -104.000
line12.SampleX = -0.774
line12.SampleY = +0.755
line12.SampleZ = -1.238
line12.description = Alignment Tool #1 Phosphor (-104)
line12.updated = 31 Jan 11:15
line2.Center X = +0.000
line2.Center Y = +0.000
line2.Center Z = +0.000
line2.Phi =
line2.SamplePhi = -0.000
line2.SampleX = +0.263
line2.SampleY = +0.549
line2.SampleZ = -0.799
line2.description = SAXS/WAXS Sample Cell (middle) 1
line2.updated = 31 May 10:25
line3.Center X = +0.000
line3.Center Y = +0.000
line3.Center Z = +0.000
line3.Phi =
line3.SamplePhi = -0.000
line3.SampleX = +0.167
line3.SampleY = +0.321
line3.SampleZ = -12.274
line3.description = Sample Cell (Start)
line3.updated = 01 Mar 22:51
line4.Center X = +0.000
line4.Center Y = +0.000
line4.Center Z = +0.000
line4.Phi =
line4.SamplePhi = +0.000
line4.SampleX = +12.000
line4.SampleY = -12.000
line4.SampleZ = +13.200
line4.description = Sample Cell retracted
line4.updated = 26 Feb 09:55
line5.Center X = +0.000
line5.Center Y = +0.000
line5.Center Z = +0.000
line5.Phi =
line5.SamplePhi = -0.000
line5.SampleX = +0.493
line5.SampleY = +0.612
line5.SampleZ = -12.374
line5.description = Sample Cell Phosphor
line5.updated = 01 Mar 11:52
line6.Center X = +0.000
line6.Center Y = +0.000
line6.Center Z = +0.000
line6.Phi =
line6.SamplePhi = -0.000
line6.SampleX = +0.254
line6.SampleY = +0.448
line6.SampleZ = +0.265
line6.description = Laue Sample Cell
line6.updated = 01 Mar 17:02
line7.Center X = -0.767
line7.Center Y = -0.064
line7.Center Z = -1.381
line7.Phi =
line7.SamplePhi = -40.500
line7.SampleX = -0.585
line7.SampleY = -0.094
line7.SampleZ = -2.051
line7.description = Alignment Tool #1 Laser (-40.5)
line7.updated = 28 Jan 10:44
line8.Center X = -0.064
line8.Center Y = +0.823
line8.Center Z = +0.000
line8.SamplePhi = -67.500
line8.SampleX = -0.393
line8.SampleY = -0.945
line8.SampleZ = +3.145
line8.description = MSM (APS)
line8.updated = 25 Feb 14:31
line9.Center X = -0.064
line9.Center Y = +0.823
line9.Center Z = +0.000
line9.SamplePhi = +3.000
line9.SampleX = -1.381
line9.SampleY = -0.338
line9.SampleZ = +3.112
line9.description = fiber laser 3 deg
line9.updated = 27 Jan 17:41<file_sep>command_row = 22
formats = ['%s', '%s', '%s', '%d']
line0.description = 'H:Alignment'
line0.Ensemble_SAXS.mode = u'Flythru-4'
line0.Ensemble_SAXS.passes = 1.0
line0.heat_load_chopper_modes.value = u'247-1.5'
line0.high_speed_chopper_modes.value = u'H-56'
line0.ChemMat_chopper_modes.value = u'H-56'
line0.updated = '24 Aug 16:26'
line10.description = 'S:T-jump(24-bunch)'
line10.Ensemble_SAXS.mode = u'Flythru-48'
line10.Ensemble_SAXS.passes = 1.0
line10.heat_load_chopper_modes.value = u'247-1.5'
line10.high_speed_chopper_modes.value = u'S-24'
line10.ChemMat_chopper_modes.value = u'S-24'
line10.updated = '24 Aug 18:53'
line11.description = 'S:Time-resolved(1-bunch)'
line11.Ensemble_SAXS.mode = u'Flythru-4'
line11.Ensemble_SAXS.passes = 24.0
line11.heat_load_chopper_modes.value = u'247-1.5'
line11.high_speed_chopper_modes.value = u'S-1t'
line11.ChemMat_chopper_modes.value = u'S-1t'
line11.updated = '24 Aug 18:53'
line12.description = 'S:Time-resolved(5-bunch)'
line12.Ensemble_SAXS.mode = u'Flythru-4'
line12.Ensemble_SAXS.passes = 5.0
line12.heat_load_chopper_modes.value = u'247-1.5'
line12.high_speed_chopper_modes.value = u'S-5'
line12.ChemMat_chopper_modes.value = u'S-5'
line12.updated = '24 Aug 18:53'
line13.description = 'S:Time-resolved(24-bunch)'
line13.Ensemble_SAXS.mode = u'Flythru-4'
line13.Ensemble_SAXS.passes = 1.0
line13.heat_load_chopper_modes.value = u'247-1.5'
line13.high_speed_chopper_modes.value = u'S-24'
line13.ChemMat_chopper_modes.value = u'S-24'
line13.updated = '24 Aug 18:53'
line1.description = 'H:T-ramp'
line1.Ensemble_SAXS.mode = u'Flythru-4'
line1.Ensemble_SAXS.passes = 5.0
line1.heat_load_chopper_modes.value = u'247-1.5'
line1.high_speed_chopper_modes.value = u'H-1'
line1.ChemMat_chopper_modes.value = u'H-1'
line1.updated = '24 Aug 16:26'
line2.description = 'H:T-jump(singlet)'
line2.Ensemble_SAXS.mode = u'Flythru-48'
line2.Ensemble_SAXS.passes = 5.0
line2.heat_load_chopper_modes.value = u'247-1.5'
line2.high_speed_chopper_modes.value = u'H-1'
line2.ChemMat_chopper_modes.value = u'H-1'
line2.updated = '24 Aug 16:26'
line3.description = 'H:T-jump(superbunch)'
line3.Ensemble_SAXS.mode = u'Flythru-48'
line3.Ensemble_SAXS.passes = 1.0
line3.heat_load_chopper_modes.value = u'247-1.5'
line3.high_speed_chopper_modes.value = u'H-56'
line3.ChemMat_chopper_modes.value = u'H-56'
line3.updated = '24 Aug 18:52'
line4.description = 'H:Time-resolved(singlet)'
line4.Ensemble_SAXS.mode = u'Flythru-4'
line4.Ensemble_SAXS.passes = 5.0
line4.heat_load_chopper_modes.value = u'247-1.5'
line4.high_speed_chopper_modes.value = u'H-1'
line4.ChemMat_chopper_modes.value = u'H-1'
line4.updated = '24 Aug 18:52'
line5.description = 'H:Time-resolved(superbunch)'
line5.Ensemble_SAXS.mode = u'Flythru-4'
line5.Ensemble_SAXS.passes = 1.0
line5.heat_load_chopper_modes.value = u'247-1.5'
line5.high_speed_chopper_modes.value = u'H-56'
line5.ChemMat_chopper_modes.value = u'H-56'
line5.updated = '24 Aug 18:52'
line6.description = 'S:Alignment'
line6.Ensemble_SAXS.mode = u'Flythru-4'
line6.Ensemble_SAXS.passes = 1.0
line6.heat_load_chopper_modes.value = u'247-1.5'
line6.high_speed_chopper_modes.value = u'S-24'
line6.ChemMat_chopper_modes.value = u'S-24'
line6.updated = '24 Aug 18:52'
line7.description = 'S:T-ramp'
line7.Ensemble_SAXS.mode = u'Flythru-4'
line7.Ensemble_SAXS.passes = 5.0
line7.heat_load_chopper_modes.value = u'247-1.5'
line7.high_speed_chopper_modes.value = u'S-5'
line7.ChemMat_chopper_modes.value = u'S-5'
line7.updated = '24 Aug 18:53'
line8.description = 'S:T-jump(1-bunch)'
line8.Ensemble_SAXS.mode = u'Flythru-48'
line8.Ensemble_SAXS.passes = 24.0
line8.heat_load_chopper_modes.value = u'247-1.5'
line8.high_speed_chopper_modes.value = u'S-1t'
line8.ChemMat_chopper_modes.value = u'S-1t'
line8.updated = '24 Aug 18:53'
line9.description = 'S:T-jump(5-bunch)'
line9.Ensemble_SAXS.mode = u'Flythru-48'
line9.Ensemble_SAXS.passes = 5.0
line9.heat_load_chopper_modes.value = u'247-1.5'
line9.high_speed_chopper_modes.value = u'S-5'
line9.ChemMat_chopper_modes.value = u'S-5'
line9.updated = '24 Aug 18:53'
motor_labels = ['HS Chopper', 'HL Chopper', 'Ensemble Mode', 'Passes per image']
motor_names = ['high_speed_chopper_modes.value', 'heat_load_chopper_modes.value', 'Ensemble_SAXS.mode', 'Ensemble_SAXS.passes']
names = ['high_speed_chopper_mode', 'heat_load_chopper_mode', 'Ensemble_mode', 'passes_per_image']
nrows = 23
title = 'SAXS-WAXS Methods'
line14.high_speed_chopper_modes.value = u'C-56'
line14.heat_load_chopper_modes.value = '247-1.5'
line14.Ensemble_SAXS.mode = u'Flythru-4'
line14.Ensemble_SAXS.passes = 1.0
line14.updated = '13 Sep 09:50'
line15.high_speed_chopper_modes.value = 'C-1'
line15.heat_load_chopper_modes.value = '247-1.5'
line15.Ensemble_SAXS.mode = u'Flythru-4'
line15.Ensemble_SAXS.passes = 5.0
line15.updated = '13 Sep 09:50'
line16.high_speed_chopper_modes.value = 'C-1'
line16.heat_load_chopper_modes.value = '247-1.5'
line16.Ensemble_SAXS.mode = u'Flythru-48'
line16.Ensemble_SAXS.passes = 5
line16.updated = '13 Sep 09:50'
line17.high_speed_chopper_modes.value = u'C-56'
line17.heat_load_chopper_modes.value = '247-1.5'
line17.Ensemble_SAXS.mode = u'Flythru-48'
line17.Ensemble_SAXS.passes = 1.0
line17.updated = '13 Sep 09:50'
line18.high_speed_chopper_modes.value = 'C-1'
line18.heat_load_chopper_modes.value = '247-1.5'
line18.Ensemble_SAXS.mode = u'Flythru-4'
line18.Ensemble_SAXS.passes = 5.0
line18.updated = '13 Sep 09:50'
line19.high_speed_chopper_modes.value = u'C-56'
line19.heat_load_chopper_modes.value = '247-1.5'
line19.Ensemble_SAXS.mode = u'Flythru-4'
line19.Ensemble_SAXS.passes = 1.0
line19.updated = '13 Sep 09:50'
line14.description = 'C:Alignment'
line15.description = 'C:T-ramp'
line16.description = 'C:T-jump(singlet)'
line17.description = 'C:T-jump(superbunch)'
line18.description = 'C:Time-resolved(singlet)'
line19.description = 'C:Time-resolved(superbunch)'
line20.high_speed_chopper_modes.value = 'C-1'
line20.heat_load_chopper_modes.value = '247-1.5'
line20.Ensemble_SAXS.mode = 'Laue-10Hz'
line20.Ensemble_SAXS.passes = 10
line20.updated = '14 Sep 10:00'
line20.description = 'C:Laue(singlet)'
line21.description = 'C:Laue(superbunch)'
line21.high_speed_chopper_modes.value = u'C-56'
line21.heat_load_chopper_modes.value = '247-1.5'
line21.Ensemble_SAXS.mode = 'Laue-10Hz'
line21.Ensemble_SAXS.passes = 10
line21.updated = '14 Sep 10:01'
line22.high_speed_chopper_modes.value = 'C-1'
line22.heat_load_chopper_modes.value = '82-1.5'
line22.Ensemble_SAXS.mode = 'Laue-10Hz'
line22.Ensemble_SAXS.passes = 1
line22.updated = '23 Oct 09:30'
line22.description = 'Alignment'
show_in_list = False<file_sep>#!/usr/bin/env python
"""Upload and download files across the network,
from and to the FPGA timing system.
Setup:
A server program, named "file-server" to be
running on the timing system (in "/home/timing_system").
Usage examples:
wput("test\n","//id14timing3.cars.aps.anl.gov:2001/tmp/test.txt")
wput("."*1000000,"//id14timing3.cars.aps.anl.gov:2001/tmp/test.dat")
data = wget("//id14timing3.cars.aps.anl.gov:2001/tmp/test.dat")
wdel("//id14timing3.cars.aps.anl.gov:2001/tmp/test.txt")
Transfer speed: 8.2 MB/s upload, 8.1 MB/s download
: 15 us per file upload, 8 ms per file download
<NAME>, Nov 21, 2015 - Aug 28, 2017
"""
__version__ = "1.4" # (ip_address,port) -> ip_address_and_port
from logging import debug,info,warn,error
from tcp_client import connection
default_port_number = 2001
from thread import allocate_lock
lock = allocate_lock()
def wput(data,URL):
"""Upload a file across the network
data: content of the file to upload.
URL: e.g. "//id14timing3.cars.aps.anl.gov:2001/tmp/test.txt"
"""
##debug("%s, %d bytes %r " % (URL,len(data),data[0:21]))
with lock: # Allow only one thread at a time inside this function.
import socket
url = URL
default_port = 80 if url.startswith("http:") else default_port_number
url = url.replace("http:","")
if url.startswith("//"): url = url[2:]
ip_address_and_port = url.split("/")[0].split("@")[-1]
if not ":" in ip_address_and_port: ip_address_and_port += ":"+str(default_port)
pathname = "/"+"/".join(url.split("/")[1:])
s = "PUT %s\n" % pathname
s += "Content-Length: %d\n" % len(data)
s += "\n"
s += data
for attempt in range(0,2):
try:
c = connection(ip_address_and_port)
if c is None: break
c.sendall(s)
except socket.error: continue
break
def wget(URL):
"""Download a file from the network
URL: e.g. "//id14timing3.cars.aps.anl.gov:2001/tmp/test.txt"
"""
##debug("wget %r queued" % URL)
with lock: # Allow only one thread at a time inside this function.
##debug("wget %r..." % URL)
import socket
url = URL
default_port = 80 if url.startswith("http:") else default_port_number
url = url.replace("http:","")
if url.startswith("//"): url = url[2:]
ip_address_and_port = url.split("/")[0]
if not ":" in ip_address_and_port: ip_address_and_port += ":"+str(default_port)
pathname = "/"+"/".join(url.split("/")[1:])
s = "GET %s\n" % pathname
s += "\n"
data = ""
for attempt in range(0,2):
try:
c = connection(ip_address_and_port)
if c is None: break
c.sendall(s)
reply = ""
while not "\n\n" in reply:
r = c.recv(65536)
if len(r) == 0: break
reply += r
if len(r) == 0: continue
header_size = reply.find("\n\n")+2
keyword = "Content-Length: "
if not keyword in reply: return ""
start = reply.find(keyword)+len(keyword)
end = start+reply[start:].find("\n")
file_size = int(reply[start:end])
while len(reply) < header_size+file_size:
r = c.recv(65536)
if len(r) == 0: break
reply += r
if len(r) == 0: continue
data = reply[header_size:]
if len(data) != file_size:
warn("file server %s: expecting %d,got %d bytes" %
(ip_address_and_port,file_size,len(data)))
except socket.error: continue
break
##debug("wget %r: %-.20r" % (URL,data))
return data
def wdel(URL):
"""Download a file from the network
URL: e.g. "//id14timing3.cars.aps.anl.gov:2001/tmp/test.txt"
"""
with lock: # Allow only one thread at a time inside this function.
import socket
url = URL
default_port = 80 if url.startswith("http:") else default_port_number
url = url.replace("http:","")
if url.startswith("//"): url = url[2:]
ip_address_and_port = url.split("/")[0]
if not ":" in ip_address_and_port: ip_address_and_port += ":"+str(default_port)
pathname = "/"+"/".join(url.split("/")[1:])
s = "DEL %s\n" % pathname
s += "\n"
for attempt in range(0,2):
try:
c = connection(ip_address_and_port)
if c is None: break
c.sendall(s)
except socket.error: continue
break
def wexists(URL):
"""Download a file from the network
url: e.g. "//id14timing3.cars.aps.anl.gov:2001/tmp/test.txt"
"""
with lock: # Allow only one thread at a time inside this function.
import socket
url = URL
default_port = 80 if url.startswith("http:") else default_port_number
url = url.replace("http:","")
if url.startswith("//"): url = url[2:]
ip_address_and_port = url.split("/")[0]
if not ":" in ip_address_and_port: ip_address_and_port += ":"+str(default_port)
pathname = "/"+"/".join(url.split("/")[1:])
s = "EXISTS %s\n" % pathname
s += "\n"
data = ""
for attempt in range(0,2):
try:
c = connection(ip_address_and_port)
if c is None: break
c.sendall(s)
reply = ""
while not "\n\n" in reply:
r = c.recv(65536)
if len(r) == 0: break
reply += r
if len(r) == 0: continue
header_size = reply.find("\n\n")+2
keyword = "Content-Length: "
if not keyword in reply: return ""
start = reply.find(keyword)+len(keyword)
end = start+reply[start:].find("\n")
file_size = int(reply[start:end])
while len(reply) < header_size+file_size:
r = c.recv(65536)
if len(r) == 0: break
reply += r
if len(r) == 0: continue
data = reply[header_size:]
if len(data) != file_size:
warn("file server %s: expecting %d,got %d bytes" %
(ip_address_and_port,file_size,len(data)))
except socket.error: continue
break
return data == "True\n"
def wdir(URL):
"""Download a file from the network
URL: e.g. "//id14timing3.cars.aps.anl.gov:2001/tmp/*"
"""
with lock: # Allow only one thread at a time inside this function.
import socket
url = URL
default_port = 80 if url.startswith("http:") else default_port_number
url = url.replace("http:","")
if url.startswith("//"): url = url[2:]
ip_address_and_port = url.split("/")[0]
if not ":" in ip_address_and_port: ip_address_and_port += ":"+str(default_port)
pathname = "/"+"/".join(url.split("/")[1:])
s = "DIR %s\n" % pathname
s += "\n"
data = ""
for attempt in range(0,2):
try:
c = connection(ip_address_and_port)
if c is None: break
c.sendall(s)
reply = ""
while not "\n\n" in reply:
r = c.recv(65536)
if len(r) == 0: break
reply += r
if len(r) == 0: continue
header_size = reply.find("\n\n")+2
keyword = "Content-Length: "
if not keyword in reply: return ""
start = reply.find(keyword)+len(keyword)
end = start+reply[start:].find("\n")
file_size = int(reply[start:end])
while len(reply) < header_size+file_size:
r = c.recv(65536)
if len(r) == 0: break
reply += r
if len(r) == 0: continue
data = reply[header_size:]
if len(data) != file_size:
warn("file server %s: expecting %d,got %d bytes" %
(ip_address_and_port,file_size,len(data)))
except socket.error: continue
break
return data
def wsize(URL):
"""Download a file from the network
URL: e.g. "//id14timing3.cars.aps.anl.gov:2001/tmp/test.txt"
"""
with lock: # Allow only one thread at a time inside this function.
import socket
url = URL
default_port = 80 if url.startswith("http:") else default_port_number
url = url.replace("http:","")
if url.startswith("//"): url = url[2:]
ip_address_and_port = url.split("/")[0]
if not ":" in ip_address_and_port: ip_address_and_port += ":"+str(default_port)
pathname = "/"+"/".join(url.split("/")[1:])
s = "SIZE %s\n" % pathname
s += "\n"
data = ""
for attempt in range(0,2):
try:
c = connection(ip_address_and_port)
if c is None: break
c.sendall(s)
reply = ""
while not "\n\n" in reply:
r = c.recv(65536)
if len(r) == 0: break
reply += r
if len(r) == 0: continue
header_size = reply.find("\n\n")+2
keyword = "Content-Length: "
if not keyword in reply: return ""
start = reply.find(keyword)+len(keyword)
end = start+reply[start:].find("\n")
file_size = int(reply[start:end])
while len(reply) < header_size+file_size:
r = c.recv(65536)
if len(r) == 0: break
reply += r
if len(r) == 0: continue
data = reply[header_size:]
if len(data) != file_size:
warn("file server %s: expecting %d,got %d bytes" %
(ip_address_and_port,file_size,len(data)))
except socket.error: continue
break
data = data.strip()
try: size = int(data)
except:
warn("file server %s: expecting integer, got %r" %
(ip_address_and_port,data))
size = 0
return size
if __name__ == "__main__":
from pdb import pm
from sys import argv,stderr
if len(argv) != 3:
stderr.write("Usage: %s test.txt http://id14timing3.cars.aps.anl.gov:2001/tmp/test.txt\n" % argv[0])
else:
filename,URL = argv[1],argv[2]
wput(file(filename).read(),URL)
##wput('22'.ljust(22)+'\n','id14timing3.cars.aps.anl.gov:2001/tmp/sequencer_fs/queue_max_repeat_count')
<file_sep>"""For converting '100ps' <-> 1e-10, etc.
Author: <NAME>
Date created: 2009-08-26
Date last modified: 2018-10-27
"""
from __future__ import division # 1/2 = 0.5
__version__ = "1.5.4" # isnan -> isfinite
from logging import debug,info,warn,error
def vectorize(f):
"""Generalize function f(x) so it returns an array if x is an array"""
from numpy import array
def F(X,*args,**kwargs):
if isscalar(X): return f(X,*args,**kwargs)
return array([f(x,*args,**kwargs) for x in X])
F.__doc__ = f.__doc__
return F
def isscalar(x):
"""Is x a scalar type?"""
# Workaroud for a bug in numpy's "isscalar" returning false for None.
from numpy import isscalar
return isscalar(x) or x is None
# Problem: 'vectorize' returns a array of strings, not a chararray.
def as_chararray(f):
"""Make sure f returns a numpy array of type 'chararray'"""
from numpy import chararray
def F(x,*args,**kwargs):
if isscalar(x): return f(x,*args,**kwargs)
return f(x,*args,**kwargs).view(chararray)
F.__doc__ = f.__doc__
return F
@vectorize
def seconds(s):
"""Convert time string to number. e.g. '100ps' -> 1e-10"""
from numpy import nan
try: return float(s)
except: pass
s = s.replace("min","*60")
s = s.replace("h","*60*60")
s = s.replace("d","*60*60*24")
s = s.replace("s","")
s = s.replace("p","*1e-12")
s = s.replace("n","*1e-9")
s = s.replace("u","*1e-6")
s = s.replace("m","*1e-3")
try: return float(eval(s))
except: return nan
@as_chararray
@vectorize
def time_string(t,precision=3):
"""Convert time given in seconds in more readable format
such as ps, ns, ms, s.
precision: number of digits"""
from numpy import isnan,isinf
if t is None: return "off"
if t == "off": return "off"
try: t=float(t)
except: return "off"
if isnan(t): return "off"
if isinf(t) and t>0: return "inf"
if isinf(t) and t<0: return "-inf"
if t == 0: return "0"
if abs(t) < 0.5e-12: return "0"
if abs(t) < 999e-12: return "%.*gps" % (precision,t*1e12)
if abs(t) < 999e-9: return "%.*gns" % (precision,t*1e9)
if abs(t) < 999e-6: return "%.*gus" % (precision,t*1e6)
if abs(t) < 999e-3: return "%.*gms" % (precision,t*1e3)
if abs(t) < 60: return "%.*gs" % (precision,t)
if abs(t) < 60*60: return "%.*gmin" % (precision,t/60.)
if abs(t) < 24*60*60: return "%.*gh" % (precision,t/(60.*60))
return "%.*gd" % (precision,t/(24*60.*60))
def timestamp(date_time,timezone=None):
"""Convert a date string to number of seconds since 1 Jan 1970 00:00 UTC
date: e.g. "2016-01-27 12:24:06.302724692-08"
"""
from dateutil.parser import parse
from numpy import nan
try:
t = parse(date_time)
if t.tzinfo is None:
if timezone is None:
from dateutil.tz import tzlocal
from datetime import datetime
timezone = datetime.now(tzlocal()).tzname()
debug("timestamp: %r: Assuming time zone %r" % (date_time,timezone))
t = parse(date_time+timezone)
t0 = parse("1970-01-01 00:00:00+0000")
T = (t-t0).total_seconds()
except Exception,msg: error("timestamp: %r: %s" % (msg,date_time)); T = nan
return T
def date_time(seconds,timezone=""):
"""Date and time as formatted ASCII text, precise to 1 ms
seconds: time elapsed since 1 Jan 1970 00:00:00 UTC
e.g. '2016-02-01 19:14:31.707016-08:00' """
from datetime import datetime
import pytz
from dateutil.tz import tzlocal
from numpy import isfinite
if isfinite(seconds):
timeUTC = datetime.utcfromtimestamp(seconds)
timezoneLocal = pytz.timezone(timezone) if timezone else tzlocal()
utc = pytz.utc
timeLocal = utc.localize(timeUTC).astimezone(timezoneLocal)
date_time = str(timeLocal)
# Time zone should be formatted "-0800" not "-08:00"
if date_time.endswith(":00"): date_time = date_time[:-3]+"00"
else: date_time = ""
return date_time
if __name__ == "__main__":
import logging
logging.basicConfig(level=logging.DEBUG,
format="%(asctime)s: %(levelname)s %(message)s")
print('date_time(timestamp("1970-01-01 00:00:00"))')
print('date_time(timestamp("27 Aug 2018 21:00"))')
print('date_time(timestamp("27 Aug 2018 21:00 EDT"))')
print('date_time(timestamp("27 Aug 2018 21:00 EST"))')
print('date_time(timestamp("2018-08-27 21:00:00-0400"))')
<file_sep>"""
Sample Frozen module
Authors: <NAME>
Date created: 26 Feb 2018 - original optical freeze detection agent
Date last modified: March 2 2019
Utilizes center 50x50 pixels to measure mean value within
"""
__version__ = "1.0" # write a comment
from CAServer import casput,casdel, casget
from CA import caget
from datetime import datetime
from thread import start_new_thread
from pdb import pm
import os
#from SAXS_WAXS_control import SAXS_WAXS_control, SampleX, SampleY
#from Ensemble_client import ensemble
from time import sleep,time
from persistent_property import persistent_property
from instrumentation import temperature
#from instrumentation import optical_scattering
from optical_scattering import optical_scattering
from numpy import nan
from logging import debug,info,warn,error
import traceback
import matplotlib.pyplot as plt
class Sample_Frozen_Optical(object):
intervention_enabled = persistent_property('intervention_enabled', False)
i_global = persistent_property('i_global', 1)
frozen_threshold_temperature = persistent_property('frozen_threshold_temperature', -5.0)
scattering_threshold = persistent_property('scattering_threshold', 80)
def __init__(self):
self.name = 'sample_frozen_optical'
self.time_last_interventation = 0
self.bckg_change_flag_down = True
self.bckg_change_flag_up = False
self.circular_buffer = []
def init(self):
"""
define parameters for current operation
initializes image analyzer
"""
self.is_intervention_enabled = self.intervention_enabled
self.startup()
def startup(self):
from CAServer import casput,casmonitor
from CA import caput,camonitor
from numpy import nan
casput(self.prefix+".ENABLE",self.intervention_enabled)
casput(self.prefix+'.RUNNING', self.running)
casput(self.prefix+".KILL",value = 'write password to kill the process')
casput(self.prefix+".LIST_ALL_PVS",value = self.get_pv_list())
# Monitor client-writable PVs.
casmonitor(self.prefix+".KILL",callback=self.monitor)
def monitor(self,PV_name,value,char_value):
"""Process PV change requests"""
from CAServer import casput
from CA import caput
print("monitor: %s = %r" % (PV_name,value))
if PV_name == self.prefix + ".KILL":
if value == 'shutdown': #the secret word to shutdown the process is 'shutdown'
self.shutdown()
if PV_name == self.prefix + ".ENABLE":
self.intervention_enabled = value
def get_pv_list(self):
from CAServer import PVs
lst = list(PVs.keys())
#lst_new = []
#for item in lst:
# lst_new.append(item.replace(self.prefix,'').replace('.',''))
return lst#lst_new
def get_is_running(self):
return self.running
def set_is_running(self,value):
from thread import start_new_thread
if value and not self.running:
self.init()
self.running = True
start_new_thread(self.run,())
else: self.running = False
casput(self.CAS_prefix+'.RUNNING', self.running)
is_running = property(get_is_running,set_is_running)
def get_is_intervention_enabled(self):
from time import time
return self.intervention_enabled
def set_is_intervention_enabled(self,value):
from CAServer import casput
self.intervention_enabled = value
casput(self.CAS_prefix+'.ENABLED', self.intervention_enabled)
is_intervention_enabled = property(get_is_intervention_enabled,set_is_intervention_enabled)
def get_deicing(self):
"""Is the motion controller program instructed to run in 'deice' mode?"""
from freeze_intervention import freeze_intervention
return freeze_intervention.active
def set_deicing(self,value):
from freeze_intervention import freeze_intervention
freeze_intervention.active = value
#from Ensemble_client import ensemble
#ensemble.integer_registers[3] = 3 if value else 0
#info("ensemble.integer_registers[3] = %r" % ensemble.integer_registers[3])
deicing = property(get_deicing,set_deicing)
def get_retract(self):
"""Is the motion controller program instructed to run in 'deice' mode?"""
from SAXS_WAXS_control import SAXS_WAXS_control
return SAXS_WAXS_control.retracted
def set_retract(self,value):
from SAXS_WAXS_control import SAXS_WAXS_control
SAXS_WAXS_control.retracted = value
retract = property(get_retract,set_retract)
def retract_intervention(self):
from SAXS_WAXS_control import SAXS_WAXS_control
if SAXS_WAXS_control.inserted:
SAXS_WAXS_control.retracted = True
sleep(self.retracted_time)
SAXS_WAXS_control.inserted = True
def aux_intervention(self):
"""
sends freeze intervention command to the freeze_intervention module
(check freeze_intervention.py for details)
"""
from freeze_intervention import freeze_intervention
from time import sleep
info('freeze intervention')
sleep(0.01)
freeze_intervention.active = True
def start(self):
"""run in background"""
info('Freeze detector has started')
self.is_running = True
def stop(self):
self.running = False
def close(self):
self.running = False
self.cleanup()
def run(self):
from time import sleep,time
from CAServer import casput
self.running = True
while self.running:
self.running_timestamp = time()
try:
self.run_once()
except:
error(traceback.format_exc())
warn('Microscope camera is not working')
self.is_running = False
self.scattering = nan
#self.cleanup()
def run_once(self):
from optical_image_analyzer import image_analyzer
from CAServer import casput, casget
from freeze_intervention import freeze_intervention
from numpy import rot90
if self.bckg_change_flag_down and temperature.value < 1.0:
#self.set_background()
debug('circular buffer zeroed')
self.circular_buffer = []
self.bckg_change_flag_down = False
self.bckg_change_flag_up = True
if self.bckg_change_flag_up and temperature.value > 3.0:
self.bckg_change_flag_down = True
self.bckg_change_flag_up = False
img = image_analyzer.get_image()
debug('image received: image counter %r, image dimensions %r' %(image_analyzer.imageCounter, img.shape))
if self.orientation == 'horizontal2' or self.orientation == 'horizontal' or self.orientation == 'on-axis-h':
img = rot90(img,3,axes=(1,2))
res_dic = self.is_frozen(img)
debug('res_dic = %r' %res_dic)
is_frozen_flag = res_dic['flag']
casput(self.CAS_prefix+".MEAN_TOP",res_dic['mean_top'])
casput(self.CAS_prefix+".MEAN_BOTTOM",res_dic['mean_bottom'])
casput(self.CAS_prefix+".MEAN_MIDDLE",res_dic['mean_middle'])
casput(self.CAS_prefix+".MEAN",res_dic['mean_value'])
casput(self.CAS_prefix+".RBV",res_dic['mean_value'])
casput(self.CAS_prefix+".STDEV",res_dic['stdev'])
self.intervention_enabled = casget(self.CAS_prefix+'.ENABLED')
casput(self.CAS_prefix+".VAL",is_frozen_flag)
if is_frozen_flag and temperature.value < self.frozen_threshold_temperature:
print('freezing detected')
"""Intervention"""
if self.intervention_enabled:
self.retract_intervention()
else:
print('Intervention was disabled')
def is_frozen(self,img):
"""
determines if the images is frozen or not
"""
from optical_image_analyzer import image_analyzer
from numpy import subtract, mean, std, rot90, array
from freeze_intervention import freeze_intervention
from temperature import temperature
from PIL import Image
dx = int(self.box_dimensions*2/2.0)
dy = int(self.box_dimensions*2/2.0)
self.orient_dic['on-axis-h'] = {'up':[(0,0),(0,0)],
'middle':[(512-dx,680-dy),(512+dx,680+dy)],
'down':[(0,0),(0,0)]}
self.orient_dic['on-axis-v'] = {'up':[(0,0),(0,0)],
'middle':[(680-dy,512-dx),(680+dy,512+dx)],
'down':[(0,0),(0,0)]}
section_up = image_analyzer.masked_section(img,anchors = self.orient_dic[self.orientation]['up'])
section_middle = image_analyzer.masked_section(img,anchors = self.orient_dic[self.orientation]['middle'])
section_down = image_analyzer.masked_section(img,anchors = self.orient_dic[self.orientation]['down'])
flag = False
dict0 = self.analyse(section_up)
dict1 = self.analyse(section_down)
dict2 = self.analyse(section_middle)
## dict0 = {}
## dict1 = {}
## dict2 = {}
## dict0['mean'] = 0
## dict1['mean'] = 0
## dict2['mean'] = 0
mean_top = dict0['mean']
mean_bottom = dict1['mean']
mean_middle = dict2['mean']
if self.orientation == 'on-axis-h' or self.orientation == 'on-axis-v' :
mean_value = dict2['mean']
stdev = dict2['stdev']
else:
mean_value = dict2['mean']-(dict0['mean']/2.)-(dict1['mean']/2.)
stdev = (dict2['stdev']**2-(dict0['stdev']/2)**2-(dict1['stdev']/2)**2)**0.5
self.scattering = round(mean_value,3)
if not freeze_intervention.active:
#if mean_value - mean(self.circular_buffer) > self.scattering_threshold and len(self.circular_buffer) >5:
if self.scattering > (self.scattering_threshold) and len(self.circular_buffer) >5:
if temperature.value < self.frozen_threshold_temperature:
flag = True
else:
flag = False
self.time_last_interventation = time()
elif freeze_intervention.active != True:
flag = False
self.circular_buffer.append(self.scattering)
if len(self.circular_buffer) >10:
self.circular_buffer.pop(0)
else:
flag = False
info('Not enough time since last intervention (%r)' % (time () - self.time_last_interventation))
res_dic = {}
res_dic['flag'] = flag
res_dic['mean_top']=mean_top
res_dic['mean_bottom']=mean_bottom
res_dic['mean_middle']=mean_middle
res_dic['mean_value']=mean_value
res_dic['stdev'] = stdev
return res_dic
def analyse(self,array):
from numpy import mean, std
dic = {}
dic['mean'] = mean(array[0,:,:]*1.0+array[1,:,:]*1.0+array[2,:,:]*1.0)
dic['mean_R'] = mean(array[0,:,:])
dic['mean_G'] = mean(array[1,:,:])
dic['mean_B'] = mean(array[2,:,:])
dic['stdev'] = std(array[0,:,:]*1.0+array[1,:,:]*1.0+array[2,:,:]*1.0)
dic['stdev_R'] = std(array[0,:,:])
dic['stdev_G'] = std(array[1,:,:])
dic['stdev_B'] = std(array[2,:,:])
return dic
def cleanup(self):
"""orderly cleanup of all channel access server process variables."""
from CAServer import casdel
lst = self.get_pv_list()
for item in lst:
casdel(item)
def shutdown(self):
from CAServer import casdel
print('SHUTDOWN command received')
self.running = False
self.cleanup()
del self
###Libraries for testing and data processing
def test_folder(self):
folder = '//volumes/data/anfinrud_1810/Test/Laue/opt_images/freezing/Microscope/'
return folder
def get_filenames(self,folder):
import os
from numpy import zeros,asarray
lst_temp = os.listdir(folder)
lst = []
for i in lst_temp:
if '.tiff' in i:
lst.append(i.split('_'))
sorted_lst = sorted(lst,key=lambda x: (x[0],x[1]))
lst_s = []
for i in sorted_lst:
lst_s.append([i[0],folder + '_'.join(i)])
return lst_s
def get_image_from_file(self,filename):
from PIL import Image
from numpy import rot90, array, zeros,flipud, mean, flip, sum
img = array(Image.open(filename))
gray = sum(img,2)
arr = zeros((4,1024,1360))
for i in range(3):
for j in range(1024):
for k in range(1360):
arr[i,j,k] = img[j,k,i]
i = 3
for j in range(1024):
for k in range(1360):
arr[i,j,k] = gray[j,k]
arr = flip(arr,1)
return arr
def get_vector(self,img):
from numpy import mean, sum
dic = {}
dic['mean_total'] = mean(img[3,:,:],axis = 1)
dic['sum_total'] = sum(img[3,:,:],axis = 1)
dic['mean_R'] = mean(img[0,:,:],axis = 1)
dic['sum_R'] = sum(img[0,:,:],axis = 1)
dic['mean_G'] = mean(img[1,:,:],axis = 1)
dic['sum_G'] = sum(img[1,:,:],axis = 1)
dic['mean_B'] = mean(img[2,:,:],axis = 1)
dic['sum_B'] = sum(img[2,:,:],axis = 1)
dic['frozen'] = self.is_frozen(img)
return dic
def run_test(self):
from time import time
folder = self.test_folder()
filenames = self.get_filenames(folder)
res_lst = []
t1 = time()
i = 0
for name in filenames:
img = self.get_image_from_file(name[1])
result = self.get_vector(img)
self.save_obj(result,name[1].split('.tiff')[0]+'.pickle')
res_lst.append(self.get_vector(img))
print(time()-t1,len(filenames)-i)
i+=1
def save_obj(self,obj, name ):
import pickle
with open(name, 'wb') as f:
pickle.dump(obj, f, pickle.HIGHEST_PROTOCOL)
def load_obj(self,name):
import pickle
with open(name, 'rb') as f:
return pickle.load(f)
def get_all_pickle(self,folder):
lst_temp = os.listdir(folder)
lst = []
for item in lst_temp:
i = item.split('.pickle')[0]
lst.append(i.split('_'))
sorted_lst = sorted(lst,key=lambda x: (x[0],x[1],x[2],x[3]))
lst_s = []
for i in sorted_lst:
lst_s.append([i[0],folder + '_'.join(i),i[2],i[3]])
return lst_s
def test2(self,fr,to, folder = ''):
from matplotlib import pyplot as plt
from time import time
i = 0
if folder =='':
lst = self.get_all_pickle(self.test_folder())
else:
lst = self.get_all_pickle(folder)
for item in lst[fr:to]:
item[1] = item[1] + '.pickle'
arr = self.load_obj(item[1])['mean_total']
plt.plot(arr)
def plot_mean_values(self,folder):
from matplotlib import pyplot as plt
from time import time
from numpy import std
from numpy import asarray
i = 0
arr = []
arrT = []
if folder =='':
lst = self.get_all_pickle(self.test_folder())
else:
lst = self.get_all_pickle(folder)
for item in lst:
item[1] = item[1] + '.pickle'
arr.append(self.load_obj(item[1])['frozen']['mean_value'])
arrT.append(float(item[3])*0.1)
arr = asarray(arr)
arrT = asarray(arrT)
plt.plot(arr)
plt.plot(arrT)
plt.show()
def process_data(self,folder):
from matplotlib import pyplot as plt
from time import time
from numpy import std
from numpy import asarray
result = []
if folder =='':
lst = self.get_all_pickle(self.test_folder())
else:
lst = self.get_all_pickle(folder)
for item in lst:
dic = {}
item[1] = item[1] + '.pickle'
dic['temperature'] = float(item[3])
dic['inserted'] = item[2]
dic['frozen'] = self.load_obj(item[1])['frozen']['flag']
dic['frozen_data'] = self.load_obj(item[1])['frozen']
dic['data'] = self.load_obj(item[1])
result.append(dic)
return result
def plot_all_T(self,T = [0,1],folder = ''):
from matplotlib import pyplot as plt
i =0
for item in T:
num = len(T)*100 +10 +i+1
plt.subplot(num)
self.plot_fixed_temperature(0,2631,folder,T[i])
plt.ylim(30,150)
i+=1
plt.show()
def plot_N_image_slice(self,N,folder):
from matplotlib import pyplot as plt
from time import time
from numpy import std
i = 0
temp_lst
if folder =='':
lst = self.get_all_pickle(self.test_folder())
else:
lst = self.get_all_pickle(folder)
for item in lst[fr:to]:
item[1] = item[1] + '.pickle'
temperature = item[3]
arr = self.load_obj(item[1])['mean_total']
arrG = self.load_obj(item[1])['mean_G']
arrR = self.load_obj(item[1])['mean_R']
arrB = self.load_obj(item[1])['mean_B']
plt.plot(arr, label = 'total', color= 'k')
plt.plot(arrR, label = 'Red', color = 'r')
plt.plot(arrG, label = 'Green' , color = 'g')
plt.plot(arrB, label = 'Blue', color = 'b')
plt.title('Image = %r @ T = %r C' %(N,temperature))
def plot_fixed_temperature(self,fr,to, folder = '',temperature = 0):
from matplotlib import pyplot as plt
from time import time
from numpy import std
i = 0
if folder =='':
lst = self.get_all_pickle(self.test_folder())
else:
lst = self.get_all_pickle(folder)
for item in lst[fr:to]:
item[1] = item[1] + '.pickle'
arr = self.load_obj(item[1])['mean_total']
if temperature == 999 and std(arr) != 0:
plt.plot(arr, label = str(self.load_obj(item[1])['frozen']['mean_value']))
elif abs(float(item[3]) - temperature) < 0.2 and std(arr) != 0:
plt.plot(arr, label = str(self.load_obj(item[1])['frozen']['mean_value']))
i +=1
plt.title('N of images = %r @ T = %r C' %(i,temperature))
def test3(self):
from matplotlib import pyplot as plt
from time import time
lst = self.get_all_pickle(self.test_folder())
lsttt = []
for item in lst:
lsttt.append(self.load_obj(item[1])['frozen']['mean_value'])
#plt.plot(lsttt)
return lsttt
sample_frozen_optical = Sample_frozen_optical()
sample_frozen_optical.orientation = 'on-axis-h'
sample_frozen_optical.init()
if __name__ == "__main__":
import logging
from tempfile import gettempdir
logging.basicConfig(level=logging.INFO,
format="%(asctime)s %(levelname)s: %(message)s",
filename=gettempdir()+"/scattering_optical.log",
)
self = sample_frozen_optical # for testing
#self.start()
#if self.intervention_enabled:
# print('GOOD: Intervention is enabled')
#else:
# print('WARNING: Intervention is disabled')
print('self.start()')
print('self.stop()')
print('self.close()')
print('self.is_running = True')
print('self.is_running = False')
<file_sep>#!/usr/bin/env python
"""High-magnification, small field of view video camera of the diffractometer,
used for aligneing a crystal in the X-ray beam
<NAME>, 19 Feb 2008 - 6 Jul 2017"""
__version__ = "1.8.1" # __main__
import logging; from tempfile import gettempdir
logfile = gettempdir()+"/MicroscopeCamera.log"
logging.basicConfig(level=logging.DEBUG,format="%(asctime)s: %(message)s",
filename=logfile)
logging.debug("MicroscopeCamera started")
from os import chmod
try: chmod(logfile,0666)
except Exception,msg: print("%s: %s" % (logfile,msg))
import wx
wx.app = wx.App(redirect=False)
from SampleAlignmentViewer import SampleAlignmentViewer
# Except "name" and "title" the parameters passed to "SampleAlignmentViewer"
# are just default values that can be overridden by user-editable settings
# within the Camera application. The default values are noly used at first run,
# or when the settigns file is lost or otherwise unusable.
viewer = SampleAlignmentViewer(
name="MicroscopeCamera",
title="Microscope [advanced] (-30 deg)",
orientation=0,mirror=True,
pixelsize=0.000526,
camera_angle=-30,
)
wx.app.MainLoop()
logging.debug("MicroscopeCamera closed")
<file_sep>#!/bin/bash
# Python Envronment for XPP Beamline
# <NAME> Jan 22, 2016
# <NAME>, Jan 22, 2016
source /reg/g/psdm/etc/ana_env.sh
export PSPKG_ROOT=/reg/common/package
source /reg/g/pcds/setup/pathmunge.sh
source $PSPKG_ROOT/etc/set_env.sh
export XPPFOLDER=/reg/g/pcds/pyps/xpp/prod/xpp
pythonpathmunge ${XPPFOLDER}
pythonpathmunge ${XPPFOLDER}/xpp
SETUPDIR="/reg/g/pcds/pyps/xpp/current/xpp"
source ${SETUPDIR}/xppenv.sh
<file_sep>#!/usr/bin/env python
from CAServer import casput,casget
from CA import caput,caget,cainfo
casput("NIH:TEST.ARRAY",[])
print('caget("NIH:TEST.ARRAY")')
print('cainfo("NIH:TEST.ARRAY")')
print('caput("NIH:TEST.ARRAY",[])')
print('casget("NIH:TEST.ARRAY")')
<file_sep>"""
EPICS Channel Access via SSH Tunnel
Setup required:
Edit script "NIH Tunnel.sh":
hosts = "... pico7.niddk.nih.gov ..."
ports="... 5064 5065 5066 ..."
Author: <NAME>
Date created: 2018-06-12
Date last modified: 2018-06-12
"""
from os import environ
from CA1 import caget,caput
environ["EPICS_CA_ADDR_LIST"] = "pico7.niddk.nih.gov"
print caget("NIH:TEMP.VAL")
<file_sep>#!/usr/bin/env python
"""Ice diffraction detection
Authors: <NAME>, <NAME>
Date created: 2017-10-31
Date last modified: 2017-11-01
"""
from logging import debug,warn,info,error
from sample_frozen import sample_frozen
from Panel import BasePanel,PropertyPanel,ButtonPanel,TogglePanel,TweakPanel
import wx
__version__ = "1.3" # ROI
class SampleFrozenPanel(BasePanel):
name = "SampleFrozenPanel"
title = "Sample Frozen"
standard_view = [
"Diffraction Spots",
"Threshold [spots]",
"Deice enabled",
"Deicing",
]
parameters = [
[[PropertyPanel,"Diffraction Spots",sample_frozen,"diffraction_spots"],{"read_only":True}],
[[PropertyPanel,"Threshold [spots]",sample_frozen,"threshold_N_spts"],{"choices":[1,10,20,50]}],
[[TogglePanel, "Deice enabled", sample_frozen,"running"],{"type":"Off/Monitoring"}],
[[TogglePanel, "Deicing", sample_frozen,"deicing"],{"type":"Not active/Active"}],
[[PropertyPanel,"ROIX", sample_frozen,"ROIX"],{"choices":[1000,900]}],
[[PropertyPanel,"ROIY", sample_frozen,"ROIY"],{"choices":[1000,900]}],
[[PropertyPanel,"WIDTH", sample_frozen,"WIDTH"],{"choices":[150,300,400]}],
]
def __init__(self,parent=None):
BasePanel.__init__(self,
parent=parent,
name=self.name,
title=self.title,
icon="Tool",
parameters=self.parameters,
standard_view=self.standard_view,
)
if __name__ == '__main__':
from pdb import pm
import logging
from tempfile import gettempdir
logfile = gettempdir()+"/SampleFrozenPanel.log"
logging.basicConfig(level=logging.INFO,
format="%(asctime)s %(levelname)s: %(message)s",
logfile=logfile,
)
# Needed to initialize WX library
if not "app" in globals(): app = wx.App(redirect=False)
panel = SampleFrozenPanel()
app.MainLoop()
<file_sep>counter_name = 'y'
Size = wx.Size(640, 457)
logfile = '/net/mx340hs/data/anfinrud_1511/Logfiles/beamstop-1.log'
average_count = 1
max_value = 174.46
min_value = 174.36
start_fraction = 0.952
reject_outliers = False
outlier_cutoff = 2.5
show_statistics = False
time_window = 21600
<file_sep>#!/usr/bin/env python
"""Control panel for timing system configuration
Author: <NAME>
Date created: 2016-07-14
Date last modified: 2019-03-15
"""
__version__ = "2.0" # Timing_Channel_Configuration_Panel
from logging import debug,info,warn,error
from Panel import BasePanel
class Timing_Channel_Configuration_Panel(BasePanel):
name = "TimingConfiguration"
title = "Channel Configuration"
icon = "timing-system"
update = None
def __init__(self,parent=None,update=None):
if update is not None: self.update = update
if self.update is None:
from Ensemble_SAXS_pp import Ensemble_SAXS
self.update = [Ensemble_SAXS.update]
from timing_system import timing_system
self.object = timing_system
self.standard_view = ["#"]+[str(timing_system.channels[i].channel_number+1)
for i in range(0,len(timing_system.channels))]
import wx
self.layout = [[
"#",
[wx.StaticText,[],{"label":"PP","size":(35,-1)}],
[wx.StaticText,[],{"label":"I/O","size":(50,-1)}],
[wx.StaticText,[],{"label":"Description","size":(140,-1)}],
[wx.StaticText,[],{"label":"Mnemonic","size":(75,-1)}],
[wx.StaticText,[],{"label":"Special\nPP","size":(75,-1)}],
[wx.StaticText,[],{"label":"Special\nHW","size":(70,-1)}],
[wx.StaticText,[],{"label":"Offset\nHW","size":(100,-1)}],
[wx.StaticText,[],{"label":"Offset\nsign","size":(50,-1)}],
[wx.StaticText,[],{"label":"Duration\nHW","size":(75,-1)}],
[wx.StaticText,[],{"label":"Duration\nHW reg","size":(75,-1)}],
[wx.StaticText,[],{"label":"Offset\nPP ticks","size":(70,-1)}],
[wx.StaticText,[],{"label":"Duration\nPP ticks","size":(75,-1)}],
[wx.StaticText,[],{"label":"Cont.","size":(45,-1)}],
[wx.StaticText,[],{"label":"Slaved","size":(72,-1)}],
[wx.StaticText,[],{"label":"Gated","size":(72,-1)}],
[wx.StaticText,[],{"label":"Count\nEnabled","size":(50,-1)}],
[wx.StaticText,[],{"label":"State","size":(60,-1)}],
]]
from Panel import PropertyPanel,TogglePanel
from numpy import inf
self.layout += [[
str(timing_system.channels[i].channel_number+1),
[TogglePanel, [],{"name":"channels[%d].PP_enabled"%i,"type":"/PP","width":35,"refresh_period":inf}],
[PropertyPanel,[],{"name":"channels[%d].input.count"%i,"type":"Out/IN","width":50,"refresh_period":inf}],
[PropertyPanel,[],{"name":"channels[%d].description"%i,"width":140,"refresh_period":inf}],
[PropertyPanel,[],{"name":"channels[%d].mnemonic"%i,"width":75,"refresh_period":inf}],
[PropertyPanel,[],{"name":"channels[%d].special"%i,"width":75,"refresh_period":inf}],
[PropertyPanel,[],{"name":"channels[%d].specout.count"%i,"type":"/70MHz/diag1/diag2","width":70,"refresh_period":inf}],
[PropertyPanel,[],{"name":"channels[%d].offset_HW"%i,"type":"time.6","width":100,"refresh_period":inf}],
[PropertyPanel,[],{"name":"channels[%d].offset_sign"%i,"type":"float","width":50,"refresh_period":inf}],
[PropertyPanel,[],{"name":"channels[%d].pulse_length_HW"%i,"type":"time","width":75,"refresh_period":inf}],
[PropertyPanel,[],{"name":"channels[%d].pulse.value"%i,"type":"time","width":75,"refresh_period":inf}],
[PropertyPanel,[],{"name":"channels[%d].offset_PP"%i,"type":"float","width":70,"refresh_period":inf}],
[PropertyPanel,[],{"name":"channels[%d].pulse_length_PP"%i,"type":"float","width":70,"refresh_period":inf}],
[TogglePanel, [],{"name":"channels[%d].enable.count"%i,"type":"/Cont","width":45,"refresh_period":inf}],
[PropertyPanel,[],{"name":"channels[%d].timed"%i,"width":72,"refresh_period":inf}],
[PropertyPanel,[],{"name":"channels[%d].gated"%i,"width":72,"refresh_period":inf}],
[PropertyPanel,[],{"name":"channels[%d].counter_enabled"%i,"type":"/On","width":50,"refresh_period":inf}],
[PropertyPanel,[],{"name":"channels[%d].output_status"%i,"width":60,"refresh_period":inf}],
] for i in range(0,len(timing_system.channels))]
BasePanel.__init__(self,
parent=parent,
name=self.name,
title=self.title,
icon=self.icon,
object=self.object,
layout=self.layout,
standard_view=self.standard_view,
label_width=25,
refresh=True,
live=True,
update=update,
)
if __name__ == '__main__':
from pdb import pm # for debugging
from redirect import redirect
redirect("Timing_Channel_Configuration_Panel")
import wx
app = wx.App(redirect=False) # to initialize WX...
panel = Timing_Channel_Configuration_Panel()
app.MainLoop()
<file_sep>#!/usr/bin/env python
from timing_sequence import *
<file_sep>"""Author: <NAME>, Oct 21, 2015 - Mar 11, 2016
"""
__version__ = "1.6" # 1/hscf -> timing_system.hsct
from pdb import pm # for debugging
from timing_system import timing_system,ps,ns,us,ms
from timing_sequence import timing_sequencer
from time import sleep,time
from numpy import *
import logging
from tempfile import gettempdir
logging.basicConfig(level=logging.DEBUG,format="%(asctime)s: %(message)s",
filename=gettempdir()+"/lauecollect_debug.log")
timepoints = [
100*ps,178*ps,316*ps,562*ps,
1*ns,1.78*ns,3.16*ns,5.62*ns,
10*ns,17.8*ns,31.6*ns,56.2*ns,
100*ns,178*ns,316*ns,562*ns,
1*us,1.78*us,3.16*us,5.62*us,
10*us,17.8*us,31.6*us,56.2*us,
100*us,178*us,316*us,562*us,
1*ms,1.78*ms,3.16*ms,5.62*ms,
10*ms,17.8*ms,31.6*ms,
32*timing_system.hsct,64*timing_system.hsct,128*timing_system.hsct
]
timepoints=timepoints
laser_mode = [0,1]
npulses = 2
ps_lxd = array([t for t in timepoints for l in laser_mode])
pst_on = array([l for t in timepoints for l in laser_mode])
image_numbers = arange(1,len(ps_lxd)+1)
npulses = [1 if l else 12 for l in pst_on]
waitt = [96*timing_system.hsct if l else 8*timing_system.hsct for l in pst_on]
ms_on = [1 if l else 0 for l in pst_on]
xatt_on = [0 if l else 1 for l in pst_on]
# for debugging
laser_on = delays = lxd = nsq_on = s3_on = None
self = timing_sequencer
##image_numbers = array([62,64,66,68,70])
##ps_lxd = ps_lxd[image_numbers-1]
##laser_ons = laser_ons[image_numbers-1]
##npulses = npulses[image_numbers-1]
def start():
timing_system.image_number.value = 0
timing_system.pass_number.value = 0
timing_system.pulses.value = 0
upload()
def upload():
timing_sequencer.acquire(ps_lxd=ps_lxd,pst_on=pst_on,
npulses=npulses,waitt=waitt,
image_numbers=image_numbers,
ms_on=ms_on,xatt_on=xatt_on)
def test():
while True:
start()
while len(timing_sequencer.queue) > 10: sleep(1)
print("timing_system.ip_address = %r" % timing_system.ip_address)
print("timing_sequencer.cache_enabled = %r" % timing_sequencer.cache_enabled)
print("timing_sequencer.queue_length")
print("timing_sequencer.clear_queue()")
print("timing_sequencer.abort()")
print("timing_sequencer.update()")
print("timing_sequencer.cache_clear()")
print("t=time(); upload(); time()-t")
print("t=time(); start(); time()-t")
print("test()")
<file_sep>#!/usr/bin/env python
"""
Grapical User Interface for FPGA Timing System.
Author: <NAME>
Date created: 2019-03-26
Date last modified: 2019-05-29
"""
__version__ = "1.1" # p0_shift, cleanup
from logging import debug,info,warn,error
import wx
from Panel import BasePanel
class Timing_Calibration_Panel(BasePanel):
name = "Calibration"
title = "Calibration"
icon = "timing-system"
update = None
standard_view = [
"X-ray Scope Trigger",
"Laser to X-ray Delay",
"Ps Laser Oscillator Phase",
"Ps Laser Trigger",
"Laser Scope Trigger",
"High-Speed Chopper Phase",
]
def __init__(self,parent=None,update=None,*args,**kwargs):
if update is not None: self.update = update
if self.update is None:
from Ensemble_SAXS_pp import Ensemble_SAXS
self.update = [Ensemble_SAXS.update]
##from timing_sequence import timing_sequencer
##update=[timing_sequencer.cache_clear,timing_sequencer.update]
from timing_system import timing_system
self.parameters = [
[[timing_system.channels.xosct, "X-ray Scope Trigger", ],{"update": self.update}],
[[timing_system.channels.delay, "Laser to X-ray Delay", ],{"update": self.update}],
[[timing_system.channels.psod3, "Ps Laser Osc. Delay", ],{"update": self.update}],
##[[timing_system.channels.psd1, "Ps Laser Osc. Delay GigaBaudics",],{"update": self.update}],
[[timing_system.channels.pst, "Ps Laser Trigger", ],{"update": self.update}],
[[timing_system.channels.nsq, "Ns Laser Q-Switch Trigger", ],{"update": self.update}],
[[timing_system.channels.nsf, "Ns Laser Flash Lamp Trigger", ],{"update": self.update}],
[[timing_system.channels.losct, "Laser Scope Trigger", ],{"update": self.update}],
[[timing_system.channels.lcam, "Laser Camera Trigger", ],{"update": self.update}],
[[timing_system.hlcnd, "Heatload Chopper Phase", ],{"keep_value": True}],
[[timing_system.hlcad, "Heatload Chop. Act. Phase", ],{"keep_value": True}],
[[timing_system.channels.hsc.delay,"High-Speed Chopper Phase", ],{"update": self.update, "keep_value": True}],
[[timing_system.p0_shift, "P0 Shift", ],{}],
[[timing_system.channels.ms, "X-ray Shutter Delay", ],{"update": self.update}],
[[timing_system.channels.ms, "X-ray Shutter Pulse Length", ],{"update": self.update,"attribute": "pulse_length"}],
[[timing_system.channels.xdet, "X-ray Detector Delay", ],{"update": self.update}],
[[timing_system.channels.xdet, "X-ray Detector Pulse Length", ],{"update": self.update,"attribute": "pulse_length"}],
[[timing_system.channels.trans, "Sample Transl. Delay", ],{"update": self.update}],
[[timing_system.channels.trans, "Sample Transl. Pulse Length", ],{"update": self.update,"attribute": "pulse_length"}],
]
BasePanel.__init__(self,
parent=parent,
name=self.name,
icon=self.icon,
title=self.title,
component=CalibrationControl,
parameters=self.parameters,
standard_view=self.standard_view,
label_width=250,
refresh=False,
live=False,
*args,
**kwargs
)
from Panel import BasePanel
class CalibrationControl(wx.Panel):
"""A component for calibration window"""
from persistent_property import persistent_property
step = persistent_property("step",10e-9)
icon = "timing-system"
def __init__(self,parent,register,title,update=[lambda: None],
pre_update=None,post_update=None,keep_value=False,attribute="offset",
*args,**kwargs):
"""
update: list of procedures to be called after tweeking the offset
pre_update: procedure to be called before tweeking the offset
"""
wx.Panel.__init__(self,parent)
self.title = title
self.register = register
if update is not None: self.update = update
if pre_update is not None: self.pre_update = pre_update
if post_update is not None: self.post_update = post_update
self.keep_value = keep_value
self.attribute = attribute
self.name = "TimingPanel.Calibration."+str(register)
from Icon import SetIcon
SetIcon(self,self.icon)
# Controls
style = wx.TE_PROCESS_ENTER
from EditableControls import TextCtrl
self.Current = TextCtrl(self,size=(155,-1),style=style)
self.Decr = wx.Button(self,label="<",size=(30,-1))
self.Incr = wx.Button(self,label=">",size=(30,-1))
self.Set = wx.Button(self,label="Set...",size=(50,-1))
from numpy import arange,unique
from timing_system import round_next
choices = 10**arange(-11.0,-2.01,1)
dt = self.register.stepsize
choices = [round_next(t,dt) for t in choices]
choices = unique(choices)
choices = choices[choices>0]
from time_string import time_string
choices = [time_string(t) for t in choices]
from EditableControls import ComboBox
self.Step = ComboBox(self,size=(80,-1),choices=choices,style=style,
value=time_string(self.next_step(self.step)))
# Callbacks
self.Bind(wx.EVT_TEXT_ENTER,self.OnChange,self.Current)
self.Bind(wx.EVT_COMBOBOX,self.OnChange,self.Current)
self.Bind(wx.EVT_TEXT_ENTER,self.OnStep,self.Step)
self.Bind(wx.EVT_COMBOBOX,self.OnStep,self.Step)
self.Bind(wx.EVT_BUTTON,self.OnDecr,self.Decr)
self.Bind(wx.EVT_BUTTON,self.OnIncr,self.Incr)
self.Bind(wx.EVT_BUTTON,self.OnSet,self.Set)
# Layout
layout = wx.GridBagSizer(1,1)
layout.SetEmptyCellSize((0,0))
av = wx.ALIGN_CENTRE_VERTICAL
ah = wx.ALIGN_CENTRE_HORIZONTAL
e = wx.EXPAND
t = wx.StaticText(self,label=self.title,size=(110,-1))
t.Wrap(110)
layout.Add (t,(0,0),span=(2,1),flag=av)
layout.Add (self.Decr,(0,2),flag=av)
layout.Add (self.Current,(0,3),flag=av|e)
layout.Add (self.Incr,(0,4),flag=av)
group = wx.BoxSizer(wx.HORIZONTAL)
t = wx.StaticText(self,label="Step")
group.Add (t,flag=av)
group.AddSpacer ((5,5))
group.Add (self.Step,flag=av)
group.AddSpacer ((5,5))
group.Add (self.Set,flag=av)
layout.Add (group,(1,2),span=(1,3),flag=ah)
self.SetSizer(layout)
self.Fit()
self.keep_alive()
def keep_alive(self,event=None):
"""Periodically refresh the displayed settings (every second)."""
self.refresh()
self.timer = wx.Timer(self)
self.Bind (wx.EVT_TIMER,self.keep_alive,self.timer)
self.timer.Start(1000,oneShot=True)
def refresh(self):
from numpy import isnan
value = getattr(self.register,self.attribute)
self.Current.Value = self.format(value,12)+" s" if not isnan(value) else ""
@staticmethod
def format(x,precision=12):
"""Arrage the digits places after the decimal point in groups of three
for easy reading.
t: time in seconds"""
s = "%+.*f" % (precision,x)
i,f = s.split(".")[0],s.split(".")[-1]
s = i+"."+" ".join([f[i:i+3] for i in range(0,len(f),3)])
return s
def OnChange(self,event):
from time_string import seconds
value = seconds(self.Current.Value.replace(" ",""))
self.pre_update()
setattr(self.register,self.attribute,value)
for proc in self.update: proc()
self.refresh()
def OnStep(self,event):
from time_string import time_string,seconds
step = self.next_step(seconds(self.Step.Value))
self.step = step
self.Step.Value = time_string(self.step)
self.refresh()
def OnDecr(self,event):
from time_string import seconds
step = self.next_step(seconds(self.Step.Value))
self.pre_update()
value = getattr(self.register,self.attribute)
value -= step
setattr(self.register,self.attribute,value)
self.post_update()
for proc in self.update: proc()
self.refresh()
def OnIncr(self,event):
from time_string import seconds
step = self.next_step(seconds(self.Step.Value))
self.pre_update()
value = getattr(self.register,self.attribute)
value += step
setattr(self.register,self.attribute,value)
self.post_update()
for proc in self.update: proc()
self.refresh()
def OnSet(self,event):
from time_string import time_string,seconds
from numpy import isnan
dlg = wx.TextEntryDialog(self,"New user value",
"Redefine User Value","")
dlg.Value = time_string(self.register.value)
OK = (dlg.ShowModal() == wx.ID_OK)
if not OK: return
value = seconds(dlg.Value)
if isnan(value): return
setattr(self.register,self.attribute,value - self.register.dial)
##self.register.define_value(value)
self.refresh()
def pre_update(self):
"""Keep the user value constant while tweeking the dial"""
if self.keep_value:
new_value = self.register.value
stepsize = getattr(self.register,"stepsize",0)
if not abs(new_value-self.value) < stepsize:
self.value = new_value
def post_update(self):
"""Keep the user value constant while tweeking the dial"""
from numpy import isnan
if self.keep_value and not isnan(self.value):
self.register.value = self.value
from numpy import nan
value = nan
def next_step(self,step):
"""Closest possible value for the offset increment
step: offset increment in seconds"""
from timing_system import round_next
stepsize = self.register.stepsize
if step > 0.5*stepsize:
step = max(round_next(step,stepsize),stepsize)
return step
if __name__ == '__main__':
from pdb import pm # for debugging
from redirect import redirect
redirect("Timing_Calibration_Panel")
import wx
app = wx.App(redirect=False)
panel = Timing_Calibration_Panel()
app.MainLoop()
<file_sep>"""
A propery object to be used inside a class, it value is kept in a permanent
storage in a file.
Usage example:
class EnsembleSAXS(object):
name = "Ensemble_SAXS"
mode_changed = persistent_property("mode_changed")
<NAME>, Mar 7, 2015 - Jul 6, 2017
"""
from logging import debug,warn,info,error
__version__ = "1.2.2" # eval: -OrderdDict +wx
def persistent_property(name,default_value=0.0):
"""A propery object to be used inside a class"""
def get(self):
class_name = getattr(self,"name",self.__class__.__name__)
if not "{name}" in name:
if class_name: dbname = class_name+"."+name
else: dbname = name
else: dbname = name.replace("{name}",class_name)
##debug("persistent_property.get: %s: %r, %r: %r" % (name,self,class_name,dbname))
from DB import dbget
t = dbget(dbname)
if type(default_value) == str and default_value.startswith("self."):
def_val = getattr(self,default_value[len("self."):])
else: def_val = default_value
dtype = type(def_val)
try: from numpy import nan,inf,array # for "eval"
except: pass
try: import wx # for "eval"
except: pass
try: t = dtype(eval(t))
except: t = def_val
return t
def set(self,value):
class_name = getattr(self,"name",self.__class__.__name__)
if not "{name}" in name:
if class_name: dbname = class_name+"."+name
else: dbname = name
else: dbname = name.replace("{name}",class_name)
##debug("persistent_property.set: %s: %r, %r: %r" % (name,self,class_name,dbname))
from DB import dbput
dbput(dbname,repr(value))
return property(get,set)
<file_sep>"""This script is to test various implementations of the Python to EPICS interface.
It checks wether these are multi-thread safe. That means that a caput and caget
to the same process valiable succeeds both from the forground and from a background
thread.
EpicsCA: <NAME>, U Chicago
epics: <NAME>, U Chicago
CA: <NAME>, NIH
<NAME>, APS, 14 Apr 2010
"""
import sys
sys.path += ["/Femto/C/All Projects/APS/Instrumentation/Software/Python"]
from epics import caget,caput,PV # choices: EpicsCA, epics, CA
from time import sleep
from threading import Thread
def run_test(count=1):
for i in range(0,count):
x = caget("14IDB:m3.VAL")
caput("14IDB:m3.VAL",x+0.001)
print x,caget("14IDB:m3.RBV")
print "Foreground:"
run_test(2)
print "Background:"
thread = Thread(target=run_test,args=(2,))
thread.start()
thread.join()
print 'Done'
<file_sep>description = 'Sample slits horiz. gap'
prefix = '14IDB:m25'
target = 0.15015
EPICS_enabled = True<file_sep>#!/bin/bash
dir=`dirname "$0"`
prog=`basename "$0"`
source "$dir/setup_env.sh"
python "$dir/$prog.py"
<file_sep>#!/bin/env python
"""Extract images from and LCLS datastream an save them in a Lauecollect
directory structure.
Setup: source /reg/g/psdm/etc/ana_env.sh
<NAME>, Jan 25, 2016 - Feb 8, 2016
"""
__version__ = "1.0.2"
from pdb import pm # for debugging
from find import find
from table import table
from sleep import sleep
from os.path import exists,dirname,basename
from shutil import copy2
from datastream import datastream,timestamp,date_time
from numimage import numimage
from logging import error,warn,info,debug
import logging
data_root = "/reg/d/psdm/xpp/xppj1216/ftc/xppopr_xppj1216/Data/MbCO"
# This is how the images are tagged in the datastram.
exp = "exp=xppj1216"
options = ":smd:live:dir=/reg/d/ffb/xpp/xppj1216/xtc"
image_detector = "rayonix:data16"
# Additional detectors to read from the data stream an add to the logfile.
detectors = [
"XppSb2_Ipm:sum", # X-ray pulse intensity at "Strongback 2"
"XppSb3_Ipm:sum", # X-ray pulse intensity at "Strongback 3"
"XppEnds_Ipm0:channel:0", # Laser pulse intensity
"XppEnds_Ipm0:channel:1", # X-ray pulse intensity at sample (scattering foil)
"XPP:TIMETOOL:FLTPOS_PS", # laser to X-ray time delay in ps
"lxt_ttc", # nominal laser to X-ray time delay in s
]
logging.basicConfig(level=logging.INFO, # DEBUG,INFO,WARN,ERROR
format="%(asctime)s: %(levelname)s: %(message)s",
filename=data_root+"/process_datastream.log")
# Find all lauecollect log files in the data directory.
info("Checking log files...")
# Excludes files and directories which are not useful.
exclude = ["*/alignment*","*/trash*","*/backup*","*._*","*/process_datastream*"]
logfiles = find(data_root,name="*.log",exclude=exclude)
info("Found %d logfile(s)." % len(logfiles))
for logfile in logfiles:
# Create a backup copy of the original Lauecollect log file.
backup_file = logfile+".orig"
if not exists(backup_file): copy2(logfile,backup_file)
log = table(backup_file,separator="\t")
log.add_column("run")
log.add_column("image_event_number")
log.add_column("image_event_id",dtype="S160")
log.add_column("image_timestamp",dtype="S60")
log.add_column("image_size")
for j in range(0,12): log.add_column("event_number(%d)"%(j+1))
for j in range(0,12): log.add_column("timestamp(%d)"%(j+1),dtype="S40")
for j in range(0,12): log.add_column("fiducial(%d)"%(j+1))
for d in detectors:
for j in range(0,12): log.add_column(d+"(%d)"%(j+1))
dir = dirname(logfile)
event_number = {}
event_ids = []
for i in range(0,len(log)):
# Find the datastream event_id based on the time stamp
datetime = log["date time"][i]
run = datastream.run(exp+options,timestamp(datetime+"-0800"))
exp_run = "%s:run=%d" % (exp,run)
if not run in event_number:
# What is the event number for the first image in the datastream?
event_number[run] = \
datastream.get_event_number(exp_run+":event=rayonix,0"+options)
# Useful data starts after the first image (which is discarded)
event_number[run] += 1
debug("%r: starting event number %r" % (exp_run,event_number[run]))
log["run"][i] = run
# Put the detector reading for the 12 events leadign up to the next
# image into the log file, using 12 columns per detector.
for j in range(0,12):
event_id = exp_run+":event=%d" % event_number[run]
log["event_number(%d)"%(j+1)][i] = event_number[run]
log["timestamp(%d)"%(j+1)][i] = date_time(datastream.timestamp(event_id+options))
log["fiducial(%d)"%(j+1)][i] = datastream.fiducial(event_id+options)
for d in detectors:
log[d+"(%d)"%(j+1)][i] = datastream.get(event_id+options,d)
event_number[run] += 1
log["image_event_number"][i] = event_number[run]
log["image_timestamp"][i] = date_time(datastream.timestamp(event_id+options))
log["image_event_id"][i] = event_id
image_file = dir+"/xray_images/"+log["file"][i]
# Locate the image in the datastream by its event ID and
# save it as TIFF file by the name specified in the logfile's
# "file" column.
image = datastream.get(event_id+options,image_detector)
if image is not None:
debug("Got image %s from %s" % (basename(image_file),event_id))
log["image_size"][i] = len(image)
##numimage(image).save(image_file)
else: log["image_size"][i] = 0
info("updating %r" % logfile)
log.save(logfile)
<file_sep>#!/bin/bash -l
# Determine the location of the Python module to load from the script pathname.
dir=`dirname "$0"`
path=`cd "$dir/../../../../../.." ; pwd`
exec python "$path/TimingPanel.py" >> ~/Library/Logs/Python.log 2>&1
<file_sep>#!/usr/bin/env python
"""
Archive EPICS process variable via Channel Access
Author: <NAME>
Date created: 2017-10-04
Date last modified: 2018-07-08
"""
__version__ = "1.0.2" # platform-independent pathnames
from logging import debug,info,warn,error
class ChannelArchiver(object):
name = "channel_archiver"
from persistent_property3 import persistent_property
PVs = persistent_property("PVs",[])
__directory__ = persistent_property("directory",".")
monitored_PVs = []
__running__ = False
def get_directory(self):
from normpath3 import normpath
return normpath(self.__directory__)
def set_directory(self,value):
self.__directory__ = value
directory = property(get_directory,set_directory)
def get_running(self):
"""Actively collecting data?"""
return self.__running__
def set_running(self,value):
from thread import start_new_thread
if value:
if not self.__running__: start_new_thread(self.run,())
else: self.__running__ = False
running = property(get_running,set_running)
def run(self):
"""Track the list of monitored process variables"""
from time import sleep
self.__running__ = True
while self.__running__:
self.monitor(self.PVs)
sleep(1)
self.stop_monitoring()
def monitor(self,PVs):
"""Update list of monitored process variables"""
from CA import camonitor,camonitor_clear
for PV in self.monitored_PVs+[]:
if not PV in PVs:
camonitor_clear(PV,self.callback)
self.monitored_PVs.remove(PV)
for PV in PVs:
if not PV in self.monitored_PVs:
camonitor(PV,callback=self.callback)
self.monitored_PVs += [PV]
def stop_monitoring(self):
"""Undo 'monitor'"""
from CA import camonitor_clear
for PV in self.monitored_PVs+[]:
camonitor_clear(PV,self.callback)
self.monitored_PVs.remove(PV)
def callback(self,PV_name,value,char_value):
"""Handle an update fo a process variable"""
##debug("%s = %s" % (PV_name,value))
self.log(PV_name,value)
def log(self,PV_name,value):
"""Archive a value"""
self.logfile(PV_name).log(value)
def logfile(self,PV_name):
"""logfile object"""
from logfile3 import logfile
f = logfile(name=PV_name,columns=["date time","value"],
filename=self.filename(PV_name))
return f
def filename(self,PV_name):
filename = "%s/%s.txt" % (self.directory,PV_name.replace(":","."))
return filename
def history(self,PV_name,start_time,end_time):
"""Retreive values from the archive
PV_name: string, e.g. "NIH:TEMP.RBV"
start_time: seconds since 1970-01-01 00:00:00 UT
end_time: seconds since 1970-01-01 00:00:00 UT
"""
values = self.logfile(PV_name).history("date time","value",
time_range=(start_time,end_time))
return values
channel_archiver = ChannelArchiver()
if __name__ == "__main__": # for testing
from pdb import pm # for debugging
self = channel_archiver # for debugging
import logging
logging.basicConfig(level=logging.DEBUG,
format="%(asctime)s %(levelname)s: %(message)s")
from time import time
print('channel_archiver.PVs = %r' % channel_archiver.PVs)
print('channel_archiver.directory = %r' % channel_archiver.directory)
print('')
print('channel_archiver.PVs = ["NIH:TEMP.RBV","BNCHI:BunchCurrentAI.VAL"]')
print('channel_archiver.running = True')
print('channel_archiver.running = False')
print('self.history("NIH:TEMP.RBV",time()-1,time())')
<file_sep>"""
Support module for LaueCrystallographyControlPanel.py
Serial Laue crystallography application level (AL) module
Author: <NAME>
Date created: Sep 28, 2017
Date last modified: Oct 17, 2017
"""
__version__ = "1.0.4" # X-ray detector
class Laue_Crystallography(object):
"""Serial Laue crystallography"""
from persistent_property import persistent_property
from action_property import action_property
# instumentation
from image_scan import image_scan
from cavro_centris_syringe_pump_IOC import volume,port # volume[0],...,volume[3]
mother_liquor = volume[0]
mother_liquor_dV = persistent_property("mother_liquor_dV",10)
crystal_liquor = volume[2]
crystal_liquor_dV = persistent_property("crystal_liquor_dV",10)
from cavro_centris_syringe_pump import PumpController
pump = p = PumpController()
from cavro_centris_syringe_pump import S_flow,S_load,S_flowIM
from CA import PV
upstream_pressure = PV("NIH:DI245.56671FE403.CH1.pressure")
downstream_pressure = PV("NIH:DI245.56671FE403.CH3.pressure")
from instrumentation import microscope_camera as camera
from instrumentation import DetZ
det_inserted_pos = 185.8
det_retracted_pos = 485.8
def get_det_inserted(self):
from numpy import isnan,nan
value = abs(self.DetZ.value-self.det_inserted_pos) < 0.001\
if not isnan(self.DetZ.value) else nan
return value
def set_det_inserted(self,value):
if value: self.DetZ.command_value = self.det_inserted_pos
else: self.DetZ.moving = False
det_inserted = property(get_det_inserted,set_det_inserted)
def get_det_retracted(self):
from numpy import isnan,nan
value = abs(self.DetZ.value-self.det_retracted_pos) < 0.001\
if not isnan(self.DetZ.value) else nan
return value
def set_det_retracted(self,value):
if value: self.DetZ.command_value = self.det_retracted_pos
else: self.DetZ.moving = False
det_retracted = property(get_det_retracted,set_det_retracted)
def get_stage_enabled(self):
from instrumentation import SampleX,SampleY,SampleZ
return SampleX.enabled * SampleY.enabled * SampleZ.enabled
def set_stage_enabled(self,value):
from instrumentation import SampleX,SampleY,SampleZ
SampleX.enabled,SampleY.enabled,SampleZ.enabled = True,True,True
stage_enabled = property(get_stage_enabled,get_stage_enabled)
@property
def stage_online(self):
from instrumentation import ensemble
return ensemble.connected
def get_centered(self):
return self.image_scan.position == self.image_scan.center
def set_centered(self,value):
if value: self.image_scan.position = self.image_scan.center
centered = property(get_centered,set_centered)
def define_center(self):
self.image_scan.center = self.image_scan.position
inserted = centered
@property
def retracted_position(self):
x,y,z = self.image_scan.center
return x,y+11,z
def get_retracted(self):
return self.image_scan.position == self.retracted_position
def set_retracted(self,value):
if value: self.image_scan.position = self.retracted_position
retracted = property(get_retracted,set_retracted)
scanning = action_property("self.image_scan.acquire()",
stop="self.image_scan.cancelled = True")
@property
def crystal_coordinates(self):
"""X,Y,Z in mm as formatted text"""
XYZ = self.image_scan.crystal_XYZ
lines = "\n".join(["%+.3f,%+.3f,%+.3f" % tuple(xyz) for xyz in XYZ.T])
return lines
@property
def pump_online(self):
from numpy import isnan
return not isnan(self.volume[0].value)
def init(self):
"""Home all motors"""
self.p.init()
def get_flowing(self):
return self.mother_liquor.moving and \
self.mother_liquor.speed == self.S_flow
def set_flowing(self,value):
if value: self.p.flow()
else: self.p.abort()
flowing = property(get_flowing,set_flowing)
def inject(self):
"""Load crystals"""
self.inject_count += 1
self.p.inject()
inject_count = persistent_property("inject_count",0)
def get_injecting(self):
return self.mother_liquor.moving \
and self.mother_liquor.speed == self.S_flowIM
def set_injecting(self,value):
if value:
self.inject_count += 1
self.p.inject()
else: self.p.abort()
injecting = property(get_injecting,set_injecting)
def get_mother_liquor_refilling(self):
return self.mother_liquor.moving \
and self.mother_liquor.speed == self.S_load
def set_mother_liquor_refilling(self,value):
if value: self.p.refill_1()
else: self.p.abort()
mother_liquor_refilling = property(get_mother_liquor_refilling,
set_mother_liquor_refilling)
def get_crystal_liquor_refilling(self):
return self.crystal_liquor.moving \
and self.crystal_liquor.speed == self.S_load
def set_crystal_liquor_refilling(self,value):
if value:
self.inject_count = 0
self.p.refill_3()
else: self.p.abort()
crystal_liquor_refilling = property(get_crystal_liquor_refilling,
set_crystal_liquor_refilling)
image_rootname = persistent_property("image_rootname","")
def save_image(self):
"""Record photo"""
from os.path import dirname
directory = dirname(self.image_scan.directory)
filename = "%s/%s.jpg" % (directory,self.image_rootname)
self.camera.save_image(filename)
Laue_crystallography = Laue_Crystallography()
control = Laue_crystallography
if __name__ == "__main__": # for debugging
from pdb import pm
self = Laue_crystallography # for debugging
import logging
logging.basicConfig(level=logging.INFO,
format="%(asctime)s %(levelname)s: %(message)s")
##print('control.scanning = True')
##print('control.scanning = False')
<file_sep>"""
Author: <NAME>
Date created: 2019-05-29
Date last modified: 2019-05-30
"""
__version__ = "1.0"
from configuration import configuration
from time import sleep
conf = configuration("Julich_chopper_modes")
descriptions = conf.descriptions
X = conf.positions[0]
Y = conf.positions[1]
Phi = conf.positions[2]
S_1 = descriptions.index("S-1")
def update():
new_Y = Y[:]
new_Phi = Phi[:]
for N in range(3,25+1):
if "S-%d" % N in descriptions:
row = descriptions.index("S-%d" % N)
new_Y[row] = Y[S_1] - N*0.0377+0.035
new_Phi[row] = Phi[S_1] + N*2.744e-9
Y[:] = new_Y
Phi[:] = new_Phi
new_X = X[:]
for row in range(0,len(X)):
if descriptions[row] != "Bypass":
new_X[row] = X[S_1]
X[:] = new_X
print("update()")
<file_sep>#!/usr/bin/env python
"""Needed for wxPython 4.0 for backward compatibility 3.0
Author: <NAME>
Date created: 2018-03-09
Date last modified: 2018-03-21
"""
__version__ = "1.0"
import wx
# When trying to access a closed window object 3.0 raised a PyDeadObjectError
# exception. 4.0 raises RuntimeError instead.
if not hasattr(wx,"PyDeadObjectError"): wx.PyDeadObjectError = RuntimeError
# wximage = wx.EmptyImage(self.ImageWidth,self.ImageHeight)
# "Call to deprecated item EmptyImage. Use class wx.Image instead."
if wx.__version__.startswith("4"): wx.EmptyImage = wx.Image
# "Call to deprecated item BitmapFromImage. Use class wx.Bitmap instead."
if wx.__version__.startswith("4"): wx.BitmapFromImage = wx.Bitmap
# self.SetCursor(wx.StockCursor(wx.CURSOR_SIZING))
# "wxPyDeprecationWarning: Using deprecated class. Use Cursor instead."
if wx.__version__.startswith("4"): wx.StockCursor = wx.Cursor
# self.Bind(wx.grid.EVT_GRID_CELL_CHANGE,self.apply)
# AttributeError: 'module' object has no attribute 'EVT_GRID_CELL_CHANGE'
import wx.grid
if not hasattr(wx.grid,"EVT_GRID_CELL_CHANGE"):
wx.grid.EVT_GRID_CELL_CHANGE = wx.grid.EVT_GRID_CELL_CHANGED
# buttons.AddSpacer((5,5))
# TypeError: BoxSizer.AddSpacer(): argument 1 has unexpected type 'tuple'
if wx.__version__.startswith("4"):
wx.BoxSizer.AddSpacer_v4 = wx.BoxSizer.AddSpacer
def AddSpacer(self,size,*args,**kwargs):
if type(size) == tuple: size = size[0]
return wx.BoxSizer.AddSpacer_v4(self,size,*args,**kwargs)
wx.BoxSizer.AddSpacer = AddSpacer
# ComboBox(self,style=wx.CB_DROPDOWN|wx.PROCESS_ENTER)
# AttributeError: 'module' object has no attribute 'PROCESS_ENTER'
if not hasattr(wx,"PROCESS_ENTER"): wx.PROCESS_ENTER = wx.TE_PROCESS_ENTER
# dlg = wx.FileDialog(self,"Load Settings",style=wx.OPEN,
# AttributeError: 'module' object has no attribute 'OPEN'
if not hasattr(wx,"OPEN"): wx.OPEN = wx.FD_OPEN
# wx.FileDialog(self,"Save Settings As",
# style=wx.SAVE|wx.OVERWRITE_PROMPT,
# AttributeError: 'module' object has no attribute 'OVERWRITE_PROMPT'
if not hasattr(wx,"SAVE"): wx.SAVE = wx.FD_SAVE
if not hasattr(wx,"OVERWRITE_PROMPT"): wx.OVERWRITE_PROMPT = wx.FD_OVERWRITE_PROMPT
# event.Checked()
# AttributeError: 'CommandEvent' object has no attribute 'Checked'
if not hasattr(wx.CommandEvent,"Checked"):
def Checked(self): return wx.CommandEvent.IsChecked(self)
wx.CommandEvent.Checked = Checked
<file_sep>#! /usr/bin/env ipython
#-nobanner
"""<NAME>, 25 Nov 2013 """
__version__ = 1.0
import virtualmotor
import motor_newport
# make dummy object that holds motors
class Motors(object):
pass
xppmotors = Motors()
#import xppmotors
#xppmotors = xppmotors.XppMotors()
# initialize newport controller
xpsL2=motor_newport.XPS("xpp-las2")
# initialize delay stage
newportL2_8=motor_newport.Motor(xpsL2,8)
# add motor object
virtualmotor.VirtualMotor(xppmotors,"las_tt_delay",newportL2_8.move_and_wait,newportL2_8.get_position,newportL2_8.wait,pvpos="XPP:USER:LAS:TT_DELAY_POS",pvoff="XPP:USER:LAS:TT_DELAY_OFF",backlash_dist=.2)
# laser stuff, delay etc.
import lasersystem
xpplaser=lasersystem.LaserSystem(system=3,beamline="xpp")
# laser delay macros
import laserdelaystage_new as laserdelaystage
xppTTdelay = laserdelaystage.DelayStage2time("ttDelay",xppmotors.las_tt_delay,direction=-1)
# make time delay motor, NB: this one does the lowgain high gain stuff if you like to use it
virtualmotor.VirtualMotor(xppmotors,"lxt",xpplaser.move_delay,xpplaser.get_delay,set=xpplaser.set_delay,tolerance=30e-15,wait=xpplaser.wait)
# motor object that moves time tool stage in seconds
virtualmotor.VirtualMotor(xppmotors,"txt",xppTTdelay.mv,xppTTdelay.wm,set=xppTTdelay.set,wait=xppTTdelay.wait)
# make the compensating motor
lxt_compensate = laserdelaystage.timeStageSeries_Compensate('lxt_ttc',xppmotors.lxt,xppmotors.txt)
virtualmotor.VirtualMotor(xppmotors,"lxt_ttc",lxt_compensate.mv,lxt_compensate.wm,wait=lxt_compensate.wait)
# that's it!
<file_sep>"""
Remote control of LeCroy X-Stream series oscilloscopes using Microsoft's
COM protocol (Common Object Model).
This script runs only on a Windows machine with LeCroy XStream Software
installed.
Example:
X.Measure.P1.GateStart = 0.95
sets the low limit of the gate of measurement P1 to 0.95 divisions.
print X.Measure.P1.last.Result.Value
reads the current value of measurement P1
Setup required:
On the oscilloscope PC, in the Windows Firewall, an exception must by defined
for Microsoft RPC, TCP port 135 and the Oscilloscope application
(C:/Program Files/lecroy/xstream/lecroyxstreamdso.exe).
python needs to run under the same user account on the local PC as the
oscilloscope application on the oscilloscope PC, e.g. 'Femtoland'.
<NAME>, NIH 28 Mar 2008
"""
import pythoncom,win32com.client #need to install pywin32
from time import time # for performance testing
# This works on oscilloscope PC itself.
X = win32com.client.Dispatch("LeCroy.XStreamDSO")
# Intended for remote control. XStream software needs to be installed
# on the local (client) machine, too. Otherwise it fails.
#X = win32com.client.DispatchEx("LeCroy.XStreamDSO",
# machine="femto10") #,userName="Femtoland")
t = time()
num = X.Measure.P1.num.Result.Value
dt = time()-t
print "num(P1)=%g (time: %.3f s)" % (num,dt)
<file_sep>#!/bin/bash
dir=`dirname "$0"`
# Uncomment the appropriate line below.
source "$dir/setup_env_id14.sh"
##source "$dir/setup_env_XPP.sh"
<file_sep>counter_name = 'y'
Size = wx.Size(640, 480)
logfile = '/Mirror/Femto/C/All Projects/APS/Experiments/2014.11/Logfiles/Beamstop-test-5.log'
average_count = 1
max_value = nan
min_value = nan
start_fraction = 0.997
reject_outliers = False
outlier_cutoff = 2.5
show_statistics = True
time_window = 600
<file_sep>#!/usr/bin/env python
"""An extension of the CameraViewer with controls for positioning the sample
Author: <NAME>,
Date created: 2010-07-22
Date last modified: 2019-03-25
"""
__version__ = "4.2" # Alignment_Panel_Shown setting
import wx
from CameraViewer import CameraViewer
from EditableControls import ComboBox,TextCtrl
from logging import debug,info,warn,error
deg = u"\xB0" # Unicode character for degree sign
class SampleAlignmentViewer(CameraViewer):
__version__ = __version__
__doc__ = __doc__
from setting import setting
Illumination_Panel_Shown = setting("Illumination_Panel_Shown",True)
Alignment_Panel_Shown = setting("Alignment_Panel_Shown",False)
settings = CameraViewer.settings + [
"show_edge_controls",
"stepsize",
"camera_angle",
"x_scale",
"y_scale",
"z_scale",
"phi_stepsize",
"learn_center",
"click_center_enabled",
]
sample_settings = [
"x_motor_name","y_motor_name","z_motor_name","phi_motor_name",
"xy_rotating",
"rotation_center","calibration_z",
"samples","sample_r",
"support_points","GridOffset","GridSpacing",
"click_center_x","click_center_y","click_center_z",
"current_center_x","current_center_y",
"learn_center_history",
"show_mark_sample_controls","mark_sample_function",
"keep_centered",
]
def __init__(self,camera_angle=0.0,**kwargs):
"""
camera_angle: [default value] phi angle at which Y translation is orthogonal
to the camera viewing direction.
"""
# Defaults
self.stepsize = 0.01 # horiz. and vert. translation increment in mm
self.camera_angle = camera_angle # viewing angle of camera with respect
# to x translation at phi=0 in units of deg
self.phi_stepsize = 90.0
self.x_scale = -1 # X+ = up at camera-angle + 90 deg?
self.y_scale = 1 # Y+ = up at camera_angle?
self.z_scale = -1 # Z+ = right?
self.keep_centered = False
self.x_motor_name = "SampleX"
self.y_motor_name = "SampleY"
self.z_motor_name = "SampleZ"
self.phi_motor_name = "SamplePhi"
self.xy_rotating = True
# To which (X,Y) do you have to drive the motors for the rotation axis
# to be on the crosshair?
self.rotation_center = 0.0,0.0
# To get reproducible positioning of objects mouned on the magnetic
# based after disasambling and reassembing the the diffractmeter.
# As part of recalibrating the rotation axis a reference z position
# is defined by the fiber tip of te alignment needle.
# After the the saved coordinates of of other objects should be valid.
self.calibration_z = 0.0
self.click_center_x = 0.0 # Sample center, for "Return to Center"
self.click_center_y = 0.0 # Sample center, for "Return to Center"
self.click_center_z = 0.0 # Sample center, for "Return to Center"
self.current_center_x = 0.0
self.current_center_y = 0.0
self.learn_center = False # Currently calibrating rotation axis?
self.learn_center_history = []
self.samples = [] # Marked positions of crystals
self.current_sample = None
self.current_sample_point = "start"
self.sample_r = 0.0 # Radius of the sample (idealized as cylinder)
self.support_points = [] # outline of the crystal for Lauecollect
self.GridOffset = 0.0
CameraViewer.__init__(self,**kwargs)
# Menus
menuBar = self.GetMenuBar()
menu = menuBar.GetMenu(3) # 'Options' menu
menu.Append(402,"&Alignment Setup...","Parameters for sample alignment")
self.Bind(wx.EVT_MENU,self.OnAlignmentSetup,id=402)
menu.Append(407,"&Center...","Sample Centering")
self.Bind(wx.EVT_MENU,self.OnCenter,id=407)
menu.AppendSeparator()
menu.Append(409,"&Show Illumination Controls","Extra controls below image",
wx.ITEM_CHECK)
self.ShowIlluminationControlsMenuItem = menu.FindItemById(409)
self.ShowIlluminationControlsMenuItem.Check(self.Illumination_Panel_Shown)
self.Bind(wx.EVT_MENU,self.OnShowIlluminationControls,id=409)
menu.Append(403,"&Show Alignment Controls","Extra controls below image",
wx.ITEM_CHECK)
self.ShowAlignmentControlsMenuItem = menu.FindItemById(403)
self.ShowAlignmentControlsMenuItem.Check(self.Alignment_Panel_Shown)
self.Bind(wx.EVT_MENU,self.OnShowAlignmentControls,id=403)
menu.Append(404,"&Show Edge Controls","Extra controls below image",
wx.ITEM_CHECK)
self.ShowEdgeControlsMenuItem = menu.FindItemById(404)
self.Bind(wx.EVT_MENU,self.OnShowEdgeControls,id=404)
menu.Append(408,"&Show Mark Sample Controls","Extra controls below image",
wx.ITEM_CHECK)
self.ShowMarkSampleMenuItem = menu.FindItemById(408)
self.Bind(wx.EVT_MENU,self.OnShowMarkSample,id=408)
menu.AppendSeparator()
menu.Append(405,"&Calibrate Rotation...",
"Find the rotation center of the Phi axis")
self.Bind(wx.EVT_MENU,self.OnCalibrateRotation,id=405)
menu.Append(406,"&Sample Center...",
"Define Rotation Center of an Object")
self.Bind(wx.EVT_MENU,self.OnSampleCenter,id=406)
self.Illumination_Panel = Illumination_Panel(self.panel)
self.layout.AddSpacer(5)
self.layout.Add (self.Illumination_Panel,flag=wx.EXPAND)
self.Illumination_Panel.Shown = self.Illumination_Panel_Shown
# Alignment Panel
# Controls
panel = self.Alignment_Panel = wx.Panel(self.panel)
style = wx.TE_PROCESS_ENTER
choices = ["500 um","200 um","100 um","50 um","20 um","10 um","5 um",
"2 um","1 um"]
self.StepSize = ComboBox (panel,style=style,choices=choices,
size=(80,-1))
self.Bind (wx.EVT_COMBOBOX,self.OnStepSize,self.StepSize)
self.Bind (wx.EVT_TEXT_ENTER,self.OnStepSize,self.StepSize)
left = wx.ArtProvider.GetBitmap(wx.ART_GO_BACK)
right = wx.ArtProvider.GetBitmap(wx.ART_GO_FORWARD)
up = wx.ArtProvider.GetBitmap(wx.ART_GO_UP)
down = wx.ArtProvider.GetBitmap(wx.ART_GO_DOWN)
self.TranslateFromCamera = wx.BitmapButton(panel,bitmap=left)
self.TranslateFromCamera.ToolTip = wx.ToolTip("Move away from camera")
self.Bind (wx.EVT_BUTTON,self.OnTranslateFromCamera,self.TranslateFromCamera)
self.TranslateTowardCamera = wx.BitmapButton(panel,bitmap=right)
self.TranslateTowardCamera.ToolTip = wx.ToolTip("Move closer to camera")
self.Bind (wx.EVT_BUTTON,self.OnTranslateTowardCamera,self.TranslateTowardCamera)
self.TranslateHLeft = wx.BitmapButton(panel,bitmap=left)
self.Bind (wx.EVT_BUTTON,self.OnTranslateHLeft,self.TranslateHLeft)
self.TranslateHRight = wx.BitmapButton(panel,bitmap=right)
self.Bind (wx.EVT_BUTTON,self.OnTranslateHRight,self.TranslateHRight)
self.TranslateVUp = wx.BitmapButton(panel,bitmap=up)
self.Bind(wx.EVT_BUTTON,self.OnTranslateVUp,self.TranslateVUp)
self.TranslateVDown = wx.BitmapButton (panel,bitmap=down)
self.Bind(wx.EVT_BUTTON,self.OnTranslateVDown,self.TranslateVDown)
self.Phi = TextCtrl(panel,size=(70,-1),style=style)
self.Bind(wx.EVT_TEXT_ENTER,self.OnEnterPhi,self.Phi)
choices = ["180"+deg,"90"+deg,"45"+deg,"30"+deg,"10"+deg,"5"+deg,"1"+deg]
self.PhiStepSize = ComboBox (panel,style=style,choices=choices,
size=(65,-1))
self.Bind (wx.EVT_COMBOBOX,self.OnPhiStepSize,self.PhiStepSize)
self.Bind (wx.EVT_TEXT_ENTER,self.OnPhiStepSize,self.PhiStepSize)
self.IncrPhi = wx.BitmapButton (panel,bitmap=up,size=(40,-1))
self.Bind (wx.EVT_BUTTON,self.OnIncrPhi,self.IncrPhi)
self.DecrPhi = wx.BitmapButton (panel,bitmap=down,size=(40,-1))
self.Bind (wx.EVT_BUTTON,self.OnDecrPhi,self.DecrPhi)
self.ClickCenteringButton = wx.ToggleButton(panel,
label="Click Centering: Active")
self.Bind (wx.EVT_TOGGLEBUTTON,self.OnClickCenteringButton,
self.ClickCenteringButton)
self.ClickCenteringButton.ToolTip = wx.ToolTip("When clicking in the "
"image, translate clicked point to crosshair")
self.KeepCentered = wx.CheckBox(panel,label="Keep centered")
self.Bind (wx.EVT_CHECKBOX,self.OnKeepCentered,self.KeepCentered)
self.LearnCenter = wx.CheckBox(panel,label="Learn center")
self.Bind (wx.EVT_CHECKBOX,self.OnLearnCenter,self.LearnCenter)
self.ReturnButton = wx.Button(panel,label="Return to Center")
self.Bind (wx.EVT_BUTTON,self.OnReturnButton,self.ReturnButton)
# Layout
grid = wx.GridBagSizer (hgap=0,vgap=0)
label = wx.StaticText(self.Alignment_Panel,label="Step:")
grid.Add (label,(1,0),flag=wx.ALIGN_LEFT|wx.ALIGN_CENTER_VERTICAL)
grid.Add (self.StepSize,(1,1),flag=wx.ALIGN_CENTER)
label = wx.StaticText(self.Alignment_Panel,label="Focus:")
grid.Add (label,(2,0),flag=wx.ALIGN_LEFT|wx.ALIGN_CENTER_VERTICAL)
hbox = wx.BoxSizer(wx.HORIZONTAL)
hbox.Add (self.TranslateFromCamera,flag=wx.ALIGN_CENTER)
hbox.Add (self.TranslateTowardCamera,flag=wx.ALIGN_CENTER)
grid.Add (hbox,(2,1),flag=wx.ALIGN_LEFT|wx.ALIGN_CENTER_VERTICAL)
grid.Add (self.TranslateHLeft,(1,0+3),flag=wx.ALIGN_CENTER)
grid.Add (self.TranslateHRight,(1,2+3),flag=wx.ALIGN_CENTER)
grid.Add (self.TranslateVUp,(0,1+3),flag=wx.ALIGN_CENTER)
grid.Add (self.TranslateVDown,(2,1+3),flag=wx.ALIGN_CENTER)
label = wx.StaticText(self.Alignment_Panel,label="Phi:")
grid.Add (label,(1,4+3),flag=wx.ALIGN_CENTER)
grid.Add (self.IncrPhi,(0,5+3),flag=wx.ALIGN_CENTER)
grid.Add (self.Phi,(1,5+3),flag=wx.ALIGN_CENTER)
grid.Add (self.DecrPhi,(2,5+3),flag=wx.ALIGN_CENTER)
label = wx.StaticText(self.Alignment_Panel,label="Step:")
grid.Add (label,(1,7+3),flag=wx.ALIGN_CENTER_VERTICAL)
grid.Add (self.PhiStepSize,(1,8+3),flag=wx.ALIGN_CENTER)
grid.Add (self.ClickCenteringButton,(0,10+3),span=(1,2),flag=wx.ALIGN_CENTER|wx.EXPAND)
grid.Add (self.KeepCentered,(1,10+3),flag=wx.ALIGN_CENTER|wx.EXPAND)
grid.Add (self.LearnCenter,(1,11+3),flag=wx.ALIGN_CENTER|wx.EXPAND)
grid.Add (self.ReturnButton,(2,10+3),span=(1,2),flag=wx.ALIGN_CENTER|wx.EXPAND)
self.Alignment_Panel.SetSizer(grid)
self.layout.AddSpacer(5)
self.layout.Add (self.Alignment_Panel,flag=wx.EXPAND)
self.Alignment_Panel.Shown = self.Alignment_Panel_Shown
# Controls - Edge Panel
panel = self.edge_panel = wx.Panel(self.panel)
self.DefineEdgeButton = wx.ToggleButton(panel,label="Define Edge",
size=(-1,-1))
self.Bind (wx.EVT_TOGGLEBUTTON,self.OnDefineEdgeButton,
self.DefineEdgeButton)
self.UndoButton = wx.Button(panel,label="Undo",size=(50,-1))
self.Bind (wx.EVT_BUTTON,self.OnUndoButton,self.UndoButton)
self.ClearButton = wx.Button(panel,label="Clear All")
self.Bind (wx.EVT_BUTTON,self.OnClearButton,self.ClearButton)
self.ShowGridControl = wx.CheckBox (panel,label="Grid")
self.Bind (wx.EVT_CHECKBOX,self.OnShowGrid,self.ShowGridControl)
self.ShiftGridLeft = wx.BitmapButton (panel,bitmap=left)
self.Bind (wx.EVT_BUTTON,self.OnShiftGridLeft,self.ShiftGridLeft)
self.ShiftGridRight = wx.BitmapButton (panel,bitmap=right)
self.Bind (wx.EVT_BUTTON,self.OnShiftGridRight,self.ShiftGridRight)
choices = ["200 um","150 um","120 um","100 um","80 um"]
self.GridSpacingControl = ComboBox (panel,style=style,choices=choices,
size=(80,-1))
self.Bind (wx.EVT_COMBOBOX,self.OnGridSpacing,self.GridSpacingControl)
self.Bind (wx.EVT_TEXT_ENTER,self.OnGridSpacing,self.GridSpacingControl)
# Controls - Center Panel
panel = self.center_panel = wx.Panel(self.panel)
self.MarkSampleButton = wx.ToggleButton(panel,label="Mark",
size=(-1,-1))
self.MarkSampleDeleteButton = wx.ToggleButton(panel,label="Delete",
size=(-1,-1))
self.MarkSampleWidthButton = wx.ToggleButton(panel,label="Width",
size=(-1,-1))
self.Bind (wx.EVT_TOGGLEBUTTON,self.OnMarkSampleFunction,
self.MarkSampleButton)
self.Bind (wx.EVT_TOGGLEBUTTON,self.OnMarkSampleFunction,
self.MarkSampleDeleteButton)
self.Bind (wx.EVT_TOGGLEBUTTON,self.OnMarkSampleFunction,
self.MarkSampleWidthButton)
self.MarkSampleClearButton = wx.Button(panel,label="Clear All")
self.Bind (wx.EVT_BUTTON,self.OnMarkSampleClear,self.MarkSampleClearButton)
# Layout - Edge Panel
self.layout.AddSpacer(5)
hbox = wx.BoxSizer(wx.HORIZONTAL)
grid = wx.GridBagSizer (hgap=0,vgap=0)
grid.Add (self.DefineEdgeButton,(0,0),flag=wx.ALIGN_CENTER)
grid.Add (self.UndoButton,(0,1),flag=wx.ALIGN_CENTER)
grid.Add (self.ClearButton,(0,2),flag=wx.ALIGN_CENTER)
grid.Add (self.ShowGridControl,(0,4),flag=wx.ALIGN_CENTER)
label = wx.StaticText(self.edge_panel,label="Spacing:")
grid.Add (label,(0,6),flag=wx.ALIGN_CENTER_VERTICAL)
grid.Add (self.GridSpacingControl,(0,7),flag=wx.ALIGN_CENTER)
label = wx.StaticText(self.edge_panel,label="Shift")
grid.Add (label,(0,9),flag=wx.ALIGN_CENTER_VERTICAL)
grid.Add (self.ShiftGridLeft,(0,11),flag=wx.ALIGN_CENTER)
grid.Add (self.ShiftGridRight,(0,12),flag=wx.ALIGN_CENTER)
hbox.Add (grid,flag=wx.ALIGN_CENTER)
self.edge_panel.SetSizer(hbox)
self.layout.Add (self.edge_panel,flag=wx.EXPAND)
# Layout - Center Panel
self.layout.AddSpacer(5)
hbox = wx.BoxSizer(wx.HORIZONTAL)
grid = wx.GridBagSizer (hgap=0,vgap=0)
grid.Add (self.MarkSampleButton,(0,0),flag=wx.ALIGN_CENTER)
grid.Add (self.MarkSampleDeleteButton,(0,1),flag=wx.ALIGN_CENTER)
grid.Add (self.MarkSampleWidthButton,(0,2),flag=wx.ALIGN_CENTER)
grid.Add (self.MarkSampleClearButton,(0,3),flag=wx.ALIGN_CENTER)
hbox.Add (grid,flag=wx.ALIGN_CENTER)
self.center_panel.SetSizer(hbox)
self.layout.Add (self.center_panel,flag=wx.EXPAND)
self.layout.Layout()
# Initialization
self.edited = (255,255,220)
self.ClickCenteringButton.DefaultForegroundColour = \
self.ClickCenteringButton.ForegroundColour
self.ClickCenteringButton.DefaultBackgroundColour = \
self.ClickCenteringButton.BackgroundColour
self.DefineEdgeButton.DefaultForegroundColour = \
self.DefineEdgeButton.ForegroundColour
self.DefineEdgeButton.DefaultBackgroundColour = \
self.DefineEdgeButton.BackgroundColour
self.AddPointerFunction("Click-Center")
self.AddPointerFunction("Define Edge")
self.AddPointerFunction("Mark Sample")
self.stepsize_value = self.stepsize
self.PhiStepSize.Value = "%g%s" % (self.phi_stepsize,deg)
self.update_sample_settings()
self.update()
def get_show_edge_controls(self):
"""Is the control panel visible?"""
return self.edge_panel.Shown
def set_show_edge_controls(self,value):
self.ShowEdgeControlsMenuItem.Check(value)
self.edge_panel.Shown = value
self.layout.Layout()
show_edge_controls = \
property(get_show_edge_controls,set_show_edge_controls)
def get_show_mark_sample_controls(self):
"""Is the control panel visible?"""
return self.center_panel.Shown
def set_show_mark_sample_controls(self,value):
self.ShowMarkSampleMenuItem.Check(value)
self.center_panel.Shown = value
self.layout.Layout()
show_mark_sample_controls = \
property(get_show_mark_sample_controls,set_show_mark_sample_controls)
def update(self,event=None):
"""Update the annotations on the camera image"""
from numpy import any,isnan,array,arange,concatenate
# Update the "Grid" check box.
self.ShowGridControl.Value = self.ShowGrid
# Update the spacing indicator/control.
self.GridSpacingControl.Value = "%.0f um" % (self.GridXSpacing*1000)
# Show click center.
cx,cy = self.sample_center_camera_xy
self.AddObject("Click Center",[(cx,cy)],color=(0,255,0),type="squares")
# Mark the sample position.
for i in range(0,len(self.samples)):
sample = self.samples[i]
points = []
points += [self.sample_camera_xy(*sample["start"])]
points += [self.sample_camera_xy(*sample["end"])]
self.AddObject("Sample %d End Points" % (i+1),points,color=(0,255,255),type="squares")
if len(points) > 1:
self.AddObject("Sample %d Center Line" % (i+1),points,color=(0,0,255),type="line")
# Outline the sample shape.
x1,y1 = self.sample_camera_xy(*sample["start"])
x2,y2 = self.sample_camera_xy(*sample["end"])
r = self.sample_r
points = [[x1,y1-r],[x1,y1+r],[x2,y2+r],[x2,y2-r],[x1,y1-r]]
self.AddObject("Sample %d Outline" % (i+1),points,color=(128,128,255),type="line")
# To do: AddObjects - Add mutiple objects wth a single refresh
for i in range(len(self.samples),20):
self.DeleteObject("Sample %d End Points" % (i+1))
self.DeleteObject("Sample %d Center Line" % (i+1))
self.DeleteObject("Sample %d Outline" % (i+1))
# Outline the sample shape.
dz = self.GridXSpacing
if len(self.support_points) > 0:
z1,z2 = self.z_range()[0]-dz/2,self.z_range()[1]+dz/2
Z = concatenate((arange(z1,z2,0.02),[z2]))
phi = self.phi - self.camera_angle
OFFSET = array([self.interpolated_offset(phi,z) for z in Z])
points = [self.camera_position(z,o) for z,o in zip(Z,OFFSET)]
# Shift the points, following the same translation.
cy = self.sample_center_offset
points = [(x,y+cy) for (x,y) in points]
else: points = []
self.AddObject("Edge",points,color=(0,0,255),type="line")
# Show the support points.
points = []
dphi = max(getattr(self.phi_motor,"readback_slop",0),1.0)
for phi,x,y,z,offset in self.support_points:
if abs(phi % 360 - (self.phi - self.camera_angle) % 360) < dphi:
points += [self.camera_position(z,offset)]
# Shift the points, following the same translation.
cy = self.sample_center_offset
points = [(x,y+cy) for (x,y) in points]
self.AddObject("Edge Points",points,color=(0,255,255),type="squares")
# Update vertical grid lines.
offset = (self.z * self.z_scale + self.GridOffset) % self.GridXSpacing
if not isnan(offset): self.GridXOffset = offset
# Show rotation axis.
offset = self.rotation_axis_offset
p1 = self.camera_position(-10,offset)
p2 = self.camera_position(10,offset)
self.AddObject("Rotation axis",[p1,p2],color=(128,128,255),type="line")
# Update controls
self.TranslateFromCamera.Enabled = not isnan(self.zc)
self.TranslateTowardCamera.Enabled = not isnan(self.zc)
self.TranslateHLeft.Enabled = not isnan(self.xc)
self.TranslateHRight.Enabled = not isnan(self.xc)
self.TranslateVUp.Enabled = not isnan(self.yc)
self.TranslateVDown.Enabled = not isnan(self.yc)
self.Phi.Value = "%.3f%s" % (self.phi,deg) if not isnan(self.phi) else ""
self.stepsize_value = self.stepsize
self.PhiStepSize.Value = "%g%s" % (self.phi_stepsize,deg)
self.Phi.Enabled = not isnan(self.phi)
self.PhiStepSize.Enabled = not isnan(self.phi)
self.IncrPhi.Enabled = not isnan(self.phi)
self.DecrPhi.Enabled = not isnan(self.phi)
# Update Buttons
self.KeepCentered.Value = self.keep_centered
self.UndoButton.Enabled = (len(self.support_points) > 0)
self.ClearButton.Enabled = (len(self.support_points) > 0)
self.KeepCentered.Value = self.keep_centered
self.LearnCenter.Value = self.learn_center
# Update pointer
if self.mark_sample_enabled: self.PointerFunction = "Mark Sample"
elif self.click_center_enabled: self.PointerFunction = "Click-Center"
elif self.define_edge_enabled: self.PointerFunction = "Define Edge"
else: self.PointerFunction = ""
# Relaunch yourself.
self.update_timer = wx.Timer(self)
self.Bind (wx.EVT_TIMER,self.update,self.update_timer)
self.update_timer.Start(1000,oneShot=True)
def update_sample_settings(self,event=None):
"""Monitors the settings file and reloads it if it is updated.
Or, updates the file, if settings changed."""
from os import makedirs,remove,rename
from os.path import exists
def getmtime(filename): # Modification timestamp of a file
from os.path import getmtime
try: return getmtime(filename)
except: return 0
settings_file = self.settings_dir()+"/sample_settings.py"
if not hasattr(self,"sample_timestamp"): self.sample_timestamp = 0
if not hasattr(self,"saved_sample_state"):
self.saved_sample_state = self.SampleState
if exists(settings_file) and getmtime(settings_file) != self.sample_timestamp:
# (Re)load settings file.
try:
settings = file(settings_file).read()
self.SampleState = file(settings_file).read()
self.saved_sample_state = self.SampleState
self.sample_timestamp = getmtime(settings_file)
except IOError,msg: error("Failed to read %s: %s\n" % (settings_file,msg))
elif self.SampleState != self.saved_sample_state or not exists(settings_file):
# Update settings file.
if not exists(self.settings_dir()): makedirs(self.settings_dir())
try:
file(settings_file+".tmp","wb").write(self.SampleState)
if exists(settings_file): remove(settings_file)
rename(settings_file+".tmp",settings_file)
self.saved_sample_state = self.SampleState
self.sample_timestamp = getmtime(settings_file)
except IOError:
error("Failed to update %r" % settings_file)
# Relaunch this procedure after 2 s
self.sample_settings_timer = wx.Timer(self)
self.Bind (wx.EVT_TIMER,self.update_sample_settings,self.sample_settings_timer)
self.sample_settings_timer.Start(2000,oneShot=True)
def GetSampleState(self):
state = ""
for attr in self.sample_settings:
line = attr+" = "+repr(eval("self."+attr))
state += line+"\n"
return state
def SetSampleState(self,state):
for line in state.split("\n"):
line = line.strip(" \n\r")
if line != "":
try: exec("self."+line)
except: warn("ignoring line %r" % line); pass
SampleState = property(GetSampleState,SetSampleState)
def get_x_motor(self):
return self.motor(self.x_motor_name)
x_motor = property(get_x_motor)
def get_y_motor(self):
return self.motor(self.y_motor_name)
y_motor = property(get_y_motor)
def get_z_motor(self):
return self.motor(self.z_motor_name)
z_motor = property(get_z_motor)
def get_phi_motor(self):
return self.motor(self.phi_motor_name)
phi_motor = property(get_phi_motor)
def motor(self,name):
if not hasattr(self,"cache"): self.cache = {}
if not name in self.cache: self.cache[name] = motor(name)
return self.cache[name]
def get_x(self): return self.x_motor.value
def set_x(self,value): self.x_motor.value = value
x = property(get_x,set_x)
def get_y(self): return self.y_motor.value
def set_y(self,value): self.y_motor.value = value
y = property(get_y,set_y)
def get_z(self): return self.z_motor.value
def set_z(self,value): self.z_motor.value = value
z = property(get_z,set_z)
def get_phi(self): return self.phi_motor.value
def set_phi(self,value): self.phi_motor.value = value
phi = property(get_phi,set_phi)
def get_xc(self): return self.x_motor.command_value
def set_xc(self,value): self.x_motor.command_value = value
xc = property(get_xc,set_xc)
def get_yc(self): return self.y_motor.command_value
def set_yc(self,value): self.y_motor.command_value = value
yc = property(get_yc,set_yc)
def get_zc(self): return self.z_motor.command_value
def set_zc(self,value): self.z_motor.command_value = value
zc = property(get_zc,set_zc)
def get_phic(self): return self.phi_motor.command_value
def set_phic(self,value): self.phi_motor.command_value = value
phic = property(get_phic,set_phic)
def rotate(self,phi):
"""Rotate the spindle to the new angle phi, keeping te sample
centered"""
if self.keep_centered:
# While rotating, keep the sample centered on the cross hair.
self.current_center_x,self.current_center_y = \
self.sample_center_xy(self.xc,self.yc,self.phic)
cx,cy = self.sample_center_xy_phi(phi)
self.xc,self.yc = cx,cy
self.phic = phi
GridSpacing = CameraViewer.GridXSpacing
def OnStepSize(self,event):
"""Change the step size to the value displayed by the control"""
# Called when the user enters a new step size on the the control
from numpy import isnan
if not isnan(self.stepsize_value): self.stepsize = self.stepsize_value
self.stepsize_value = self.stepsize
def get_stepsize_value(self):
"""Step size as displayed by the stepsize control"""
from numpy import nan
value = self.StepSize.Value.replace("um","")
try: value = float(eval(value))/1000
except ValueError: value = nan
return value
def set_stepsize_value(self,value):
from numpy import isnan
text = "%g um" % (value*1000) if not isnan(value) else ""
self.StepSize.Value = text
stepsize_value = property(get_stepsize_value,set_stepsize_value)
def OnTranslateTowardCamera(self,event):
"""Move the same closer to the camera"""
self.move_relative(0,0,-self.stepsize_value)
if self.learn_center:
self.camera_rotation_center_xc -= self.stepsize_value
def OnTranslateFromCamera(self,event):
"""Move the same away from the camera"""
self.move_relative(0,0,+self.stepsize_value)
if self.learn_center:
self.camera_rotation_center_xc += self.stepsize_value
def OnTranslateHLeft(self,event):
"""Tweak the position horizontally"""
self.move_relative(-self.stepsize_value,0,0)
def OnTranslateHRight(self,event):
"""Tweak the position horizontally"""
self.move_relative(+self.stepsize_value,0,0)
def OnTranslateVUp(self,event):
"""Tweak the position vertically"""
self.move_relative(0,+self.stepsize_value,0)
if self.learn_center:
self.camera_rotation_center_yc += self.stepsize_value
def OnTranslateVDown(self,event):
"""Tweak the position vertically"""
self.move_relative(0,-self.stepsize_value,0)
if self.learn_center:
self.camera_rotation_center_yc -= self.stepsize_value
def move_relative(self,camera_dx,camera_dy,camera_dz):
"""Execute a relative move in the camera coordinate system.
camera_dx: horizontal direction in mm, pos = left
camera_dy: vertical direction, in mm, pos = up
camera_dz: along the viewing direction (focus direction) in mm, pos = farther
"""
dx,dy,dz = self.dxdydz_of_camera_dxdydz(camera_dx,camera_dy,camera_dz)
self.current_center_x,self.current_center_y = \
self.sample_center_xy(self.xc+dx,self.yc+dy,self.phic)
self.xc += dx; self.yc += dy;
if dz != 0: self.zc += dz
def OnEnterPhi(self,event):
"""Called when Enter is pressed in the text box."""
value = self.Phi.Value.replace(deg,"")
try: phi = float(eval(value))
except ValueError: return
self.rotate(phi)
def OnPhiStepSize(self,event):
"""Called if the rotation step size is changed"""
value = self.PhiStepSize.Value.replace(deg,"")
try: self.phi_stepsize = float(eval(value))
except ValueError: pass
self.PhiStepSize.Value = "%g%s" % (self.phi_stepsize,deg)
def OnDecrPhi(self,event):
"""Rotate the sample"""
self.rotate(self.phic - self.phi_stepsize)
def OnIncrPhi(self,event=None):
"""Rotate the sample"""
self.rotate(self.phic + self.phi_stepsize)
def OnClickCenteringButton(self,event):
"""Called when the 'Click Centering' button is pressed or released"""
self.UpdateClickCenteringButton()
def get_click_center_enabled(self):
"""Does clicking the image move the motors?"""
return self.ClickCenteringButton.Value
def set_click_center_enabled(self,enabled):
self.ClickCenteringButton.Value = enabled
self.UpdateClickCenteringButton()
def UpdateClickCenteringButton(self):
if self.ClickCenteringButton.Value == True:
self.ClickCenteringButton.Label = "Click Centering: Active"
self.ClickCenteringButton.BackgroundColour = (255,255,0)
self.ClickCenteringButton.ForegroundColour = (255,0,0)
else:
self.ClickCenteringButton.Label = "Click Centering: Off "
self.ClickCenteringButton.BackgroundColour = \
self.ClickCenteringButton.DefaultBackgroundColour
self.ClickCenteringButton.ForegroundColour = \
self.ClickCenteringButton.DefaultForegroundColour
click_center_enabled = property(get_click_center_enabled,set_click_center_enabled)
def OnKeepCentered(self,event):
"""Called when the status of the 'Keep Centered' checkbox changes"""
self.keep_centered = self.KeepCentered.Value
def OnLearnCenter(self,event):
"""Called when the status of the 'Learn Center' checkbox changes"""
self.learn_center = self.LearnCenter.Value
def OnReturnButton(self,event):
"""Called when the 'Return to Center' button is pressed"""
self.current_center_x,self.current_center_y = \
self.click_center_x,self.click_center_y
self.x,self.y = self.sample_centered_xy
self.z = self.click_center_z+self.calibration_z
def OnDefineEdgeButton(self,event):
"""Called when the 'Define Edge' button is pressed or released"""
self.UpdateDefineEdgeButton()
def get_define_edge_enabled(self):
return self.DefineEdgeButton.Value
def set_define_edge_enabled(self,value):
self.DefineEdgeButton.Value = value
self.UpdateDefineEdgeButton()
define_edge_enabled = property(get_define_edge_enabled,set_define_edge_enabled)
def UpdateDefineEdgeButton(self):
if self.DefineEdgeButton.Value == True:
self.DefineEdgeButton.BackgroundColour = (255,255,0)
self.DefineEdgeButton.ForegroundColour = (255,0,0)
else:
self.DefineEdgeButton.BackgroundColour = \
self.DefineEdgeButton.DefaultBackgroundColour
self.DefineEdgeButton.ForegroundColour = \
self.DefineEdgeButton.DefaultForegroundColour
def OnUndoButton(self,event):
"""Called when the 'Undo' button is pressed"""
self.UndoLastEdgeDefinition()
def OnClearButton(self,event):
"""Called when the 'Reset' button is pressed"""
self.ResetEdgeDefinition()
def OnShowGrid(self,event):
"""Toggle vertical grid on/off"""
self.ShowGrid = self.ShowGridControl.Value
def OnShiftGridLeft(self,event):
"""Tweak the grid position horizontally"""
stepsize = self.GridXSpacing*0.02
self.GridOffset = (self.GridOffset - stepsize) % self.GridXSpacing
def OnShiftGridRight(self,event):
"""Tweak the grid position horizontally"""
stepsize = self.GridXSpacing*0.02
self.GridOffset = (self.GridOffset + stepsize) % self.GridXSpacing
def OnGridSpacing(self,event):
"Change the horizontal grid spacing"
value = self.GridSpacingControl.Value.replace("um","")
try: self.GridXSpacing = float(eval(value))/1000
except ValueError: pass
self.GridSpacingControl.Value = "%.0f um" % (self.GridXSpacing*1000)
def OnMarkSampleFunction(self,event):
"""Called when switching between 'Start','End','Width' """
if event.EventObject == self.MarkSampleButton:
mark_sample_function = "mark"
if event.EventObject == self.MarkSampleDeleteButton:
mark_sample_function = "delete"
elif event.EventObject == self.MarkSampleWidthButton:
mark_sample_function = "width"
buttons = self.MarkSampleButton,self.MarkSampleWidthButton
if not any([button.Value for button in buttons]):
mark_sample_function = ""
self.mark_sample_function = mark_sample_function
def get_mark_sample_function(self):
"""What does a mouse click define?
"mark" or "width"
"" for nothing."""
if self.MarkSampleButton.Value == True: return "mark"
if self.MarkSampleDeleteButton.Value == True: return "delete"
if self.MarkSampleWidthButton.Value == True: return "width"
return ""
def set_mark_sample_function(self,value):
self.MarkSampleButton.Value = (value == "mark")
self.MarkSampleDeleteButton.Value = (value == "delete")
self.MarkSampleWidthButton.Value = (value == "width")
mark_sample_function = property(get_mark_sample_function,set_mark_sample_function)
def get_mark_sample_enabled(self):
if not self.show_mark_sample_controls: return False
if self.MarkSampleButton.Value == True: return True
if self.MarkSampleDeleteButton.Value == True: return True
if self.MarkSampleWidthButton.Value == True: return True
return False
def set_mark_sample_enabled(self,enabled):
buttons = self.MarkSampleButton,self.MarkSampleWidthButton
if not enabled:
for button in buttons: button.Value = False
else:
if not any([button.Value for button in buttons]):
self.MarkSampleButton.Value = True
mark_sample_enabled = property(get_mark_sample_enabled,set_mark_sample_enabled)
def OnMarkSampleClear(self,event):
"""Called when the 'Clear' button is pressed"""
self.samples = []
def OnAlignmentSetup(self,event):
"""Change parameters controlling click-centering procedure"""
dlg = AlignmentSetup(self)
dlg.CenterOnParent()
dlg.Show()
def OnCenter(self,event):
"""Inspect parameters controlling sample centering"""
dlg = Center(self)
dlg.CenterOnParent()
dlg.Show()
def OnShowIlluminationControls(self,event):
show = event.Checked()
self.ShowIlluminationControlsMenuItem.Check(show)
self.Illumination_Panel.Shown = show
self.Illumination_Panel_Shown = show
self.layout.Layout()
def OnShowAlignmentControls(self,event):
show = event.Checked()
self.ShowAlignmentControlsMenuItem.Check(show)
self.Alignment_Panel.Shown = show
self.Alignment_Panel_Shown = show
self.layout.Layout()
def OnShowEdgeControls(self,event):
"""Show/hide extra controls related to sample aligment"""
self.show_edge_controls = not self.show_edge_controls
def OnShowMarkSample(self,event):
"""Show/hide extra controls related to sample aligment"""
self.show_mark_sample_controls = not self.show_mark_sample_controls
def OnCalibrateRotation(self,event):
""""Find the rotation center of the Phi axis"""
dlg = CalibrateRotation(self)
dlg.CenterOnParent()
dlg.Show()
def OnSampleCenter(self,event):
"""Define Rotation Center of an Object"""
dlg = SampleCenter(self)
dlg.CenterOnParent()
dlg.Show()
def OnPointerFunction(self,name,x,y,event):
"""Called when click-centering is activated and the left mouse
button is pressed.
(x,y) position of pointer relative to crosshair in mm
event: 'down','drag' or 'up'"""
##debug("OnPointerFunction:%r,%r,%r,%r" % (name,x,y,event))
# Convert from 2D camera to 3D diffractometer coordinates.
# assuming the object is clicked on is in the focal plane of the camera.
dx,dy,dz = self.dxdydz_of_camera_dxdydz(x,y,0)
cx,cy,cz = self.xc-dx,self.yc-dy,self.zc-dz
self.learn_center_register(cx,cy,cz,self.phic)
if self.click_center_enabled and event == "down":
self.current_center_x,self.current_center_y = \
self.sample_center_xy(cx,cy,self.phic)
self.xc,self.yc,self.zc = cx,cy,cz
if self.mark_sample_enabled:
##if self.mark_sample_function in ("mark"):
## self.xc,self.yc,self.zc = cx,cy,cz
self.MarkSample(self.mark_sample_function,x,y,event)
if name == "Define Edge" and event == "down": self.DefineEdge(x,y)
def learn_center_register(self,x,y,z,phi):
"""Build history of clicks"""
# Eliminate entries with duplicate phi in the history.
def matches(phi1,phi2): return phi1 % 360 == phi2 % 360
self.learn_center_history = [entry for entry in self.learn_center_history
if hasattr(entry,"keys") and "phi" in entry and not matches(entry["phi"],phi)]
# Add new click event to history.
self.learn_center_history += [{"x":x,"y":y,"z":z,"phi":phi}]
# Limit the number of entries in the history.
self.learn_center_history = self.learn_center_history[-4:]
def accept_rotation_center(self):
"""Use the new rotation center from the 'learn center' history"""
from numpy import isnan
cx,cy = self.rotation_center_xy_based_on_history
if not any(isnan([cy,cy])): self.rotation_center = cx,cy
self.calibration_z = self.zc
@property
def rotation_center_xy_based_on_history(self):
"""rotation center calculated from 'learn center' history"""
from numpy import nan, average,sort,allclose
try:
if len(self.learn_center_history) < 4: cx,cy = nan,nan
else:
# Make sure the four angles are 90 deg appart.
phi = [entry["phi"] for entry in self.learn_center_history[0:4]]
phi = sort(phi)-min(phi)
if not allclose(phi,[0,90,180,270]): cx,cy = nan,nan
else:
# If the four phi angle are 90 deg appart, the center is the
# average of the x and y coordinates.
x = [entry["x"] for entry in self.learn_center_history[0:4]]
y = [entry["y"] for entry in self.learn_center_history[0:4]]
cx,cy = average(x),average(y)
except Exception,msg:
warn("rotation_center_xy_based_on_history: %r: %s" %
(self.learn_center_history,msg))
cx,cy = nan,nan
return cx,cy
def get_camera_sample_xc(self):
"""The shift of the sample relative to the sample position at
(X,Y) = (0,0), along the to the camera viewing direction"""
x,y = self.camera_xy(self.xc,self.yc)
return x
def set_camera_sample_xc(self,value):
x,y = self.camera_xy(self.xc,self.yc)
x = value
self.xc,self.yc = self.diffractometer_xy(x,y)
camera_sample_xc = property(get_camera_sample_xc,set_camera_sample_xc)
def get_camera_sample_yc(self):
"""The shift of the sample relative to the sample position at
(X,Y) = (0,0), orthognal to the camera viewing direction"""
x,y = self.camera_xy(self.xc,self.yc)
return y
def set_camera_sample_yc(self,value):
x,y = self.camera_xy(self.xc,self.yc)
y = value
self.xc,self.yc = self.diffractometer_xy(x,y)
camera_sample_yc = property(get_camera_sample_yc,set_camera_sample_yc)
def get_camera_rotation_center_xc(self):
"""Phi motor rotation axis, at (X,Y) = (0,0),
along the to the camera viewing direction"""
x,y = self.camera_xy(*self.rotation_center)
return x
def set_camera_rotation_center_xc(self,value):
x,y = self.camera_xy(*self.rotation_center)
x = value
self.rotation_center = self.diffractometer_xy(x,y)
camera_rotation_center_xc = property(get_camera_rotation_center_xc,
set_camera_rotation_center_xc)
def get_camera_rotation_center_yc(self):
"""Phi motor rotation axis, at (X,Y) = (0,0),
orthognal to the camera viewing direction"""
x,y = self.camera_xy(*self.rotation_center)
return y
def set_camera_rotation_center_yc(self,value):
x,y = self.camera_xy(*self.rotation_center)
y = value
self.rotation_center = self.diffractometer_xy(x,y)
camera_rotation_center_yc = property(get_camera_rotation_center_yc,
set_camera_rotation_center_yc)
def get_camera_sample_center_xc(self):
"""Phi motor rotation axis, at (X,Y) = (0,0),
along the to the camera viewing direction"""
x,y = self.camera_xy(self.current_center_x,self.current_center_y)
return x
def set_camera_sample_center_xc(self,value):
x,y = self.camera_xy(self.current_center_x,self.current_center_y)
x = value
self.current_center_x,self.current_center_y = self.diffractometer_xy(x,y)
camera_sample_center_xc = property(get_camera_sample_center_xc,
set_camera_sample_center_xc)
def get_camera_sample_center_yc(self):
"""Phi motor rotation axis, at (X,Y) = (0,0),
orthognal to the camera viewing direction"""
x,y = self.camera_xy(self.current_center_x,self.current_center_y)
return y
def set_camera_sample_center_yc(self,value):
x,y = self.camera_xy(self.current_center_x,self.current_center_y)
y = value
self.current_center_x,self.current_center_y = self.diffractometer_xy(x,y)
camera_sample_center_yc = property(get_camera_sample_center_yc,
set_camera_sample_center_yc)
def camera_xy(self,x,y):
"""Transform from diffractometer to camera coordinates.
Return value: (x',y')
x': distance from the camera plane of focus in the camera viewing direction
(positive = far, negative = close)
y': projection in the camara plan of focus
(positive = up in the image, negative = down in the image)"""
from numpy import sin,cos,radians
phi = -self.camera_angle
xp = self.x_scale*x*cos(radians(phi)) - self.y_scale*y*sin(radians(phi))
yp = self.x_scale*x*sin(radians(phi)) + self.y_scale*y*cos(radians(phi))
return xp,yp
def diffractometer_xy(self,xp,yp):
"""Transform from camera to diffractometer coordinates.
Return value: (x,y)"""
from numpy import sin,cos,radians
phi = -self.camera_angle
x = ( xp*cos(radians(phi)) + yp*sin(radians(phi))) / self.x_scale
y = (-xp*sin(radians(phi)) + yp*cos(radians(phi))) / self.y_scale
return x,y
@property
def rotation_axis_offset(self):
"""Vertical offset of the rotation axis with respect to
the crosshair in units of mm"""
from numpy import sin,cos,radians
x,y = self.x,self.y
cx,cy = self.rotation_center
dx,dy = x-cx,y-cy
phi = -self.camera_angle
d = self.x_scale*dx*sin(radians(phi)) + self.y_scale*dy*cos(radians(phi))
return d
@property
def rotation_axis_depth(self):
"""Distance of the rotation axis from the camera focal plane
in viewing direction in units of mm"""
from numpy import sin,cos,radians
x,y = self.x,self.y
cx,cy = self.rotation_center
dx,dy = x-cx,y-cy
phi = -self.camera_angle
d = -self.x_scale*dx*cos(radians(phi)) + self.y_scale*dy*sin(radians(phi))
return d
@property
def sample_centered_xy(self):
"""How does the sample need to be translated such that the click
center is on the crosshair?"""
return self.sample_center_xy_phi(self.phic)
def sample_center_xy_phi(self,phi):
"""Where does the sample need to be translated such that the current
center is on the crosshair?"""
from numpy import degrees,arctan2,sqrt,sin,cos,radians
x0,y0 = self.current_center_x,self.current_center_y
r = sqrt(x0**2+y0**2)
phi0 = degrees(arctan2(-y0,x0)) % 360
phi1 = (phi0 + phi) % 360
dx = r*cos(radians(phi1))
dy = -r*sin(radians(phi1))
cx,cy = self.rotation_center
x,y = cx+dx,cy+dy
return x,y
@property
def current_sample_center_xy(self):
"""x and y offset of the sample center from the rotation axis
at phi = 0 based on the current values of x,y and phi,
assuming the sample is centered in te crosshair and in focus."""
return self.sample_center_xy(self.xc,self.yc,self.phic)
def sample_center_xy(self,x,y,phi):
"""x and y offset of the sample center from the rotation axis
at phi = 0 based
assuming the sample is centered in the crosshair and in focus.
as x,y,phi"""
# Transform from x,y,phi to x0,y0,0
from numpy import degrees,arctan2,sqrt,sin,cos,radians
cx,cy = self.rotation_center
dx,dy = x-cx,y-cy
r = sqrt(dx**2+dy**2)
phi1 = degrees(arctan2(-dy,dx)) % 360
phi0 = phi1 - phi
x0 = r*cos(radians(phi0))
y0 = -r*sin(radians(phi0))
return x0,y0
def sample_camera_xy(self,x,y,z):
"""Vertical offset of the with respect to the crosshair
of a sample a x,y with respect to the rotation axis at phi=0"""
from numpy import sin,cos,radians,degrees,arctan2,sqrt
r = sqrt(x**2+y**2)
phi0 = degrees(arctan2(-y,x)) % 360
phi = phi0 + self.phi - self.camera_angle
d = r*sin(radians(phi))
offset = d + self.rotation_axis_offset
cz = z + self.calibration_z
cx,cy = self.camera_position(cz,offset)
return cx,cy
def sample_camera_xyz(self,x,y,z):
"""Horizontal and vertical offset with respect to the crosshair
of a sample a x,y with respect to the rotation axis at phi=0
the Third coordinate if te out of plane distance in camera viewing
direction, with respect to the focal plane of the camera."""
from numpy import sin,cos,radians,degrees,arctan2,sqrt
r = sqrt(x**2+y**2)
phi0 = degrees(arctan2(-y,x)) % 360
phi = phi0 + self.phi - self.camera_angle
cy0 = r*sin(radians(phi))
cz0 = -r*cos(radians(phi))
cy1 = cy0 + self.rotation_axis_offset
cz = cz0 + self.rotation_axis_depth
cx1 = z + self.calibration_z
cx,cy = self.camera_position(cx1,cy1)
return cx,cy,cz
@property
def sample_center_camera_xy(self):
"""Position of sample with respect to the crosshair, as seen by the
camera."""
offset = self.sample_center_offset
cz = self.click_center_z + self.calibration_z
x,y = self.camera_position(cz,offset)
return x,y
@property
def sample_center_r(self):
"""Distance of the sample center from the rotation axis"""
from numpy import sqrt
x,y = self.current_center_x,self.current_center_y
r = sqrt(x**2+y**2)
return r
@property
def sample_center_direction_angle(self):
"""Direction of the sameple from the roation center at phi=0"""
from numpy import degrees,arctan2
x,y = self.current_center_x,self.current_center_y
phi = degrees(arctan2(-y,x)) % 360
return phi
@property
def sample_center_offset(self):
"""Vertical offset of the sample center with respect to the crosshair"""
from numpy import sin,cos,radians,degrees,arctan2,sqrt
x,y = self.click_center_x,self.click_center_y
r = sqrt(x**2+y**2)
phi0 = degrees(arctan2(-y,x)) % 360
phi = phi0 + self.phi - self.camera_angle
d = r*sin(radians(phi))
offset = d + self.rotation_axis_offset
return offset
def get_x_translation_angle(self):
"""The angle between the camera viewing direction and the
X translation, in units of degrees"""
if self.xy_rotating:
phi = self.phic - self.camera_angle
else:
phi = -self.camera_angle
return phi
x_translation_angle = property(get_x_translation_angle)
def get_y_translation_angle(self):
"""The angle between the camera viewing direction and the
Y translation, in units of degrees"""
if self.xy_rotating:
phi = self.phic - self.camera_angle - 90
else:
phi = -self.camera_angle - 90
return phi
y_translation_angle = property(get_y_translation_angle)
def dxdydz_of_camera_dxdydz(self,camera_dx,camera_dy,camera_dz):
"""Motor translation based on camera viewing plane translation.
camera_dx: horizontal direction in mm, pos = left
camera_dy: vertical direction, in mm, pos = up
camera_dz: along the viewing direction (focus direction) in mm, pos = farther
return value: motor dx,dy,dz in mm"""
dz = self.z_scale * camera_dx
x0,y0 = self.camera_xy(0,0)
dx,dy = self.diffractometer_xy(x0-camera_dz,y0+camera_dy)
return dx,dy,dz
def camera_xyz(self,x,y,z):
"""Where is the object the is centers at motor position (x,y,z)
currently in the field of view of te camera?
return value: x0,y0,z0
x0 = horizonal offset from crosshair in mm
y0 = vertical offset from crosshair in mm
z0 = distance fro mcal place in camera direction in mm"""
dx,dy,dz = x-self.xc,y-self.yc,z-self.zc
z0,y0 = self.camera_xy(dx,dy) # depth, vertical offset, sign?
x0 = -dz * self.z_scale # sign?
return x0,y0,z0
def DefineEdge(self,x,y):
"""x,y position of mouse clock with respect to cross hair in mm.
x: positive = right, y: positive = up"""
from numpy import rint
phi = (self.phic - self.camera_angle) % 360
z = self.zc - self.z_scale * x
# Round to the next grid point
z0 = self.GridOffset; dz = self.GridXSpacing
z = rint((z-z0)/dz)*dz+z0
offset = y
self.AddSupportPoint(phi,z,offset)
def AddSupportPoint(self,phi,z,offset):
from numpy import array,where,concatenate
x,y = self.xc,self.yc
if len(self.support_points) > 0:
PHI,X,Y,Z,OFFSET = array(self.support_points).T
else: PHI,X,Y,Z,OFFSET = array([[],[],[],[],[]])
existing_points = where((PHI == phi) & (Z == z))[0]
if len(existing_points) > 0:
OFFSET[existing_points] = offset
else:
PHI = concatenate((PHI,[phi]))
X = concatenate((X,[x]))
Y = concatenate((Y,[y]))
Z = concatenate((Z,[z]))
OFFSET = concatenate((OFFSET,[offset]))
self.support_points = zip(PHI,X,Y,Z,OFFSET)
def ResetEdgeDefinition(self):
"""Clear all support points"""
self.support_points = []
def UndoLastEdgeDefinition(self):
"Clear last support point"
if len(self.support_points) > 0: self.support_points.pop()
def MarkSample(self,function,x,y,event):
"""x,y image coordinates wirth respect to the camera center.
x: positive = right, y: positive = up
event: 'up','drag' or 'down'"""
##debug("MarkSample %r,%+.3f,%+.3f,%r" % (self.mark_sample_function,x,y,event))
click_dist = 0.02 # mm, should change with zoom
# Convert from 2D camera to 3D diffractometer coordinates.
# assuming the object is clicked on is in the focal plane of the camera.
sx,sy,sz = self.sample_xyz_of_camera_xyz(x,y,0)
if function not in ["width","delete"]:
if event == "down":
# Find the closest control point
self.current_sample = None
dmin = 1e9
for i in range(0,len(self.samples)):
for point in ["start","end"]:
tx,ty = self.sample_camera_xy(*self.samples[i][point])
d = distance((x,y),(tx,ty))
dmin = min(d,dmin)
for i in range(0,len(self.samples)):
for point in ["start","end"]:
tx,ty = self.sample_camera_xy(*self.samples[i][point])
d = distance((x,y),(tx,ty))
if d == dmin and dmin < click_dist:
self.current_sample = i
self.current_sample_point = point
if self.current_sample is None:
self.samples += [{"start":(sx,sy,sz),"end":(sx,sy,sz)}]
self.current_sample = len(self.samples) - 1
self.current_sample_point = "end"
elif event == "drag" or event == "up":
if self.current_sample is not None and len(self.samples) > 0:
# Maintain depth with respect to camera plane while dragging.
##debug(" x, y, z = %+.3f,%+.3f,%+.3f" % ( x, y, 0))
sx,sy,sz = self.samples[self.current_sample][self.current_sample_point]
##debug("sx,sy,sz = %+.3f,%+.3f,%+.3f" % (sx,sy,sz))
ox,oy,oz = self.sample_camera_xyz(sx,sy,sz)
##debug("ox,oy,oz = %+.3f,%+.3f,%+.3f" % (ox,oy,oz))
x,y,z = x,y,oz
##debug(" x, y, z = %+.3f,%+.3f,%+.3f" % ( x, y, 0))
sx,sy,sz = self.sample_xyz_of_camera_xyz(x,y,z)
##debug("sx,sy,sz = %+.3f,%+.3f,%+.3f" % (sx,sy,sz))
self.samples[self.current_sample][self.current_sample_point] = sx,sy,sz
if function == "width":
if self.current_sample is not None and len(self.samples) > 0:
sample = self.samples[self.current_sample]
p1 = self.sample_camera_xy(*sample["start"])
p2 = self.sample_camera_xy(*sample["end"])
self.sample_r = point_line_distance((x,y),(p1,p2))
##self.sample_r = point_line_distance((sx,sy,sz),(sample["start"],sample["end"]))
if function == "delete":
self.current_sample = None
dmin = 1e9
for i in range(0,len(self.samples)):
sample = self.samples[i]
p1 = self.sample_camera_xy(*sample["start"])
p2 = self.sample_camera_xy(*sample["end"])
d = point_line_distance((x,y),(p1,p2))
dmin = min(d,dmin)
for i in range(0,len(self.samples)):
sample = self.samples[i]
p1 = self.sample_camera_xy(*sample["start"])
p2 = self.sample_camera_xy(*sample["end"])
d = point_line_distance((x,y),(p1,p2))
if d == dmin and dmin < click_dist:
self.current_sample = i
if self.current_sample is not None:
i = self.current_sample
self.samples = self.samples[0:i]+self.samples[i+1:]
def sample_xyz_of_camera_xyz(self,x,y,z):
"""x,y,z coordinates in mm realtive to the rotation center.
x camera horizonal in mm
y camera vertical in mm
z depth relative to the camera focal plane in viewing direction in mm
"""
dx,dy,dz = self.dxdydz_of_camera_dxdydz(x,y,z)
cx,cy,cz = self.xc-dx,self.yc-dy,self.zc-dz
sx,sy,sz = list(self.sample_center_xy(cx,cy,self.phic))+[cz-self.calibration_z]
return sx,sy,sz
def z_range(self):
"""translation range along phi axis for data collection.
Defined as range over which support points have been entered"""
from numpy import array
if len(self.support_points) == 0: return self.z,self.z
PHI,X,Y,Z,OFFSET = array(self.support_points).T
return min(Z),max(Z)
def camera_position(self,Z,offset):
"""Transform from Z, offset to camera viewing plane 2D
coordinates, using the current settigs of X,Y,Z, and Phi."""
x = (self.z - Z) * self.z_scale
y = offset
return x,y
def current_offset(self,phi,x0,y0,offset0):
"""Transform offset0 measured at (x0,y0) and angle phi0
to offset at current position (X,Y)
The inputs phi,x0,y0,offset0 may by numpy arrays."""
cx,cy = self.xc,self.yc
return self.relative_offset(phi,x0,y0,offset0,cx,cy)
def relative_offset(self,phi,x0,y0,offset0,cx,cy):
"""Transform offset0 measured at (x0,y0) and angle phi0
to offset with respect to position (cy,cy)"""
from numpy import sin,cos,radians
x = x0 + offset0*sin(radians(phi))
y = y0 - offset0*cos(radians(phi))
offset = (x-cx)*sin(radians(phi)) - (y-cy)*cos(radians(phi))
return offset
def interpolated_offset(self,phi,z):
"""Interpolate the offset as function of phi and z, using measured
support points
The returned offset are with respect to the center of the sample
as defined by visual click centering."""
from numpy import array,concatenate
PHI,X,Y,Z,OFFSET = array(self.support_points).T
PHI = concatenate((PHI-360,PHI,PHI+360))
Z = concatenate((Z,Z,Z))
OFFSET = concatenate((OFFSET,OFFSET,OFFSET))
return interpolate_2D(PHI,Z,OFFSET,phi % 360,z)
class Illumination_Panel(wx.Panel):
"""Light switch for LED illuminator controlled by timing system"""
def __init__(self,parent):
wx.Panel.__init__(self,parent)
# Controls - Illumination Panel
hbox = wx.BoxSizer(wx.HORIZONTAL)
self.Sizer = hbox
label = wx.StaticText(self,label="Illumination:")
hbox.Add (label,flag=wx.ALIGN_CENTER)
self.Illumination_State = wx.ToggleButton(self,label="On",size=(45,-1))
hbox.Add (self.Illumination_State,flag=wx.ALIGN_CENTER)
self.Bind (wx.EVT_TOGGLEBUTTON,self.OnIllumination_State,self.Illumination_State)
from instrumentation import timing_system
timing_system.scl.override_state.monitor(self.IlluminationUpdate)
self.Illumination_PP_Control = wx.CheckBox(self,label="PP Controlled")
hbox.Add (self.Illumination_PP_Control,flag=wx.ALIGN_CENTER)
self.Bind (wx.EVT_CHECKBOX,self.OnIllumination_PP_Control,self.Illumination_PP_Control)
from instrumentation import timing_system
timing_system.scl.override.monitor(self.IlluminationUpdate)
def IlluminationUpdate(self):
"""Handle register change"""
State = self.Illumination_State
PP_Control = self.Illumination_PP_Control
from instrumentation import timing_system
if timing_system.online:
state = timing_system.scl.override_state.value
PP_controlled = not timing_system.scl.override.value
State.Value = state
PP_Control.Value = PP_controlled
State.Enabled = not PP_controlled
State.Label = "On" if state == True else "Off"
else:
PP_Control.Enabled = False
State.Enabled = False
State.Label = "Offline"
def OnIllumination_State(self,event):
"""Handle toogle button on/off"""
value = event.IsChecked()
info("Illumination_State: %r" % value)
from instrumentation import timing_system
timing_system.scl.override_state.value = value
def OnIllumination_PP_Control(self,event):
"""Handle toogle button on/off"""
value = event.IsChecked()
info("Illumination_PP_Control: %r" % value)
from instrumentation import timing_system
timing_system.scl.override.value = not value
def motor(name):
"""name: EPICS PV or Python motor defined in 'id14.py'"""
if not ":" in name:
exec("from id14 import *")
try: return eval(name)
except: pass
from EPICS_motor import motor
return motor(name)
def interpolate_2D(X,Y,Z,x,y):
"""
Z is a scalar function of the variables x and y.
X,Y: vector of length N, support points
Z: vector of length N, function values at support points
x,y: where to evaluate the function Z
"""
from numpy import array,unique
X,Y,Z = array(X),array(Y),array(Z)
UY = unique(Y)
UZ = [interpolate(zip(X[Y==uy],Z[Y==uy]),x) for uy in UY]
return interpolate(zip(UY,UZ),y)
def interpolate_2D_v1(X,Y,Z,x,y):
"""
Z is a scalar function of the variables x and y.
X,Y: vector of length N, support points
Z: vector of length N, function values at support points
x,y: where to evaluate the function Z
"""
from numpy import array,unique
X,Y,Z = array(X),array(Y),array(Z)
UX = unique(X)
UZ = [interpolate(zip(Y[X==ux],Z[X==ux]),y) for ux in UX]
return interpolate(zip(UX,UZ),x)
def interpolate_2D_v2(X,Y,Z,x,y):
"""
Z is a scalar function of the variables x and y.
X,Y: vector of length N, support points
Z: vector of length N, function values at support points
x,y: where to evaluate the function Z
"""
from numpy import array,argsort,isnan,nan
from matplotlib.mlab import griddata
X,Y,Z = array(X),array(Y),array(Z)
if len(X) == 0: return nan
# The Delauney triangulation routine used by 'griddata' cannot
# handle the case of supprt points lying on a straight line.
# In this case, use 1D intepolation.
if all(X == X[0]): return interpolate(zip(Y,Z),y)
if all(Y == Y[0]): return interpolate(zip(X,Z),x)
try: z = griddata(X,Y,Z,array([x]),array([y]))
except: z = nan
# 'griddata' returnes a masked array
z = float(array(z)) # avoid "Warning: converting a masked element to nan."
# 'griddata' does no extrapolation.
# If point is outside convex hull defined by input data, it returns nan.
if not isnan(z): return z
# Find the find closes support points in phi and z
nearest = argsort((X-x)**2+(Y-y)**2)[0]
return Z[nearest]
def interpolate(xy_data,xval):
"Linear interpolation"
from numpy import array,argsort,nan
x = array(xvals(xy_data)); y = array(yvals(xy_data)); n = len(xy_data)
if n == 0: return nan
if n == 1: return y[0]
order = argsort(x)
x = x[order]; y= y[order]
for i in range (1,n):
if x[i]>xval: break
if x[i-1]==x[i]: return (y[i-1]+y[i])/2.
yval = y[i-1]+(y[i]-y[i-1])*(xval-x[i-1])/(x[i]-x[i-1])
return yval
def xvals(xy_data):
"xy_data = list of (x,y)-tuples. Teturns list of x values only."
xvals = []
for i in range (0,len(xy_data)): xvals.append(xy_data[i][0])
return xvals
def yvals(xy_data):
"xy_data = list of (x,y)-tuples. Returns list of y values only."
yvals = []
for i in range (0,len(xy_data)): yvals.append(xy_data[i][1])
return yvals
class AlignmentSetup (wx.Dialog):
"""Allows the use to configure camera properties"""
def __init__ (self,parent):
wx.Dialog.__init__(self,parent,-1,"Alignment Setup")
# Controls
style = wx.TE_PROCESS_ENTER
self.X = ComboBox(self,size=(160,-1),style=style,
choices=["SampleX","NIH:SAMPLEX","14IDB:ESP300X"])
self.Y = ComboBox(self,size=(160,-1),style=style,
choices=["SampleY","NIH:SAMPLEY","14IDB:ESP300Y"])
self.Z = ComboBox(self,size=(160,-1),style=style,
choices=["SampleZ","NIH:SAMPLEZ","14IDB:ESP300Z"])
self.Phi = ComboBox(self,size=(160,-1),style=style,
choices=["SamplePhi","NIH:SAMPLEPHI","14IDB:m16"])
self.XYType = ComboBox(self,size=(160,-1),style=style,
choices=["rotating","stationary"])
self.CameraAngle = TextCtrl(self,size=(160,-1),style=style)
self.XDesc = wx.StaticText(self)
self.XSign = ComboBox(self,size=(160,-1),style=style,
choices=["up","down"])
self.YDesc = wx.StaticText(self)
self.YSign = ComboBox(self,size=(160,-1),style=style,
choices=["up","down"])
self.ZSign = ComboBox(self,size=(160,-1),style=style,
choices=["right","left"])
self.PixelSize = TextCtrl(self,size=(160,-1),style=style)
self.RotationCenterX = TextCtrl(self,size=(160,-1),style=style)
self.RotationCenterY = TextCtrl(self,size=(160,-1),style=style)
self.CalibrationZ = TextCtrl(self,size=(160,-1),style=style)
# Callbacks
self.Bind(wx.EVT_TEXT_ENTER,self.OnEnter)
self.Bind(wx.EVT_COMBOBOX,self.OnEnter)
# Layout
layout = wx.BoxSizer()
grid = wx.FlexGridSizer(cols=2,hgap=5,vgap=5)
flag = wx.ALIGN_CENTER_VERTICAL
label = "X Translation:"
grid.Add (wx.StaticText(self,label=label),flag=flag)
grid.Add (self.X,flag=flag)
label = "Y Translation:"
grid.Add (wx.StaticText(self,label=label),flag=flag)
grid.Add (self.Y,flag=flag)
label = "Z Translation:"
grid.Add (wx.StaticText(self,label=label),flag=flag)
grid.Add (self.Z,flag=flag)
label = "Phi Rotation:"
grid.Add (wx.StaticText(self,label=label),flag=flag)
grid.Add (self.Phi,flag=flag)
label = "XY Translation Type:"
grid.Add (wx.StaticText(self,label=label),flag=flag)
grid.Add (self.XYType,flag=flag)
label = "Y is orthogonal to viewing direction at:"
grid.Add (wx.StaticText(self,label=label),flag=flag)
grid.Add (self.CameraAngle,flag=flag)
grid.Add (self.YDesc,flag=flag)
grid.Add (self.YSign,flag=flag)
grid.Add (self.XDesc,flag=flag)
grid.Add (self.XSign,flag=flag)
label = "Z direction:"
grid.Add (wx.StaticText(self,label=label),flag=flag)
grid.Add (self.ZSign,flag=flag)
label = "Pixel size:"
grid.Add (wx.StaticText(self,label=label),flag=flag)
grid.Add (self.PixelSize,flag=flag)
label = "Rotation Axis X:"
grid.Add (wx.StaticText(self,label=label),flag=flag)
grid.Add (self.RotationCenterX,flag=flag)
label = "Rotation Axis Y:"
grid.Add (wx.StaticText(self,label=label),flag=flag)
grid.Add (self.RotationCenterY,flag=flag)
label = "Calibration Z:"
grid.Add (wx.StaticText(self,label=label),flag=flag)
grid.Add (self.CalibrationZ,flag=flag)
# Leave a 10-pixel wide space around the panel.
layout.Add (grid,flag=wx.EXPAND|wx.ALL,border=10)
self.SetSizer(layout)
self.Fit()
self.update()
def update(self,Event=0):
parent = self.Parent
self.X.Value = parent.x_motor_name
self.Y.Value = parent.y_motor_name
self.Z.Value = parent.z_motor_name
self.Phi.Value = parent.phi_motor_name
self.XYType.Value = "rotating" if parent.xy_rotating else "stationary"
self.CameraAngle.Value = str(parent.camera_angle)+deg
self.XDesc.Label = "X direction at %g%s:" %\
(parent.camera_angle-90,deg)
self.XSign.Value = "up" if parent.x_scale > 0 else "down"
self.YDesc.Label = "Y direction at %g%s:" %\
(parent.camera_angle,deg)
self.YSign.Value = "up" if parent.y_scale > 0 else "down"
self.ZSign.Value = "right" if parent.z_scale > 0 else "left"
self.PixelSize.Value = str(parent.PixelSize*1000)+" um"
x,y = parent.rotation_center
self.RotationCenterX.Value = "%.4f mm" % x
self.RotationCenterY.Value = "%.4f mm" % y
self.CalibrationZ.Value = "%.4f mm" % parent.calibration_z
# Relaunch yourself.
self.update_timer = wx.Timer(self)
self.Bind(wx.EVT_TIMER,self.update,self.update_timer)
self.update_timer.Start(2000,oneShot=True)
def OnEnter(self,event):
parent = self.Parent
parent.x_motor_name = self.X.Value
parent.y_motor_name = self.Y.Value
parent.z_motor_name = self.Z.Value
parent.phi_motor_name = self.Phi.Value
parent.xy_rotating = True if self.XYType.Value == "rotating" else False
value = self.CameraAngle.Value.replace(deg,"")
try: parent.camera_angle = float(eval(value))
except: pass
parent.x_scale = 1 if self.XSign.Value == "up" else -1
parent.y_scale = 1 if self.YSign.Value == "up" else -1
parent.z_scale = 1 if self.ZSign.Value == "right" else -1
value = self.PixelSize.Value.replace("um","")
try: value = float(eval(value))/1000
except: pass
parent.PixelSize = value
x,y = parent.rotation_center
value = self.RotationCenterX.Value.replace("mm","")
try: x = float(eval(value))
except: pass
value = self.RotationCenterY.Value.replace("mm","")
try: y = float(eval(value))
except: pass
parent.rotation_center = x,y
value = self.CalibrationZ.Value.replace("mm","")
try: parent.calibration_z = float(eval(value))
except: pass
self.update()
class Center(wx.Dialog):
"""Click-Centering"""
def __init__ (self,parent):
wx.Dialog.__init__(self,parent,-1,"Center")
# Controls
style = wx.TE_PROCESS_ENTER
self.SampleCenterX = TextCtrl(self,size=(160,-1),style=style)
self.SampleCenterY = TextCtrl(self,size=(160,-1),style=style)
self.SampleCenterZ = TextCtrl(self,size=(160,-1),style=style)
self.CurrentCenterX = TextCtrl(self,size=(160,-1),style=style)
self.CurrentCenterY = TextCtrl(self,size=(160,-1),style=style)
self.CurrentCenterZ = TextCtrl(self,size=(160,-1),style=style)
self.Bind(wx.EVT_TEXT_ENTER,self.OnEnter)
# Layout
layout = wx.BoxSizer()
grid = wx.FlexGridSizer(cols=2,hgap=5,vgap=5)
flag = wx.ALIGN_CENTER_VERTICAL
label = "Sample Center X:"
grid.Add (wx.StaticText(self,label=label),flag=flag)
grid.Add (self.SampleCenterX,flag=flag)
label = "Sample Center Y:"
grid.Add (wx.StaticText(self,label=label),flag=flag)
grid.Add (self.SampleCenterY,flag=flag)
label = "Sample Center Z:"
grid.Add (wx.StaticText(self,label=label),flag=flag)
grid.Add (self.SampleCenterZ,flag=flag)
label = "Current Center X:"
grid.Add (wx.StaticText(self,label=label),flag=flag)
grid.Add (self.CurrentCenterX,flag=flag)
label = "Current Center Y:"
grid.Add (wx.StaticText(self,label=label),flag=flag)
grid.Add (self.CurrentCenterY,flag=flag)
label = "Current Center Z:"
grid.Add (wx.StaticText(self,label=label),flag=flag)
grid.Add (self.CurrentCenterZ,flag=flag)
# Leave a 10-pixel wide space around the panel.
layout.Add (grid,flag=wx.EXPAND|wx.ALL,border=10)
self.SetSizer(layout)
self.Fit()
self.update()
def update(self,Event=0):
parent = self.Parent
self.SampleCenterX.Value = "%.4f mm" % parent.click_center_x
self.SampleCenterY.Value = "%.4f mm" % parent.click_center_y
self.SampleCenterZ.Value = "%.4f mm" % parent.click_center_z
self.CurrentCenterX.Value = "%.4f mm" % parent.current_center_x
self.CurrentCenterY.Value = "%.4f mm" % parent.current_center_y
self.CurrentCenterZ.Value = "%.4f mm" % (parent.zc - parent.calibration_z)
# Relaunch yourself.
self.update_timer = wx.Timer(self)
self.Bind(wx.EVT_TIMER,self.update,self.update_timer)
self.update_timer.Start(2000,oneShot=True)
def OnEnter(self,event):
parent = self.Parent
value = self.SampleCenterX.Value.replace("mm","")
try: parent.click_center_x = float(eval(value))
except: pass
value = self.SampleCenterY.Value.replace("mm","")
try: parent.click_center_y = float(eval(value))
except: pass
value = self.SampleCenterZ.Value.replace("mm","")
try: parent.click_center_z = float(eval(value))
except: pass
value = self.CurrentCenterX.Value.replace("mm","")
try: parent.current_center_x = float(eval(value))
except: pass
value = self.CurrentCenterY.Value.replace("mm","")
try: parent.current_center_y = float(eval(value))
except: pass
value = self.CurrentCenterZ.Value.replace("mm","")
try: parent.zc = float(eval(value)) + parent.calibration_z
except: pass
self.update()
class CalibrateRotation(wx.Dialog):
"""Find the rotation center of the Phi axis"""
def __init__ (self,parent):
wx.Dialog.__init__(self,parent,-1,"Calibrate Rotation")
# Controls
self.History = TextCtrl(self,size=(180,75),
style=wx.TE_MULTILINE|wx.TE_PROCESS_ENTER)
self.Current = TextCtrl(self,size=(160,-1),style=wx.TE_PROCESS_ENTER)
self.New = TextCtrl(self,size=(160,-1),style=wx.TE_PROCESS_ENTER)
self.ClearButton = wx.Button (self,label="Clear")
self.AcceptButton = wx.Button (self,label="Accept")
# Callbacks
self.Bind (wx.EVT_TEXT_ENTER,self.OnHistory,self.History)
self.Bind (wx.EVT_BUTTON,self.OnClear,self.ClearButton)
self.Bind (wx.EVT_BUTTON,self.OnAccept,self.AcceptButton)
self.Bind (wx.EVT_CLOSE,self.OnClose)
# Layout
layout = wx.BoxSizer(wx.VERTICAL)
layout.Add (self.History,flag=wx.EXPAND|wx.ALL,border=10)
grid = wx.FlexGridSizer(cols=2,hgap=5,vgap=5)
flag = wx.ALIGN_CENTER_VERTICAL
grid.Add (wx.StaticText(self,label="New:"),flag=flag)
grid.Add (self.New,flag=flag)
grid.Add (wx.StaticText(self,label="Current:"),flag=flag)
grid.Add (self.Current,flag=flag)
layout.Add (grid,flag=wx.EXPAND|wx.ALL,border=10)
buttons = wx.BoxSizer(wx.HORIZONTAL)
buttons.Add (self.ClearButton)
buttons.AddSpacer(5)
buttons.Add (self.AcceptButton)
layout.Add (buttons,flag=wx.EXPAND|wx.ALL,border=10)
self.SetSizer(layout)
self.Fit()
self.update()
def update(self,Event=0):
"""Update displayed history"""
self.History.Value = self.format_history(self.Parent.learn_center_history)
xc,yc = self.Parent.rotation_center
zc = self.Parent.calibration_z
xn,yn = self.Parent.rotation_center_xy_based_on_history
zn = self.Parent.zc
self.New.Value = "%.3f,%.3f,%.3f mm" % (xn,yn,zn)
self.Current.Value = "%.3f,%.3f,%.3f mm" % (xc,yc,zc)
self.ClearButton.Enabled = len(self.Parent.learn_center_history) > 0
from numpy import allclose,isnan
self.AcceptButton.Enabled = not allclose([xc,yc],[xn,yn]) and \
not any(isnan([xn,yn]))
# Relaunch yourself.
self.update_timer = wx.Timer(self)
self.Bind(wx.EVT_TIMER,self.update,self.update_timer)
self.update_timer.Start(2000,oneShot=True)
def OnHistory(self,event):
"""Accept Edits"""
try:
history = self.parse_history(self.History.Value)
self.Parent.learn_center_history = history
except: pass
self.update()
def OnClear(self,event):
"""Reset click-center history"""
self.Parent.learn_center_history = []
self.update()
def OnAccept(self,event):
"""Update sample center, using click-center history"""
self.Parent.accept_rotation_center()
self.update()
def OnClose(self,event):
"""Called when the widnows's close button is clicked"""
self.Destroy()
@staticmethod
def format_history(learn_center_history):
"""Convert history from list to string"""
from numpy import nan
keys = "<KEY>"
lines = []
for entry in learn_center_history:
values = []
for key in keys:
try: value = entry[key]
except: value = nan
values += [value]
lines += [", ".join(["%.3f" % value for value in values])]
s = "\n".join(lines)
return s
@staticmethod
def parse_history(s):
"""Convert history from string to list"""
from numpy import nan
keys = "<KEY>"
learn_center_history = []
for line in split(s,"\n"):
values = line.split(",")
entry = {}
for i in range(0,len(keys)):
try: entry[keys[i]] = eval(values[i])
except: entry[keys[i]] = nan
learn_center_history += [entry]
return learn_center_history
class SampleCenter(wx.Dialog):
"""Define Rotation Center of an Object"""
def __init__ (self,parent):
wx.Dialog.__init__(self,parent,-1,"Sample Center")
# Controls
self.Current = TextCtrl(self,size=(175,-1),style=wx.TE_PROCESS_ENTER)
self.New = TextCtrl(self,size=(175,-1),style=wx.TE_PROCESS_ENTER)
self.AcceptButton = wx.Button (self,label="Accept")
# Callbacks
self.Bind (wx.EVT_BUTTON,self.OnAccept,self.AcceptButton)
self.Bind (wx.EVT_CLOSE,self.OnClose)
# Layout
layout = wx.BoxSizer(wx.VERTICAL)
grid = wx.FlexGridSizer(cols=2,hgap=5,vgap=5)
flag = wx.ALIGN_CENTER_VERTICAL
grid.Add (wx.StaticText(self,label="New:"),flag=flag)
grid.Add (self.New,flag=flag)
grid.Add (wx.StaticText(self,label="Current:"),flag=flag)
grid.Add (self.Current,flag=flag)
layout.Add (grid,flag=wx.EXPAND|wx.ALL,border=10)
buttons = wx.BoxSizer(wx.HORIZONTAL)
buttons.Add (self.AcceptButton)
layout.Add (buttons,flag=wx.EXPAND|wx.ALL,border=10)
self.SetSizer(layout)
self.Fit()
self.update()
def update(self,Event=0):
"""Update displayed history"""
x1,y1,z1 = self.Parent.click_center_x,self.Parent.click_center_y,\
self.Parent.click_center_z
x2,y2 = self.Parent.current_sample_center_xy
z2 = self.Parent.zc - self.Parent.calibration_z
self.Current.Value = "%.3f,%.3f,%.3f mm" % (x1,y1,z1)
self.New.Value = "%.3f,%.3f,%.3f mm" % (x2,y2,z2)
from numpy import allclose,isnan
self.AcceptButton.Enabled = not allclose([x1,y1,z1],[x2,y2,z2]) \
and not any(isnan([x2,y2,z2]))
# Relaunch yourself.
self.update_timer = wx.Timer(self)
self.Bind(wx.EVT_TIMER,self.update,self.update_timer)
self.update_timer.Start(2000,oneShot=True)
def OnAccept(self,event):
"""Update sample center, using history"""
self.Parent.current_center_x,self.Parent.current_center_y = \
self.Parent.click_center_x,self.Parent.click_center_y = \
self.Parent.current_sample_center_xy
self.Parent.click_center_z = self.Parent.zc - self.Parent.calibration_z
self.update()
def OnClose(self,event):
"""Called when the widnows's close button is clicked"""
self.Destroy()
@staticmethod
def parse_history(s):
"""Convert history from string to list"""
return eval(s)
def point_line_distance (P,line):
"""Distance of a point to a line segment of finite length
P: (x,y,z)
line: ((x1,y1,z1),(x2,y2,z2))"""
# Source: softsurfer.com/Archive/algorithm_0102/algorithm_0102.htm
# 18 May 2007
from numpy import dot
P0 = line[0]; P1 = line[1]
v = vector(P0,P1); w0 = vector(P0,P); w1 = vector(P1,P)
# If the angle (P,P0,P1) is obtuse (>=90 deg), it is the distance to P0.
if dot(w0,v) <= 0: return distance(P,P0)
# If the angle(P,P1,P0) is obtuse (>=90 deg), it is the distance to P1.
if dot(w1,v) >= 0: return distance(P,P1)
# Otherwise, it is the orthognal distance to the line.
b = dot(w0,v) / float(dot(v,v))
Pb = translate(P0,scale(v,b))
return distance(P,Pb)
def vector(p1,p2):
"""Vector from point p1 to point p2
p1: (x1,y1,z1)
p2: (x2,y2,z2)"""
from numpy import asarray
p1,p2 = asarray(p1),asarray(p2)
return p2-p1
def translate(p,v):
"""Applies the vector (vx,vy) to point (x,y)
p: (x,y,z)
v: (vx,vy,vz)"""
from numpy import asarray
p,v = asarray(p),asarray(v)
return p+v
def scale(v,a):
"""Multiplies vector with scalar
v: (x,y,z)"""
from numpy import asarray
v = asarray(v)
return v*a
def distance(p1,p2):
"""Distance between two points p1 and p2
p1: (x1,y1,z1)
p2: (x2,y2,z2)"""
from numpy import asarray
p1,p2 = asarray(p1),asarray(p2)
from numpy.linalg import norm
return norm(p2-p1)
def interpreter():
"""For debugging: run a python interpreter"""
from sys import stdin,stdout,stderr
import readline
readline.parse_and_bind("tab: complete")
while True:
try: command = raw_input(">>> ")
except EOFError: break
if command == "": break
try: print("%r" % eval(command))
except:
try: exec(command)
except Exception,msg: stderr.write("%s\n" % msg)
# The following is only executed when run as stand-alone application.
if __name__ == '__main__': # for testing
from pdb import pm # for debugging
name = "MicroscopeCamera"
from redirect import redirect
redirect(name,format="%(asctime)s %(levelname)s %(module)s.py, "
"line %(lineno)d, %(funcName)s: %(message)s")
##import CameraViewer as x; x.DEBUG = True # for debugging
##import logging
##logging.basicConfig(level=logging.DEBUG,format="%(asctime)s: %(message)s")
wx.app = wx.App(redirect=False)
viewer = SampleAlignmentViewer(name=name)
self = viewer # for debugging
##from thread import start_new_thread
##start_new_thread(interpreter,())
wx.app.MainLoop()
<file_sep>#!/usr/bin/env python
"""
Grapical User Interface for FPGA Timing System.
Author: <NAME>
Date created: 2015-05-27
Date last modified: 2019-05-29
"""
__version__ = "5.3" # hsc_delay, cleanup
from logging import debug,info,warn,error
import wx, wx3_compatibility
from Panel import BasePanel
class Timing_Panel(BasePanel):
"""Control Panel for FPGA Timing System"""
name = "Timing_Panel"
title = "Timing"
icon = "timing-system"
def hlc_choices():
from timing_system import timing_system
from numpy import arange,finfo
eps = finfo(float).eps
hsct = timing_system.hsct
choices = arange(-12*hsct,+12*hsct+eps,hsct)
return choices
def hsc_choices():
from timing_system import timing_system
from numpy import arange,finfo
eps = finfo(float).eps
P0t = timing_system.P0t
choices = arange(-12*P0t/24,12*P0t/24+eps,P0t/24)
return choices
from Ensemble_SAXS_pp import Ensemble_SAXS
from timing_sequence import timing_sequencer
parameters = [
[("Delay", Ensemble_SAXS,"delay", "time" ),{}],
[("Nom. Delay", Ensemble_SAXS,"nom_delay","time" ),{}],
[("Mode", Ensemble_SAXS,"mode" ),{}],
[("Period [1-kHz cycles]", Ensemble_SAXS,"trigger_period_in_1kHz_cycles"),{}],
[("Laser", Ensemble_SAXS,"laser_on", "Off/On"),{}],
[("X-ray ms shutter", Ensemble_SAXS,"ms_on", "Off/On"),{}],
[("Pump", Ensemble_SAXS,"pump_on", "Off/On"),{}],
[("Trigger code", Ensemble_SAXS,"transc", "binary"),{}],
[("X-ray detector trigger",Ensemble_SAXS,"xdet_on", "Off/On"),{}],
[("Image number", Ensemble_SAXS,"image_number" ),{}],
[("X-ray detector count", Ensemble_SAXS,"xdet_count", "integer"),{}],
[("X-ray detector trigger count", timing_sequencer,"xdet_trig_count", "integer"),{}],
[("X-ray detector acquistion count",timing_sequencer,"xdet_acq_count", "integer"),{}],
[("X-ray scope trigger count", timing_sequencer,"xosct_trig_count","integer"),{}],
[("X-ray scope acquistion count", timing_sequencer,"xosct_acq_count", "integer"),{}],
[("Laser scope trigger count", timing_sequencer,"losct_trig_count","integer"),{}],
[("Laser scope acquistion count", timing_sequencer,"losct_acq_count", "integer"),{}],
[("Passes", Ensemble_SAXS,"passes" ),{}],
[("Pass number", Ensemble_SAXS,"pass_number" ),{}],
[("Pulses", Ensemble_SAXS,"pulses" ),{}],
[("Image number increment",Ensemble_SAXS,"image_number_inc","Off/On"),{}],
[("Pass number increment", Ensemble_SAXS,"pass_number_inc" ,"Off/On"),{}],
[("Acquiring", timing_sequencer, "acquiring", "Idle/Acquiring"),{}],
[("Queue active", timing_sequencer, "queue_active" ,"Not Active/Active"),{}],
[("Queue length [sequences]",timing_sequencer, "queue_length", "integer"),{}],
[("Current queue length [seq]",timing_sequencer,"current_queue_length","integer"),{}],
[("Queue sequence count" ,timing_sequencer, "queue_sequence_count","integer"),{}],
[("Current queue sequence cnt",timing_sequencer,"current_queue_sequence_count","integer"),{}],
[("Queue repeat count" ,timing_sequencer, "queue_repeat_count","integer"),{}],
[("Current queue repeat count",timing_sequencer,"current_queue_repeat_count","integer"),{}],
[("Queue max repeat count", timing_sequencer, "queue_max_repeat_count","integer"),{}],
[("Current queue max repeat",timing_sequencer,"current_queue_max_repeat_count","integer"),{}],
[("Next queue sequence cnt",timing_sequencer,"next_queue_sequence_count","integer"),{}],
[("Cache", timing_sequencer,"cache_enabled","Disabled/Caching"),{}],
[("Packets generated", timing_sequencer,"cache_size"),{}],
[("Packets loaded", timing_sequencer,"remote_cache_size"),{}],
[("Sequencer Running", Ensemble_SAXS,"running","Stopped/Running"),{}],
[("Sequence generator", Ensemble_SAXS,"generator"),{"read_only":True}],
[("Sequence generator version",Ensemble_SAXS,"generator_version"),{"read_only":True}],
[("Heatload chopper phase",Ensemble_SAXS,"hlcnd","time.6" ),{"choices":hlc_choices}],
[("Heatload chop. act. phase",Ensemble_SAXS,"hlcad","time.6" ),{"choices":hlc_choices}],
[("High-speed chopper phase",Ensemble_SAXS,"hsc_delay","time.4"),{"choices":hsc_choices}],
[("P0 shift", timing_sequencer,"p0_shift","time.4"),{}],
[("X-ray delay", Ensemble_SAXS,"xd","time.6"),{}],
]
standard_view = [
"Delay",
"Mode",
"Period [1-kHz cycles]",
"Laser",
"X-ray ms shutter","Pump",
"Trigger code",
"X-ray detector trigger",
"X-ray scope trigger",
"Laser scope trigger",
"Sequencer Running",
]
def __init__(self,parent=None):
from Panel import PropertyPanel
from Timing_Setup_Panel import Timing_Setup_Panel
from Timing_Channel_Configuration_Panel import Timing_Channel_Configuration_Panel
from Timing_Calibration_Panel import Timing_Calibration_Panel
from Timing_Clock_Configuration_Panel import Timing_Clock_Configuration_Panel
from PP_Modes_Panel import PP_Modes_Panel
from Sequence_Modes_Panel import Sequence_Modes_Panel
from Timing_Configuration_Panel import Timing_Configuration_Panel
BasePanel.__init__(self,parent=parent,
name=self.name,
title=self.title,
icon=self.icon,
component=PropertyPanel,
parameters=self.parameters,
standard_view=self.standard_view,
label_width=180,
refresh=True,
live=True,
subpanels=[
["Setup...", Timing_Setup_Panel],
["Channel Configuration...",Timing_Channel_Configuration_Panel],
["Calibration...", Timing_Calibration_Panel],
["Clock Configuration...", Timing_Clock_Configuration_Panel],
["PP Modes...", PP_Modes_Panel],
["Sequence Modes...", Sequence_Modes_Panel],
["Configuration...", Timing_Configuration_Panel],
],
buttons=[
["Cal..",Timing_Calibration_Panel],
["Conf..",Timing_Channel_Configuration_Panel],
["Setup..",Timing_Setup_Panel],
["Modes..",PP_Modes_Panel],
],
)
if __name__ == '__main__':
from pdb import pm # for debugging
from redirect import redirect
redirect("Timing_Panel")
import autoreload
import wx
wx.app = wx.App(redirect=False)
panel = Timing_Panel()
wx.app.MainLoop()
<file_sep>"""Delay line linearity characterization
<NAME>, Jul 22, 2015 - Jul 23, 2015
Setup:
Ramsay-100B RF Generator, 351.93398 MHz +10 dBm -> FPGA RF IN
FPGA 1: X-scope trig -> CH1, DC50, 500 mV/div
FPGA 13: ps L oscill -> DC block -> 90-MHz low-pass -> CH2, DC50, 500 mV/div
Timebase 5 ns/div
Measurement P1 CH2, time@level, Percent, 50%, Slope Pos, Gate Start 4.5 div, Stop 5.5 div
FPGA Frequency: 41 Hz
"""
__version__ = "2.1"
from instrumentation import timing_system,lxd,bcf,clksrc,lecroy_scope
from scan import rscan,timescan as tscan
from sleep import sleep
delay = lecroy_scope("pico21").measurement(1)
tmax = 5/bcf
def scan():
lxd.value = 0
data = rscan([lxd,delay.gate.start,delay.gate.stop],0,[tmax,-tmax,-tmax],
640,delay,averaging_time=60.0,logfile="logfiles/delay.log")
def timescan():
data = tscan(delay,averaging_time=4.0,logfile="logfiles/delay.log")
def peridiocally_interrupt_clock():
while True:
try:
clksrc.state = 'RJ45:1'
sleep(4)
clksrc.state = 'RF IN'
sleep(60-4)
except KeyboardInterrupt: break
clksrc.state = 'RF IN'
if __name__ == "__main__":
print('timing_system.ip_address = %r' % timing_system.ip_address)
print('scan()')
print('peridiocally_interrupt_clock()')
print('timescan()')
<file_sep>#!/usr/bin/env python
"""
Python interface for the LCLS XPP laser timing system
Laser-to-X-ray time delay + Timing Tool correction
Laser-to-X-ray time delay: electronic phase shift
Timing Tool correction: mechanical delay stage
What is the current value? m.lxt_ttc.wm()
Change value: m.lxt_ttc.mv()
Is it changing? m.las_tt_delay.ismoving()
<NAME>, 19 Oct 2010 - 27 Jan 2016
"""
__version__ = "2.1" # replaced "lxt_tt" with "lxt"
from numpy import isnan,nan,inf,array
from DB import dbput,dbget
from time import sleep,time
from thread import start_new_thread
from logging import debug,info,warn,error
try: import xppbeamline
except: warn("module 'xppbeamline' not available")
from numpy import isnan
class Lxd(object):
"""Laser x-ray time delay in seconds"""
sign = 1
unit = "s"
# This is to make sure that this command is called in main thread first.
# If is called from a different thread the first time, it raises an
# Exception:
# channel already created in create_channel() file pyca/pyca.cc at line
# 25 PV XPP:USER:VIT:T0
if "xppbeamline" in globals():
t = xppbeamline.m.lxt.wm()
xppbeamline.m.lxt.mv(t)
def get_command_dial(self):
"""Uncalibrated nominal time delay in units of seconds."""
try: value = xppbeamline.m.lxt_ttc.wm()
except Exception,msg:
warn("Timing_XPP: lxd: m.lxt_ttc.wm(): %s" % msg); value = nan
return value
def set_command_dial(self,value):
if not isnan(value):
start_new_thread(xppbeamline.m.lxt.mv,(value,))
command_dial = property(get_command_dial,set_command_dial)
def get_readback_dial(self):
"""Uncalibrated actual time delay in units of s."""
try: value = xppbeamline.m.lxt_ttc.wm()
except Exception,msg:
warn("Timing_XPP: lxd: m.lxt_ttc.wm(): %s" % msg); value = nan
return value
readback_dial = property(get_readback_dial)
dial = property(get_readback_dial,set_command_dial)
def get_moving(self):
"""Is timing still shifting?"""
return False
def set_moving(self,value):
"""Is value = False stop the ramping"""
pass
moving = property(get_moving,set_moving)
def stop():
"""If the phase shift is still ramping, stop the ramping"""
self.moving = False
def user_to_dial(self,value):
"Convert calibrated to uncalibrated time delay"
dial_value = (value - self.offset) * self.sign
return dial_value
def dial_to_user(self,dial_value):
"Convert uncalibrated to calibrated time delay"
user_value = dial_value*self.sign + self.offset
return user_value
def get_command_value(self):
"""Calibrated Laser to X-ray time delay in units of seconds.
Positive value means X-ray comes after laser"""
return self.dial_to_user(self.command_dial)
def set_command_value(self,value):
self.command_dial = self.user_to_dial(value)
command_value = property(get_command_value,set_command_value)
def get_readback_value(self):
"""Calibrated Laser to X-ray time delay in units of seconds.
Positive value means X-ray comes after laser"""
return self.dial_to_user(self.dial)
readback_value = property(get_readback_value)
value = property(get_readback_value,set_command_value)
def define_value(self,value):
"""Modify the user-to-dial offset such that the new user value is
'value'"""
self.offset = value - self.dial * self.sign
# user = dial*sign + offset; offset = user - dial*sign
def get_min(self):
"""Smallest possible time delay in s"""
return min(self.dial_to_user(self.min_dial),self.dial_to_user(self.max_dial))
min = property(get_min)
def get_max(self):
"""Largest possible time delay in s"""
return max(self.dial_to_user(self.min_dial),self.dial_to_user(self.max_dial))
max = property(get_max)
def get_offset(self):
"""Calibration offset in seconds"""
offset = dbget("timing.lxd.offset")
try: return float(offset)
except Exception: return 0.0
def set_offset(self,value):
dbput("timing.lxd.offset",str(value))
offset = property(get_offset,set_offset)
def get_min_dial(self):
"""Calibration min_dial in seconds"""
min_dial = dbget("timing.lxd.min_dial")
try: return float(min_dial)
except Exception: return -inf
def set_min_dial(self,value):
dbput("timing.lxd.min_dial",str(value))
min_dial = property(get_min_dial,set_min_dial)
def get_max_dial(self):
"""Calibration max_dial in seconds"""
max_dial = dbget("timing.lxd.max_dial")
try: return float(max_dial)
except Exception: return inf
def set_max_dial(self,value):
dbput("timing.lxd.max_dial",str(value))
max_dial = property(get_max_dial,set_max_dial)
lxd = Lxd()
if __name__ == "__main__": # for testing
from time import sleep
self = lxd
delays = [0,100e-15,1e-12,10e-12,100e-12,1e-9]
<file_sep>ip_address = 'id14l-scope.cars.aps.anl.gov:2000'
trig_count_name = 'losct_trig_count'
acq_count_name = 'losct_acq_count'
auto_synchronize = True
auto_acquire = True<file_sep>Calibration.CustomView = ['X-ray Scope Trigger', 'Ps Laser Osc. Delay', 'Ps Laser Trigger', 'Ns Laser Q-Switch Trigger', 'Ns Laser Flash Lamp Trigger', 'Heatload Chopper Phase', 'Heatload Chop. Act. Phase', 'High-Speed Chopper Phase', 'X-ray Shutter Delay', 'X-ray Detector Pulse Length']
Calibration.clk_shift.step = 1.0312799999999999e-10
Calibration.hlcnd.step = 1.0001875351628431e-06
Calibration.hsc_delay.step = 2.841441861258077e-09
Calibration.lcam.step = 1.0001875920023408e-06
Calibration.losct.step = 1.0001875920023408e-06
Calibration.ms.step = 0.001
Calibration.nsf.step = 1.9999488540464975e-05
Calibration.nsq.step = 1.4207209306290384e-09
Calibration.ps_lxd.step = 1e-08
Calibration.psd1.step = 1.0048e-09
Calibration.psg.step = 0.0010000000568288405
Calibration.pso.step = 1e-10
Calibration.pst.step = 2.841441861258077e-09
Calibration.s1.step = 0.0010000000568288405
Calibration.s3.step = 0.001
Calibration.trans.step = 0.0010000000568288405
Calibration.view = 'Custom'
Calibration.xosct.step = 2.841441861258077e-09
Configuration.CustomView = ['RF clock in', 'RF clock frequency', 'Clock multiplier', 'Clock DFS frequency mode', 'Clock DLL frequency mode', 'Clock multiplier working', 'Bunch clock frequency', 'SB clock in', 'SB clock frequency', 'Clock shift step size', '1-kHz clock divider of RF/4', '1-kHz clock frequency', '1-kHz clock phased by SB clock', '1-kHz clock divider of SB clock', 'Heatload chopper encoder in', 'Heatload chopper slots count', 'X-ray base frequency divider of 1-kHz clock', 'X-ray base frequency', 'Ns laser divider of 1-kHz clock', 'Ns laser frequency', 'Ps oscillator clock auto-lock']
Configuration.view = 'Custom'
CustomView = ['Delay', 'Laser', 'Waitting time', 'Pulses per image', 'Burst waitting time', 'Burst delay', 'X-ray ms shutter mode', 'X-ray det. trigger mode', 'X-ray scope trigger', 'Laser scope trigger', 'Laser camera trigger', 'Sample Translation', 'X-ray detector count', 'Image number', 'Image Number Increment', 'Acquiring', 'Queue active', 'Queue repeat count', 'Queue max repeat count', 'Queue sequence count', 'Queue length [sequences]', 'Cache', 'Cache size [passes]', 'Sequencer Running', 'Sequence generator', 'Sequence generator version', 'Heatload chopper phase', 'High-speed chopper phase']
View = ['Laser Mode', 'Trigger Mode', 'Laser Trigger', 'Laser Scope Trigger', 'X-Ray Scope Trigger', 'X-Ray Detector Trigger', 'Base Frequency', 'Frequency', 'Burst Period', 'Burst Delay', 'Burst Length', 'Bursts per Image', 'Image Count', 'Image Burst Count', 'Laser to X-ray Delay']
refresh_period = 1.0
view = 'Custom'
Calibration.channel(13).step = 5e-11
Calibration.psod2.step = 9.96904e-10
Calibration.channel(12).step = 2.841441861258077e-09
Calibration.0xF0FFB058+0:20.step = 9.94504651440327e-09
TimingConfiguration.CustomView = ['#', '1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23', '24']
Calibration.psod3.step = 1e-09
Calibration.channel(0).step = 2.841441861258077e-09
Calibration.channel(count = 5,mnemonic='ms').step = 0.001
Calibration.cmcnd.step = 1.0229190700529076e-07
Calibration.ch4_delay.step = 0.001
Calibration.hlcad.step = 0.0010000056828837224
Calibration.ch18.step = 1.4207209306290384e-09
Calibration.ch1.step = 1.4207209306290384e-09
Calibration.ch6.step = 0.001
Calibration.ch17.step = 1.4207209306290384e-09<file_sep>#!/usr/bin/env python
"""Ice diffraction detection
Authors: <NAME>, <NAME>, <NAME>
Date created: 2017-10-31
Date last modified: 2018-10-31
"""
from logging import debug,warn,info,error
from sample_frozen import sample_frozen
#from sample_frozen_optical2 import sample_frozen_optical
print('1')
from Panel import BasePanel,PropertyPanel,ButtonPanel,TogglePanel,TweakPanel
print('2')
import wx
print('3')
__version__ = "1.4" # ROI
class SampleFrozenPanel(BasePanel):
name = "SampleFrozenPanel"
title = "Sample Frozen"
standard_view = [
"Diffraction Spots",
"Threshold [spots]",
"Deice enabled",
"Deicing",
]
parameters = [
[[PropertyPanel,"Diffraction Spots",sample_frozen,"diffraction_spots"],{"read_only":True}],
[[PropertyPanel,"Threshold [spots]",sample_frozen,"threshold_N_spts"],{"choices":[1,10,20,50]}],
[[TogglePanel, "Deice enabled", sample_frozen,"running"],{"type":"Off/Monitoring"}],
[[TogglePanel, "Deicing", sample_frozen,"deicing"],{"type":"Not active/Active"}],
[[PropertyPanel,"ROIX", sample_frozen,"ROIX"],{"choices":[1000,900]}],
[[PropertyPanel,"ROIY", sample_frozen,"ROIX"],{"choices":[1000,900]}],
[[PropertyPanel,"WIDTH", sample_frozen,"WIDTH"],{"choices":[150,300,400]}],
#[[TogglePanel, "Optical Server enabled", sample_frozen_optical,"is_running"],{"type":"Off/On"}],
#[[TogglePanel, "Optical Intervention enabled", sample_frozen_optical,"is_intervention_enabled"],{"type":"Off/Monitoring"}],
#[[PropertyPanel, "Scattering", sample_frozen_optical,"scattering"],{"read_only":True}],
]
def __init__(self,parent=None):
BasePanel.__init__(self,
parent=parent,
name=self.name,
title=self.title,
icon="Tool",
parameters=self.parameters,
standard_view=self.standard_view,
)
if __name__ == '__main__':
from pdb import pm
import logging
from tempfile import gettempdir
print('4')
logfile = gettempdir()+"/SampleFrozenPanel.log"
logging.basicConfig(level=logging.DEBUG,
format="%(asctime)s %(levelname)s: %(message)s",
#logfile=logfile,
)
print('5')
# Needed to initialize WX library
if not "app" in globals(): app = wx.App(redirect=False)
print('6')
panel = SampleFrozenPanel()
print('7')
app.MainLoop()
<file_sep>CustomView = ['Data']
view = 'Standard'<file_sep>#!/usr/bin/env python
"""Low magnification, wide field of view video camera of the diffractometer,
used for aligning a crystal in the X-ray beam
<NAME>, 19 Feb 2008 - 26 Jun 2017"""
__version__ = "1.8.1" # name changed to WideFieldCamera
import logging; from tempfile import gettempdir
logfile = gettempdir()+"/WideFieldCamera.log"
logging.basicConfig(level=logging.DEBUG,format="%(asctime)s: %(message)s",
filename=logfile)
logging.debug("WideFieldCamera started")
from os import chmod
try: chmod(logfile,0666)
except Exception,msg: print("%s: %s" % (logfile,msg))
import wx
wx.app = wx.App(redirect=False)
from SampleAlignmentViewer import SampleAlignmentViewer
# Except "name" and "title" the parameters passed to "SampleAlignmentViewer"
# are just default values that can be overridden by user-editable settings
# within the Camera application. The default values are noly used at first run,
# or when the settigns file is lost or otherwise unusable.
viewer = SampleAlignmentViewer(
name="WideFieldCamera",
title="Wide-Field camera [advanced] (60 deg)",
orientation=0,
pixelsize=0.00465, # CCD pixel size 4.65 um, magnification ca. 1X
camera_angle=60,
)
wx.app.MainLoop()
logging.debug("WideFieldCamera closed")
<file_sep>"""This script is to test various implementations of the Python to EPICS interface.
It checks wether these are multi-thread safe. That means that a caput and caget
to the same process valiable succeeds both from the forground and from a background
thread.
EpicsCA: <NAME>, U Chicago
epics: <NAME>, U Chicago
CA: <NAME>, NIH
<NAME>, APS, 14 Apr 2010
"""
##import epics; epics.ca.PREEMPTIVE_CALLBACK = False
from epics import caput,caget # choices: EpicsCA, epics, CA
from time import sleep
from threading import Thread
def run_test(count=1):
# Communicate with SSCS Oasis 160 Thermoelectric chiller using a serial
# interface.
fail_count = 0
for i in range(0,count):
# Faults
caput("14IDB:serial13.NRRD",2,wait=True,timeout=1)
caput("14IDB:serial13.AOUT","H",wait=True,timeout=1)
##sleep(0.2)
result = caget("14IDB:serial13.TINP")
expected = 'H\\000'
print "expecting %r, got %r" % (expected,result)
if result != expected: fail_count += 1
# Nominal temperature
caput("14IDB:serial13.NRRD",3,wait=True,timeout=1)
caput("14IDB:serial13.AOUT","A",wait=True,timeout=1)
##sleep(0.2)
result = caget("14IDB:serial13.TINP")
expected = 'A\\226\\000'
print "expecting %r, got %r" % (expected,result)
if result != expected: fail_count += 1
if fail_count: print "[Test failed (%d/%d).]" % (fail_count,count*2)
print "Foreground:"
run_test(2)
print "Background:"
thread = Thread(target=run_test,args=(2,))
thread.start()
thread.join()
<file_sep>#!/usr/bin/env python
"""
Grapical User Interface for inspecting images.
Author: <NAME>, 16 Jan 2009 - 29 Jun 2017
"""
import wx
from math import sqrt,atan2,sin,cos,pi,log10
from numpy import *
__version__ = "4.2.2" # show_image
class ImageViewer_Window (wx.Frame):
image_timestamp = 0
def __init__(self,show=True,image_file="",mask_file=""):
"""
default_orientation: default image rotation in degrees
positive = counter-clock wise
allowed values: 0,-90,90,180
only use at first invecation as default value, last saved value
overrides this value.
show: display the window immediately
"""
wx.Frame.__init__(self,parent=None,size=(425,340))
self.Bind (wx.EVT_CLOSE,self.OnClose)
# Menus
menuBar = wx.MenuBar()
menu = wx.Menu()
menu.Append (101,"&Open Image...\tCtrl+O","File formats: TIFF,JPEG,PNG")
self.Bind (wx.EVT_MENU,self.OpenImage,id=101)
menu.Append (111,"&New Window...\tCtrl+N","Open Image in a new window")
self.Bind (wx.EVT_MENU,self.NewWindow,id=111)
menu.Append (102,"&Overlay Mask...","File formats: TIFF,JPEG,PNG")
self.Bind (wx.EVT_MENU,self.OpenMask,id=102)
menu.Append (103,"&Close Image")
self.Bind (wx.EVT_MENU,self.CloseImage,id=103)
menu.Append (104,"&Close Mask")
self.Bind (wx.EVT_MENU,self.CloseMask,id=104)
menu.AppendSeparator()
menu.Append (107,"&Save Image As...\tCtrl+S","File formats: TIFF,JPEG,PNG")
self.Bind (wx.EVT_MENU,self.SaveImage,id=107)
menu.Append (108,"&Save Mask As...","File formats: TIFF,JPEG,PNG")
self.Bind (wx.EVT_MENU,self.SaveMask,id=108)
menu.AppendSeparator()
menu.Append (110,"E&xit","Terminates this application.")
self.Bind (wx.EVT_MENU,self.OnExit,id=110)
menuBar.Append (menu,"&File")
menu = wx.Menu()
menu.Append (201,"&Copy Image","Puts full image into clipboard")
self.Bind (wx.EVT_MENU,self.CopyImage,id=201)
menuBar.Append (menu,"&Edit")
menu = self.OrientationMenu = wx.Menu()
style = wx.ITEM_RADIO
menu.Append (301,"Original","Do not rotate image",style)
menu.Append (302,"Rotated Clockwise","Rotate image by -90 deg",style)
menu.Append (303,"Rotated Counter-clockwise","Rotate image by +90 deg",style)
menu.Append (304,"Upside down","Rotate image by 180 deg",style)
for id in range(301,305): self.Bind (wx.EVT_MENU,self.OnOrientation,id=id)
menuBar.Append (menu,"&Orientation")
self.SetMenuBar (menuBar)
# Controls
self.CreateStatusBar()
self.panel = wx.Panel(self)
self.ImageViewer = ImageViewer (self.panel)
self.LiveImage = wx.CheckBox (self.panel,label="Live")
self.LiveImage.ToolTip = wx.ToolTip("Follow the data collection, show latest image")
self.First = wx.Button(self.panel,label="|<",size=(40,-1))
self.First.ToolTip = wx.ToolTip("Go to the first image in current directory")
self.Bind (wx.EVT_BUTTON,self.OnFirst,self.First)
self.Back = wx.Button(self.panel,label="< Back")
self.Back.ToolTip = wx.ToolTip("Go to the previous image in current directory")
self.Bind (wx.EVT_BUTTON,self.OnBack,self.Back)
self.Next = wx.Button(self.panel,label="Next >")
self.Next.ToolTip = wx.ToolTip("Go to the next image in current directory")
self.Bind (wx.EVT_BUTTON,self.OnNext,self.Next)
self.Last = wx.Button(self.panel,label=">|",size=(40,-1))
self.Last.ToolTip = wx.ToolTip("Go to the last image in current directory")
self.Bind (wx.EVT_BUTTON,self.OnLast,self.Last)
self.Order = wx.Choice(self.panel,choices=["By Name","By Time"])
self.Order.ToolTip = wx.ToolTip("Step through images by name or timestamp?")
self.Filter = wx.ComboBox(self.panel,size=(85,-1),style=wx.TE_PROCESS_ENTER,
choices=["*.*","*.mccd","*.rx","*.tif","*.tiff"])
self.Filter.Value = "*.*"
self.Filter.ToolTip = wx.ToolTip("Filter pattern for image files, e.g. *.tif")
# Layout
self.layout = wx.BoxSizer(wx.VERTICAL)
self.layout.Add (self.ImageViewer,proportion=1,flag=wx.EXPAND) # growable
self.Controls = wx.BoxSizer(wx.HORIZONTAL)
self.Controls.AddSpacer((5,5))
self.Controls.Add (self.LiveImage,flag=wx.ALIGN_CENTER)
self.Controls.AddSpacer((5,5))
self.Controls.Add (self.First,flag=wx.ALIGN_CENTER)
self.Controls.Add (self.Back,flag=wx.ALIGN_CENTER)
self.Controls.Add (self.Next,flag=wx.ALIGN_CENTER)
self.Controls.Add (self.Last,flag=wx.ALIGN_CENTER)
self.Controls.AddSpacer((5,5))
self.Controls.Add (self.Order,flag=wx.ALIGN_CENTER)
self.Controls.AddSpacer((5,5))
self.Controls.Add (self.Filter,flag=wx.ALIGN_CENTER)
self.Controls.AddSpacer((5,5))
self.layout.Add (self.Controls,flag=wx.EXPAND)
self.panel.SetSizer(self.layout)
# Restore last saved settings.
name = "ImageViewer"
self.config_file=wx.StandardPaths.Get().GetUserDataDir()+"/"+name+".py"
self.config = wx.FileConfig (localFilename=self.config_file)
state = self.config.Read('State')
if state:
try: self.State = eval(state)
except Exception,exception:
print "Restore failed: %s: %s" % (exception,state)
# Display images.
from os.path import exists
if exists(image_file): self.image_file = image_file
if exists(mask_file): self.mask_file = mask_file
# Initialization
self.Orientation = self.ImageViewer.Orientation
self.update_title()
if show: self.Show()
self.timer = wx.Timer(self)
self.Bind (wx.EVT_TIMER,self.update,self.timer)
self.timer.Start(1000,oneShot=True)
def OnFirst(self,event):
"""Go to the previous (older) image in current directory"""
self.live_image = False
next = newer_file if self.order == "By Time" else next_file
self.image_file = next(self.image_file,-1e6,self.filter)
def OnBack(self,event):
"""Go to the previous (older) image in current directory"""
self.live_image = False
next = newer_file if self.order == "By Time" else next_file
self.image_file = next(self.image_file,-1,self.filter)
def OnNext(self,event):
"""Go to the next (newer) image in current directory"""
self.live_image = False
next = newer_file if self.order == "By Time" else next_file
self.image_file = next(self.image_file,+1,self.filter)
def OnLast(self,event):
"""Go to the previous (older) image in current directory"""
self.live_image = False
next = newer_file if self.order == "By Time" else next_file
self.image_file = next(self.image_file,+1e6,self.filter)
def update(self,event=None):
"""Periodocally called on timer"""
if self.live_image and self.image_to_show and \
(self.image_to_show != self.image_file\
or getmtime(self.image_to_show) != self.image_timestamp):
##print "loading",self.image_to_show
self.image_file = self.image_to_show
self.timer = wx.Timer(self)
self.Bind (wx.EVT_TIMER,self.update,self.timer)
self.timer.Start(1000,oneShot=True)
def get_live_image(self):
"""Follow the data collection"""
return self.LiveImage.Value
def set_live_image(self,value):
self.LiveImage.Value = value
live_image = property(get_live_image,set_live_image)
def get_order(self):
"""Follow the data collection"""
return self.Order.StringSelection
def set_order(self,value):
self.Order.StringSelection = value
order = property(get_order,set_order)
def get_filter(self):
"""Follow the data collection"""
return self.Filter.Value
def set_filter(self,value):
self.Filter.Value = value
filter = property(get_filter,set_filter)
def get_image_file(self):
return getattr(self,"__image_file__","")
def set_image_file(self,image_file):
from os.path import exists
from numimage import numimage
try: image = numimage(image_file)
except Exception,message:
from sys import stderr
stderr.write("%s: %s\n" % (image_file,message))
image = None
self.ImageViewer.Image = image
self.image_timestamp = getmtime(image_file)
self.__image_file__ = image_file
self.update_title()
##print "image file: %r" % image_file
image_file = property(get_image_file,set_image_file)
def get_mask_file(self):
return getattr(self.ImageViewer.Mask,"filename","")
def set_mask_file(self,mask_file):
from os.path import exists
from numimage import numimage
if not exists(mask_file): mask = None
else:
try: mask = numimage(mask_file)
except Exception,message:
from sys import stderr
stderr.write("%s: %s\n" % (mask_file,message))
mask = None
self.ImageViewer.Mask = mask
self.update_title()
mask_file = property(get_mask_file,set_mask_file)
def update_title(self):
"""Displays the file name of the current image in the title bar of the
window."""
from os.path import basename
title = ""
if self.image_file: title += self.image_file[-80:]+", "
if self.mask_file: title += "mask "+basename(self.mask_file)
if len(title) < 40: title = "Image Viever - "+title
title = title.strip("-, ")
self.Title = title
def OpenImage(self,event):
"""Open an image in te current Window"""
from os.path import dirname,basename
dlg = wx.FileDialog(self,"Open Image",
wildcard="Image Files (*.mccd;*.tif;*.tiff;*.rx;*.png;*.jpg)|"\
"*.mccd;*.tif;*.tiff;*.rx;*.png;*.jpg",
defaultDir=dirname(self.image_file),
defaultFile=basename(self.image_file),
style=wx.OPEN)
if dlg.ShowModal() == wx.ID_OK:
filename = str(dlg.Path)
self.image_file = filename
dlg.Destroy()
def NewWindow(self,event):
"""Open an image in a new Window"""
from os.path import dirname,basename
dlg = wx.FileDialog(self,"Open Image",
wildcard="Image Files (*.mccd;*.tif;*.tiff;*.png;*.jpg)|"\
"*.mccd;*.tif;*.tiff;*.png;*.jpg",
defaultDir=dirname(self.image_file),
defaultFile=basename(self.image_file),
style=wx.OPEN)
if dlg.ShowModal() == wx.ID_OK:
filename = str(dlg.Path)
app.OpenFile(filename)
dlg.Destroy()
@property
def image_to_show(self):
"""Automatically load this image"""
from DB import dbget
from os.path import exists
from numpy import array
filenames = dbget("ImageViewer.images")
try: filenames = array(eval(filenames))
except: return ""
filenames = filenames[array(exist_files(filenames))]
if len(filenames) == 0: return ""
return filenames[-1]
def OpenMask(self,event):
"Called from menu File/Open Mask..."
from os.path import dirname,basename
dlg = wx.FileDialog(self,"Open Image",
wildcard="Image Files (*.png;*.tif;*.tiff;*.jpg)|"\
"*.png;*.tif;*.tiff;*.jpg",
defaultDir=dirname(self.mask_file),
defaultFile=basename(self.mask_file),
style=wx.OPEN)
if dlg.ShowModal() == wx.ID_OK: self.mask_file = str(dlg.Path)
dlg.Destroy()
def CloseImage(self,event):
"Called from menu File/Close Mask..."
self.ImageViewer.Image = None
self.image_file = ""
self.image_timestamp = 0
self.update_title()
def CloseMask(self,event):
"Called from menu File/Close Mask..."
self.mask_file = ""
self.update_title()
def SaveImage(self,event):
"Called from menu File/Save Mask As..."
dlg = wx.FileDialog(self,"Save Image As",wildcard="*.tif;*.png;*.jpg",
defaultFile=self.image_file,style=wx.SAVE|wx.OVERWRITE_PROMPT)
if dlg.ShowModal() == wx.ID_OK:
self.image_file = str(dlg.Path)
image = self.ImageViewer.Image
image.save (self.image_file)
dlg.Destroy()
def SaveMask(self,event):
"Called from menu File/Save Mask As..."
if not self.ImageViewer.Mask: return
dlg = wx.FileDialog(self,"Save Mask As",wildcard="*.png;*.tif;*.jpg",
defaultFile=self.mask_file,style=wx.SAVE|wx.OVERWRITE_PROMPT)
if dlg.ShowModal() == wx.ID_OK:
self.mask_file = str(dlg.Path)
mask = self.ImageViewer.Mask
mask.save (self.mask_file)
dlg.Destroy()
def CopyImage(self,event):
"Called from menu Edit/Copy Image"
bitmap = wx.BitmapFromImage (self.ImageViewer.Image)
bmpdo = wx.BitmapDataObject(bitmap)
if wx.TheClipboard.Open():
wx.TheClipboard.SetData(bmpdo)
wx.TheClipboard.Close()
else: wx.MessageBox("Unexpected clipboard problem","Error")
def OnOrientation(self,event):
id = event.GetId()
if id == 301: orientation = 0 # As image
if id == 302: orientation = -90 # Rotated Clockwise
if id == 303: orientation = +90 # Rotated Counter-clockwise
if id == 304: orientation = 180 # Upside down
self.Orientation = orientation
self.ImageViewer.Orientation = orientation
def GetOrientation(self):
"""Reads the image rotation as selected by the 'Orientation' menu.
Returns either 0,-90,90 or 180"""
if self.OrientationMenu.IsChecked(301): return 0
if self.OrientationMenu.IsChecked(302): return -90
if self.OrientationMenu.IsChecked(303): return 90
if self.OrientationMenu.IsChecked(304): return 180
def SetOrientation(self,value):
"""Updates the'Orientation' menu and the displayed image"""
if value == 0: self.OrientationMenu.Check(301,True)
if value == -90: self.OrientationMenu.Check(302,True)
if value == +90: self.OrientationMenu.Check(303,True)
if value == 180: self.OrientationMenu.Check(304,True)
Orientation = property (GetOrientation,SetOrientation,doc=
"Image rotation as defined by the 'Orientation' menu")
def GetState(self):
"This is to save the current settings of the window"
state = {}
state["Size"] = self.Size
state["Position"] = self.Position
state["ImageViewer.State"] = self.ImageViewer.State
state["mask_file"] = self.mask_file
state["order"] = self.order
state["filter"] = self.filter
return state
def SetState(self,state):
"This is to restore the current state of the window"
##print "MainWindow: restoring %r" % state
for key in state: exec("self."+key+"="+repr(state[key]))
State = property(GetState,SetState,doc="settings of the window")
def OnClose(self,event):
"Called on File/Exit or when the widnows's close button is clicked"
# Save settings for next time.
from os.path import exists,dirname
from os import makedirs
directory = dirname(self.config_file)
if not exists(directory): makedirs(directory)
self.config.Write ('State',repr(self.State))
self.config.Flush()
app.CloseWindow(self)
def OnExit(self,event):
"Called on File/Exit or when the widnows's close button is clicked"
# Save settings for next time.
self.config.Write ('State',repr(self.State))
self.config.Flush()
app.ExitApp()
class ImageViewer (wx.Panel):
"""Grapical User Interface for inspecting images."""
def __init__(self,parent):
"""Parent: top level window"""
wx.Panel.__init__(self,parent)
# Controls
self.ImageWindow = ImageWindow(self)
choices = ["200%","100%","50%","33%","25%","Fit Width"]
self.ScaleFactorControl = wx.ComboBox(self,value="100%",
choices=choices,style=wx.CB_DROPDOWN|wx.TE_PROCESS_ENTER)
self.SaturationLevelText = wx.TextCtrl (self,size=(50,-1),
style=wx.TE_PROCESS_ENTER)
self.SaturationValue_modified = False
self.SaturationLevelText.Bind (wx.EVT_CHAR,self.OnTypeSaturationValue)
self.SaturationLevelSlider = wx.Slider (self,maxValue=1000)
self.AutoContrastControl = wx.CheckBox (self,label="Auto")
# Layout
layout = wx.BoxSizer(wx.VERTICAL)
layout.Add (self.ImageWindow,proportion=1,flag=wx.EXPAND) # growable
layout.AddSpacer((2,2))
controls = wx.BoxSizer(wx.HORIZONTAL)
controls.AddSpacer((5,5))
controls.Add (self.ScaleFactorControl,flag=wx.ALIGN_CENTER)
controls.AddSpacer((5,5))
controls.Add (self.SaturationLevelText,flag=wx.ALIGN_CENTER)
controls.AddSpacer((5,5))
# Make exposure slider growable (proportion=1)
controls.Add (self.SaturationLevelSlider,proportion=1,flag=wx.ALIGN_CENTER)
controls.AddSpacer((5,5))
controls.Add (self.AutoContrastControl,flag=wx.ALIGN_CENTER)
controls.AddSpacer((5,5))
layout.Add (controls,flag=wx.EXPAND)
self.SetSizer(layout)
# Callbacks
self.Bind (wx.EVT_COMBOBOX,self.OnChangeScaleFactor,self.ScaleFactorControl)
self.Bind (wx.EVT_TEXT_ENTER,self.OnChangeScaleFactor,self.ScaleFactorControl)
self.Bind (wx.EVT_TEXT_ENTER,self.OnEnterSaturationValue,self.SaturationLevelText)
self.Bind (wx.EVT_SLIDER,self.OnMoveSlider,self.SaturationLevelSlider)
self.Bind(wx.EVT_CHECKBOX,self.OnAutoContrast,self.AutoContrastControl)
self.ImageWindow.Bind (wx.EVT_MOUSEWHEEL,self.OnMouseWheel)
# Initialization
self.ScaleFactor = self.ImageWindow.ScaleFactor
self.SaturationLevelTextValue = self.ImageWindow.SaturationLevel
self.SaturationLevelSliderValue = self.ImageWindow.SaturationLevel
def GetImage(self): return self.ImageWindow.Image
def SetImage(self,image): self.ImageWindow.Image = image
Image = property(GetImage,SetImage,doc="displayed image")
def GetMask(self): return self.ImageWindow.Mask
def SetMask(self,mask): self.ImageWindow.Mask = mask
Mask = property(GetMask,SetMask,doc="bitmap overlaid to image")
def GetPixelSize(self): return self.ImageWindow.PixelSize
def SetPixelSize(self,value): self.ImageWindow.PixelSize = value
PixelSize = property(GetPixelSize,SetPixelSize,doc="image raster in mm")
def GetCenter(self): return self.ImageWindow.Crosshair
def SetCenter(self,value): self.ImageWindow.Crosshair = value
Center = property(GetCenter,SetCenter,doc="crosshair position in pixels")
def OnChangeScaleFactor(self,event):
"Called when a different zoom is selected"
self.ImageWindow.ScaleFactor = self.ScaleFactorValue
def GetScaleFactorValue(self):
"""Reads the image scale control and returns is a number between 0
and 1, or None if 'Fit Width' is selected'."""
selection = self.ScaleFactorControl.GetValue()
try: return float(selection.strip("%"))/100
except: return None
def SetScaleFactorValue(self,scale):
"""Changes the scale control.
scale is a number between 0 and 1, scale=None means 'Fit Width'"""
if scale != None: self.ScaleFactorControl.SetValue("%.3g%%" % (scale*100.))
else: self.ScaleFactorControl.SetValue("Fit Width")
ScaleFactorValue = property (GetScaleFactorValue,SetScaleFactorValue,
doc="Current value of scale control as float or None")
def GetScaleFactor(self): return self.ImageWindow.ScaleFactor
def SetScaleFactor (self,value):
self.ImageWindow.ScaleFactor = value
self.ScaleFactorValue = value
ScaleFactor = property(GetScaleFactor,SetScaleFactor,doc=
"Scale factor applied to image for display")
def OnTypeSaturationValue(self,event):
"""Called when any test is typed in the exposure time field"""
self.SaturationValue_modified = True
# Pass this event on to further event handlers bound to this event.
# Otherwise, the typed text does not appear in the window.
event.Skip()
def OnEnterSaturationValue(self,event):
"""Called when Enter is pressed in the text box displaying the
exposure time."""
# Update the exposure time indicator
self.SaturationLevelSliderValue = self.SaturationLevelTextValue
# Apply the new exposure time to the image.
self.ImageWindow.SaturationLevel = self.SaturationLevelTextValue
self.ImageWindow.AutoContrast = False
self.AutoContrastControl.SetValue(False)
self.SaturationValue_modified = False
def SetSaturationLevelTextValue(self,count):
if not self.SaturationValue_modified:
self.SaturationLevelText.SetValue("%.0f" % count)
def GetSaturationLevelTextValue(self):
text = self.SaturationLevelText.GetValue()
try: return float(text)
except: return 500.0 # default value: 500 counts
SaturationLevelTextValue = property (GetSaturationLevelTextValue,
SetSaturationLevelTextValue,
doc="Count beyond which a pixel is rendred white")
def OnMoveSlider(self,event):
"Called if the slider controlling the exposure time is moved."
# Update the exposure time indicator
self.SaturationLevelTextValue = self.SaturationLevelSliderValue
self.AutoContrastControl.SetValue(False)
# Apply the new exposure time to the image.
self.ImageWindow.AutoContrast = False
self.ImageWindow.SaturationLevel = self.SaturationLevelSliderValue
def GetSaturationLevelSliderValue(self):
"Reads the exposure time in seconds from the slder position"
# The slider position is an integer value from 0 to Max
Max = self.SaturationLevelSlider.GetMax()
fraction = float(self.SaturationLevelSlider.GetValue())/Max
# This is translated into 0 to 65535 counts on a non-linear scale
count = 65535 * fraction**2
return count
def SetSaturationLevelSliderValue(self,count):
"Changes the slider position and exposure time indicator"
# This translates the range 0 to 1 seconds non-linearly to a fraction
# of the slider range.
fraction = (count/65535.0)**0.5
Max = self.SaturationLevelSlider.GetMax()
self.SaturationLevelSlider.SetValue(fraction*Max)
SaturationLevelSliderValue = property (GetSaturationLevelSliderValue,
SetSaturationLevelSliderValue,
doc="Count beyond which a pixel is rendred white")
def GetSaturationLevel(self): return self.ImageWindow.SaturationLevel
def SetSaturationLevel (self,value):
self.ImageWindow.SaturationLevel = value
self.SaturationLevelSliderValue = value
self.SaturationLevelTextValue = value
SaturationLevel = property(GetSaturationLevel,SetSaturationLevel,doc=
"Count beyond which a pixel is rendered white")
def OnAutoContrast(self,event):
"Called when the 'Auto' Checkbox is clicked"
self.ImageWindow.AutoContrast = self.AutoContrastControl.GetValue()
self.SaturationLevelSliderValue = self.ImageWindow.SaturationLevel
self.SaturationLevelTextValue = self.ImageWindow.SaturationLevel
def GetAutoContrast(self): return self.ImageWindow.AutoContrast
def SetAutoContrast (self,value):
self.ImageWindow.AutoContrast = value
self.AutoContrastControl.SetValue(value)
AutoContrast = property(GetAutoContrast,SetAutoContrast,doc=
"Automatically scale the image intensity")
def GetOrientation(self): return self.ImageWindow.orientation
def SetOrientation(self,value):
self.ImageWindow.orientation = value
self.ImageWindow.Refresh()
Orientation = property (GetOrientation,SetOrientation,doc=
"Image rotation as defined by the 'Orientation' menu")
def GetState(self):
"This is to save the current settings of the window"
state = {}
state["ScaleFactor"] = self.ScaleFactor
state["SaturationLevel"] = self.SaturationLevel
state["AutoContrast"] = self.AutoContrast
state["ImageWindow.State"] = self.ImageWindow.State
return state
def SetState(self,state):
"This is to restore the current state of the window"
##print "ImageView: restoring %r" % state
for key in state: exec("self."+key+"="+repr(state[key]))
State = property(GetState,SetState,doc="settings of the window")
def OnMouseWheel(self,event):
"Zoom in or out with the middle mouse scroll button."
nsteps = event.GetWheelRotation()/event.GetWheelDelta()
self.ScaleFactor *= 2**(0.25*nsteps)
class ImageWindow(wx.ScrolledWindow):
def __init__(self,parent,pixelsize=None,**options):
"pixelsize: in units of mm; used for measurements"
wx.ScrolledWindow.__init__(self,parent,**options)
from numpy import zeros,uint16
from numimage import numimage
self.image = numimage(zeros((2048,2048),uint16))
self.mask = None
self.scale_factor = 1.0
# Crosshair coordinates in pixels from the top left
self.crosshair = (1024,1024)
self.pixelsize = 1.0
if pixelsize: self.PixelSize = pixelsize;
self.orientation = 0
self.show_crosshair = True
self.crosshair_size = (0.05,0.05) # default crosshair size: 50x50 um
self.crosshair_color = wx.Colour(255,0,255) # magenta
self.dragging = None
self.scale = None # Measuement line drawn on the image
self.scale_color = wx.Colour(128,128,255) # light blue
self.show_scale = False # Draw measurement line drawn on the image?
self.scale_selected = False
self.boxsize = (0.1,0.06) # default box size: 100x60 um
self.box_color = wx.Colour(128,128,255)
self.show_box = False
self.tool = None # Role of mouse pointer: measure, move crosshair
self.saturation = 1000 # count beyond which a pixel is rendered white
self.auto_contrast = False # automtically set contrast
self.show_mask = True
self.mask_color = (255,0,0) # red
self.mask_opacity = 0.5 # 1 = opaque, 0 = invisible
self.SetVirtualSize((self.Image.shape[-1],self.Image.shape[-2]))
self.SetScrollRate(1,1)
w,h = self.ImageSize
self.ViewportCenter = w/2,h/2
# Callbacks
self.Bind (wx.EVT_PAINT, self.OnPaint)
self.Bind (wx.EVT_ERASE_BACKGROUND, self.OnEraseBackground)
self.Bind (wx.EVT_SIZE, self.OnResize)
self.Bind (wx.EVT_SCROLLWIN, self.OnScroll)
self.Bind (wx.EVT_LEFT_DOWN, self.OnLeftButtonEvent)
self.Bind (wx.EVT_LEFT_UP, self.OnLeftButtonEvent)
self.Bind (wx.EVT_MOTION, self.OnLeftButtonEvent)
self.Bind (wx.EVT_CONTEXT_MENU, self.OnContextMenu)
def GetState(self):
"This is to save the current settings of the window"
state = {}
state["orientation"] = self.orientation
state["ViewportCenter"] = self.ViewportCenter
state["tool"] = self.tool
state["show_box"] = self.show_box
state["boxsize"] = self.boxsize
state["box_color"] = self.box_color
state["show_scale"] = self.show_scale
state["Scale"] = self.Scale
state["pixelsize"] = self.PixelSize
state["scale_color"] = self.scale_color
state["show_crosshair"] = self.show_crosshair
state["crosshair"] = self.crosshair
state["crosshair_size"] = self.crosshair_size
state["crosshair_color"] = self.crosshair_color
state["show_mask"] = self.show_mask
state["mask_color"] = self.mask_color
state["mask_opacity"] = self.mask_opacity
return state
def SetState(self,state):
"This is to restore the current state of the window"
##print "ImageWindow: Restoring %r" % state
for key in state: exec("self."+key+"="+repr(state[key]))
State = property(GetState,SetState,doc="settings of the window")
def GetImage(self):
"""Displayed image as numpy array"""
return self.image
def SetImage(self,image):
"""Replaces to currently displayed image by a new image.
The image size should not by 0."""
self.image = image
if self.image == None:
from numpy import zeros,uint16
from numimage import numimage
self.image = numimage(zeros((2048,2048),uint16))
if hasattr(image,"pixelsize") and not isnan(image.pixelsize):
self.PixelSize = image.pixelsize
self.adjust_contrast()
w = self.image.shape[-2] * self.ScaleFactor
h = self.image.shape[-1] * self.ScaleFactor
self.SetVirtualSize ((w,h))
# Preserve the viewport center.
if hasattr(self,"viewport_center"):
self.ViewportCenter = self.viewport_center
self.Refresh()
Image = property(GetImage,SetImage)
def GetMask(self):
"""Bitmap overlayed to image as 2D numpy array of type boolean or 'None'
"""
return self.mask
def SetMask(self,mask):
if mask != None: self.mask = (mask != 0)
else: self.mask = None
self.Refresh()
Mask = property(GetMask,SetMask)
def GetPixelSize(self): return self.pixelsize
def SetPixelSize(self,value):
if not value: value = 1.0
if value != self.pixelsize:
self.pixelsize = value
self.Refresh()
PixelSize = property(GetPixelSize,SetPixelSize,doc="image raster in mm")
def GetScaleFactor(self):
"Returns the scale factor to be applied to image for display"
scale = self.scale_factor
if scale == None: # Fit image into the width of the window
if self.Image.shape[-2] != 0:
scale = float(self.GetClientSize().x)/self.Image.shape[-2]
else: scale = 1.0
return scale
def SetScaleFactor (self,value):
if value != self.scale_factor:
self.scale_factor = value
w = self.Image.shape[-2] * self.ScaleFactor
h = self.Image.shape[-1] * self.ScaleFactor
self.SetVirtualSize ((w,h))
# Preserve the viewport center.
if hasattr(self,"viewport_center"):
self.ViewportCenter = self.viewport_center
self.Refresh()
ScaleFactor = property(GetScaleFactor,SetScaleFactor,doc=
"Scale factor applied to image for display")
def OnResize (self,event):
w = self.Image.shape[-2] * self.ScaleFactor
h = self.Image.shape[-1] * self.ScaleFactor
self.SetVirtualSize ((w,h))
# Preserve the viewport center.
if hasattr(self,"viewport_center"):
self.ViewportCenter = self.viewport_center
self.Refresh()
def OnScroll (self,event):
"Called on every scroll event"
event.Skip() # call default event handler
# Only by scrolling the viewport center is allowed to change, not by
# resizing or zooming.
if hasattr(self,"viewport_center"):
self.viewport_center = self.ViewportCenter
def GetSaturationLevel(self): return self.saturation
def SetSaturationLevel (self,value):
if value != self.saturation:
self.saturation = value
self.Refresh()
SaturationLevel = property(GetSaturationLevel,SetSaturationLevel,doc=
"Count beyond which a pixel is rendered white")
def GetAutoContrast (self): return self.auto_contrast
def SetAutoContrast (self,value):
if value != self.auto_contrast:
self.auto_contrast = value
self.adjust_contrast()
self.Refresh()
AutoContrast = property(GetAutoContrast,SetAutoContrast,doc=
"Automatically scale the image intensity")
def adjust_contrast (self):
"This automatically scales the intensity of the image."
if not self.AutoContrast: return
from numpy import average,histogram
image = self.Image
# Convert to grayscale if needed.
if image.ndim > 2: image = average(image,axis=0)
# Set the saturation level such that 99% of all pixels are
# below saturation level.
hist = histogram(image,bins=65536,range=[0,65535],normed=True)[0]
##print "sum(hist) = %g" % sum(hist)
integral = 0
for i in range(0,65536):
integral += hist[i]
if integral > 0.99: break
##print "sum(hist[0:%d]) = %g" % (i,sum(hist[0:i]))
self.SaturationLevel = i
def GetImageSize(self):
w,h = self.Image.shape[-2:]
return w*self.PixelSize,h*self.PixelSize
ImageSize = property(GetImageSize,doc="width and height of image in mm")
def GetViewportCenter(self):
"""Center (x,y) coordinates of the part of the image displayed in the
window in mm with respect to the top left corner of the image.
"""
w,h = self.ClientSize
x0,y0 = self.ViewStart
sx,sy = self.GetScrollPixelsPerUnit()
ox,oy = self.origin()
s = self.ScaleFactor
dx = self.PixelSize
cx,cy = (x0*sx-ox+w/2)/s*dx, (y0*sy-oy+h/2)/s*dx
return cx,cy
def SetViewportCenter(self,(cx,cy)):
"""Scroll such than the center the window is x mm from the
left edge and y mm from the top edge of the image.
"""
w,h = self.ClientSize
sx,sy = self.GetScrollPixelsPerUnit()
ox,oy = self.origin()
s = self.ScaleFactor
dx = self.PixelSize
x0 = cx/sx/dx*s-w/2+ox
y0 = cy/sx/dx*s-h/2+oy
self.Scroll(x0,y0)
self.viewport_center = self.GetViewportCenter()
ViewportCenter = property(GetViewportCenter,SetViewportCenter,
doc=GetViewportCenter.__doc__)
def GetImageOrigin(self):
if self.crosshair != None: x,y = self.crosshair
else: x,y = (self.Image.shape[-2]/2,self.Image.shape[-1]/2)
w,h = self.Image.shape[-2:]
return -x*self.PixelSize,-(h-y)*self.PixelSize
ImageOrigin = property(GetImageOrigin,doc="image center defined by crosshair")
def GetCrosshair(self):
"Returns the crosshair coordinates in pixels from the top left as (x,y) tuple"
return self.crosshair
def SetCrosshair (self,position):
"position must be a tuple (x,y)"
self.crosshair = position
self.Refresh()
Crosshair = property(GetCrosshair,SetCrosshair,doc=
"Coordinates of cross displayed on the image in pixels from top left")
def GetScale(self):
"Returns list of tuples [(x1,y1),(x2,y2)]"
return self.scale
def SetScale (self,line):
"'line' must be a list of tuples [(x1,y1),(x2,y2)]"
self.scale = line
self.Refresh()
Scale = property(GetScale,SetScale,doc="""movable measurement line drawn
on the image, format [(x1,y1),(x2,y2)]""")
def GetScaleUnit(self):
"mm or pixels"
if self.PixelSize != 1: return "mm"
else: return "pixels"
ScaleUnit = property(GetScaleUnit)
def origin(self):
"""
Top left corner of the image in virtual pixel coordinates.
(Orgin: top left of the vitual scrolling area = (0,0)).
By default, a Scrolled Window places its active area in the top
left, if it is smaller than the window size.
Instead, I want it centered in the window.
The function calculates the active area origin as function of window
size.
"""
width,height = self.GetSizeTuple()
x = (width - self.Image.shape[-2]*self.ScaleFactor)/2
y = (height - self.Image.shape[-1]*self.ScaleFactor)/2
if x<0: x = 0
if y<0: y = 0
return x,y
def rotate(self,point):
"used to apply the rotation to the image center to the cross-hair"
if point == None: return
(x,y) = point
(w,h) = (self.Image.shape[-2],self.Image.shape[-1])
if self.orientation == 0: return (x,y)
if self.orientation == -90: return (h-y,x)
if self.orientation == 90: return (y,w-x)
if self.orientation == 180: return (w-x,h-y)
return (x,y)
def unrotate(self,point):
"used to apply the rotation to the image center to the cross-hair"
if point == None: return
(x,y) = point
(w,h) = (self.Image.shape[-2],self.Image.shape[-1])
if self.orientation == 0: return (x,y)
if self.orientation == -90: return (y,h-x)
if self.orientation == 90: return (w-y,x)
if self.orientation == 180: return (w-x,h-y)
return (x,y)
def OnPaint (self,event):
"""Called by WX whenever the contents of the window
needs re-rendering. E.g. when the window is brought to front,
uncovered, restored from minimized state."""
dc = wx.PaintDC(self)
dc = wx.BufferedDC(dc) # avoids flickering
self.PrepareDC(dc)
# Need to fill the area no covered by the image
# because automatic background erase was turned off.
dc.SetBrush (wx.Brush("GREY"))
dc.SetPen (wx.Pen("GREY",0))
width,height = self.GetSizeTuple()
dc.DrawRectangle (0,0,width,height)
# This centers the image in the window, if the window is larger than
# the image.
if dc.GetDeviceOriginTuple() == (0,0):
dc.SetDeviceOrigin(*self.origin())
self.draw(dc)
def OnEraseBackground(self, event):
"""Override default background fill, avoiding flickering"""
def draw (self,dc):
"""Render the contents of the window."""
from numpy import uint8,ndarray
from time import time; t = [time()]; m = ""
# Compress the dynamic range from 0...SaturationLevel to 0...256.
scale = 255./max(self.SaturationLevel,1)
image = minimum(self.Image*scale,255).astype(uint8)
t += [time()]; m += "Scale to 8 bits %.3f s\n" % (t[-1]-t[-2])
# Convert from gray scale to RGB format if needed.
if image.ndim < 3:
w,h = self.Image.shape[-2:]
RGB = ndarray((3,w,h),uint8,order="F")
RGB[0],RGB[1],RGB[2] = image,image,image
image = RGB
t += [time()]; m += "RGB array %.3f s\n" % (t[-1]-t[-2])
# Superimpose the mask if present.
if self.show_mask and self.Mask != None:
mask = self.Mask
R,G,B = image
r,g,b = self.mask_color
x = self.mask_opacity
R[mask] = (1-x)*R[mask]+x*r
G[mask] = (1-x)*G[mask]+x*g
B[mask] = (1-x)*B[mask]+x*b
t += [time()]; m += "Mask %.3f s\n" % (t[-1]-t[-2])
# Convert image from numpy to WX image format.
##data = image.T.tostring()
##t += [time()]; m += "Transpose %.3f s\n" % (t[-1]-t[-2])
data = image
w,h = self.Image.shape[-2:]
image = wx.ImageFromData(w,h,data)
t += [time()]; m += "WX image %.3f s\n" % (t[-1]-t[-2])
# Scale the image.
w = image.Width * self.ScaleFactor
h = image.Height * self.ScaleFactor
# Use 'quality=wx.IMAGE_QUALITY_HIGH' for bicubic and box averaging
# resampling methods for upsampling and downsampling respectively.
if self.ScaleFactor < 1: quality = wx.IMAGE_QUALITY_HIGH
else: quality = wx.IMAGE_QUALITY_NORMAL
image = image.Scale(w,h) ## quality=quality
t += [time()]; m += "Resample %.3f s\n" % (t[-1]-t[-2])
if self.orientation == 90: image=image.Rotate90(clockwise=False)
if self.orientation == -90: image=image.Rotate90(clockwise=True)
if self.orientation == 180: image=image.Rotate90().Rotate90()
t += [time()]; m += "Rotate %.3f s\n" % (t[-1]-t[-2])
bitmap = wx.BitmapFromImage(image)
t += [time()]; m += "WX bitmap %.3f s\n" % (t[-1]-t[-2])
dc.DrawBitmap (bitmap,0,0)
t += [time()]; m += "Render %.3f s\n" % (t[-1]-t[-2])
self.draw_crosshair(dc)
self.draw_box(dc)
self.draw_scale(dc)
t += [time()]; m += "Annotate %.3f s\n" % (t[-1]-t[-2])
m += "Total %.3f s\n" % (t[-1]-t[0])
##print m
def draw_crosshair (self,dc):
"Indicates the X-ray beam position as a cross"
if self.show_crosshair and self.crosshair != None:
dc.SetPen (wx.Pen(self.crosshair_color,1))
w,h = self.crosshair_size
x1,y1 = self.pixel((-w/2,0)); x2,y2 = self.pixel((+w/2,0))
dc.DrawLine (x1,y1,x2,y2)
x1,y1 = self.pixel((0,-h/2)); x2,y2 = self.pixel((0,+h/2))
dc.DrawLine (x1,y1,x2,y2)
def draw_box (self,dc):
"Draws a box around the cross hair to indicate X-ray beam size."
if self.show_box:
w,h = self.boxsize
x1,y1 = self.pixel((w/2,h/2))
x2,y2 = self.pixel((-w/2,-h/2))
dc.SetPen (wx.Pen(self.box_color,1))
dc.DrawLines ([(x1,y1),(x2,y1),(x2,y2),(x1,y2),(x1,y1)])
def draw_scale (self,dc):
if not self.show_scale or self.scale == None: return
P1,P2 = self.scale
x1,y1 = self.pixel(P1)
x2,y2 = self.pixel(P2)
dc.SetPen (wx.Pen(self.scale_color,1))
dc.DrawLine (x1,y1,x2,y2)
length = distance(P1,P2)
if self.ScaleUnit == "mm":
if length < 1: label = "%.0f um" % (length*1000)
else: label = "%.3f mm" % length
else: label = "%g %s" % (length,self.ScaleUnit)
font = wx.SystemSettings.GetFont(wx.SYS_DEFAULT_GUI_FONT)
font.SetPointSize(10)
dc.SetFont(font)
dc.SetTextForeground(self.scale_color)
w,h = dc.GetTextExtent(label)
cx = (x1+x2)/2; cy = (y1+y2)/2
phi = atan2(y2-y1,x2-x1)
tx = cx - (w/2*cos(phi) - h*sin(phi))
ty = cy - (h*cos(phi) + w/2*sin(phi))
dc.DrawRotatedText (label,tx,ty,-phi/pi*180)
if self.scale_selected: # Highlight the end points by 5x5 pixel squares
dc.DrawRectangle(x1-2,y1-2,4,4)
dc.DrawRectangle(x2-2,y2-2,4,4)
def pixel(self,(x,y)):
"Converts from mm (x,y) to virtual pixel coordinates"
if self.crosshair != None: center = self.crosshair
else: center = (self.Image.shape[-2]/2,self.Image.shape[-1]/2)
px = int(round((x/self.PixelSize+center[0])*self.ScaleFactor))
py = int(round((-y/self.PixelSize+center[1])*self.ScaleFactor))
return px,py
def point(self,(px,py)):
"Converts from pixel virtual (px,py) to mm (x,y) coordinates"
if self.crosshair != None: center = self.crosshair
else: center = (self.Image.shape[-2]/2,self.Image.shape[-1]/2)
x = (px/self.ScaleFactor-center[0])*self.PixelSize
y = -(py/self.ScaleFactor-center[1])*self.PixelSize
return x,y
def SetStatusText(self,status_text):
"display the in the status bar of te top level window"
window = self.Parent
while not hasattr(window,"SetStatusText"): window = window.Parent
window.SetStatusText(status_text)
def OnLeftButtonEvent (self,event):
"for dragging the crosshair or scale"
# This makes sure that keyboard input goes to this window seleting
# it by clicking the mouse button inside.
# It makes also sure that mouse wheel events are received.
if event.LeftDown(): self.SetFocus()
p = self.cursor_pos(event)
if event.LeftDown() or event.Dragging():
# Report the image pixle coordinates and pixel intenity at the
# Cursor position in the window's status bar.
from math import floor
x,y = int(floor(p[0]/self.ScaleFactor)),int(floor(p[1]/self.ScaleFactor))
w,h = self.Image.shape[-2:]
if x >= 0 and x < w and y >= 0 and y < h:
if self.Image.ndim == 2: count = self.Image[x,y]
elif self.Image.ndim == 3: count = self.Image[:,x,y]
self.SetStatusText("(%d,%d) count %s" % (x,y,count))
else: self.SetStatusText("")
if self.scale != None:
p1,p2 = self.pixel(self.scale[0]),self.pixel(self.scale[1])
else: p1,p2 = ((-100,-100),(-100,-100))
if self.MoveCrosshair:
if event.LeftDown():
self.SetFocus()
self.set_crosshair(event)
self.CaptureMouse()
self.dragging = "crosshair"
self.Refresh()
elif event.Dragging() and self.dragging:
self.set_crosshair(event)
self.Refresh()
elif event.LeftUp() and self.dragging:
self.ReleaseMouse()
self.dragging = None
self.Refresh()
elif self.show_scale or self.tool == "measure":
if event.LeftDown():
if self.tool == "measure":
P = self.point(p)
self.scale = [P,P]
self.show_scale = True
self.dragging = "scale2"
self.scale_selected = False
else:
if point_line_distance(p,(p1,p2)) < 5: self.scale_selected = True
else: self.scale_selected = False
if point_line_distance(p,(p1,p2)) < 5:
self.dragging = (self.point(p),list(self.scale))
if distance(p1,p) < 5: self.dragging = "scale1"
if distance(p2,p) < 5: self.dragging = "scale2"
if self.dragging:
self.SetFocus()
self.set_scale(event)
self.CaptureMouse()
self.Refresh()
elif event.Dragging() and self.dragging:
self.set_scale(event)
self.Refresh()
elif event.LeftUp() and self.dragging:
self.ReleaseMouse()
self.dragging = None
self.Refresh()
# Update the pointer shape to reflect the mouse function.
if self.MoveCrosshair:
self.SetCursor (wx.StockCursor(wx.CURSOR_PENCIL))
#self.SetCursor (self.crosshair_cursor) # garbled under Linux
# CURSOR_CROSS would be better than CURSOR_PENCIL.
# However, under Windows, the cross cursor does not have a white
# border and is hard to see on black background.
elif self.tool == "measure":
self.SetCursor (wx.StockCursor(wx.CURSOR_PENCIL))
elif self.dragging == "scale1" or self.dragging == "scale2":
self.SetCursor (wx.StockCursor(wx.CURSOR_SIZENESW))
elif self.dragging: self.SetCursor(wx.StockCursor(wx.CURSOR_SIZING))
elif self.scale_selected and (distance(p1,p) < 5 or distance(p2,p) < 5):
self.SetCursor(wx.StockCursor(wx.CURSOR_SIZENESW))
elif point_line_distance(p,(p1,p2)) < 5:
self.SetCursor(wx.StockCursor(wx.CURSOR_SIZING))
else: self.SetCursor (wx.StockCursor(wx.CURSOR_DEFAULT))
# CURSOR_SIZENESW would be better when the pointer is hovering over
# the and of the end point.
# However, under Linux, the pointer shape does not update
# to CURSOR_PENCIL while dragging, only after the mouse button is
# released.
# CURSOR_CROSS would be better than CURSOR_PENCIL.
# However, under Windows, the cross cursor does not have a white
# border and is hard to see on black background.
def set_crosshair (self,event):
"Updates the crosshair position based on the last mouse event"
x,y = self.cursor_pos(event)
self.crosshair = (int(round(x/self.ScaleFactor)),int(round(y/self.ScaleFactor)))
def set_scale (self,event):
"Updates the scale based on the last mouse event"
p = self.cursor_pos(event)
if self.dragging == "scale1": self.scale[0] = self.point(p)
elif self.dragging == "scale2": self.scale[1] = self.point(p)
else:
P = self.point(p)
P0,(P1,P2) = self.dragging
self.scale[0] = translate(P1,vector(P0,P))
self.scale[1] = translate(P2,vector(P0,P))
def cursor_pos (self,event):
"""cursor position (x,y) during the given event, in virtual pixel
coordinates, relative to the top left corner of the image, in units
of screen pixels (not image pixels).
"""
x,y = self.CalcUnscrolledPosition (event.GetX(),event.GetY())
ox,oy = self.origin()
return x-ox,y-oy
def OnContextMenu (self,event):
menu = wx.Menu()
menu.Append (10,"Show Mask","",wx.ITEM_CHECK)
if self.show_mask: menu.Check(10,True)
self.Bind (wx.EVT_MENU,self.OnShowMask,id=10)
menu.Append (1,"Show Scale","",wx.ITEM_CHECK)
if self.show_scale: menu.Check(1,True)
self.Bind (wx.EVT_MENU,self.OnShowScale,id=1)
menu.Append (2,"Show Box","",wx.ITEM_CHECK)
if self.show_box: menu.Check(2,True)
self.Bind (wx.EVT_MENU,self.OnShowBox,id=2)
menu.Append (6,"Show Crosshair","",wx.ITEM_CHECK)
if self.show_crosshair: menu.Check(6,True)
self.Bind (wx.EVT_MENU,self.OnShowCrosshair,id=6)
menu.AppendSeparator()
menu.Append (7,"Measure","",wx.ITEM_CHECK)
self.Bind (wx.EVT_MENU,self.OnMeasure,id=7)
if self.tool == "measure": menu.Check(7,True)
menu.AppendSeparator()
if self.show_scale: menu.Append (8,"Scale...","")
self.Bind (wx.EVT_MENU,self.OnScaleProperties,id=8)
if self.show_crosshair: menu.Append (4,"Crosshair...","")
self.Bind (wx.EVT_MENU,self.OnCrosshairProperties,id=4)
if self.show_box: menu.Append (5,"Box...","")
self.Bind (wx.EVT_MENU,self.OnBoxProperties,id=5)
# Display the menu. If an item is selected then its handler will
# be called before 'PopupMenu' returns.
self.PopupMenu(menu)
menu.Destroy()
def OnShowMask (self,event):
"Called if 'Show Scale' is selected from the context menu"
self.show_mask = not self.show_mask
self.Refresh()
def OnShowScale (self,event):
"Called if 'Show Scale' is selected from the context menu"
self.show_scale = not self.show_scale
if self.show_scale and self.scale == None: self.set_default_scale()
self.Refresh()
def set_default_scale(self):
"Set default position for scale"
w,h = self.ImageSize; x,y = self.ImageOrigin
l = 0.4*w; l = round(l,int(round(-log10(l)+0.5)))
self.scale = [(x+w*0.5-l/2,y+h*0.05),(x+w*0.5+l/2,y+h*0.05)]
def OnShowBox (self,event):
"Called if 'Show Box' is selected from the context menu"
self.show_box = not self.show_box
self.Refresh()
def OnShowCrosshair (self,event):
"Called if 'Show Crosshair' is selected from the context menu"
self.show_crosshair = not self.show_crosshair
self.Refresh()
def GetMoveCrosshair (self): return (self.tool == "move crosshair")
def SetMoveCrosshair (self,value):
if value == True: self.tool = "move crosshair"
else: self.tool = None
MoveCrosshair = property(GetMoveCrosshair,SetMoveCrosshair,doc=
"Determines whether the crosshair is movable or locked")
def OnMeasure (self,event):
"Called if 'Measure' is selected from the context menu"
if self.tool != "measure": self.tool = "measure"
else: self.tool = None
def OnScaleProperties (self,event):
dlg = ScaleProperties(self)
dlg.CenterOnParent()
pos = dlg.GetPosition(); pos.y += 100; dlg.SetPosition(pos)
dlg.Show()
def OnCrosshairProperties (self,event):
dlg = CrosshairProperties(self)
dlg.CenterOnParent()
pos = dlg.GetPosition(); pos.y += 100; dlg.SetPosition(pos)
dlg.Show()
def OnBoxProperties (self,event):
dlg = BoxProperties(self)
dlg.CenterOnParent()
pos = dlg.GetPosition(); pos.y += 100; dlg.SetPosition(pos)
dlg.Show()
class CrosshairProperties (wx.Dialog):
"""Allows the user to to read the cross position, enter the position
numerically and change its color."""
def __init__ (self,parent):
wx.Dialog.__init__(self,parent,-1,"Crosshair")
# Controls
self.Coordinates = wx.TextCtrl (self,size=(75,-1),
style=wx.TE_PROCESS_ENTER)
self.Bind (wx.EVT_TEXT_ENTER,self.OnEnterCoordinates,self.Coordinates)
self.Coordinates.SetValue("%d,%d" % parent.Crosshair)
self.Movable = wx.CheckBox(self,label="Movable")
self.Bind (wx.EVT_CHECKBOX,self.OnMovable,self.Movable)
if parent.MoveCrosshair: self.Movable.SetValue(True)
self.CrosshairSize = wx.TextCtrl (self,size=(75,-1),
style=wx.TE_PROCESS_ENTER)
self.Bind (wx.EVT_TEXT_ENTER,self.OnEnterCrosshairSize,
self.CrosshairSize)
self.CrosshairSize.SetValue("%.3f,%.3f" % parent.crosshair_size)
self.ShowCrosshair = wx.CheckBox(self,label="Show")
self.Bind (wx.EVT_CHECKBOX,self.OnShowCrosshair,self.ShowCrosshair)
if parent.show_crosshair: self.ShowCrosshair.SetValue(True)
h = self.Coordinates.GetSize().y
from wx.lib.colourselect import ColourSelect,EVT_COLOURSELECT
self.Color = ColourSelect (self,colour=parent.crosshair_color,size=(h,h))
self.Color.Bind (EVT_COLOURSELECT,self.OnSelectColour)
# Layout
layout = wx.FlexGridSizer (cols=3,hgap=5,vgap=5)
label = wx.StaticText (self,label="Position (x,y) [pixels]:")
layout.Add (label,flag=wx.ALIGN_CENTER_VERTICAL)
layout.Add (self.Coordinates,flag=wx.ALIGN_CENTER_VERTICAL)
layout.Add (self.Movable,flag=wx.ALIGN_CENTER_VERTICAL)
label = wx.StaticText (self,label="Size (w,h) [mm]:")
layout.Add (label,flag=wx.ALIGN_CENTER_VERTICAL)
layout.Add (self.CrosshairSize,flag=wx.ALIGN_CENTER_VERTICAL)
layout.Add (self.ShowCrosshair,flag=wx.ALIGN_CENTER_VERTICAL)
label = wx.StaticText (self,label="Line color:")
layout.Add (label,flag=wx.ALIGN_CENTER_VERTICAL)
layout.Add (self.Color,flag=wx.ALIGN_CENTER_VERTICAL)
self.SetSizer(layout)
self.Fit()
self.Bind (wx.EVT_CLOSE,self.OnClose)
def OnEnterCoordinates(self,event):
text = self.Coordinates.GetValue()
try:
(tx,ty) = text.split(",")
self.GetParent().Crosshair = (float(tx),float(ty))
except ValueError: return
def OnMovable(self,event):
self.GetParent().MoveCrosshair = self.Movable.GetValue()
def OnEnterCrosshairSize(self,event):
text = self.CrosshairSize.GetValue()
try:
(tx,ty) = text.split(",")
self.GetParent().crosshair_size = (float(tx),float(ty))
except ValueError: return
self.GetParent().Refresh()
def OnShowCrosshair(self,event):
self.GetParent().show_crosshair = self.ShowCrosshair.GetValue()
self.GetParent().Refresh()
def OnSelectColour(self,event):
self.GetParent().crosshair_color = event.GetValue()
self.GetParent().Refresh()
def OnClose(self,event):
"""Called when the close button is clocked.
When the dialog is closed automatically lock the crosshair."""
self.GetParent().MoveCrosshair = False
self.Destroy()
class BoxProperties (wx.Dialog):
"""Allows the user to change the box size and color"""
def __init__ (self,parent):
wx.Dialog.__init__(self,parent,-1,"Box")
# Controls
self.BoxSize = wx.TextCtrl (self,size=(75,-1),
style=wx.TE_PROCESS_ENTER)
self.Bind (wx.EVT_TEXT_ENTER,self.OnEnterBoxSize,self.BoxSize)
self.BoxSize.SetValue("%.3f,%.3f" % parent.boxsize)
self.ShowBox = wx.CheckBox(self,label="Show")
self.Bind (wx.EVT_CHECKBOX,self.OnShowBox,self.ShowBox)
if parent.show_box: self.ShowBox.SetValue(True)
h = self.BoxSize.GetSize().y
from wx.lib.colourselect import ColourSelect,EVT_COLOURSELECT
self.Color = ColourSelect (self,colour=parent.box_color,size=(h,h))
self.Color.Bind (EVT_COLOURSELECT,self.OnSelectColour)
# Layout
layout = wx.FlexGridSizer (cols=3,hgap=5,vgap=5)
label = wx.StaticText (self,label="Width,Height [mm]:")
layout.Add (label,flag=wx.ALIGN_CENTER_VERTICAL)
layout.Add (self.BoxSize,flag=wx.ALIGN_CENTER_VERTICAL)
layout.Add (self.ShowBox,flag=wx.ALIGN_CENTER_VERTICAL)
label = wx.StaticText (self,label="Line color:")
layout.Add (label,flag=wx.ALIGN_CENTER_VERTICAL)
layout.Add (self.Color,flag=wx.ALIGN_CENTER_VERTICAL)
self.SetSizer(layout)
self.Fit()
def OnEnterBoxSize(self,event):
text = self.BoxSize.GetValue()
try:
(tx,ty) = text.split(",")
self.GetParent().boxsize = (float(tx),float(ty))
except ValueError: return
self.GetParent().Refresh()
def OnShowBox(self,event):
self.GetParent().show_box = self.ShowBox.GetValue()
self.GetParent().Refresh()
def OnSelectColour(self,event):
self.GetParent().box_color = event.GetValue()
self.GetParent().Refresh()
class ScaleProperties (wx.Dialog):
"""Allows the user to enter the length of the measurement scale numerically,
make the line exactly horizonal or vertical and change its color.
"""
def __init__ (self,parent):
wx.Dialog.__init__(self,parent,-1,"Scale")
# Controls
self.Length = wx.TextCtrl (self,size=(60,-1),style=wx.TE_PROCESS_ENTER)
self.Bind (wx.EVT_TEXT_ENTER,self.OnEnterLength,self.Length)
(P1,P2) = parent.scale; length = distance(P1,P2)
self.Length.SetValue("%.3f" % length)
self.Pixelsize = wx.TextCtrl (self,size=(60,-1),
style=wx.TE_PROCESS_ENTER)
self.Bind (wx.EVT_TEXT_ENTER,self.OnEnterPixelsize,self.Pixelsize)
self.Pixelsize.SetValue("%.3f" % parent.pixelsize)
self.Horizontal = wx.CheckBox (self,label="Horizontal")
self.Bind (wx.EVT_CHECKBOX,self.OnHorizontal,self.Horizontal)
self.Vertical = wx.CheckBox (self,label="Vertical")
self.Bind (wx.EVT_CHECKBOX,self.OnVertical,self.Vertical)
v = vector(P1,P2)
if v[1] == 0: self.Horizontal.SetValue(True)
if v[0] == 0: self.Vertical.SetValue(True)
h = self.Length.GetSize().y
from wx.lib.colourselect import ColourSelect,EVT_COLOURSELECT
self.Color = ColourSelect (self,-1,"",parent.scale_color,size=(h,h))
self.Color.Bind (EVT_COLOURSELECT,self.OnSelectColour)
# Layout
layout = wx.FlexGridSizer (cols=2,hgap=5,vgap=5)
label = wx.StaticText (self,label="Length ["+parent.ScaleUnit+"]:")
layout.Add (label,flag=wx.ALIGN_CENTER_VERTICAL)
layout.Add (self.Length,flag=wx.ALIGN_CENTER_VERTICAL)
label = wx.StaticText (self,label="Pixel size [mm]:")
layout.Add (label,flag=wx.ALIGN_CENTER_VERTICAL)
layout.Add (self.Pixelsize,flag=wx.ALIGN_CENTER_VERTICAL)
label = wx.StaticText (self,label="Direction:")
layout.Add (label,flag=wx.ALIGN_CENTER_VERTICAL)
group = wx.BoxSizer()
group.Add (self.Horizontal)
group.AddSpacer((5,5))
group.Add (self.Vertical)
layout.Add (group)
label = wx.StaticText (self,label="Line color:")
layout.Add (label,flag=wx.ALIGN_CENTER_VERTICAL)
layout.Add (self.Color,flag=wx.ALIGN_CENTER_VERTICAL)
self.SetSizer(layout)
self.Fit()
def OnEnterLength(self,event):
text = self.Length.GetValue()
try: length = float(text)
except ValueError: return
parent = self.GetParent()
(P1,P2) = parent.scale
P2 = translate(P1,scale(direction(vector(P1,P2)),length))
parent.scale = [P1,P2]
parent.Refresh()
def OnEnterPixelsize(self,event):
text = self.Pixelsize.Value
try: value = float(text)
except ValueError: self.Pixelsize.Value = "1.000"; return
parent = self.Parent
parent.pixelsize = value
parent.Refresh()
def OnHorizontal(self,event):
self.Horizontal.SetValue(True); self.Vertical.SetValue(False)
parent = self.GetParent()
(P1,P2) = parent.scale; length = distance(P1,P2)
P2 = translate(P1,(length,0))
parent.scale = [P1,P2]
parent.Refresh()
def OnVertical(self,event):
self.Horizontal.SetValue(False); self.Vertical.SetValue(True)
parent = self.GetParent()
(P1,P2) = parent.scale; length = distance(P1,P2)
P2 = translate(P1,(0,length))
parent.scale = [P1,P2]
parent.Refresh()
def OnSelectColour(self,event):
self.GetParent().scale_color = event.GetValue()
self.GetParent().Refresh()
def distance ((x1,y1),(x2,y2)):
"Distance between two points"
return sqrt((x2-x1)**2+(y2-y1)**2)
def point_line_distance (P,line):
"Distance of a point to a line segment of finite length"
# Source: softsurfer.com/Archive/algorithm_0102/algorithm_0102.htm
# 18 May 2007
P0 = line[0]; P1 = line[1]
v = vector(P0,P1); w0 = vector(P0,P); w1 = vector(P1,P)
# If the angle (P,P0,P1) is obtuse (>=90 deg), it is the distance to P0.
if dot(w0,v) <= 0: return distance(P,P0)
# If the angle(P,P1,P0) is obtuse (>=90 deg), it is the distance to P1.
if dot(w1,v) >= 0: return distance(P,P1)
# Otherwise, it is the orthognal distance to the line.
b = dot(w0,v) / float(dot(v,v))
Pb = translate(P0,scale(v,b))
return distance(P,Pb)
def vector((x1,y1),(x2,y2)):
"Vector from point (x1,y1) to point (x2,y2)"
return (x2-x1,y2-y1)
def translate((x,y),(vx,vy)):
"Applies the vector (vx,vy) to point (x,y)"
return (x+vx,y+vy)
def scale((x,y),a):
"Multiplies vector with scalar"
return (a*x,a*y)
def direction((x,y)):
"Vector (x,y) scaled to unit length"
l = sqrt(x**2+y**2)
if l == 0: return (1.,0.)
return (x/l,y/l)
def dot((x1,y1),(x2,y2)):
"Scalar product between vectors (x1,y1) and (x2,y2)"
return x1*x2+y1*y2
class ImageViewer_App(wx.App):
windows = []
def OnInit(self):
image_file = mask_file = ""
# Check whether command line argumuments have been passed.
from sys import argv
##print "argv: %r" % argv
# Take the first parameter as the file name of an image to be displayed.
if len(argv) > 1 and argv[1]!= "" and not argv[1].startswith("-"):
image_file = argv[1]
# If a second image file name is given, use this image as mask.
if len(argv) > 2 and argv[2]!= "" and not argv[2].startswith("-"):
mask_file = argv[2]
self.windows += [ImageViewer_Window(image_file=image_file,mask_file=mask_file)]
self.SetTopWindow(self.windows[0])
return True
def MacOpenFile (self,filename):
"""Callback handler for OpenFile events.
In order to have your application handle files that are dropped
on the application icon, and respond to double-clicking on some file
types from the Finder, override this method in your wxApp"""
from sys import stderr
##stderr.write("MacOpenFile %r\n" % filename)
from os.path import isfile
if not isfile(filename) or filename.endswith(".py"):
##stderr.write("MacOpenFile: Spurious OpenFile event %r" % filename)
return
# Check if image is already open. If yes, bring its window to front.
for window in self.windows:
if window.image_file == filename: window.Raise(); return
# If the first window was opened as empty window without image, use
# that window to display the image.
if len(self.windows)>0 and not self.windows[0].image_file:
self.windows[0].set_image_file (filename); return
# Open image in a new window.
self.windows += [ImageViewer_Window(image_file=filename)]
def OpenFile (self,filename):
"""Open the image 'filename' in a new window."""
from os.path import exists
if not exists(filename):
from sys import stderr
stderr.write("OpenFile: File %r not found" % filename)
return
# Check if image is already open. If yes, bring its window to front.
for window in self.windows:
if window.image_file == filename: window.Raise(); return
# If the first window was opened as empty window without image, use
# that window to display the image.
if len(self.windows)>0 and not self.windows[0].image_file:
self.windows[0].set_image_file (filename); return
# Open image in a new window.
self.windows += [ImageViewer_Window(image_file=filename)]
def CloseWindow(self,window):
""""""
window.Show(False)
window.Destroy()
if window in self.windows: self.windows.remove(window)
##if len(self.windows) == 0: self.Exit() - does not seem to be needed
def ExitApp(self):
for window in self.windows: window.Show(False)
for window in self.windows: window.Destroy()
self.windows = []
##wx.App.Exit(self)
class ImageViewerInterface(object):
def get_images(self):
"""filenames: list of pathnames"""
from DB import dbget
images = dbget("ImageViewer.images")
try: images = eval(images)
except: images = []
return images
def set_images(self,filenames):
"""filenames: list of pathnames"""
from DB import dbput
dbput("ImageViewer.images",repr(filenames).replace("\n",""))
images = property(get_images,set_images)
image_viewer = ImageViewerInterface()
def newer_file(filename,count=1,filter="*"):
"""the file with the higher(newer) timestamp in the same directory.
If the is none return the current filename.
count: 1 for newer file (default), -1 for older file"""
from os.path import dirname,exists,isdir
from glob import glob
from numpy import argsort,array,where,clip
dir = dirname(filename)
files = glob(dir+"/"+filter)
files = array([f for f in files if not isdir(f)])
timestamps = array([getmtime(f) for f in files])
order = argsort(timestamps)
timestamps = timestamps[order]
files = files[order]
if len(files) == 0: return filename
if not filename in files: return files[0]
i = where(files == filename)[0][0]
i = clip(i+count,0,len(files)-1)
next_filename = files[i]
return next_filename
def next_file(filename,count=1,filter="*"):
"""The file next alphabetically in the same directory.
If the is none return the current filename.
count: 1 for next next file (default), -1 for the proevious file"""
from os.path import dirname,exists,isdir
from glob import glob
from numpy import argsort,array,where,clip
dir = dirname(filename)
files = glob(dir+"/"+filter)
files = array([f for f in files if not isdir(f)])
order = argsort(files)
files = files[order]
if len(files) == 0: return filename
if not filename in files: return files[0]
i = where(files == filename)[0][0]
i = clip(i+count,0,len(files)-1)
next_filename = files[i]
return next_filename
def getmtime(filename):
# Work-around for a strange problem with "MacDust" files (._*) where
# "listdir" lists the file, but "getmtime" throws an exception
# (OSError [errno 2]: No such file or directory)
from os.path import getmtime
try: return getmtime(filename)
except OSError: return 0
def exist_files(filenames):
"""filenames: list of pathnames"""
from os import listdir
from os.path import exists,dirname,basename
directories = {}
exist_files = []
for f in filenames:
if not dirname(f) in directories:
try: files = listdir(dirname(f) if dirname(f) else ".")
except OSError: files = []
directories[dirname(f)] = files
exist_files += [basename(f) in directories[dirname(f)]]
return exist_files
def show_image(filename):
"""Signal the viewer to load an image for display.
filename: pathname"""
show_images([filename])
def show_images(filenames):
"""Signal the viewer to check a list if image file an display the
last one that exists.
filenames: list of pathnames"""
from DB import dbput
dbput("ImageViewer.images",repr(filenames).replace("\n",""))
if __name__ == "__main__":
from os.path import exists
filenames = ["/mnt/rayonix/data/xpp40312/Anfinrud/MbCO-L29F/MbCO-L29F-28-3"\
"/alignment/scan_phi=-0.000_z=-0.758/001.mccd"]
filename = filenames[0]
##show_images(filenames)
app = ImageViewer_App(redirect=False)
app.MainLoop()
<file_sep>"""
Data base save and recall motor positions
Author: <NAME>
Date created: 2013-11-29
Date last modified: 2019-05-28
"""
__version__ = "4.1.2" # "%s.line%d.%s" % (..,int(row),..): ValueError: cannot convert float NaN to integer
from logging import debug,info,warn,error
import numpy
numpy.warnings.filterwarnings('ignore', r'All-NaN (slice|axis) encountered')
numpy.warnings.filterwarnings('ignore', r'Mean of empty slice.')
from classproperty import classproperty,ClassPropertyMetaClass
class Configuration(object):
##class Bar(metaclass=ClassPropertyMetaClass): # Python 3+
"""Data base save and recall motor positions"""
__metaclass__ = ClassPropertyMetaClass # Python 2.7
from persistent_property import persistent_property
from numpy import nan
nrows = persistent_property("nrows",2) # How many configurations?
motor_names = persistent_property("motor_names",[]) # Python expression for motor
__names__ = persistent_property("names",[]) # mnemonics for columns
serial = persistent_property("serial",False) # Move one motor after the other?
__command_rows__ = persistent_property("command_rows",[]) # last selected state
# GUI properties
title = persistent_property("title","Configuration")
__motor_labels__ = persistent_property("motor_labels",[])
__formats__ = persistent_property("formats",[])
__widths__ = persistent_property("widths",[])
__tolerance__ = persistent_property("tolerance",[])
description_width = persistent_property("description_width",150)
row_height = persistent_property("row_height",20)
show_apply_buttons = persistent_property("show_apply_buttons",True)
apply_button_label = persistent_property("apply_button_label","Select")
show_define_buttons = persistent_property("show_define_buttons",True)
define_button_label = persistent_property("define_button_label","Update")
show_stop_button = persistent_property("show_stop_button",False)
show_in_list = persistent_property("show_in_list",True)
vertical = persistent_property("vertical",False)
multiple_selections = persistent_property("multiple_selections",False)
def __init__(self,
name="configuration_test",
motor_names=None,
motor_labels=None,
formats=None,
nrows=None,
serial=None,
locals=None,
globals=None,
):
"""name: basename of settings file"""
self.register(name)
self.name = name
if motor_names is not None: self.motor_names = motor_names
if motor_labels is not None: self.motor_labels = motor_labels
if formats is not None: self.formats = formats
if nrows is not None: self.nrows = nrows
if serial is not None: self.serial = serial
self.locals = locals
self.globals = globals
def get_globals(self):
if not hasattr(self,"__globals__") or self.__globals__ is None:
exec("from instrumentation import *") # -> locals()
self.__globals__ = globals()
return self.__globals__
def set_globals(self,value): self.__globals__ = value
globals = property(get_globals,set_globals)
def get_locals(self):
if not hasattr(self,"__locals__") or self.__locals__ is None:
exec("from instrumentation import *") # -> locals()
self.__locals__ = locals()
return self.__locals__
def set_locals(self,value): self.__locals__ = value
locals = property(get_locals,set_locals)
@classmethod
def register(cls,name):
if not name in cls.configuration_names:
cls.configuration_names += [name]
@classproperty
def configuration_names(cls):
from DB import db
return db("configuration.names",[])
@configuration_names.setter
def configuration_names(cls,names):
from DB import dbset
dbset("configuration.names",names)
@classproperty
def configurations(cls):
return [configuration(n) for n in configuration.configuration_names]
def get_motor_labels(self):
return self.resize(self.__motor_labels__,self.n_motors,default_value="?")
def set_motor_labels(self,values): self.__motor_labels__ = values
motor_labels = property(get_motor_labels,set_motor_labels)
def get_names(self):
"""Column mnemonics"""
return self.resize(self.__names__,self.n_motors,template="motor%d")
def set_names(self,values): self.__names__ = values
names = property(get_names,set_names)
def get_formats(self):
return self.resize(self.__formats__,self.n_motors,default_value="%s")
def set_formats(self,values): self.__formats__ = values
formats = property(get_formats,set_formats)
def get_widths(self):
"""Horizontal size for each motor columns in pixels"""
widths = self.resize(self.__widths__,self.n_motors,default_value=100)
if self.vertical: widths = [self.description_width]*self.n_motors
return widths
def set_widths(self,values): self.__widths__ = values
widths = property(get_widths,set_widths)
def get_tolerance(self):
return self.resize(self.__tolerance__,self.n_motors,default_value=0)
def set_tolerance(self,values): self.__tolerance__ = values
tolerance = property(get_tolerance,set_tolerance)
def get_command_rows(self):
from numpy import isnan,nan
rows = self.__command_rows__
rows = [row for row in rows if 0 <= row < self.nrows]
return rows
def set_command_rows(self,values): self.__command_rows__ = values
command_rows = property(get_command_rows,set_command_rows)
@property
def n_motors(self):
"""How many motors are there?"""
return len(self.motor_names)
@property
def motors(self):
"""List of objects with propery "value"""
return [self.motor(name) for name in self.motor_names]
@property
def are_configuration(self):
return [self.is_configuration(i) for i in range(0,self.n_motors)]
def is_configuration(self,i):
"""Is this column a linked configuration?"""
is_configuration = self.configuration_name(i) in self.configuration_names
return is_configuration
@property
def motor_configuration_names(self):
return [self.motor_configuration_name(i) for i in range(0,self.n_motors)]
def motor_configuration_name(self,i):
"""If this column a linked configuration, what it its name?"""
name = self.motor_names[i]
name = name.replace(".value","")
return name
configuration_name = motor_configuration_name
def configuration(self,i):
"""Linked configuration"""
return configuration(name=self.configuration_name(i),
locals=self.locals,globals=self.globals)
def motor(self,name):
import traceback
try: motor = eval(name,self.globals,self.locals)
except Exception,msg:
error("motor %r: %s" % (name,msg))
##error("motor %r: %s\n%s" % (name,msg,traceback.format_exc()))
motor = self.Dummy_motor()
return motor
class Dummy_motor:
from numpy import nan
value = nan
def get_current_positions(self): return self.CurrentPositions(self)
def set_current_positions(self,value): self.current_positions[:] = value
current_positions = property(get_current_positions,set_current_positions)
current_position = current_positions
class CurrentPositions(object):
def __init__(self,configuration):
self.configuration = configuration
def __getitem__(self,i):
if type(i) == slice: value = [x for x in self]
else: value = self.configuration.get_current_position(i)
return value
def __setitem__(self,i,value):
if type(i) == slice:
for j in range(0,len(value)): self[j] = value[j]
else: self.configuration.set_current_position(i,value)
def __len__(self): return len(self.configuration.motor_names)
def __iter__(self):
for i in range(0,len(self)):
if i < len(self): yield self[i]
def get_current_position(self,i):
"""Report the current position of a motor
i: zero-based index"""
name = self.motor_names[i]
value = self.motor_position(name)
if self.is_numeric(i):
from numpy import nan
try: value = float(value)
except Exception,msg:
warn("%r: float(%r): %s" % (name,value,msg))
value = nan
else:
try: value = str(value)
except Exception,msg:
warn("%r: str(%r): %s" % (name,value,msg))
value = ""
return value
def set_current_position(self,i,value):
"""Move a motor
i: zero-based index
value: new position"""
self.set_motor_position(self.motor_names[i],value)
@property
def nominal_positions(self):
"""Where should the motors be if the commanded configuration
were applied? list of positions"""
rows = self.command_rows
positions = []
for m in range(0,self.n_motors):
position = self.combined([self.positions[m][row] for row in rows],m)
positions += [position]
return positions
def combined(self,values,motor_num):
if self.is_numeric(motor_num): combined = self.combined_positions(values)
else: combined = self.combined_string(values)
return combined
def combined_positions(self,values):
from numpy import average,nan
combined = nan
if len(values)>0: combined = average(values)
return combined
def combined_string(self,values):
return ", ".join(values)
def nominal_position(self,motor_number):
"""Where should the motor be if the commanded configuration
were applied?
motor_number: zero-based index"""
m = motor_number
rows = self.command_rows
position = self.combined([self.positions[m][row] for row in rows],m)
return position
@property
def command_positions(self): return self.CommandPositions(self)
class CommandPositions(object):
def __init__(self,configuration):
self.configuration = configuration
def __getitem__(self,i):
if type(i) == slice: value = [x for x in self]
else: value = self.configuration.command_position(i)
return value
def __setitem__(self,i,value):
if type(i) == slice:
for j in range(0,len(value)): self[j] = value[j]
else: self.configuration.set_current_position(i,value)
def __len__(self): return len(self.configuration.motor_names)
def __iter__(self):
for i in range(0,len(self)):
if i < len(self): yield self[i]
def command_position(self,motor_number):
"""Report the commanded nominal position of a motor (or target if moving)
motor_number: zero-based index"""
return self.motor_command_position(self.motor_names[motor_number])
def motor_position(self,name):
"""Report the current position of a motor
name: string"""
from numpy import nan
try: value = eval(name+".value",self.globals,self.locals)
except AttributeError: # object has no attribute 'value'
try: value = eval(name,self.globals,self.locals)
except Exception,msg:
error("%s: %s" % (name,msg))
value = nan
except Exception,msg:
error("%s: %s" % (name,msg))
value = nan
return value
def motor_command_position(self,name):
"""Report the nominal position of a motor
name: string"""
from numpy import nan
try: value = eval(name+".command_value",self.globals,self.locals)
except AttributeError: # object has no attribute 'value'
try: value = eval(name,self.globals,self.locals)
except Exception,msg:
error("%s: %s" % (name,msg))
value = nan
except Exception,msg:
error("%s: %s" % (name,msg))
value = nan
return value
def set_motor_position(self,name,value):
"""name: string"""
if self.is_valid_position(value):
from numpy import nan # for exec
import traceback
try: exec("%s.value = %r" % (name,value),self.globals,self.locals)
except AttributeError: # object has no attribute 'value'
try: exec("%s = %r" % (name,value),self.globals,self.locals)
except Exception,msg:
error("%s = %r: %s\n%s" % (name,value,msg,traceback.format_exc()))
except Exception,msg:
error("%s = %r: %s\n%s" % (name,value,msg,traceback.format_exc()))
def is_valid_position(self,value):
from numpy import isfinite,nan
if isinstance(value,str):
valid = True
##valid = value != ""
else: valid = isfinite(value)
return valid
def position(self,row_or_description):
"""Saved motor positions.
row: zero-based index or description string"""
if not isinstance(row_or_description,basestring):
position = self.position_of_row(row_or_description)
else: position = self.position_of_description(row_or_description)
return position
def position_of_row(self,row):
"""List of saved motor positions"""
position = [self.positions[im][row] for im in self.n_motor]
return position
def position_of_description(self,description):
from numpy import nan
for row in range(0,self.nrows):
if self.descriptions[row] == description:
return self.position_of_row(row)
return [nan]*self.n_motors
def get_command_description(self):
from numpy import isnan,nan
rows = self.command_rows
rows = [row for row in rows if 0 <= row < self.nrows]
description = self.combined_string([self.descriptions[row] for row in rows])
return description
def set_command_description(self,description):
rows = self.rows(description)
self.command_rows = rows
self.applying = True
command_description = property(get_command_description,set_command_description)
def get_closest_description(self):
from numpy import isnan
rows = []
if self.multiple_selections: rows = self.closest_rows
elif not isnan(self.closest_row): rows = [self.closest_row]
description = self.combined_string([self.descriptions[row] for row in rows])
return description
def set_closest_description(self,value): self.command_description = value
closest_description = property(get_closest_description,set_closest_description)
def rows(self,descriptions):
""" 'NIH:H-1_ps,NIH:H-56_ps' > [0,1]"""
from numpy import isnan
list = self.description_list(descriptions)
rows = [self.row(d) for d in list if not isnan(self.row(d))]
return rows
def row(self,description):
from numpy import nan
row = nan
descriptions = self.descriptions[:]
if description in descriptions: row = descriptions.index(description)
return row
def description_list(self,descriptions):
""" 'NIH:H-1_ps,NIH:H-56_ps' > ['NIH:H-1_ps','NIH:H-56_ps']"""
descriptions = descriptions.split(",")
descriptions = [d.strip() for d in descriptions]
return descriptions
@property
def closest_descriptions(self):
descriptions = [self.descriptions[row] for row in self.closest_rows]
return descriptions
def get_matching_description(self):
from numpy import isnan
rows = self.matching_rows
# Use the last selection to make it unambiguous if possible.
if len(self.command_rows) == 1 and self.command_rows[0] in rows:
rows = self.command_rows
description = self.combined_string([self.descriptions[row] for row in rows])
return description
def set_matching_description(self,value): self.command_description = value
matching_description = property(get_matching_description,set_matching_description)
def get_descriptions(self): return self.Values(self,"description","")
def set_descriptions(self,value): self.descriptions[:] = value
descriptions = property(get_descriptions,set_descriptions)
def get_description(self):
description = self.closest_description
if self.command_description == "": description = ""
return description
def set_description(self,value): self.command_description = value
description = property(get_description,set_description)
value = description
command_value = command_description
@property
def values(self): return self.descriptions[:]
def get_matching_row(self):
"""Row that matches the actual settings, as 0-based integer"""
from numpy import nan
matching_rows = self.matching_rows
matching_command_rows = [row for row in matching_rows if row in self.command_rows]
if matching_command_rows: matching_rows = matching_command_rows
if len(matching_rows) > 0: matching_row = matching_rows[0]
else: matching_row = nan
return matching_row
def set_matching_row(self,row):
self.goto(row)
matching_row = property(get_matching_row,set_matching_row)
def get_matching_rows(self):
"""List of rows that matches the actual settings, as 0-based integer"""
matching_rows = []
from numpy import nan
positions = self.current_positions[:]
for row in range(0,self.nrows):
if self.row_matches(row,positions=positions):
matching_rows += [row]
return matching_rows
def set_matching_rows(self,rows):
for row in rows: self.define(row)
matching_rows = property(get_matching_rows,set_matching_rows)
def row_matches(self,row,positions=None):
"""Does this row match the actual settings?
row: 0-based integer"""
if positions is None: positions = self.current_positions[:]
matches = all([self.matches(row,im,positions[im]) for im in range(0,self.n_motors)])
return matches
@property
def closest_row(self):
"""Find the row the is closest to the actual settings,
as 0-based integer"""
from numpy import nan
closest_rows = self.closest_rows
closest_command_rows = [row for row in closest_rows if row in self.command_rows]
if len(closest_command_rows)>0: closest_rows = closest_command_rows
if len(closest_rows) > 0: closest_row = closest_rows[0]
else: closest_row = nan
return closest_row
@property
def closest_rows(self):
"""Find the row the is closest to the actual settings,
as 0-based integer"""
from numpy import zeros,array,average,sqrt,nanmin,where,isfinite,isnan,nan
closest = []
pos = self.current_positions[:]
dist = zeros(self.nrows)
for row in range(0,self.nrows):
distances = array([self.distance(row,im,pos[im])
for im in range(0,self.n_motors)])
distances = distances[~isnan(distances)]
dist[row] = sqrt(average(distances**2))
min_dist = nanmin(dist)
if isfinite(min_dist): closest = list(where(dist == min_dist)[0])
return closest
def stop(self):
"""To cancel any move"""
for j in range(0,self.n_motors):
motor = self.motors[j]
if hasattr(motor,"stop"): motor.stop()
def goto(self,row):
self.command_rows = [row]
self.applying = True
from thread_property import thread_property
applying = thread_property("apply")
def apply(self):
"""Move all motors motors to nominal positions
row: zero-based index"""
for motor_number in range(0,self.n_motors):
##if not self.motor_applied(motor_number):
self.current_positions[motor_number] = self.nominal_positions[motor_number]
if self.serial:
from time import sleep
while getattr(self.motors[motor_number],"moving",False): sleep(0.1)
def get_applied(self):
"""Is the nominal configuration currently active?"""
applied = True
for motor_number in range(0,self.n_motors):
if not self.motor_applied(motor_number): applied = False; break
return applied
def set_applied(self,value):
if value: self.applying = True
applied = property(get_applied,set_applied)
@property
def motors_applied(self):
return [self.motor_applied(motor_number) for motor_number in range(0,self.n_motors)]
def motor_applied(self,motor_number):
"""Reassert current posistion for this motor number?"""
actual_pos = self.current_positions[motor_number]
nominal_pos = self.nominal_positions[motor_number]
if self.is_numeric(motor_number):
motor_applied = self.position_matches(nominal_pos,actual_pos,motor_number)
else: # string-valued
motor_applied = (nominal_pos == actual_pos)
if self.is_configuration(motor_number):
if not self.configuration(motor_number).applied: motor_applied = False
return motor_applied
def define(self,row):
"""Remember the current motor positions
row: zero-based index"""
for i in range(0,self.n_motors):
self.positions[i][row] = self.command_positions[i]
def update_timestamp(self,row):
self.updated[row] = self.current_timestamp
@property
def current_timestamp(self):
from time import strftime
timestamp = strftime("%Y-%m-%d %H:%M:%S") # 2019-01-28 13:24:52
return timestamp
def get_positions_match(self):
"""Usage: self.positions_match[motor_number][row]"""
return self.Positions_Match(self)
def set_positions_match(self,value): pass
positions_match = property(get_positions_match,set_positions_match)
class Positions_Match(object):
"""Usage: self.positions[motor_number][row]
or: self.positions[motor_number][row] = value"""
def __init__(self,configuration):
self.configuration = configuration
def __getitem__(self,i):
if type(i) == slice: value = [x for x in self]
else:
motor_number = i
rows = range(0,self.configuration.nrows)
value = [self.configuration.matches(row,motor_number) for row in rows]
return value
def __len__(self): return self.configuration.n_motors
def __iter__(self):
for i in range(0,len(self)):
if i < len(self): yield self[i]
def matches(self,row,motor_number,actual_pos=None):
"""True of False
row: 0-based index
motor_number: column, 0-based index
actual_pos: current position of motor number *motor_number*
(optional, given to speed up calculation)
"""
if actual_pos is None:
actual_pos = self.current_positions[motor_number]
nominal_pos = self.positions[motor_number][row]
if self.is_numeric(motor_number):
matches = self.position_matches(nominal_pos,actual_pos,motor_number)
else: # string-valued
matches = self.string_matches(nominal_pos,actual_pos,motor_number)
##debug("%s, row %r, col %r: %r==%r? %r" %
## (self.name,row,motor_number,actual_pos,nominal_pos,matches))
return matches
def position_matches(self,nominal_pos,actual_pos,motor_number):
tolerance = self.tolerance[motor_number]
matches = not abs(nominal_pos - actual_pos) > tolerance
return matches
def distance(self,row,motor_number,actual_pos):
"""Positional difference
row: 0-based index
motor_number: column, 0-based index
actual_pos: current position of motor
"""
from numpy import inf,nan
nominal_pos = self.positions[motor_number][row]
if self.is_numeric(motor_number):
distance = abs(nominal_pos - actual_pos)
else: # string-valued
if actual_pos == "" or nominal_pos == "": distance = nan
elif self.string_matches(nominal_pos,actual_pos,motor_number): distance = 0
else: distance = inf
return distance
def string_matches(self,nominal_pos,actual_pos,motor_number):
matches = (nominal_pos == actual_pos)
if self.multiple_selections:
# e.g. actual_pos='NIH:H-1_ps,NIH:H-56_ps', nominal_pos='NIH:H-1_ps'
matches = nominal_pos in actual_pos and nominal_pos != ""
if actual_pos == "" and nominal_pos == "": matches = True
##debug("matches(%r,%r): %r" % (nominal_pos,actual_pos,matches))
return matches
def default_value(self,motor_number):
"""Not a Number (nan) or empty string ("")
motor_number: 0-based index"""
from numpy import nan
default_value = nan if self.is_numeric(motor_number) else ""
return default_value
@property
def are_numeric(self):
return [self.is_numeric(i) for i in range(0,self.n_motors)]
def is_numeric(self,motor_number):
"""If the motor position a number?
motor_number: 0-based index"""
format = self.formats[motor_number]
# "%s" -> False, "%.3f" -> True
is_numeric = False if "s" in format else True
return is_numeric
def get_updated(self): return self.Values(self,"updated","")
def set_updated(self,value): self.updated[:] = value
updated = property(get_updated,set_updated)
def get_positions(self):
"""Usage: self.positions[motor_number][row]
or: self.positions[motor_number][row] = value"""
return self.Positions(self)
def set_positions(self,value): self.positions[:] = value
positions = property(get_positions,set_positions)
class Positions(object):
"""Usage: self.positions[motor_number][row]
or: self.positions[motor_number][row] = value"""
def __init__(self,configuration):
self.configuration = configuration
def __getitem__(self,i):
from numpy import nan
if type(i) == slice: value = [x for x in self]
else: value = self.configuration.Values(self.configuration,
self.configuration.motor_names[i],
self.configuration.default_value(i))
return value
def __setitem__(self,i,value):
if type(i) == slice:
for j in range(0,len(value)): self[j] = value[j]
else: self[i][:] = value
def __len__(self): return self.configuration.n_motors
def __iter__(self):
for i in range(0,len(self)):
if i < len(self): yield self[i]
class Values(object):
def __init__(self,configuration,name,default_value):
self.configuration = configuration
self.name = name
self.default_value = default_value
def __getitem__(self,row):
from DB import db
if type(row) == slice: value = [x for x in self]
else: value = db(self.db_key(row),self.default_value)
return value
def __setitem__(self,row,value):
##debug("configuration.Values[%r] = %r" % (row,value))
if type(row) == slice:
for i in range(0,len(value)): self[i] = value[i]
elif value != self[row]:
from DB import dbset
dbset(self.db_key(row),value)
if self.name not in ["description","updated"]:
debug("self.configuration.update_timestamp(%r)" % row)
self.configuration.update_timestamp(row)
def db_key(self,row):
try: row = str(int(row))
except: row = ""
key = "%s.line%s.%s" % (self.configuration.name,row,self.name)
return key
def __len__(self): return self.configuration.nrows
def __repr__(self): return "%s.Values(%r,%r)" % \
(self.configuration.name,self.name,self.default_value)
def __iter__(self):
for i in range(0,len(self)):
if i < len(self): yield self[i]
def __repr__(self): return "configuration(%r)" % self.name
def __getattr__(self,name):
"""Usage example: SAXS_WAXS_methods.passes_per_image.value"""
if name in self.names: return self.Property(self,name)
else: raise AttributeError("Is %r a name?" % name)
class Property(object):
"""Usage example: SAXS_WAXS_methods.passes_per_image.value"""
def __init__(self,configuration,name):
self.configuration = configuration
self.name = name
def get_value(self):
return self.configuration.current_positions[self.motor_num]
def set_value(self,value):
self.configuration.current_positions[self.motor_num] = value
value = property(get_value,set_value)
def get_command_value(self):
return self.configuration.nominal_positions[self.motor_num]
command_value = property(get_command_value,set_value)
@property
def motor_num(self): return self.configuration.names.index(self.name)
def __repr__(self): return "%r.%s" % (self.configuration,self.name)
def resize(self,values,length,default_value=None,template=None):
"""Change the length of a list by truncating it or appending new items
using default_value.
template: e.g. "motor%d", will be expanded to "motor0","motor1",...
"""
values = list(values)
while len(values) < length:
if template: value = self.format_string(template,len(values))
else: value = default_value
values.append(value)
while len(values) > length: values.pop()
return values
def format_string(self,string,value):
""" format="motor%d",value=1 -> "motor1" """
try: formatted_string = string % value
except: formatted_string = string
return formatted_string
configuration = Configuration
config = configuration
class Configurations(object):
"""Name space containing all defined configurations"""
def __getattr__(self,name):
if name == "__members__": return configuration.configuration_names
if name.startswith("__") and name.endswith("__"):
raise AttributeError("%s" % name)
return configuration(name)
configurations = Configurations()
configs = configurations
if __name__ == '__main__': # for testing
from pdb import pm # for debugging
from time import time # for performance testing
import logging
for h in logging.root.handlers[:]: logging.root.removeHandler(h)
logging.basicConfig(level=logging.DEBUG,
format="%(asctime)s %(levelname)s %(module)s.%(funcName)s: %(message)s",
)
##from instrumentation import * # -> globals()
##name = ""
##name = "beamline_configuration"
##name = "sequence_modes"
##name = "Julich_chopper_modes"
##name = "heat_load_chopper_modes"
name = "timing_modes"
##name = "sequence_modes"
##name = "delay_configuration"
##name = "temperature_configuration"
##name = "power_configuration"
##name = "scan_configuration"
##name = "alio_diffractometer_saved"
##name = "detector_configuration"
##name = "diagnostics_configuration"
##name = "method"
self = configuration(name=name)
##self = configuration(name=name,locals=locals(),globals=globals())
##print("self.name=%r" % self.name)
##print("self.motor_names[:]")
##print("self.current_positions[:]")
##print("self.goto(0)")
##print("self.define(4)")
##print("self.matching_description")
##print("self.closest_description")
##print("self.command_description")
##print("self.value")
##print("self.command_value")
##print("self.command_rows")
##print("self.matching_rows")
##print("self.closest_rows")
##print("self.apply()")
##print("self.applied")
##print("self.motors_applied")
print("self.descriptions")
from CAServer import casput,casget,PV_value
from CA import caget,cainfo
PV_name = "TEST:TEST.TEST"
value = self.descriptions
print("casput(PV_name,value)")
print("casget(PV_name)")
print("caget(PV_name)")
print("PV_value(PV_name)")
print("PV_value(PV_name) == value")
<file_sep>line0.timing_system.channels.hsc.delay = 4.97e-06
line0.Phase [s] = 5.4527e-06
line0.ChopX = 33.79
line0.ChopY = 30.17
line0.description = 'S-1t'
line0.updated = '17 Oct 15:03'
line1.timing_system.channels.hsc.delay = 0.0
line1.ChopX = 37.28
line1.ChopY = 30.925
line1.description = 'S-1'
line1.updated = '17 Oct 15:05'
line2.timing_system.channels.hsc.delay = 6.000000000000001e-09
line2.ChopX = 37.28
line2.ChopY = 30.85
line2.description = 'S-3'
line2.updated = '17 Oct 15:05'
line3.timing_system.channels.hsc.delay = 1.1000000000000001e-08
line3.ChopX = 37.28
line3.ChopY = 30.775
line3.description = 'S-5'
line3.updated = '17 Oct 15:06'
line4.timing_system.channels.hsc.delay = 2.3e-08
line4.ChopX = 37.28
line4.ChopY = 30.555
line4.description = 'S-11'
line4.updated = '17 Oct 15:06'
line5.timing_system.channels.hsc.delay = -1.4000000000000001e-08
line5.ChopX = 37.28
line5.ChopY = 30.505
line5.description = 'S-24'
line5.updated = '17 Oct 15:07'
line6.timing_system.channels.hsc.delay = 0.0
line6.ChopX = 37.28
line6.ChopY = 30.555
line6.description = 'H-1'
line6.updated = '17 Oct 15:08'
line7.timing_system.channels.hsc.delay = -1.84e-06
line7.ChopX = 37.28
line7.ChopY = 30.555
line7.description = 'H-56'
line7.updated = '04 Nov 19:17'
line8.timing_system.channels.hsc.delay = nan
line8.ChopX = 37.67
line8.ChopY = 30.925
line8.description = 'Bypass'
line8.updated = '17 Oct 15:10'
motor_names = ['ChopX', 'ChopY', 'timing_system.channels.hsc.delay', 'timing_system.cmcnd']
motor_labels = ['X', 'Y', 'Julich Phase', 'ChemMat Phase']
nrows = 13
formats = ['%+6.3f', '%+6.3f', 'time.6', 'time.6']
title = 'High-Speed Chopper Modes'
line9.description = 'CH-1'
line9.updated = '23 Oct 09:37'
line9.ChopX = 30.58
line9.ChopY = 9.0
line9.timing_system.channels.hsc.delay = nan
line10.description = 'CH-56'
line10.updated = '23 Oct 09:37'
line10.ChopX = 30.58
line10.ChopY = 9.0
line10.timing_system.channels.hsc.delay = nan
tolerance = [0.001, 0.001, 3e-09, 1e-08]
command_row = 12
line11.description = 'C Bypass'
line11.updated = '23 Oct 09:37'
line11.ChopX = 28.58
line11.ChopY = 9.0
line11.timing_system.channels.hsc.delay = nan
names = ['X', 'Y', 'Julich_phase', 'CMC_phase']
line10.timing_system.cmcnd = -1.8409999999999998e-06
line11.timing_system.cmcnd = nan
line9.timing_system.cmcnd = 0.0
line12.description = 'CS-19'
line12.ChopX = 30.58
line12.ChopY = 9.0
line12.timing_system.channels.hsc.delay = 4.9694833463094414e-06
line12.timing_system.cmcnd = 0.00021999579466604535
line12.updated = '23 Oct 09:37'
show_in_list = False
command_rows = [1]<file_sep>#!/usr/bin/env python
"""
Control panel for optical freeze detector
Runs code to retract the sample from the cooling stream and operate the pump
at high speed as an AeroBasic program "Freeze_Intervention.ab".
Authors: <NAME>, <NAME>
Date created: 8 Mar 2018
Date last modified: 8 Mar 2018
"""
__version__ = "1.0"
from logging import debug,info,warn,error
import wx
from freeze_intervention import freeze_intervention # passed on in "globals()"
class FreezeInterventionPanel(wx.Frame):
title = "Freeze Intervention"
def __init__(self):
wx.Frame.__init__(self,parent=None,title=self.title)
# Icon
from Icon import SetIcon
SetIcon(self,"Tool")
self.panel = self.ControlPanel
self.Fit()
self.Show()
# Refresh
self.timer = wx.Timer(self)
self.Bind (wx.EVT_TIMER,self.OnTimer,self.timer)
self.timer.Start(5000,oneShot=True)
def OnTimer(self,event):
"""Perform periodic updates"""
try: self.update_controls()
except Exception,msg:
error("%s" % msg)
import traceback
traceback.print_exc()
self.timer.Start(5000,oneShot=True)
def update_controls(self):
if self.code_outdated:
self.update_code()
panel = self.ControlPanel
self.panel.Destroy()
self.panel = panel
self.Fit()
@property
def code_outdated(self):
from inspect import getfile
from os.path import getmtime,basename
filename = getfile(self.__class__)
##debug("module: %s" % filename)
if self.timestamp == 0: self.timestamp = getmtime(filename)
outdated = getmtime(filename) != self.timestamp
return outdated
def update_code(self):
from inspect import getfile
from os.path import getmtime,basename
filename = getfile(self.__class__)
##debug("module: %s" % filename)
self.timestamp = getmtime(filename)
module_name = basename(filename).replace(".pyc",".py").replace(".py","")
module = __import__(module_name)
reload(module)
debug("Reloaded module %r" % module.__name__)
debug("Updating class of %r instance" % self.__class__.__name__)
self.__class__ = getattr(module,self.__class__.__name__)
timestamp = 0
@property
def ControlPanel(self):
# Controls and Layout
panel = wx.Panel(self)
from EditableControls import ComboBox,TextCtrl
from Controls import Control
from BeamProfile_window import BeamProfile
flag = wx.ALIGN_CENTRE_HORIZONTAL|wx.ALL
border = 2
l = wx.ALIGN_LEFT; r = wx.ALIGN_RIGHT; cv = wx.ALIGN_CENTER_VERTICAL
a = wx.ALL
layout = wx.BoxSizer(wx.HORIZONTAL)
left_panel = wx.BoxSizer(wx.VERTICAL)
group = wx.BoxSizer(wx.VERTICAL)
text = wx.StaticText(panel,label="Status")
group.Add (text,flag=flag,border=border)
control = Control(panel,type=wx.ToggleButton,
name="FreezeInterventionPanel.Enabled",
globals=globals(),
label="Disabled/Enabled",
size=(180,-1))
group.Add (control,flag=flag,border=border)
control = Control(panel,type=wx.ToggleButton,
name="FreezeInterventionPanel.Active",
globals=globals(),
label="Inactive/Active",
size=(180,-1))
group.Add (control,flag=flag,border=border)
left_panel.Add (group,flag=flag,border=border)
layout.Add (left_panel,flag=flag,border=border)
panel.SetSizer(layout)
panel.Fit()
return panel
if __name__ == '__main__':
from pdb import pm
import logging; from tempfile import gettempdir
logfile = gettempdir()+"/FreezeInterventionPanel.log"
logging.basicConfig(level=logging.DEBUG,
format="%(asctime)s %(levelname)s: %(message)s",
filename=logfile,
)
# Needed to initialize WX library
if not hasattr(wx,"app"): wx.app = wx.App(redirect=False)
panel = FreezeInterventionPanel()
wx.app.MainLoop()
<file_sep>MEAN.filename = '//mx340hs/data/anfinrud_1903/Archive/NIH.SAMPLE_FROZEN_OPTICAL2.MEAN.txt'<file_sep>"""<NAME>, 9 Dec 2010 - Jan 27, 2016
"""
__version__ = "1.0"
class DummyMotor(object):
name = "Dummy Motor"
unit = ""
value = 0
def __init__(self,*args,**kwargs):
if len(args)>0: self.name = args[0]
def get_moving(self): return False
def set_moving(self,value): pass
moving = property(get_moving,set_moving)
def stop(): pass
dummy_motor = DummyMotor()
<file_sep>"""
Optimize the X-ray beam position on the X-ray area detector.
<NAME>, Nov 1, 2016 - Nov 2, 2016
"""
from instrumentation import MirrorH,MirrorV,shg,svg,ccd,timing_system
from profile import xy_projections,FWHM,CFWHM,xvals,yvals,overloaded_pixels,SNR
from Ensemble_SAXS_pp import Ensemble_SAXS
from CA import caget,caput,PV
from persistent_property import persistent_property
from numpy import average,asarray,where
from thread import start_new_thread
from time import sleep,time
from ImageViewer import show_images
from logfile import LogFile
from os.path import exists
from normpath import normpath
from logging import debug,info,warn,error
__version__ = "1.0"
class Xray_Beam_Position_Check(object):
name = "xray_beam_position_check"
class Settings(object):
name = "settings"
# X-Ray beam steering controls.
# Horizontal deflection mirror jacks
def get_x1_motor(self): return MirrorH.m1.prefix
def set_x1_motor(self,value): MirrorH.m1.prefix = value
x1_motor = property(get_x1_motor,set_x1_motor)
def get_x2_motor(self): return MirrorH.m2.prefix
def set_x2_motor(self,value): MirrorH.m2.prefix = value
x2_motor = property(get_x2_motor,set_x2_motor)
def get_y_motor(self): return MirrorV.prefix
def set_y_motor(self,value): MirrorV.prefix = value
y_motor = property(get_y_motor,set_y_motor)
# To narrow down aperture upstream of the detector for higher senitivity
def get_x_aperture_motor(self): return shg.prefix
def set_x_aperture_motor(self,value): shg.prefix = value
x_aperture_motor = property(get_x_aperture_motor,set_x_aperture_motor)
def get_y_aperture_motor(self): return svg.prefix
def set_y_aperture_motor(self,value): svg.prefix = value
y_aperture_motor = property(get_y_aperture_motor,set_y_aperture_motor)
x_aperture_norm = persistent_property("x_aperture_norm",0.150)
y_aperture_norm = persistent_property("y_aperture_norm",0.050)
x_aperture_scan = persistent_property("x_aperture_scan",0.050)
y_aperture_scan = persistent_property("y_aperture_scan",0.020)
def get_x_aperture(self): return shg.command_value
def set_x_aperture(self,value): shg.command_value = value
x_aperture = property(get_x_aperture,set_x_aperture)
def get_y_aperture(self): return svg.command_value
def set_y_aperture(self,value): svg.command_value = value
y_aperture = property(get_y_aperture,set_y_aperture)
def get_timing_system_ip_address(self): return timing_system.ip_address
def set_timing_system_ip_address(self,value): timing_system.ip_address = value
timing_system_ip_address = property(get_timing_system_ip_address,set_timing_system_ip_address)
acquire_image_timeout = 30 # seconds
x_gain = persistent_property("x_gain",0.143) # mrad/mm
y_gain = persistent_property("y_gain",2.7) # V/mm was: 1/3.3e-3
x_nominal = persistent_property("x_nominal",175.927) # mm from left, 2016-03-05
y_nominal = persistent_property("y_nominal",174.121) # mm from top, 2016-03-05
history_length = persistent_property("history_length",50)
average_samples = persistent_property("average_samples",1)
x_enabled = persistent_property("x_enabled",False)
y_enabled = persistent_property("y_enabled",False)
ROI_width = persistent_property("ROI_width",1.0) # mm
x_ROI_center = persistent_property("x_ROI_center",175.9) # mm from left
y_ROI_center = persistent_property("y_ROI_center",174.1) # mm from top
min_SNR = persistent_property("min_SNR",5.0) # signal-to-noise ratio
image_filename = persistent_property("image_filename",
"//mx340hs/data/rayonix_scratch/xray_beam_position.rx")
settings = Settings()
log = LogFile(name+".log",["date time","x","y","x_control","y_control","image_timestamp"])
if log.filename == "":
log.filename = "//mx340hs/data/anfinrud_1611/Logfiles/xray_beam_position_check.log"
def update(self):
t = self.image_timestamp
if t != 0 and abs(t - self.last_image_timestamp) >= 0.1:
x,y = self.beam_position
xc,yc = self.x_control,self.y_control
self.log.log(x,y,xc,yc,t)
@property
def x_average(self): return average(self.x_samples)
@property
def y_average(self): return average(self.y_samples)
@property
def x_history(self): return self.log.history("x",count=self.settings.history_length)
@property
def y_history(self): return self.log.history("y",count=self.settings.history_length)
@property
def t_history(self): return self.log.history("date time",count=self.settings.history_length)
@property
def x_samples(self): return self.log.history("x",count=self.settings.average_samples)
@property
def y_samples(self): return self.log.history("y",count=self.settings.average_samples)
@property
def last_image_timestamp(self):
t = self.log.history("image_timestamp",count=1)
t = t[0] if len(t)>0 else 0
return t
def get_x_control(self): return tofloat(caget(self.x_read_PV))
def set_x_control(self,value): return caput(self.x_PV,value)
x_control = property(get_x_control,set_x_control)
def get_y_control(self): return tofloat(caget(self.y_read_PV))
def set_y_control(self,value): return caput(self.y_PV,value)
y_control = property(get_y_control,set_y_control)
def get_x_control_average(self): return average(self.x_control_samples)
def set_x_control_average(self,value): self.x_control = value
x_control_average = property(get_x_control_average,set_x_control_average)
def get_y_control_average(self): return average(self.y_control_samples)
def set_y_control_average(self,value): self.y_control = value
y_control_average = property(get_y_control_average,set_y_control_average)
@property
def x_control_samples(self):
return self.log.history("x_control",count=self.settings.average_samples)
@property
def y_control_samples(self):
return self.log.history("y_control",count=self.settings.average_samples)
@property
def x_control_history(self):
return self.log.history("x_control",count=self.settings.history_length)
@property
def y_control_history(self):
return self.log.history("y_control",count=self.settings.history_length)
@property
def x_control_corrected(self):
"""Value for the y control in order to bring the x position back to
its nominal value"""
x_control = self.x_control_average - \
(self.x_average - self.x_nominal)*self.settings.x_gain
return x_control
@property
def y_control_corrected(self):
"""Value for the y control in order to bring the y position back to
its nominal value"""
y_control = self.y_control_average - \
(self.y_average - self.y_nominal)*self.settings.y_gain
return y_control
def apply_correction(self):
self.apply_x_correction()
self.apply_y_correction()
def apply_x_correction(self):
self.x_control = self.x_control_corrected
def apply_y_correction(self):
self.y_control = self.y_control_corrected
cancelled = persistent_property("cancelled",False)
acquire_image_started = persistent_property("acquire_image_started",0.0)
def get_x_control(self): return MirrorH.command_value
def set_x_control(self,value): MirrorH.command_value = value
x_control = property(get_x_control,set_x_control)
def x_next(self,x):
"""The next value that is an intergal motor step"""
offset = MirrorH.offset
dx = self.settings.x_resolution
return round_next(x-offset,dx)+offset
def y_next(self,y):
"""The next value that is an intergal motor step"""
offset = 0 ##MirrorV.offset
dy = self.settings.y_resolution
return round_next(y-offset,dy)+offset
def get_y_control(self): return MirrorV.command_value
def set_y_control(self,value): MirrorV.command_value = value
y_control = property(get_y_control,set_y_control)
def acquire_image_setup(self):
self.settings.x_aperture = self.settings.x_aperture_scan
self.settings.y_aperture = self.settings.y_aperture_scan
def acquire_image_unsetup(self):
self.settings.x_aperture = self.settings.x_aperture_norm
self.settings.y_aperture = self.settings.y_aperture_norm
def get_acquire_image_running(self):
return self.acquire_image_started > time()-self.settings.acquire_image_timeout
def set_acquire_image_running(self,value):
if value:
if not self.acquire_image_running: self.start_acquire_image()
else: self.cancelled = True
acquire_image_running = property(get_acquire_image_running,set_acquire_image_running)
def start_acquire_image(self):
self.cancelled = False
start_new_thread(self.acquire_image,())
def acquire_image(self):
self.acquire_image_started = time()
self.acquire_image_setup()
ccd.ignore_first_trigger = False
ccd.acquire_images_triggered([normpath(self.settings.image_filename)])
show_images(normpath(self.settings.image_filename))
Ensemble_SAXS.acquire(delays=[0],laser_on=[False])
tmax = time()+self.settings.acquire_image_timeout
while ccd.state() != "idle" and not self.cancelled and time()<tmax: sleep(0.05)
ccd.abort()
self.acquire_image_unsetup()
self.acquire_image_started = 0
self.update()
@property
def x_beam(self): return self.beam_position[0]
@property
def y_beam(self): return self.beam_position[1]
@property
def beam_position(self):
xprofile,yprofile = xy_projections(self.image,self.ROI_center,
self.ROI_width)
x,y = CFWHM(xprofile),CFWHM(yprofile)
return x,y
@property
def x_error(self): return self.x_beam - self.x_nominal
@property
def y_error(self): return self.y_beam - self.y_nominal
@property
def image_OK(self):
return not self.image_overloaded and self.SNR > self.settings.min_SNR
@property
def image_overloaded(self):
return overloaded_pixels(self.image,self.ROI_center,self.ROI_width)
@property
def SNR(self):
xprofile,yprofile = xy_projections(self.image,self.ROI_center,
self.ROI_width)
return (SNR(xprofile)+SNR(yprofile))/2
@property
def image(self):
from numimage import numimage
filename = normpath(self.settings.image_filename)
if exists(filename): image = numimage(filename)
else: image = self.default_image
# Needed for "BeamProfile" to detect image updates.
# If a memory-mapped image would be chached by "BeamProfile", the
# comparison with the new image would show no difference, since the
# cached image dynamically updates.
image = image.copy()
return image
@property
def x_ROI_center(self): return self.settings.x_ROI_center
@property
def y_ROI_center(self): return self.settings.y_ROI_center
@property
def ROI_center(self): return self.x_ROI_center,self.y_ROI_center
@property
def ROI_width(self): return self.settings.ROI_width
@property
def x_nominal(self): return self.settings.x_nominal
@property
def y_nominal(self): return self.settings.y_nominal
@property
def default_image(self):
from numimage import numimage
from numpy import uint16
image = numimage((3840,3840),pixelsize=0.0886,dtype=uint16)+10
return image
@property
def image_timestamp(self):
"""Full pathname of the last recorded image"""
from os.path import getmtime,dirname
from os import listdir
filename = normpath(self.settings.image_filename)
if exists(filename): listdir(dirname(filename)) # for NFS attibute caching
t = getmtime(filename) if exists(filename) else 0
return t
xray_beam_position_check = Xray_Beam_Position_Check()
def round_next(x,step):
"""Rounds x up or down to the next multiple of step."""
if step == 0: return x
return round(x/step)*step
if __name__ == "__main__":
from pdb import pm
from CA import cainfo
from instrumentation import mir2X1,mir2X2,mir2Th
self = xray_beam_position_check # for debugging
##print('xray_beam_position_check.settings.timing_system_ip_address = %r' % xray_beam_position_check.settings.timing_system_ip_address)
##print('xray_beam_position_check.settings.x1_motor = %r' % xray_beam_position_check.settings.x1_motor)
##print('xray_beam_position_check.settings.x2_motor = %r' % xray_beam_position_check.settings.x2_motor)
##print('xray_beam_position_check.settings.y_motor = %r' % xray_beam_position_check.settings.y_motor)
##print('xray_beam_position_check.settings.x_aperture_motor=%r' % xray_beam_position_check.settings.x_aperture_motor)
##print('xray_beam_position_check.settings.y_aperture_motor=%r' % xray_beam_position_check.settings.y_aperture_motor)
##print('xray_beam_position_check.x_control = %.4f' % xray_beam_position_check.x_control)
##print('xray_beam_position_check.y_control = %.4f' % xray_beam_position_check.y_control)
print('xray_beam_position_check.acquire_image()')
print('xray_beam_position_check.image')
##print('xray_beam_position_check.x_average')
##print('xray_beam_position_check.y_average')
##print('xray_beam_position_check.x_control_corrected')
##print('xray_beam_position_check.y_control_corrected')
<file_sep>#!/usr/bin/env python
"""Grapical User Interface for X-ray beam stabilization
<NAME>, Nov 1, 2016 - Nov 1, 2016
"""
from pdb import pm # for debugging
from logging import debug,warn,info,error
##import logging; logging.basicConfig(level=logging.DEBUG)
from xray_beam_position_check import xray_beam_position_check,Xray_Beam_Position_Check
from Panel import BasePanel,PropertyPanel,ButtonPanel,TogglePanel,TweakPanel
from BeamProfile_window import BeamProfile
from TimeChart import TimeChart
from persistent_property import persistent_property
import wx
__version__ = "1.0"
class XrayBeamCheckPanel(BasePanel,Xray_Beam_Position_Check):
title = "X-Ray Beam Position Check"
standard_view = [
"Image",
"X [mrad]",
"Y [V]",
"X Corr. [mrad]",
"Y Corr. [V]",
"Acquire Image",
"X Correction",
"Y Correction",
]
saturation_level = persistent_property("saturation_level",10000.0) # counts
def __init__(self,parent=None):
Xray_Beam_Position_Check.__init__(self)
parameters = [
[[BeamProfile, "Image", self ],{}],
[[TweakPanel, "Saturation level", self,"saturation_level" ],{"digits":0}],
[[PropertyPanel,"Image timestamp", self,"image_timestamp" ],{"type":"date","read_only":True}],
[[PropertyPanel,"Image usable", self,"image_OK" ],{"type":"Unusable/OK","read_only":True}],
[[PropertyPanel,"Overloaded pixels", self,"image_overloaded" ],{"read_only":True}],
[[PropertyPanel,"Signal-to-noise ratio", self,"SNR" ],{"digits":1,"read_only":True}],
[[PropertyPanel,"X Beam [mm]", self,"x_beam" ],{"digits":3,"read_only":True}],
[[PropertyPanel,"Y Beam [mm]", self,"y_beam" ],{"digits":3,"read_only":True}],
[[PropertyPanel,"X Error [mm]", self,"x_error" ],{"digits":3,"read_only":True}],
[[PropertyPanel,"Y Error [mm]", self,"y_error" ],{"digits":3,"read_only":True}],
[[PropertyPanel,"X Beam avg. [mm]", self,"x_average" ],{"digits":3,"read_only":True}],
[[PropertyPanel,"Y Beam avg. [mm]", self,"y_average" ],{"digits":3,"read_only":True}],
[[TweakPanel, "X [mrad]", self,"x_control" ],{"digits":4}],
[[TweakPanel, "Y [V]", self,"y_control" ],{"digits":4}],
[[PropertyPanel,"X Corr. [mrad]", self,"x_control_corrected"],{"digits":4,"read_only":True}],
[[PropertyPanel,"Y Corr. [V]", self,"y_control_corrected"],{"digits":4,"read_only":True}],
[[TogglePanel, "Acquire Image", self,"acquire_image_running"],{"type":"Start/Cancel"}],
[[ButtonPanel, "Correction", self,"apply_correction" ],{"label":"Apply"}],
[[ButtonPanel, "X Correction", self,"apply_x_correction" ],{"label":"Apply"}],
[[ButtonPanel, "Y Correction", self,"apply_y_correction" ],{"label":"Apply"}],
]
BasePanel.__init__(self,
parent=parent,
name=self.name,
title=self.title,
parameters=parameters,
standard_view=self.standard_view,
subpanels=[Settings],
)
class Settings(BasePanel,Xray_Beam_Position_Check.Settings):
title = "Settings"
standard_view = [
"X1 Motor",
"X2 Motor",
"Y Motor",
"X Aperture Motor",
"Y Aperture Motor",
"X Aperture (scan) [mm]",
"Y Aperture (scan) [mm]",
"X Aperture (norm) [mm]",
"Y Aperture (norm) [mm]",
"History Length",
"Average count",
"ROI center X [mm]",
"ROI center Y [mm]",
"ROI width [mm]",
"Nominal X [mm]",
"Nominal Y [mm]",
]
def __init__(self,parent=None):
Xray_Beam_Position_Check.__init__(self)
parameters = [
[[PropertyPanel,"Timing System", self,"timing_system_ip_address"],{}],
[[PropertyPanel,"X1 Motor", self,"x1_motor" ],{}],
[[PropertyPanel,"X2 Motor", self,"x2_motor" ],{}],
[[PropertyPanel,"Y Motor", self,"y_motor" ],{}],
##[[TweakPanel, "X Resolution [mrad]",self,"x_resolution" ],{"digits":4}],
##[[TweakPanel, "Y Resolution [V]", self,"y_resolution" ],{"digits":4}],
[[PropertyPanel,"X Aperture Motor", self,"x_aperture_motor" ],{}],
[[PropertyPanel,"Y Aperture Motor", self,"y_aperture_motor" ],{}],
[[TweakPanel, "X Aperture [mm]", self,"x_aperture" ],{"digits":4}],
[[TweakPanel, "Y Aperture [mm]", self,"y_aperture" ],{"digits":4}],
[[TweakPanel, "X Aperture (scan) [mm]",self,"x_aperture_scan"],{"digits":4}],
[[TweakPanel, "Y Aperture (scan) [mm]",self,"y_aperture_scan"],{"digits":4}],
[[TweakPanel, "X Aperture (norm) [mm]",self,"x_aperture_norm"],{"digits":4}],
[[TweakPanel, "Y Aperture (norm) [mm]",self,"y_aperture_norm"],{"digits":4}],
[[TweakPanel, "Calibration X [mrad/mm]",self,"x_gain" ],{"digits":4}],
[[TweakPanel, "Calibration Y [V/mm]", self,"y_gain" ],{"digits":4}],
[[PropertyPanel,"History Length", self,"history_length" ],{}],
[[TweakPanel, "Average count", self,"average_samples" ],{"digits":0}],
[[TweakPanel, "ROI center X [mm]", self,"x_ROI_center" ],{"digits":3}],
[[TweakPanel, "ROI center Y [mm]", self,"y_ROI_center" ],{"digits":3}],
[[TweakPanel, "ROI width [mm]", self,"ROI_width" ],{"digits":3}],
[[TweakPanel, "Nominal X [mm]", self,"x_nominal" ],{"digits":3}],
[[TweakPanel, "Nominal Y [mm]", self,"y_nominal" ],{"digits":3}],
[[PropertyPanel,"Image filename", self,"image_filename" ],{"read_only":True}],
]
BasePanel.__init__(self,
parent=parent,
name=self.name,
title=self.title,
parameters=parameters,
standard_view=self.standard_view,
subname=True,
)
if __name__ == '__main__':
import logging; logging.basicConfig(level=logging.DEBUG)
# Needed to initialize WX library
if not "app" in globals(): app = wx.App(redirect=False)
panel = XrayBeamCheckPanel()
app.MainLoop()
<file_sep>#!/usr/bin/env python
"""
Configuration panel for the BioCARS FPGA timing system
Clock settings
Author: <NAME>
Date created: 2019-03-2
Date last modified: 2019-06-01
"""
__version__ = "1.0.2" # name
from logging import debug,info,warn,error
from Panel import BasePanel
class Timing_Clock_Configuration_Panel(BasePanel):
name = "Timing_Clock_Configuration_Panel"
title = "Clock Configuration"
icon = "timing-system"
channels = dict([(i,"Channel %d"%i) for i in range(1,25)])
RJ = dict([(24+i,"RJ45:%d"%i) for i in range(1,5)])
input_sources = {0:'RF IN'}; input_sources.update(channels); input_sources.update(RJ)
clock_sources = {}; clock_sources.update(input_sources); clock_sources.update({29:'int. 350 MHz'})
sync_inton_sources = {0:'int. 10 Hz'}; sync_inton_sources.update(channels)
from timing_sequence import timing_sequencer
parameters = [
[("RF clock in", timing_sequencer, "clk_src", repr(clock_sources)),{}],
[("RF clock in frequency", timing_sequencer, "clock_period", "frequency.6"),{"choices": [1/351933980.,1/350e6,1/80e6]}],
[("Clock manager", timing_sequencer, "clk_on", "Bypassed/Enabled"),{}],
[("Clock multiplier", timing_sequencer, "clock_multiplier", "integer"),{"choices": range(1,33)}],
[("Clock divider", timing_sequencer, "clock_divider", "integer"),{"choices": range(1,33)}],
[("Clock DFS frequency mode", timing_sequencer, "clk_dfs_mode", "Low freq./High freq."),{}],
[("Clock DLL frequency mode", timing_sequencer, "clk_dll_mode", "Low freq./High freq."),{}],
[("Clock multiplier status", timing_sequencer, "clk_locked", "Fault/Phase-locked"),{"read_only": True}],
[("Internal clock frequency", timing_sequencer, "bct", "frequency.6"),{"choices": [1/351933980.,1/350000000.]}],
[("SB clock in", timing_sequencer, "sbclk_src", repr(input_sources)),{}],
[("SB clock frequency", timing_sequencer, "P0t", "frequency.6"),{"choices": [1/(351933980./1296),1/120.]}],
[("Clock shift step size", timing_sequencer, "clk_shift_stepsize","time.6"),{"choices": [8.594e-12,8.907e-12]}],
[("1-kHz clock divider of RF/4", timing_sequencer, "clk_88Hz_div_1kHz","integer"),{"choices": [1296/4*275,91500,83333]}],
[("1-kHz clock frequency", timing_sequencer, "hsct", "frequency.4"),{"choices": [1/(351933980./1296/275),1/960.]}],
[("1-kHz clock phased by SB clock", timing_sequencer, "p0_phase_1kHz", "Off/On"),{}],
[("1-kHz clock divider of SB clock", timing_sequencer, "p0_div_1kHz", "integer"),{"choices": [275,1]}],
[("Heatload chopper encoder in", timing_sequencer, "hlc_src", repr(input_sources)),{}],
[("Heatload chopper slots count", timing_sequencer, "hlc_nslots", "integer"),{"choices": [12,4,1]}],
[("X-ray base frequency divider of 1-kHz clock",timing_sequencer,"hlc_div", "integer"),{"choices": [12,4,1]}],
[("X-ray base frequency", timing_sequencer, "hlct", "frequency.4"),{"choices": [1/(351933980./1296/275),1/(351933980./1296/275/4),1/(351933980./1296/275/12),1/120.]}],
[("Ns laser divider of 1-kHz clock", timing_sequencer, "nsl_div", "integer"),{"choices": [96,48]}],
[("Ns laser frequency", timing_sequencer, "nslt", "frequency.4"),{"choices": [1/(351933980./1296/275/12/8),1/(351933980./1296/275/12/4)]}],
[("Ps oscillator clock auto-lock", timing_sequencer, "clk_shift_auto_reset","Off/On"),{}],
]
standard_view = [
"RF clock in",
"RF clock in frequency"
"SB clock in",
"Clock manager",
"Clock multiplier",
"Clock divider",
"Clock DFS frequency mode",
"Clock DLL frequency mode",
"Clock multiplier status",
"Internal clock frequency",
]
def __init__(self,parent=None,update=lambda: None):
from Panel import PropertyPanel
BasePanel.__init__(self,parent=parent,
name=self.name,
title=self.title,
icon=self.icon,
component=PropertyPanel,
parameters=self.parameters,
standard_view=self.standard_view,
label_width=250,
refresh=True,
live=True,
)
if __name__ == '__main__':
from pdb import pm # for debugging
from redirect import redirect
redirect("Timing_Clock_Configuration_Panel")
import wx
app = wx.App(redirect=False)
panel = Timing_Clock_Configuration_Panel()
app.MainLoop()
<file_sep>filename = '//mx340hs/data/anfinrud_1710/Archive/test.txt'<file_sep>VAL.filename = '//mx340hs/data/anfinrud_1906/Archive/NIH.TEMP.VAL.txt'
RBV.filename = '/net/mx340hs/data/anfinrud_1906/Archive/NIH.TEMP.RBV.txt'
I.filename = '//mx340hs/data/anfinrud_1906/Archive/NIH.TEMP.I.txt'
P.filename = '//mx340hs/data/anfinrud_1906/Archive/NIH.TEMP.P.txt'
i.filename = '/net/femto/C/All Projects/APS/Experiments/2019.05/Test/Archive/NIH.TEMP.i.txt'<file_sep>"""
Persistent property of WX GUI applications that are specific for each computer,
not global line "persistent_property"
Example:
A window that remembers its size.
wx.app = wx.App(redirect=False)
class Window(wx.Frame):
size = setting("size",(400,250))
def __init__(self):
wx.Frame.__init__(self,parent=None,size=self.size)
self.Bind(wx.EVT_SIZE,self.OnResize)
self.Layout()
self.Show()
def OnResize(self,event):
event.Skip()
self.size = tuple(self.Size)
win = Window()
wx.app.MainLoop()
Author: <NAME>
Date created: 2017-11-20
Date last modified: 2018-12-04
"""
__version__ = "1.1" # name: accepting "TimingPanel.refresh_period"
import wx
from logging import debug,info,warn,error
def setting(name,default_value=0.0):
"""A presistent property of a class"""
def class_name(self):
if "." in name: class_name = name.split(".")[0]
else: class_name = getattr(self,"name",self.__class__.__name__)
return class_name
def my_name():
if "." in name: my_name = name.split(".")[1]
else: my_name = name
return my_name
def get(self):
from time import time
if not hasattr(self,"config") or self.config.last_read < time()-1:
self.config = wx.Config(class_name(self))
self.config.last_read = time()
value = self.config.Read(my_name())
dtype = type(default_value)
from numpy import nan,inf # for eval
try: value = dtype(eval(value))
except: value = default_value
return value
def set(self,value):
debug("%s.%s = %r" % (class_name(self),my_name(),value))
from time import time
if not hasattr(self,"config"):
self.config = wx.Config(class_name(self))
self.config.last_read = time()
self.config.Write(my_name(),repr(value))
self.config.Flush()
return property(get,set)
if __name__ == "__main__":
from pdb import pm # for debugging
import logging # for debugging
logging.basicConfig(
level=logging.DEBUG,
format="%(asctime)s %(levelname)s: %(message)s",
)
import wx
app = wx.App(redirect=False)
##config = wx.Config("TimingPanel")
class Timing_Setup_Panel(object):
refresh_period = setting("TimingPanel.refresh_period",1.0)
TimingPanel = Timing_Setup_Panel()
self = TimingPanel # for debugging
##print('config.Read("refresh_period")')
##print('config.Write("refresh_period","1.0"); config.Flush()')
##print('config.Write("refresh_period","2.0"); config.Flush()')
print('TimingPanel.refresh_period')
print('TimingPanel.refresh_period = 1.0')
print('TimingPanel.refresh_period = 2.0')
<file_sep>level = u'DEBUG'<file_sep>prefix = '14IDB:m151'
description = 'Alio Phi'
target = -29.999821271195714
EPICS_enabled = True<file_sep>from syringe_pump_new import *
from sim_motor import sim_motor
P1,P2 = sim_motor("sim_syringe_pump"),sim_motor("sim_syringe_pump2")
PC = SyringePumpCombined("syringe_pump_combined",P1,P2)
self = PC # for debugging
print('PC.dV = 0; PC.V = 10')
print('P1.value = 5; P2.value=15')
print('P1.value = 50; P2.value=50')
print('(P1.value,P2.value),(PC.V_min,PC.V,PC.V_max)')
print('(P1.value,P2.value),(PC.dV_min,PC.dV,PC.dV_max)')
<file_sep>title = 'Scan Configuration'
motor_names = ['collect.scan_points', 'collect.scan_return', 'collect.scan_relative', 'collect.scan_motor_name']
widths = [200, 55, 55, 100]
names = ['points', 'return', 'relative', 'motors']
motor_labels = ['list of values', 'return', 'relative', 'motor']
line0.description = 'Laue Crystallography'
line0.collect.scan_points = 'arange(0,180,5)'
line0.collect.scan_return = '0'
line0.collect.scan_relative = '0'
line0.collect.scan_motor = 'Phi'
description_width = 200
line1.description = 'NIH:Channel-Cut-Scan'
line1.collect.scan_points = 'arange(8,14,0.01)'
line1.collect.scan_return = 1.0
line1.collect.scan_relative = 0
line1.collect.scan_motor = 'Energy'
line0.updated = '23 Oct 4:02'
line1.updated = '2019-01-29 19:28:50'
command_row = 2
line0.collect.scan_motor_string = 'Phi'
line1.collect.scan_motor_string = 'Energy'
line1.collect.scan_motor_name = 'Energy'
line0.collect.scan_motor_name = 'Phi'
formats = ['%s', '%d', '%d', '%s']
nrows = 7
line2.description = 'NIH:Overlap_scan_Z'
line2.collect.scan_return = 1.0
line2.collect.scan_relative = 1.0
command_rows = []
multiple_selections = False
line2.updated = '03 Nov 15:42'
line2.collect.scan_points = 'arange(-0.6,0.6,0.05)'
line2.collect.scan_motor_name = 'LaserZ'
line3.description = 'NIH:Overlap_scan_X'
line3.collect.scan_points = 'arange(-0.2,0.2,0.02)'
line3.updated = '03 Nov 15:44'
line3.collect.scan_return = 1.0
line3.collect.scan_relative = 1.0
line3.collect.scan_motor_name = 'LaserX'
row_height = 23
line4.description = 'NIH:Slit-Scan-Z'
line4.collect.scan_points = 'arange(-0.4,0.4,0.02)'
line4.collect.scan_return = 1.0
line4.collect.scan_relative = 1.0
line4.collect.scan_motor_name = 'GonZ'
line4.updated = '2019-01-28 19:39:25'
line5.description = 'NIH:Slit-Scan-Y'
line5.collect.scan_points = 'arange(-2,2,0.05)'
line5.updated = '2019-01-28 22:06:06'
line5.collect.scan_return = 1.0
line5.collect.scan_relative = 1.0
line5.collect.scan_motor_name = 'GonY'
line6.collect.scan_points = 'arange(11.9,12.0,0.002)'
line6.updated = '2019-03-19 17:09:57'
line6.collect.scan_return = 1
line6.collect.scan_relative = 0
line6.collect.scan_motor_name = 'Energy'
line6.description = 'NIH:Channel-Cut-Scan Calib.'<file_sep>PHI.tweak_value = 180.0
PHI.tweak_values = [3600.0, 1800.0, 720.0, 360.0, 180.0, 90.0, 60.0, 30.0, 10.0, 5.0, 1.0]
PumpA+B+.tweak_value = 1.0
PumpA+B+.tweak_values = [1.0, 5.0, 10.0, 45.0, 90.0]
PumpA-B+.tweak_value = 15.0
PumpA-B+.tweak_values = [1.0, 5.0, 10.0, 15.0]
PumpA.tweak_value = 1.0
PumpA.tweak_values = [1.0, 10.0, 50.0, 200.0, 1000.0]
PumpB.tweak_value = 50.0
PumpB.tweak_values = [1.8, 15.0, 45.0, 90.0]
Sample Phi.tweak_value = 90.0
Sample Phi.tweak_values = [1.0, 10.0, 15.0, 30.0, 45.0, 60.0, 90.0, 360.0]
Sample X.tweak_value = 0.01
Sample X.tweak_values = [10.0, 1.0, 0.1, 0.01]
Sample Y.tweak_value = 1.0
Sample Y.tweak_values = [10.0, 1.0, 0.1, 0.01, 0.001]
Sample Z.tweak_value = 0.01
Sample Z.tweak_values = [20.0, 1.0, 0.1, 0.01]
X.tweak_value = 0.3
Y.tweak_value = 0.3
Z.tweak_value = 1.0
Z.tweak_values = [0.1, 0.5, 1.0]<file_sep>#!/usr/bin/env python
"""High-speed diffractometer.
<NAME>, 31 Oct 2013 - 2 Jul 2014"""
__version__ = "1.1"
import wx
from MotorPanel import MotorWindow
# Needed to initialize WX library
if not "app" in globals(): app = wx.App(redirect=False)
from peristaltic_pump import PumpA,PumpB,peristaltic_pump
window = MotorWindow([PumpA,PumpB,peristaltic_pump.V,peristaltic_pump.dV],
title="Peristaltic Pump")
app.MainLoop()
<file_sep>motor_names = ['Phi', 'GonX', 'GonY', 'GonZ']
motor_labels = ['Phi', 'GonX', 'GonY', 'GonZ']
formats = ['%+6.3f', '%+6.3f', '%+6.3f', '%+6.3f']
nrows = 9
line0.description = 'Alignment Jig 1 (C fiber)'
line0.updated = '2019-05-29 18:50:35'
line0.GonX = -0.09406250000000001
line0.GonY = 0.49203125000000003
line0.GonZ = 0.51015625
line0.Phi = -29.999999910677303
line1.description = 'Ceramic Slit (0.3x1.5)'
line1.updated = '2019-05-30 11:49:41'
line1.GonX = -1.53421875
line1.GonY = 0.93390625
line1.GonZ = -5.10796875
line1.Phi = 90.00000003572907
line2.description = 'MSM Photoconductor'
line2.updated = '2019-03-18 16:07:19'
line2.GonX = 0.351
line2.GonY = 0.501
line2.GonZ = -1.953
line2.Phi = 45.00000004466135
line3.description = 'Fiber Laser'
line3.updated = '2019-03-18 16:07:24'
line3.GonX = 0.101
line3.GonY = 0.557
line3.GonZ = -1.741
line3.Phi = 45.00000004466135
line4.description = 'Alignment Jig 1 (Phosphor)'
line4.updated = '2019-05-29 18:57:55'
line4.GonX = 0.63
line4.GonY = 0.4109375
line4.GonZ = 3.98203125
line4.Phi = -14.999999946406376
line5.description = 'Alignment Jig 1 (laser)'
line5.updated = '2019-05-28 19:47:26'
line5.GonX = -3.18390625
line5.GonY = -0.5890625
line5.GonZ = -3.4679687500000003
line5.Phi = -104.99999985708368
line6.description = 'Retract'
line6.updated = '2019-03-18 16:07:44'
line6.GonX = 0.611
line6.GonY = 0.411
line6.GonZ = -47.568
line6.Phi = -14.999999919609564
line7.description = 'BioCARS Phosphor'
line7.updated = '2019-03-18 16:07:50'
line7.GonX = 0.336
line7.GonY = 0.765
line7.GonZ = -5.515
line7.Phi = -14.999999919609564
serial = 1
title = 'Alio Diffractometer Saved Positions'
show_in_list = True
command_row = 5
description_width = 200
tolerance = [0.001, 0.001, 0.001, 0.001]
row_height = 21
command_rows = [5]
line8.Phi = 7.145814606701606e-08
line8.updated = '2019-05-30 12:56:36'
line8.GonX = 0.78296875
line8.GonY = 0.1609375
line8.GonZ = -1.71796875
line8.description = 'Channel-cut mono'<file_sep>"""
Load an image and convert it into a numpy array for processing.
Author: <NAME>
Date created: 4 Sep 2013
Date last modified: Nov 1, 2017
"""
__version__ = "1.9.6" # conditional debug
DEBUG = False
from logging import debug,warn,info,error
import numpy
class numimage(numpy.ndarray):
"""An image represented as a 2D image numpy array."""
from numpy import nan
# "numimage" is a subclass of "recarray".
# Because "recarray" uses a __new__ rather than an __init__ constructor,
# __new__ rather than __init__ needs to be overridden.
def __new__(subclass,arg=None,filename="",dtype=numpy.float32,shape=(0,0),
format="",array=None,pixelsize=nan):
"""filename: TIFF,PNG,JPEG or GIF image."""
##print "numimage.__new__(%r,%r)" % (subclass,filename)
from numpy import zeros,ndarray,nan
import numpy
if isinstance(arg,basestring): filename = arg
elif isinstance(arg,ndarray): array = arg
elif isinstance(arg,tuple) and len(arg) == 2: shape = arg
else: raise(RuntimeError,"%s: expecting str,array or (w,h)" % type(arg))
info = {}
self = None
if filename:
from normpath import normpath
filename = normpath(filename)
# A MAR CCD or Rayonix image is a TIFF image with NxN pixels,
# depth 16 bit and a fixed-size 4096-byte TIFF header.
# N = Nmax/bin_factor
# Nmax = 7680 for MX340HS
# Nmax = 4096 for MAR CCD
image_sizes = [3840,1920,960,480,2048,1024,512] # pixels
headersize = 4096 # bytes
TIFF_header_size = 1024
from os.path import getsize
filesize = getsize(filename)
for image_size in image_sizes:
image_nbytes = 2*image_size**2
if filesize == headersize+image_nbytes:
format = "RX"
if DEBUG: debug("using memmap")
from numpy import memmap,uint16,int32
self = memmap(filename,uint16,'r',headersize,(image_size,image_size),'F')
# Read TIFF header.
from struct import pack,unpack
header = file(filename).read(headersize)
offset, = unpack("I",header[4:8])
ntags, = unpack("h",header[offset:offset+2])
offset = offset+2; size = 12
class tag():
def __init__(self,type,dtype,length,data):
self.type,self.dtype,self.length,self.data = type,dtype,length,data
def __repr__(self):
return "%r,%r,%r,%r" % (self.type,self.dtype,self.length,self.data)
tags = {}
for i in range(0,ntags):
data = header[offset+i*size:offset+(i+1)*size]
type,dtype,length,data = unpack("<HHII",data)
tags[type] = tag(type,dtype,length,data)
if 283 in tags: # x resolution, type rational, data = pointer
offset = tags[283].data
num,den = unpack("II",header[offset:offset+8])
res = float(num)/den # in dpi
if DEBUG: debug("TIFF: 283: resolution num/den %r/%r=%g" % (num,den,res))
unit = nan
if 296 in tags: # resolution unit, code 2 = inch, 3 = cm
code = tags[296].data
if code == 2: unit = 25.4 # inch
elif code == 3: unit = 10 # cm
if DEBUG: debug("TIFF: 296: resolution unit %r = %r mm" % (code,unit))
pixelsize = unit/res
if DEBUG: debug("TIFF: pixelsize (%r mm)/%g = %.6f mm" % (unit,res,pixelsize))
# Rayonix High Speed Detector Manual v. 0.3, <NAME>, <NAME>
# Chapter 8: Image Format (marccd)
# Rayonix_HS_detector_manual-0.3a.pdf
start = TIFF_header_size+193*4; end = start+4
if DEBUG: debug("RX: pixelsize [nm]: header[%r:%r] = %r" % (start,end,header[start:end]))
frame_header = memmap(filename,int32,'r',TIFF_header_size,
(headersize-TIFF_header_size),'F')
pixelsize_nm = frame_header[193]
pixelsize = pixelsize_nm*1e-9/1e-3 # convert from nm to mm
if DEBUG: debug("RX: int 193: pixelsize = %r nm = %.6f mm" % (pixelsize_nm,pixelsize))
if self is None:
if filename.upper().endswith(".EDF"):
header = file(filename).read(1024)
headersize = header.find("}\n")+2
header = header[0:headersize]
lines = header.split("\n")
for line in lines:
line = line.strip(" ;")
if line.startswith("Dim_1 = "): w = int(line.replace("Dim_1 = ",""))
if line.startswith("Dim_2 = "): h = int(line.replace("Dim_2 = ",""))
from numpy import memmap,uint16,int32
self = memmap(filename,uint16,'r',headersize,(w,h),'F')
format = "EDF"
else:
from PIL import Image
from numpy import uint8,uint16,uint32,float32
PIL_image = Image.open(filename)
mode = PIL_image.mode
##PIL_image = PIL_image.convert("I")
if mode == "1": self = numpy.array(PIL_image,bool).T
elif mode == "I;8": self = numpy.array(PIL_image,uint8).T
elif mode == "I;16": self = numpy.array(PIL_image,uint16).T
elif mode == "I;32": self = numpy.array(PIL_image,uint32).T
elif mode == "F;32": self = numpy.array(PIL_image,float32).T
else:
warn("Unknown data type %s" % mode)
format = PIL_image.format
info = PIL_image.info
if "dpi" in info: pixelsize = 25.4/info["dpi"][0] # convert from DPI to mm
elif array is not None: self = array
else: self = zeros(shape,dtype)
self = self.view(subclass)
self.filename = filename
self.format = format
self.info = info
self.pixelsize = pixelsize
return self
def __array_finalize__(self,x):
"""Called after an oject has been copied.
Passes non-array attributes from the original to the new
object."""
from numpy import nan
self.filename = getattr(x,"filename","")
self.format = getattr(x,"format","")
self.info = getattr(x,"info",{})
self.pixelsize = getattr(x,"pixelsize",nan)
def get_width(self): return self.shape[0]
width = property(get_width)
def get_height(self): return self.shape[1]
height = property(get_height)
def save(self,filename=None,format=""):
from numpy import array,uint16,uint32,uint8,rint,clip,nan_to_num,nanmax,isnan
from PIL import Image
from os.path import splitext,dirname,exists
from os import makedirs
if filename != None: self.filename = filename
dir = dirname(self.filename)
if dir:
try: makedirs(dir)
except OSError: pass
if format == "": format = self.format
format = format.upper()
if format == "":
format = splitext(self.filename)[-1].strip(".").upper()
if format == "TIF": format = "TIFF"
if format == "": format = self.format
if format in ("TIFF","TIF"):
if nanmax(self) > 255:
data_16bit = array(clip(nan_to_num(rint(self)),0,65535),uint16)
PIL_image = Image.fromarray(data_16bit.T,"I;16")
elif nanmax(self) > 1:
data_8bit = array(clip(nan_to_num(rint(self)),0,255),uint8)
PIL_image = Image.fromarray(data_8bit.T,"L")
else:
# When converting 8-bit to 1-bit, the threshold is 128.
data_8bit = array(clip(nan_to_num(rint(self)),0,1)*255,uint8)
PIL_image = Image.fromarray(data_8bit.T,"L").convert("1")
if not isnan(self.pixelsize):
dpi = 25.4/self.pixelsize
PIL_image.info["dpi"] = (dpi,dpi)
# PIL only generates uncompressed TIFF image. There are no options.
PIL_image.save(self.filename,format)
elif format in ("MCCD","RX","RAYONIX"):
# Rayonix images have a 4096-byte TIFF-compatible header,
# with a custom non-standard tag containing diffractometer
# information (phi angle, oscillation range, detector distance...).
# The program "ADXV" reads only impages with Rayonix header,
# not plain TIFF images.
from rayonix_image_header import header # for size 1920x1920
# Update header for current image size:
# offset 18: width (4-byte little-endian integer)
# offset 30: height (4-byte integer)
# offset 102: rows per strip (=height) (4-byte integer)
# offset 1104: width (4-byte integer)
# offset 1108: height (4-byte integer)
# offset 1116: strip byte count (4-byte integer)
w,h = self.shape
from struct import pack
width,height = pack("<I",w),pack("<I",h)
rows_per_strip = height
strip_byte_count = pack("<I",w*2)
# Convert pixel size from mm to nm.
pixelsize_nm = toint(rint(self.pixelsize*1e-3/1e-9))
##if DEBUG: debug("pixelsize [nm] = %r" % pixelsize_nm)
pixelsize = pack("<I",pixelsize_nm)
##if DEBUG: debug("pixelsize [nm] = %r" % pixelsize)
from time import time
t = time()
from datetime import datetime
timestamp = datetime.fromtimestamp(t).strftime("%m%d%H%M%Y.%S %f")\
.replace(" ","\0").ljust(32,"\0")
acquire_timestamp = header_timestamp = save_timestamp = timestamp
header = \
header[ 0: 18]+width+\
header[ 22: 30]+height+\
header[ 34: 102]+rows_per_strip+\
header[ 106:1104]+width+height+\
header[1112:1116]+strip_byte_count+\
header[1120:1796]+pixelsize+\
header[1800:2048+320]+acquire_timestamp+\
header_timestamp+\
save_timestamp+\
header[2048+416:]
# Convert image to 16-bit depth
data_16bit = array(clip(nan_to_num(rint(self)),0,65535),uint16)
image_data = header + data_16bit.tostring()
file(self.filename,"wb").write(image_data)
else: # e.g. PNG file format
if nanmax(self) > 255:
# PIL's PNG driver does not support mode I;16 but I (32-bit)
data_32bit = array(clip(nan_to_num(rint(self)),0,2**32-1),uint32)
PIL_image = Image.fromarray(data_32bit.T,"I")
elif nanmax(self) > 1:
data_8bit = array(clip(nan_to_num(rint(self)),0,255),uint8)
PIL_image = Image.fromarray(data_8bit.T,"L")
else:
# When converting 8-bit to 1-bit, the theshold is 128.
data_8bit = array(clip(nan_to_num(rint(self)),0,1)*255,uint8)
PIL_image = Image.fromarray(data_8bit.T,"L").convert("1")
# Optimize = True: the PNG output driver will try dfferent
# output filters to achive the optimal compression.
PIL_image.save(self.filename,format,optimize=True)
self.format = format
write = save
def toint(x):
"""Convert x to an integer value without throwing an expection"""
try: return int(x)
except: return 0
if __name__ == "__main__": # for testing
from numpy import uint16
from marccd_image import timestamp_mccd
from time_string import date_time
##import logging; logging.basicConfig(level=logging.DEBUG)
filename = "/tmp/test.rx"
size = 1920; pixelsize = 0.08
self = numimage((size,size),dtype=uint16,pixelsize=pixelsize)
print('self.save(filename)')
print('self = numimage(filename)')
print('date_time(timestamp_mccd(filename))')
<file_sep>"""
Author: <NAME>
Date created: 2017-10-17
Date last modified: 2018-03-11
"""
__version__ = "1.0.3" # timeout
from logging import debug,info,warn,error
def action_property(command,stop="",locals=None,globals=None,timeout=30):
"""
command: executable string
stop: executable string
locals: context for execution
globals: context for execution
timeout: seconds
"""
from DB import db,dbset
from thread import start_new_thread
from time import time
def running(self):
class_name = getattr(self,"name",self.__class__.__name__)
running = db("%s.%s.running" % (class_name,command),False)
timeout_start = db("%s.%s.timeout_start" % (class_name,command),0.0)
timed_out = time() - timeout_start > timeout
return running and not timed_out
def set_running(self,value):
class_name = getattr(self,"name",self.__class__.__name__)
dbset("%s.%s.running" % (class_name,command),value)
dbset("%s.%s.timeout_start" % (class_name,command),time())
def run(self):
info("action: starting %r..." % command)
try: exec command in locals,globals
except Exception,msg: error("action: %r: %s" % (command,msg))
info("action: finished %r" % command)
set_running(self,False)
def cancel(self):
info("action: cancelling %r..." % stop)
self.cancelled = True
try: exec stop in locals,globals
except Exception,msg: error("action: %r: %s" % (stop,msg))
info("action: finished %r" % stop)
def get_active(self):
"""Is procedure running?"""
return running(self)
def set_active(self,value):
if value:
set_running(self,True)
start_new_thread(run,(self,))
else:
set_running(self,False)
self.cancelled = True
start_new_thread(cancel,(self,))
active = property(get_active,set_active)
return active
<file_sep>RBV.filename = '//mx340hs/data/anfinrud_1903/Archive/NIH.CHILLER.RBV.txt'<file_sep>#!/usr/bin/env python
# <NAME>, 16 Nov 2014
from inspect import getfile
from os.path import dirname
def f(): pass
dir=dirname(getfile(f))
execfile(dir+"/LaserAttenuatorLaserXrayHutch.py")
<file_sep>"""Examine waveform data for completeness.
<NAME>, Jun 25, 2016 - Jun 30, 2016
"""
from os.path import exists
from os import listdir
from numpy import concatenate,array,sort,diff,round,unique
from time_string import date_time
__version__ = "1.1"
def trigger_times(pathname):
"""Pathname: directory where the trace files are stored"""
from lecroy_scope_waveform import trigger_times
t = concatenate([trigger_times(f) for f in files(pathname)])
return t
def trigger_counts(pathname):
"""Pathname: directory where the trace files are stored"""
from lecroy_scope_waveform import trigger_times
from numpy import array
t = array([len(trigger_times(f)) for f in files(pathname)])
return t
def sizes(pathname):
"""Pathname: directory where the trace files are stored"""
from os.path import getsize
from numpy import array
sizes = array([getsize(f) for f in files(pathname)])
return sizes
def file_timestamps(pathname):
"""Pathname: directory where the trace files are stored"""
from os.path import getmtime
from numpy import array
timestamps = array([getmtime(f) for f in files(pathname)])
return timestamps
def files(pathname):
"""List of file in a dirctory, sorted by timestamp."""
from os.path import getsize,getmtime
from numpy import array,argsort
files = array([pathname+"/"+f for f in listdir(pathname)])
order = argsort(array([getmtime(f) for f in files]))
files = files[order]
return files
if __name__ == "__main__":
from pdb import pm # for debugging
from lecroy_scope_waveform import read_waveform
from numpy import *
def frac(x): return x-trunc(x)
pathname = "//Femto/C/All Projects/APS/Experiments/2016.06/Temp/WAXS/AlCl3/AlCl3-2"
pathname = "/net/mx340hs/data/anfinrud_1606/Data/WAXS/Villin/Villin-static-2"
pathname = "/net/mx340hs/data/anfinrud_1606/Data/WAXS/Villin/Villin-Temp-Ramp1"
pathname = "/net/mx340hs/data/anfinrud_1606/Data/WAXS/Villin-Gdn/Villin-Gdn-Buffer-2"
pathname = "/net/mx340hs/data/anfinrud_1606/Data/WAXS/Villin/Villin-1"
print('s = sizes("%s/xray_traces")' % pathname)
print('f = files("%s/xray_traces")' % pathname)
print('N = trigger_counts("%s/xray_traces")' % pathname)
print('t = trigger_times("%s/xray_traces")' % pathname)
print('t = file_timestamps("%s/xray_traces")' % pathname)
print('date_time(t[0])')
print('dt = round(diff(t),5)')
print('i = (where(dt > 0.075)[0]+1)/41.0')
print('average(frac(i) != 0)')
<file_sep>#!/bin/env python
"""Setup:
source ~schotte/Software/Test/setup_env.sh
"""
from xppdaq import xppdaq
##from beamline import xppdaq
run_template = "exp=xppj1216:run=%d:smd:dir=/reg/d/ffb/xpp/xppj1216/xtc:live"
Nevents = 20
xppdaq.configure(Nevents)
xppdaq.begin(Nevents)
run_number = xppdaq.runnumber()
xppdaq.wait()
xppdaq.disconnect()
run = run_template % run_number
print("run: %s" % run)
<file_sep>"""
Support module for optical freeze detector
Runs code to retract the sample from the cooling stream and operate the pump
at high speed as an AeroBasic program "Freeze_Intervention.ab".
Authors: <NAME>, <NAME>
Date created: 8 Mar 2018
Date last modified: 18 May 2018
"""
__version__ = "1.0.1" # Check if already running
class Freeze_Intervention(object):
program_filename = "Freeze_Intervention.ab"
def get_active(self):
from Ensemble import ensemble
return ensemble.auxiliary_task_filename == self.program_filename
def set_active(self,value):
from Ensemble import ensemble
if value != self.active:
if value: ensemble.auxiliary_task_filename = self.program_filename
else: ensemble.auxiliary_task_filename = ""
active = property(get_active,set_active)
def get_enabled(self):
from CA import caget
return tobool(caget('NIH:SAMPLE_FROZEN_OPT_RGB:ENABLED'))
def set_enabled(self,value):
from CA import caput
caput('NIH:SAMPLE_FROZEN_OPT_RGB:ENABLED',value)
enabled = property(get_enabled,set_enabled)
freeze_intervention = Freeze_Intervention()
def tobool(value):
"""Convert value to boolean or Not a Number if not possible"""
from numpy import nan
if value is None: value = nan
else: value = bool(value)
return value
if __name__ == "__main__":
self = freeze_intervention # for debugging
from Ensemble import ensemble # for debugging
from time import sleep
print("freeze_intervention.active")
print("freeze_intervention.active = True")
print("freeze_intervention.enabled")
print("freeze_intervention.enabled = True")
print("freeze_intervention.enabled = False")
<file_sep>
from id14 import *
from time import sleep,strftime,time
from os import getcwd,remove,makedirs,listdir,chmod
# Online diagnostics:
# Setup required:
# Agilent 6-GHz oscilloscope in X-ray hutch:
# C2 = photodiode, C3 = MCP-PMT, C4 = trigger
# The first measurement needs to be defined as Delta-Time(2,3) with
# rising edge on C2 and falling edge in C3.
# The timing skews of each channel need to be set such the measured
# time delay is 0 when the nominal time delay is zero.
# The second measurement needs defined as Area(3).
# msm delay will be measured as a time between rising edges of laser and
#
f = open("/data/pub/rob/test_timing.log",'w')
f.write("Scew: Timing error, sdev, samples, sampling error,MSM: Timing error, sdev, samples, sampling error\n")
actual_delay=id14b_scope.measurement(1)
msm_delay=id14b_scope.measurement(2)
n=1
actual_delay.time_range = 0.00000002
while n<100000000:
actual_delay.start()
start = time()
while time()-start < 10 :
sleep (0.1)
t = actual_delay.average
sdev = actual_delay.stdev
N = actual_delay.count
err = sdev/sqrt(N-1)
msmt = msm_delay.average
msmsdev = msm_delay.stdev
msmN = msm_delay.count
msmerr = msmsdev/sqrt(msmN-1)
f.write(str(t)+" "+str(sdev)+" "+str(N)+" "+ str(err)+" "+str(msmt)+" "+str(msmsdev)+" "+str(smsN)+" "+ str(msmerr)+"\n")
n=n+1
f.close
<file_sep>Size = (765, 704)
Position = (89, 138)
ScaleFactor = 2.0
ZoomLevel = 1.0
Orientation = 180
Mirror = 0
NominalPixelSize = 0.00465
filename = ''
ImageWindow.Center = (580.0, 512.0)
ImageWindow.ViewportCenter = (3.4549499999999997, 2.37615)
ImageWindow.crosshair_color = (255, 0, 255)
ImageWindow.boxsize = (0.1, 0.06)
ImageWindow.box_color = (128, 128, 255)
ImageWindow.show_box = False
ImageWindow.Scale = [(-0.1, -0.1), (-0.1, 0.1)]
ImageWindow.show_scale = False
ImageWindow.scale_color = (128, 128, 255)
ImageWindow.crosshair_size = (0.05, 0.05)
ImageWindow.show_crosshair = True
ImageWindow.show_profile = True
ImageWindow.show_FWHM = True
ImageWindow.show_center = False
ImageWindow.calculate_section = False
ImageWindow.profile_color = (255, 255, 128, 255)
ImageWindow.FWHM_color = (0, 255, 64)
ImageWindow.center_color = (0, 0, 255)
ImageWindow.ROI = [[-0.48824999999999996, -0.45802499999999996], [0.44175, 0.44639999999999996]]
ImageWindow.ROI_color = (255, 128, 255, 255)
ImageWindow.show_saturated_pixels = True
ImageWindow.mask_bad_pixels = False
ImageWindow.saturation_threshold = 233
ImageWindow.saturated_color = (83, 0, 255, 255)
ImageWindow.linearity_correction = False
ImageWindow.bad_pixel_threshold = 233
ImageWindow.bad_pixel_color = (30, 30, 30)
ImageWindow.show_grid = False
ImageWindow.grid_type = 'xy'
ImageWindow.grid_color = (0, 0, 255)
ImageWindow.grid_x_spacing = 1.0
ImageWindow.grid_x_offset = 0.0
ImageWindow.grid_y_spacing = 1.0
ImageWindow.grid_y_offset = 0.0
<file_sep>RBV.filename = '/net/mx340hs/data/anfinrud_1906/Archive/NIH.CHILLER.RBV.txt'
VAL.filename = '//mx340hs/data/anfinrud_1906/Archive/NIH.CHILLER.VAL.txt'
fault_code.filename = '//mx340hs/data/anfinrud_1906/Archive/NIH.CHILLER.fault_code.txt'<file_sep>#!/usr/bin/env python
"""Optical Scattering Server Panel
Authors: <NAME>
Date created: 2019-05-30
Date last modified: 2019-05-30
"""
from logging import debug,warn,info,error
from optical_scattering import optical_scattering
from Panel import BasePanel,PropertyPanel,ButtonPanel,TogglePanel,TweakPanel
import wx
__version__ = "0.0.0" #initial
class OpticalScatteringPanel(BasePanel):
name = "OpticalScatteringPanel"
title = "Optical Scattering Panel"
standard_view = [
"Scattering",
"box dim (mm)",
]
parameters = [
[[PropertyPanel,"Scattering",optical_scattering,"mean"],{"read_only":True}],
[[PropertyPanel,"box dim (mm)",optical_scattering,"region_size_xy"],{"choices":[[100,100],[50,50],[20,20],[10,10]]}],
]
def __init__(self,parent=None):
BasePanel.__init__(self,
parent=parent,
name=self.name,
title=self.title,
icon="Tool",
parameters=self.parameters,
standard_view=self.standard_view,
)
debug('Show debug')
if __name__ == '__main__':
from pdb import pm
#import logging
from tempfile import gettempdir
#from redirect import redirect
#import autoreload
#redirect('SampleFrozenPanelOpt',level="INFO")
#logfile = gettempdir()+"/SampleFrozenPanelOpt.log"
## logging.basicConfig(
## level=logging.INFO,
## format="%(asctime)s %(levelname)s: %(message)s",
## logfile=logfile,
## )
# Needed to initialize WX library
app = wx.App(redirect=False)
panel = OpticalScatteringPanel()
#sample_frozen_optical.is_running = True
#sample_frozen.running = True
app.MainLoop()
<file_sep>#!/bin/bash
# version 1.1
# Determine the Python module to load from the script pathname.
dir=`dirname "$0"`
# Look at run-time argument to determine which Python script to run.
if [ "$1" == "" ] ; then echo "usage: `basename $0` script.py" 2>&1; exit; fi
prog="$1"
if [ -e "$dir/setup_env.sh" ] ; then source "$dir/setup_env.sh" ; fi
python "$dir/$prog"
<file_sep>"""
Simple SOCKET server for testing\learning purposes
"""
import socket
from time import time,clock
from numpy import zeros
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
port = 2207
sock.bind(('',port))
sock.listen(5)
def run():
from thread import start_new_thread
start_new_thread(run_once,())
def run_once():
while True:
global client_lst
client_lst= []
client, addr = sock.accept()
print addr
try:
print(client_lst.index(addr))
except: pass
client_lst.append((time(),addr))
t1 = clock()
#print('Got connection from ' , adrr)
#x = raw_input('type response:')
data = client.recv(3044)
client.send(data)
<file_sep>from __future__ import with_statement
"""
Intermediate server for Agilent Infiniium oscilloscope.
Translate VXI-11.2 requests into simple TCP/IP transactions.
The program is intended to run on the Agilent oscilloscope PC
"id14b-scope" as auto-start program.
<NAME>, APS, 20-23 Oct 2009
"""
import SocketServer
from vxi_11 import vxi_11_connection,VXI_11_Error # also requires rpc.py
from thread import allocate_lock
__version__ = "1.1"
ip_address = "id14b-scope.cars.aps.anl.gov" # for instrument (or "localhost")
timeout = 0.5 # instrument reply timeout in seconds
port = 2000 # listen port number of this server script
# True: write complete transcript to log file, False: errors only
verbose_logging = False
def run_server():
# make a threaded server, listen/handle clients forever
server = ThreadingTCPServer(("",port),ClientHandler)
log("server started, listening on port "+str(port))
log("verbose logging: %r" % verbose_logging)
server.serve_forever()
class ThreadingTCPServer(SocketServer.ThreadingTCPServer):
# By default, the "ThreadingTCPServer" class binds to the sever port
# without the option SO_REUSEADDR. The consequence of this is that
# when the server terminates you have to let 60 seconds pass, for the
# socket to leave to "CLOSED_WAIT" state before it can be restarted,
# otherwise the next bind call would generate the error
# 'Address already in use'.
# Setting allow_reuse_address to True makes "ThreadingTCPServer" use to
# SO_REUSEADDR option when calling "bind".
allow_reuse_address = True
class ClientHandler(SocketServer.BaseRequestHandler):
def handle(self):
"Called when a client connects. 'self.request' is the client socket"
addr = "%s:%d" % self.client_address
log("%s: accepted connection" % addr)
input_queue = ""
while 1:
# Commands from a client are not necessarily received as one packet
# but each command is terminated by a newline character.
# If 'recv' returns an empty string it means client closed the
# connection.
while input_queue.find("\n") == -1:
try: received = self.request.recv(1024)
except: received = "" # in case of connection reset
if received: log("%s: received %r" % (addr,received))
if received == "":
log ("%s: client disconnected" % addr)
break
input_queue += received
if input_queue == "": break
if input_queue.find("\n") != -1:
end = input_queue.index("\n")
command = input_queue[0:end]
input_queue = input_queue[end+1:]
else: command = input_queue; input_queue = ""
command = command.rstrip("\r\n")
if command.endswith("?"):
log("%s: processing query %r" % (addr,command))
reply = query(command)
reply += "\n"
log ("%s: returning reply %r" % (addr,reply))
self.request.sendall(reply)
elif command != "":
log("%s: sending command %r" % (addr,command))
write(command)
log ("%s: closing connection" % addr)
self.request.close()
connection = None
lock = allocate_lock()
def query(command):
"""Send a command an return the reply received."""
with lock:
global connection
for attempt in range(1,3):
try:
if connection == None: connection = vxi_11_connection(
ip_address,timeout=int(timeout*1000))
err,bytes_sent = connection.write (command)
if err:
log_error("query %r attempt %d: write error %s" %
(command,attempt,VXI_11_Error(err)))
continue
err,reason,reply = connection.read()
if err:
log_error("query %r attempt %d: read error %s" %
(command,attempt,VXI_11_Error(err)))
continue
return reply.rstrip("\n")
except Exception,message:
log_error("query %r attempt %d failed: %s" %
(command,attempt,message))
connection = None
return ""
def write(command):
"""Send a command an returns the reply received"""
with lock:
global connection
for attempt in range(1,3):
try:
if connection == None: connection = vxi_11_connection(
ip_address,timeout=int(timeout*1000))
err,bytes_sent = connection.write (command)
if err:
log_error("write %r attempt %d: error %s" %
(command,attempt,VXI_11_Error(err)))
except Exception,message:
log_error("write %r, attempt %d, failed: %s" %
(command,attempt,message))
connection = None
return ""
def log(message):
"Append a message to the log file (/tmp/agilent_scope_server.log)"
from tempfile import gettempdir
from sys import stderr
if len(message) == 0 or message[-1] != "\n": message += "\n"
timestamped_message = timestamp()+": "+message
stderr.write(timestamped_message)
if verbose_logging:
logfile = gettempdir()+"/agilent_scope_server.log"
try: file(logfile,"a").write(timestamped_message)
except IOError: pass
def log_error(message):
"""Append a message to the error log file
/tmp/agilent_scope_server_error.log.
Also log the message the normal way.
"""
from tempfile import gettempdir
from sys import stderr
if len(message) == 0 or message[-1] != "\n": message += "\n"
if len(message) == 0 or message[-1] != "\n": message += "\n"
timestamped_message = timestamp()+": "+message
stderr.write(timestamped_message)
logfile = gettempdir()+"/agilent_scope_server_error.log"
try: file(logfile,"a").write(timestamped_message)
except IOError: pass
log(message)
def timestamp():
"""Current date and time as formatted ASCCI text, precise to 1 ms"""
from datetime import datetime
timestamp = str(datetime.now())
return timestamp[:-3] # omit microsconds
run_server()
<file_sep># to do:
# had 1 hang don't understand (maybe hit end of file?)
# test boundary cases
from psana import *
import zmq
import numpy as np
import time
context = zmq.Context()
server = context.socket(zmq.PAIR)
server.bind("tcp://*:12322")
class DataStream:
def __init__(self):
self.olddsstring = None
self.nevent = -1
self.src = Source('rayonix')
def image(self,runexp_string):
fields = runexp_string.split(':')
dsstring = ":".join(fields[:-1])
eventreq = int(fields[-1])
if dsstring != self.olddsstring or eventreq<=self.nevent:
start = time.time()
try:
self.ds = DataSource(dsstring)
except:
print '*** Failed to open datasource:',dsstring
return None
self.nevent=-1
self.olddsstring = dsstring
#det = Detector('rayonix',self.ds.env())
print 'opened new datasource in',time.time()-start,'seconds'
for evt in self.ds.events():
#raw = det.raw(evt)
raw = evt.get(Camera.FrameV1,self.src)
if raw is not None: self.nevent+=1
if eventreq==self.nevent: break
if eventreq != self.nevent:
print '*** Event',eventreq,'not found'
return None
#server.send_pyobj(raw)
print 'sending image',eventreq,self.nevent,evt.get(EventId).fiducials()
return raw.data16()
stream = DataStream()
while True:
print 'waiting for request'
runexp_string = server.recv_pyobj()
print 'Received request:',runexp_string
try:
server.send_pyobj(stream.image(runexp_string),zmq.NOBLOCK)
except:
# see http://stackoverflow.com/questions/21826357/zmq-send-with-noblock-raise-resource-temporarily-unavailable
print '*** zmq send failed. perhaps the zmq.NOBLOCK has raised eagain'
<file_sep>"""
Python interface to EPICS supported counters.
<NAME>, APS, 7 Nov 2007 - 18 Apr 2010
"""
__version__ = "1.1"
from CA import caget,caput
class counter(object):
"""EPICS-controlled motor
Using the following process variables:
14IDB:sclS1.CNT - set 1 to start couter, reads 0 is counting complete
14IDB:sclS1_cts1.D - Calc result (counts/s)
14IDB:sclS1.TP - programmed count time in seconds
14IDB:sclS1.S1 - actula count time 10-MHz clock cycles
14IDB:sclS1.S2-16 - actual count
14IDB:sclS1.NM2-16 - description
"""
def __init__(self,counter_name):
"ioc_name = EPICS IOC"
object.__init__(self)
self.ioc_name = counter_name.split(".")[0]
self.channel = counter_name.split(".")[1][1:]
self.unit = "cts/s"
def get_count(self): return caget(self.ioc_name+".S"+self.channel)
count = property(fget=get_count,doc="actual count")
def get_value(self): return self.count/self.count_time
value = property(fget=get_value,doc="counts/s")
def get_name(self): return caget(self.ioc_name+".NM"+self.channel)
name = property(fget=get_name,doc="description")
def start(self): caput(self.ioc_name+".CNT",1)
def stop(self): caput(self.ioc_name+".CNT",0)
def get_count_time(self): return caget(self.ioc_name+".S1")/1e7
def set_count_time(self,value): return caput(self.ioc_name+".TP",value)
count_time = property(fget=get_count_time,fset=set_count_time,doc="integration time in s")
if __name__ == "__main__":
# 14ID-B Joerger VSC16
IC_up = counter("14IDB:sclS1.S4")
IO_detector = counter("14IDB:sclS1.S7")
Downstream_counter = counter("14IDB:sclS1.S9")
<file_sep>#!/usr/bin/env python
"""Test cross platform compatibility of the "EditableControls" module
<NAME>, APS, 27 Sep 2014 - 27 Sep 2014
"""
__version__ = "1.0"
import wx
from EditableControls import TextCtrl,ComboBox
from logging import debug
class EditableControls_Test (wx.Frame):
def __init__(self):
wx.Frame.__init__(self,parent=None,title="Editable Controls Test")
panel = wx.Panel(self)
# Controls
choices = ["Hydrogen","Helium","Lithium","Beryllium"]
self.ComboBox = ComboBox(panel,choices=choices,
style=wx.TE_PROCESS_ENTER,name="Sample ComboBox")
self.TextCtrl = TextCtrl(panel,style=wx.TE_PROCESS_ENTER,
name="Sample TextCtrl")
# Callbacks
self.Bind (wx.EVT_TEXT_ENTER,self.OnComboBox,self.ComboBox)
self.Bind (wx.EVT_COMBOBOX,self.OnComboBox,self.ComboBox)
self.Bind (wx.EVT_TEXT_ENTER,self.OnTextCtrl,self.TextCtrl)
# Layout
layout = wx.GridBagSizer(1,1)
a = wx.ALIGN_CENTRE_VERTICAL
e = wx.EXPAND
layout.Add (wx.StaticText(panel,label="ComboBox:"),(0,0),flag=a)
layout.Add (self.ComboBox,(0,1),flag=a|e)
layout.Add (wx.StaticText(panel,label="TextCtrl:"),(1,0),flag=a)
layout.Add (self.TextCtrl,(1,1),flag=a|e)
# Leave a 5 pixel wide border.
box = wx.BoxSizer(wx.VERTICAL)
box.Add (layout,flag=wx.ALL,border=5)
panel.SetSizer(box)
panel.Fit()
self.Fit()
self.Show()
# Initialization
self.timer = wx.Timer(self)
self.Bind (wx.EVT_TIMER,self.refresh,self.timer)
self.timer.Start(1000,oneShot=True)
def refresh(self,event=None):
"""Update displayed values"""
from DB import dbget
self.ComboBox.Value = dbget("EditableControls_Test.ComboBox")
self.TextCtrl.Value = dbget("EditableControls_Test.TextCtrl")
self.timer.Start(1000,oneShot=True)
def OnComboBox(self,event):
"""ComboxBox was meodified..."""
debug("ComboBox: '%s'" % self.ComboBox.Value)
from DB import dbput
dbput("EditableControls_Test.ComboBox",self.ComboBox.Value)
def OnTextCtrl(self,event):
"""TextCtrl was modified..."""
debug("TextCtrl: '%s'" % self.TextCtrl.Value)
from DB import dbput
dbput("EditableControls_Test.TextCtrl",self.TextCtrl.Value)
if __name__ == '__main__':
from pdb import pm
import logging; logging.basicConfig(level=logging.DEBUG)
# Needed to initialize WX library
wx.app = wx.App(redirect=False)
panel = EditableControls_Test()
wx.app.MainLoop()
<file_sep>#!/usr/bin/env python
"""Control panel for serial Laue crystallography.
<NAME>, Jul 2, 2017 - Oct 28, 2017"""
__version__ = "1.1" # update
from logging import debug,info,warn,error
import wx
from Laue_crystallography import control # passed on in "globals()"
class LaueCrystallographyControl(wx.Frame):
"""Control panel for serial Laue crystallography"""
def __init__(self):
wx.Frame.__init__(self,parent=None,title="Laue Crystallography Control")
# Icon
from Icon import SetIcon
SetIcon(self,"Laue Crystallography Control")
self.panel = self.ControlPanel
self.Fit()
self.Show()
# Refresh
self.timer = wx.Timer(self)
self.Bind (wx.EVT_TIMER,self.OnTimer,self.timer)
self.timer.Start(5000,oneShot=True)
def OnTimer(self,event):
"""Perform periodic updates"""
try: self.update_controls()
except Exception,msg:
error("%s" % msg)
import traceback
traceback.print_exc()
self.timer.Start(5000,oneShot=True)
def update_controls(self):
from inspect import getfile
filename = getfile(self.__class__)
##debug("module: %s" % filename)
from os.path import getmtime
if self.timestamp == 0: self.timestamp = getmtime(filename)
if getmtime(filename) != self.timestamp:
self.timestamp = getmtime(filename)
import LaueCrystallographyControlPanel
reload(LaueCrystallographyControlPanel)
from LaueCrystallographyControlPanel import LaueCrystallographyControl
self.__class__ = LaueCrystallographyControl
panel = self.ControlPanel
self.panel.Destroy()
self.panel = panel
self.Fit()
timestamp = 0
@property
def ControlPanel(self):
# Controls and Layout
panel = wx.Panel(self)
from EditableControls import ComboBox,TextCtrl
from Controls import Control
from BeamProfile_window import BeamProfile
flag = wx.ALIGN_CENTRE_HORIZONTAL|wx.ALL
border = 2
l = wx.ALIGN_LEFT; r = wx.ALIGN_RIGHT; cv = wx.ALIGN_CENTER_VERTICAL
a = wx.ALL
layout = wx.BoxSizer(wx.HORIZONTAL)
left_panel = wx.BoxSizer(wx.VERTICAL)
group = wx.BoxSizer(wx.VERTICAL)
text = wx.StaticText(panel,label="X-ray Detector:")
group.Add (text,flag=flag,border=border)
control = Control(panel,type=wx.ToggleButton,
name="LaueCrystallographyControl.XRayDetectorInserted",
globals=globals(),
label="Retract/Insert",
size=(180,-1))
group.Add (control,flag=flag,border=border)
left_panel.Add (group,flag=flag,border=border)
group = wx.BoxSizer(wx.VERTICAL)
text = wx.StaticText(panel,label="Raster Scan Center:")
group.Add (text,flag=flag,border=border)
control = Control(panel,type=wx.Button,
name="LaueCrystallographyControl.GotoSaved",globals=globals(),
label="Go To Saved XYZ Position",
size=(180,-1))
group.Add (control,flag=flag,border=border)
control = Control(panel,type=wx.Button,
name="LaueCrystallographyControl.Save",globals=globals(),
label="Save Current XYZ Positions",size=(180,-1))
group.Add (control,flag=flag,border=border)
control = Control(panel,type=wx.ToggleButton,
name="LaueCrystallographyControl.Inserted",globals=globals(),
label="Retract/Insert",
size=(180,-1))
group.Add (control,flag=flag,border=border)
left_panel.Add (group,flag=flag,border=border)
group = wx.BoxSizer(wx.VERTICAL)
text = wx.StaticText(panel,label="Raster Scan Controls:")
group.Add (text,flag=flag,border=border)
subgroup = wx.GridBagSizer(1,1)
text = wx.StaticText(panel,label="Step Size [um]")
subgroup.Add (text,(0,0),flag=l|cv|a,border=border)
control = Control(panel,type=TextCtrl,
name="LaueCrystallographyControl.StepSize",globals=globals(),
size=(70,-1))
subgroup.Add (control,(0,1),flag=l|cv|a,border=border)
text = wx.StaticText(panel,label="Vertical Range [um]")
subgroup.Add (text,(1,0),flag=l|cv|a,border=border)
control = Control(panel,type=TextCtrl,
name="LaueCrystallographyControl.VerticalRange",globals=globals(),
size=(70,-1))
subgroup.Add (control,(1,1),flag=l|cv|a,border=border)
text = wx.StaticText(panel,label="Horizontal Range [um]")
subgroup.Add (text,(2,0),flag=l|cv|a,border=border)
control = Control(panel,type=TextCtrl,
name="LaueCrystallographyControl.HorizontalRange",globals=globals(),
size=(70,-1))
subgroup.Add (control,(2,1),flag=l|cv|a,border=border)
group.Add (subgroup,flag=flag,border=border)
left_panel.Add (group,flag=flag,border=border)
border = 4
control = Control(panel,type=wx.ToggleButton,
name="LaueCrystallographyControl.StartRasterScan",globals=globals(),
label="Start Raster Scan",size=(180,-1))
left_panel.Add (control,flag=flag,border=border)
group = wx.BoxSizer(wx.VERTICAL)
text = wx.StaticText(panel,label="Crystal Coordinates:")
group.Add (text,flag=flag,border=border)
control = Control(panel,type=TextCtrl,
name="LaueCrystallographyControl.CrystalCoordinates",globals=globals(),
size=(180,120),style=wx.TE_MULTILINE)
group.Add (control,flag=flag,border=border)
left_panel.Add (group,flag=flag,border=border)
layout.Add (left_panel,flag=flag,border=border)
middle_panel = wx.BoxSizer(wx.VERTICAL)
border = 5
group = wx.BoxSizer(wx.VERTICAL)
text = wx.StaticText(panel,label="Syringe Pump Operation:")
group.Add (text,flag=flag,border=border)
border = 0
control = Control(panel,type=wx.Button,
name="LaueCrystallographyControl.Initialize",globals=globals(),
label="Initialize",
size=(120,-1))
group.Add (control,flag=flag,border=border)
control = Control(panel,type=wx.ToggleButton,
name="LaueCrystallographyControl.Flow",globals=globals(),
label="Suspend/Resume",
size=(120,-1))
group.Add (control,flag=flag,border=border)
control = Control(panel,type=wx.ToggleButton,
name="LaueCrystallographyControl.Inject",globals=globals(),
label="Inject",
size=(120,-1))
group.Add (control,flag=flag,border=border)
middle_panel.Add (group,flag=flag,border=border)
border = 3
group = wx.BoxSizer(wx.VERTICAL)
text = wx.StaticText(panel,label="Mother Liquor Syringe (250 uL)")
group.Add (text,flag=flag,border=border)
text = wx.StaticText(panel,label="Volume Expended (uL):")
group.Add (text,flag=flag,border=border)
subgroup = wx.GridBagSizer(1,1)
control = Control(panel,type=TextCtrl,
name="LaueCrystallographyControl.MotherLiquorSyringeVolume",
globals=globals(),size=(70,-1))
subgroup.Add (control,(0,0),flag=l|cv|a,border=border)
control = Control(panel,type=wx.ToggleButton,
name="LaueCrystallographyControl.MotherLiquorSyringeRefill",
globals=globals(),label="Refill",size=(70,-1))
subgroup.Add (control,(0,1),flag=l|cv|a,border=border)
control = Control(panel,type=ComboBox,
name="LaueCrystallographyControl.MotherLiquorSyringeStepsize",
globals=globals(),size=(70,-1))
subgroup.Add (control,(1,0),flag=l|cv|a,border=border)
control = Control(panel,type=wx.ToggleButton,
name="LaueCrystallographyControl.MotherLiquorSyringeDispense",
globals=globals(),label="Dispense",size=(70,-1))
subgroup.Add (control,(1,1),flag=l|cv|a,border=border)
group.Add (subgroup,flag=flag,border=border)
middle_panel.Add (group,flag=flag,border=border)
group = wx.BoxSizer(wx.VERTICAL)
text = wx.StaticText(panel,label="Crystal Liquor Syringe (250 uL)")
group.Add (text,flag=flag,border=border)
text = wx.StaticText(panel,label="Volume Expended (uL):")
group.Add (text,flag=flag,border=border)
subgroup = wx.GridBagSizer(1,1)
control = Control(panel,type=TextCtrl,
name="LaueCrystallographyControl.CrystalLiquorSyringeVolume",
globals=globals(),size=(70,-1))
subgroup.Add (control,(0,0),flag=l|cv|a,border=border)
control = Control(panel,type=wx.ToggleButton,
name="LaueCrystallographyControl.CrystalLiquorSyringeRefill",
globals=globals(),label="Refill",size=(70,-1))
subgroup.Add (control,(0,1),flag=l|cv|a,border=border)
control = Control(panel,type=ComboBox,
name="LaueCrystallographyControl.CrystalLiquorSyringeStepsize",
globals=globals(),size=(70,-1))
subgroup.Add (control,(1,0),flag=l|cv|a,border=border)
control = Control(panel,type=wx.ToggleButton,
name="LaueCrystallographyControl.CrystalLiquorSyringeDispense",
globals=globals(),label="Dispense",size=(70,-1))
subgroup.Add (control,(1,1),flag=l|cv|a,border=border)
group.Add (subgroup,flag=flag,border=border)
middle_panel.Add (group,flag=flag,border=border)
layout.Add (middle_panel,flag=flag,border=border)
group = wx.BoxSizer(wx.VERTICAL)
text = wx.StaticText(panel,label="Pressure [atm]:")
group.Add (text,flag=flag,border=border)
subgroup = wx.GridBagSizer(1,1)
text = wx.StaticText(panel,label="Upstream")
subgroup.Add (text,(0,0),flag=l|cv|a,border=border)
text = wx.StaticText(panel,label="Downstream")
subgroup.Add (text,(0,1),flag=l|cv|a,border=border)
control = Control(panel,type=TextCtrl,
name="LaueCrystallographyControl.UpstreamPressure",
globals=globals(),size=(70,-1))
subgroup.Add (control,(1,0),flag=l|cv|a,border=border)
control = Control(panel,type=TextCtrl,
name="LaueCrystallographyControl.DownstreamPressure",
globals=globals(),size=(70,-1))
subgroup.Add (control,(1,1),flag=l|cv|a,border=border)
control = Control(panel,type=ComboBox,
name="LaueCrystallographyControl.TweakStepsize",
globals=globals(),size=(70,-1))
subgroup.Add (control,(2,0),flag=l|cv|a,border=border)
control = Control(panel,type=wx.Button,
name="LaueCrystallographyControl.Tweak",
globals=globals(),label="Tweak",size=(70,-1))
subgroup.Add (control,(2,1),flag=l|cv|a,border=border)
group.Add (subgroup,flag=flag,border=border)
middle_panel.Add (group,flag=flag,border=border)
right_panel = wx.BoxSizer(wx.VERTICAL)
border = 5
text = wx.StaticText(panel,label="Microscope Image:")
right_panel.Add (text,flag=flag,border=border)
from CameraViewer import ImageWindow
control = Control(panel,type=ImageWindow,
name="LaueCrystallographyControl.Image",globals=globals(),
size=(250,300))
right_panel.Add (control,flag=flag,border=border)
control = Control(panel,type=wx.ToggleButton,
name="LaueCrystallographyControl.AcquireImage",globals=globals(),
label="Acquire Image",
size=(250,-1))
right_panel.Add (control,flag=flag,border=border)
group = wx.BoxSizer(wx.HORIZONTAL)
text = wx.StaticText(panel,label="Root name:")
group.Add (text,flag=flag,border=border)
control = Control(panel,type=TextCtrl,
name="LaueCrystallographyControl.ImageRootName",globals=globals(),
size=(170,-1))
group.Add (control,flag=flag,border=border)
right_panel.Add (group,flag=flag,border=border)
control = Control(panel,type=wx.Button,
name="LaueCrystallographyControl.SaveImage",globals=globals(),
label="Save Image",
size=(250,-1))
right_panel.Add (control,flag=flag,border=border)
layout.Add (right_panel,flag=flag,border=border)
panel.SetSizer(layout)
panel.Fit()
return panel
if __name__ == '__main__':
from pdb import pm
import logging; from tempfile import gettempdir
logfile = gettempdir()+"/LaueCrystallographyControlPanel.log"
logging.basicConfig(level=logging.INFO,
format="%(asctime)s %(levelname)s: %(message)s",
filename=logfile,
)
# Needed to initialize WX library
if not hasattr(wx,"app"): wx.app = wx.App(redirect=False)
panel = LaueCrystallographyControl()
wx.app.MainLoop()
<file_sep>#!/usr/bin/env python
"""
Prosilica GigE CCD cameras.
Author: <NAME> and <NAME>
Date created: 2017-04-13
Date last modified: 2018-10-16
based on original GigE_camera_server by <NAME>
0.0.1 - original GigE_camera_server by <NAME>
Configuration:
from DB import dbset
dbset("GigE_camera.WideFieldCamera.camera.IP_addr","pico3.niddk.nih.gov")
dbset("GigE_camera.MicroscopeCamera.camera.IP_addr","pico14.niddk.nih.gov")
dbset("GigE_camera.WideFieldCamera.ip_address","pico20.niddk.nih.gov:2001")
dbset("GigE_camera.MicroscopeCamera.ip_address","pico20.niddk.nih.gov:2002")
"""
__version__ = "0.0.1"
from GigE_camera import GigE_camera
class Camera(GigE_camera):
from persistent_property import persistent_property
IP_addr = persistent_property("GigE_camera.{name}.camera.IP_addr",
"pico3.niddk.nih.gov")
use_multicast = persistent_property("GigE_camera.{name}.use_multicast",False)
buffer_size = 10
def __init__(self,name):
GigE_camera.__init__(self)
self.name = name
self.frame_counts = []
self.images = []
self.monitoring = False
self.last_frame_count = -1
self.acquisition_requested = False
self.start_monitoring()
self.filenames = {}
def get_acquiring(self):
return self.acquisition_started
def set_acquiring(self,value):
self.acquisition_requested = value
acquiring = property(get_acquiring,set_acquiring)
def start_monitoring(self):
self.monitoring = True
from thread import start_new_thread
start_new_thread(self.monitor,())
def monitor(self):
from time import sleep
# This thread is the control thread.
# The first threat to call "resume" becomes the control thread.
# Any operation that change the state of the PvAPI library
# coming from other threads are ignored.
##self.resume()
while self.monitoring:
if self.acquisition_requested:
while not "started" in self.state:
self.start()
sleep(1)
info("%s: %s" % (self.IP_addr,self.state))
while not self.has_image or self.timestamp == 0:
sleep(0.5)
info("%s" % self.state)
while self.frame_count == self.last_frame_count:
if self.auto_resume: self.resume()
sleep(0.01)
self.save_current_image()
self.last_frame_count = self.frame_count
self.images = self.images[-(self.buffer_size-1):]+[self.rgb_data]
self.frame_counts = self.frame_counts[-(self.buffer_size-1):]+[self.frame_count]
else: self.stop(); sleep(0.5)
def acquire_sequence(self,framecounts,filenames):
"""Save a series of images"""
for framecount,filename in zip(framecounts,filenames):
if not framecount in self.filenames:
self.filenames[framecount] = []
if not filename in self.filenames[framecount]:
self.filenames[framecount] += [filename]
def save_current_image(self):
"""Check whether the last acquired image needs to be saved
and save it."""
frame_count = self.frame_count
if frame_count in self.filenames:
for filename in self.filenames[frame_count]:
self.save_image(self.rgb_data,filename)
del self.filenames[frame_count]
def save_image(self,rgb_data,filename):
"""Saves rgb_data in a file
"""
from thread import start_new_thread
from PIL import Image
image = Image.new('RGB',(self.width,self.height))
#image.fromstring(rgb_data)
image.frombytes(rgb_data)
image = self.rotated_image(image)
from os import makedirs; from os.path import dirname,exists
if not exists(dirname(filename)): makedirs(dirname(filename))
info("Saving %r" % filename)
start_new_thread(image.save,(filename,))
# in degrees counter-clockwise
orientation = persistent_property("{name}.Orientation",0)
def rotated_image(self,image):
"""image: PIL image object"""
return image.rotate(self.orientation)
camera = Camera("WideFieldCamera")
# server's listen port number
ip_address = "pico20.niddk.nih.gov:2000"
class Server(object):
@property
def name(self): return camera.name
from thread import allocate_lock
lock = allocate_lock()
from persistent_property import persistent_property
ip_address = persistent_property("GigE_camera.{name}.ip_address","pico20.niddk.nih.gov:2000")
def get_address(self):
return self.ip_address.split(":")[0]
def set_address(self,value):
self.ip_address = value+":"+str(self.port)
address = property(get_address,set_address)
def get_port(self):
if ":" in self.ip_address: port = self.ip_address.split(":")[-1]
else: port = "2000"
try: port = int(port)
except: port = 2000
return port
def set_port(self,value):
self.ip_address = self.address+":"+str(value)
port = property(get_port,set_port)
def get_running(self):
return self.server is not None
def set_running(self,value):
if self.running != value:
if value: self.start()
else: self.stop()
running = property(get_running,set_running)
server = None
def start(self):
"""make a threaded server, listen/handle clients forever"""
import socket
for self.port in range(self.port,self.port+10):
try:
self.server = self.ThreadingTCPServer(("",self.port),self.ClientHandler)
break
except socket.error,msg: warn("server port %s: %s" % (self.port,msg))
self.address = local_ip_address()
info("server version %s, listening on %s." % (__version__,self.ip_address))
from threading import Thread
self.thread = Thread(target=self.run)
self.thread.start() # Stop with: "self.server.shutdown()"
def run(self):
try: self.server.serve_forever()
except Exception,msg: info("server: %s" % msg)
info("server shutting down")
def stop(self):
if self.server is not None:
self.server.shutdown()
self.server = None
# By default, the "ThreadingTCPServer" class binds to the sever port
# without the option SO_REUSEADDR. The consequence of this is that
# when the server terminates you have to let 60 seconds pass, for the
# socket to leave to "CLOSED_WAIT" state before it can be restarted,
# otherwise the next bind call would generate the error
# 'Address already in use'.
# Setting allow_reuse_address to True makes "ThreadingTCPServer" use to
# SO_REUSEADDR option when calling "bind".
import SocketServer
class ThreadingTCPServer(SocketServer.ThreadingTCPServer):
allow_reuse_address = True
class ClientHandler(SocketServer.BaseRequestHandler):
def handle(self):
"""Called when a client connects. 'self.request' is the client socket"""
info("accepted connection from "+self.client_address[0])
input_queue = ""
while 1:
# Commands from a client are not necessarily received as one packet
# but each command is terminated by a newline character.
# If 'recv' returns an empty string it means client closed the
# connection.
while input_queue.find("\n") == -1:
try: received = self.request.recv(2*1024*1024)
except Exception,x:
error("%r %r" % (x,str(x)))
received = ""
if received == "": info("client disconnected"); break
##debug("received %8d+%8d = %8d bytes" % (len(input_queue),
## len(received),len(input_queue)+len(received)))
input_queue += received
if input_queue == "": break
if input_queue.find("\n") != -1:
end = input_queue.index("\n")
query = input_queue[0:end]
input_queue = input_queue[end+1:]
else: query = input_queue; input_queue = ""
query = query.strip("\r ")
from numpy import array,nan
if query.find("=") >= 0:
debug("executing command: '%s'" % query)
try:
with Server.lock: exec(query)
except Exception,x: error("%r %r" % (x,str(x)))
else:
debug("evaluating query: '%s'" % query)
try:
with Server.lock: reply = eval(query)
except Exception,x:
error("%r %r" % (x,str(x))); reply = str(x)
if reply is None: reply = ""
elif type(reply) == str and len(reply) > 1024:
pass # do not waste time reformatting a string
elif reply is not None:
try: reply = repr(reply)
except: reply = str(reply)
reply = reply.replace("\n","") # "\n" = end of reply
reply += "\n"
debug("sending reply: "+repr(reply))
self.request.sendall(reply)
info("closing connection to "+self.client_address[0])
self.request.close()
server = Server()
def local_ip_address():
"""IP address of the local network interface as string in dot notation"""
# Unfortunately, Python has no platform-indepdent function to find
# the IP address of the local machine.
# As a work-around let us pretend we want to send a UDP datagram to a
# non existing external IP address.
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
try: s.connect(("172.16.58.3",1024))
except socket.error: return "127.0.0.1" # Network is unreachable
# This code does not geneate any network traffic, because UDP is not
# a connection-orientation protocol.
# Now, Python can tell us what would be thet "source address" of the packets
# if we would sent a packet (but we won't actally sent a packet).
address,port = s.getsockname()
return address
def start(name):
camera.name = name
##camera.acquiring = True # needed
server.running = True
def run(name):
"""Run as a stand-alone server program"""
from time import sleep
start(name)
while True: sleep(1)
def set_defaults():
from DB import dbset
dbset("GigE_camera.WideFieldCamera.camera.IP_addr","pico3.niddk.nih.gov")
dbset("GigE_camera.MicroscopeCamera.camera.IP_addr","pico14.niddk.nih.gov")
dbset("GigE_camera.WideFieldCamera.ip_address","pico20.niddk.nih.gov:2001")
dbset("GigE_camera.MicroscopeCamera.ip_address","pico20.niddk.nih.gov:2002")
def debug(message):
"""Generate message without duplicates"""
from logging import debug
if message != last_message["debug"]: debug(message)
last_message["debug"] = message
def info(message):
"""Generate message without duplicates"""
from logging import info
if message != last_message["info"]: info(message)
last_message["info"] = message
def warn(message):
"""Generate message without duplicates"""
from logging import warn
if message != last_message["warn"]: warn(message)
last_message["warn"] = message
def error(message):
"""Generate message without duplicates"""
from logging import error
if message != last_message["error"]: error(message)
last_message["error"] = message
last_message = {"debug":"","info":"","warn":"","error":""}
if __name__ == "__main__":
import logging
logging.basicConfig(level=logging.INFO,format="%(asctime)s: %(message)s")
from sys import argv
if len(argv) > 1: run(argv[1])
self = camera # for debugging
from tempfile import gettempdir
dir = gettempdir()+"/test"
frame_counts = range(0,20)
filenames = [dir+"/%06d.tif" % i for i in frame_counts]
print('camera.acquire_sequence(frame_counts,filenames)')
print('camera.acquiring = True')
print('start("WideFieldCamera")')
<file_sep>SN = '57D81C13'
scan_lst = ['0', '1', '2', '3']
phys_ch_lst = ['0', '1', '2', '3']
gain_lst = ['5', '5', '5', 'T-thrmc']
RingBuffer_size = 4320000
time_out = 0.1
cjc_value = -2.0
calib = [0.5607564290364583, 2.704498291015625, 2.660015869140625, -3.2, 1553209216.642]
socket = ['192.168.127.12', 2030]
type_def = '\x8b\x00\xa80:init()\x01\xa91:close()\x02\xda\x00,2:broadcast fixed rate(in: float, out: None)\x03\xda\x00(3:request average of N (in:N, out:float)\x04\xda\x00,4:request buffer all(in: None, out: nparray)\x05\xda\x0005:request buffer update(in:pointer, out:nparray)\x06\xda\x00-6:perform calibration(in: None, out: nparray)\x07\xda\x00)7:get calibration(in: None, out: nparray)\x08\xda\x00%8:save to a file(in: None, out: none)\xfe\xda\x00 -2:dev_info(in: None, out: dict)\xff\xbf-1:type_def(in:None, out: dict)'<file_sep>filename = '//mx340hs/data/anfinrud_1903/Archive/channel_archiver/NIH.pressure_barometric.txt'<file_sep>"""Application Icon
author: <NAME>
Date created: Mar 28, 2017
Date last modified: 2019-03-20
"""
__version__ = "1.1.1" # Issue: "You should never have more than one dock icon!"
import wx
from logging import debug,info,warn,error
import traceback
def SetIcon(window,name,tooltip=""):
"""Set application icon
window: wx.Frame object
name: e.g. "Checklist"
"""
filename = ""
icon = None
if name:
from module_dir import module_dir
from os.path import exists
basename = module_dir(SetIcon)+"/icons/%s" % name
if exists(basename+".ico"): filename = basename+".ico"
elif exists(basename+".png"): filename = basename+".png"
else: warn("%r.{ico,png}: neither file found" % basename)
if filename:
try: icon = wx.Icon(filename)
except Exception,msg: warn("%s: %s" % (filename,msg))
if icon:
if window: window.Icon = icon
try:
if hasattr(wx,"TaskBarIcon"):
if not hasattr(wx,"taskbar_icon"):
wx.taskbar_icon = wx.TaskBarIcon(iconType=wx.TBI_DOCK)
wx.taskbar_icon.SetIcon(icon,tooltip)
except Exception,msg: warn("%s\n%s" % (msg,traceback.format_exc()))
if __name__ == "__main__":
# Needed to initialize WX library
wx.app = wx.App(redirect=False)
window = wx.Frame(None)
name = "Tool"
tooltip = "Icon"
SetIcon(window,name,tooltip)
window.Show()
wx.app.MainLoop()
<file_sep>#!/usr/bin/env python
"""This is to run a third instance of the 'DataLogger' application
<NAME>, 18 Jun 2011"""
from DataLogger import DataLogger
import wx
app = wx.PySimpleApp(0)
win = DataLogger(name="DataLogger3")
app.MainLoop()
<file_sep>#!/bin/env python
"""Framework for an instrument server that communicates via formatted text
ASCII commands.
Author: <NAME>
Date created: 2018-10-30
Date last modified: 2019-03-28
"""
__version__ = "1.4.1" # issue: select: interrupted system call
from logging import debug,info,warn,error
import traceback
class TCP_Server(object):
from persistent_property import persistent_property
default_port = 2000
def __init__(self,
ip_address_and_port_db="server.ip_address",
globals=None,
locals=None,
idle_timeout=1,
idle_callback=None
):
"""
name: defines data base entry for number
globals: passed on to 'eval' or 'exec' when processing commands
locals: passed on to 'eval' or 'exec' when processing commands
idle_timeout: wait time for idle_callback in s
"""
self.ip_address_and_port_db = ip_address_and_port_db
self.globals = globals
self.locals = locals
self.clients = []
self.idle_callbacks = []
if idle_callback is not None: self.idle_callbacks += [idle_callback]
self.idle_timeout = idle_timeout
self.listing_port = 0
def get_port(self):
port = self.ip_address_and_port.split(":")[-1:][0]
try: port = int(port)
except: port = self.default_port
return port
def set_port(self,value):
self.ip_address_and_port = self.ip_address+":"+str(value)
port = property(get_port,set_port)
def get_ip_address(self):
ip_address = self.ip_address_and_port.split(":")[0:1][0]
return ip_address
ip_address = property(get_ip_address)
def get_ip_address_and_port(self):
from DB import db
default_value = "localhost:%r" % self.default_port
return db(self.ip_address_and_port_db,default_value)
def set_ip_address_and_port(self,value):
from DB import dbset
dbset(self.ip_address_and_port_db,value)
ip_address_and_port = property(get_ip_address_and_port,set_ip_address_and_port)
def run(self):
while True:
import socket,select
if self.listing_port != self.port:
self.listen_socket = socket.socket(socket.AF_INET,socket.SOCK_STREAM,0)
self.listen_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
try:
self.listen_socket.bind(("0.0.0.0",self.port))
self.listen_socket.listen(20)
debug("listening on port %r" % self.port)
self.listing_port = self.port
except socket.error,msg:
error("bind/listen %r: %s" % (self.port,msg))
self.listing_port = 0
read_sockets = [self.listen_socket]+\
[client.socket for client in self.clients]
write_sockets = \
[client.socket for client in self.clients if client.pending_replies]
except_sockets = []
try: ready_to_read,ready_to_write,in_error = \
select.select(read_sockets,write_sockets,except_sockets,self.idle_timeout)
except select.error,msg:
if not 'Interrupted system call' in str(msg):
warn("select: %r" % msg)
ready_to_read,ready_to_write,in_error = [],[],[]
if self.listen_socket in ready_to_read:
##debug("Accepting connection...")
socket,address_port = self.listen_socket.accept()
address,port = address_port
address_port = "%s:%s" % (address,port)
debug("%s: connected" % address_port)
self.clients += [self.client(socket,address_port)]
for client in self.clients:
if client.socket in ready_to_read:
try:
input = client.socket.recv(65536)
if len(input) > 0:
##debug("%s: recv %r bytes" % (client.address_port,len(input)))
client.pending_input += input
self.process(client)
else: # count of zero indicates connection closed
debug("%s: disconnected" % address_port)
self.clients.remove(client)
except socket.error,msg:
debug("%s: recv: %s" % (client.address_port,msg))
self.clients.remove(client)
if client.socket in ready_to_write:
n = len(client.pending_replies)
##debug("%s: sending %r bytes..." % (client.address_port,n))
n = client.socket.send(client.pending_replies)
if n > 0: client.pending_replies = client.pending_replies[n:]
##debug("%s: sent %r bytes" % (client.address_port,n))
if all([len(s) == 0 for s in (ready_to_read,ready_to_write,in_error)]):
self.handle_idle()
def process(self,client):
while client.pending_input.find("\n") != -1:
end = client.pending_input.index("\n")
input = client.pending_input[0:end]
client.pending_input = client.pending_input[end+1:]
if input:
##debug("%s: recv %r" % (client.address_port,input))
reply = self.reply(input)
client.pending_replies += reply
def reply(self,input):
"""Return a reply to a client process
command: string (without newline termination)
return value: string (without newline termination)"""
try:
value = eval(input,self.globals,self.locals)
reply = self.string(value)
except Exception,msg:
error_message_eval = "%s\n%s" % (msg,traceback.format_exc())
try:
exec(input,self.globals,self.locals)
reply = "\n"
except Exception,msg:
error_message_exec = "%s\n%s" % (msg,traceback.format_exc())
error(error_message_eval)
error(error_message_exec)
reply = error_message_eval+error_message_exec
return reply
def string(self,value):
"""Format python value as string for network stransmission"""
if isinstance(value,str) and len(value) > 1024: string = value
else: string = repr(value)+"\n"
return string
def handle_idle(self):
for callback in self.idle_callbacks:
try: callback()
except Exception,msg: error("%s\n%s" % (msg,traceback.format_exc()))
class client(object):
def __init__(self,socket=None,address_port=""):
self.socket = socket
self.address_port = address_port
self.pending_input = ""
self.pending_replies = ""
tcp_server = TCP_Server # alias
if __name__ == "__main__":
from pdb import pm # for debugging
import logging
logging.basicConfig(level=logging.DEBUG,
format="%(asctime)s %(levelname)s: %(message)s")
from instrumentation import * # -> globals()
def idle(): debug("idle")
ip_address_and_port_db = "GigE_camera.MicroscopeCamera.ip_address"
server = self = TCP_Server(ip_address_and_port_db=ip_address_and_port_db,
globals=globals(),locals=locals())
server.idle_timeout = 1.0
##server.idle_callbacks += [idle]
print('self.port = %r' % self.port)
print('Test: from tcp_client import query; print query("localhost:%s","hello")' % self.port)
print('self.run() # does not return')
##self.run()
<file_sep>#!/bin/env python
"""
Acquire a series of images using the XPP Rayonix detector with the
LCLS data acquisition system and a server running on a "mond" node
Setup:
source ~schotte/Software/Lauecollect/setup_env.sh
DAQ Control: Configuration - Type BEAM_PP - check Sync Sequence 3 - Target State: Allocate
(if grayed out: daq.diconnect())
xpphome -> LSLS tab -> Event Sequencer -> Event Code Sequence 3 -> Start
ssh daq-xpp-mon05
ssh daq-xpp-mon06
~xppopr/experiments/xppj1216/software/start_zmqsend.sh:
source /reg/d/iocCommon/All/xpp_env.sh
export TIME=`date +%s`
export NAME="zmqsend.$HOSTNAME.$TIME"
source /reg/g/psdm/etc/ana_env.sh
$PROCSERV --logfile /tmp/$NAME --name zmqsend 40000 ./zmqsend.cmd
~xppopr/experiments/xppj1216/software/start_zmqsend.sh:
source /reg/g/psdm/etc/ana_env.sh
`which mpirun` -n 12 python /reg/neh/home/cpo/ipsana/xppj1216/zmqpub.py
Monitor status of servers:
telnet daq-xpp-mon05 40000
telnet daq-xpp-mon06 40000
Control-X, Control-R to restart
Author: <NAME>, Jan 26, 2016 - Jan 31, 2016
"""
from xppdaq import xppdaq
from time import time,sleep
from logging import info,warn,debug
from rayonix_detector_XPP_shmem_client import daq_shmem_client
from numimage import numimage
from thread import start_new_thread
from os.path import dirname
__version__ = "1.1.1" # hardware bin factor
class rayonix_detector(object):
__state__ = "idle"
cancelled = False
def __init__(self,*args,**kwargs):
# for compatibility with "rayonix_detector" module
pass
def acquire_images_triggered(self,filenames):
"""filename: list of absolute pathnames"""
start_new_thread(self.__acquire_images_triggered__,(filenames,))
def __acquire_images_triggered__(self,filenames):
"""filename: list of absolute pathnames"""
self.cancelled = False
# The first image in frame transfer mode has a lot of zingers and needs to be
# discarded.
# The detector trigger is connected as external trigger to the FPGA.
# The trigger pulse for the first image starts the timing seqence.
dir = dirname(filenames[0]) if len(filenames) > 0 else ""
if dir == "": dir = "."
filenames = [dir+"/discard.mccd"]+filenames
Nimages = len(filenames)
Nevents = (Nimages)*12
info("DAQ begin...")
xppdaq.begin(Nevents)
info("DAQ started...")
self.__state__ = "acquiring series"
if not self.cancelled: daq_shmem_client.save_images(filenames)
while not daq_shmem_client.completed and not self.cancelled: sleep(0.05)
if self.cancelled: daq_shmem_client.abort()
info("DAQ waiting...")
xppdaq.wait()
info("DAQ ending run...")
xppdaq.endrun()
info("DAQ run done.")
self.__state__ = "idle"
hardware_bin_factor = 2
def get_bin_factor(self):
"""Software bin factor x hardware bin factor"""
return daq_shmem_client.bin_factor*self.hardware_bin_factor
def set_bin_factor(self,value):
daq_shmem_client.bin_factor = value/self.hardware_bin_factor
bin_factor = property(get_bin_factor,set_bin_factor)
def filesize(self,bin_factor):
"""Image file size in bytes including headers
bin_facor: 2,4,8,16"""
image_size = 3840/bin_factor # MS170HS
headersize = 4096
image_nbytes = 2*image_size**2
filesize = headersize+image_nbytes
return filesize
def state(self):
"""What is the detector currently doing?"""
return self.__state__
def abort(self):
"""Cancel series acquisition"""
self.cancelled = True
def read_bkg(self):
"""Reads a fresh the backgound image, which is substracted from every
image after readout before the correction is applied."""
# for compatibility with "rayonix_detector.py" module
return True
def bkg_valid(self):
"""Does detector software have a the backgound image for the current
bin mode, which is substracted from every image after readout before
the correction is applied."""
# for compatibility with "rayonix_detector.py" module
return True
ccd = rayonix_detector()
if __name__ == "__main__":
import logging
from tempfile import gettempdir
logging.basicConfig(level=logging.DEBUG,format="%(asctime)s: %(message)s",
filename=gettempdir()+"/lauecollect_debug.log")
dir = "/reg/neh/operator/xppopr/experiments/xppj1216/Data/Test/Test1/alignment"
filenames = [dir+"/%03d.mccd" % i for i in range(0,20)]
print("ccd.bin_factor = 8")
print("ccd.acquire_images_triggered(filenames)")
print("ccd.acquire_images_triggered(filenames); sleep(1); ccd.abort()")
print("ccd.state()")
print("ccd.abort()")
<file_sep>MEAN.filename = '//mx340hs/data/anfinrud_1903/Archive/NIH.SAMPLE_FROZEN_OPTICAL.MEAN.txt'
MEAN2.filename = '//mx340hs/data/anfinrud_1903/Archive/NIH.SAMPLE_FROZEN_OPTICAL.MEAN2.txt'<file_sep>#!/usr/bin/env python
"""
Monitor status of ns laser during data collection
Author: <NAME>
Date created: 10/27/2017
Date last modified: 10/27/2017
"""
__version__ = "1.0.2"
from logging import debug,info,warn,error
def check_laser_loop():
from sleep import sleep
import traceback
info("Initializing...")
try:
while True:
try: check_laser()
except Exception,msg:
error("%s" % msg)
traceback.print_exc()
sleep(3)
except KeyboardInterrupt: pass
def check_laser():
"""Play an alret sound if the laser signal is below threshold"""
amplitude = laser_amplitude()
info("%.3f" % amplitude)
if amplitude < 0.1: alert()
def alert():
from sound import play_sound
play_sound("chimes")
def laser_amplitude():
"""Peak signal in V, typical 0.250 V"""
from numpy import nan
t,U = last_laser_waveform()
if len(U) > 0: amplitude = max(U)
else: amplitude = nan
return amplitude
def last_laser_waveform():
"""time and voltage"""
from lecroy_scope_waveform import read_waveform
from os.path import exists
file = last_laser_waveform_file()
if exists(file):
debug("last laser waveform: %s" % file)
t,U = read_waveform(file)
t,U = t[-1],U[-1]
else: t,U = [],[]
return t,U
def last_laser_waveform_file():
file = last_image()
file = file.replace("/xray_images/","/laser_traces/")
file = file.replace(".mccd","_01_laser.trc")
return file
def last_image():
from os.path import exists,dirname
filename = logfile()
if exists(filename):
f = file(filename)
f.seek(-512,2)
t = f.read(512)
line = ([""]+t.strip("\n").split("\n"))[-1]
image_file = ([""]+line.split("\t")[1:2])[-1]
else:
debug("%s not found" % filename)
image_file = ""
if image_file: image_file = dirname(filename)+"/xray_images/"+image_file
return image_file
def logfile():
"""Current collection logfile"""
import lauecollect
from normpath import normpath
lauecollect.load_settings()
file = normpath(lauecollect.logfile())
return file
if __name__ == "__main__":
import logging
logging.basicConfig(level=logging.INFO,
format="%(asctime)s %(levelname)s: %(message)s")
##print('check_laser_loop()')
check_laser_loop()
<file_sep>from timing_system import timing_system
registers = \
(timing_system.image_number,timing_system.image_number_inc),\
(timing_system.pass_number,timing_system.pass_number_inc),\
(timing_system.pulses,timing_system.pulses_inc)
for (acc,inc) in registers:
acc.count = 0
count = 100
for i in range(0,count):
inc.count=1
inc.count=0
print "%r: expecting %r, got %r" % (acc,count,acc.count)
acc.count = 0
<file_sep>#!/usr/bin/env python
"""Manage settings for different locations / instruments
Author: <NAME>
Date created: 2015-06-15
Date last modified: 2018-09-10
"""
from configurations import configurations
import wx
import wx.lib.scrolledpanel
from EditableControls import TextCtrl,ComboBox
__version__ = "1.1" # ScrolledPanel
class ConfigurationPanel(wx.Frame):
"""Manage settings for different locations / instruments"""
from setting import setting
size = setting("size",(600,800))
def __init__ (self,parent=None):
wx.Frame.__init__(self,parent,title="Configurations",size=self.size)
from Icon import SetIcon
SetIcon(self,"Tool")
# Controls
self.panel = wx.lib.scrolledpanel.ScrolledPanel(self)
style = wx.TE_PROCESS_ENTER
self.Configuration = ComboBox(self.panel,size=(240,-1),style=style)
self.SavedToCurrent = wx.Button(self.panel,label=" Saved ->",size=(160,-1))
self.CurrentToSaved = wx.Button(self.panel,label="<- Current ",size=(160,-1))
N = len(configurations.parameters.descriptions)
self.Descriptions = [TextCtrl(self.panel,size=(240,-1),style=style) for i in range(0,N)]
self.CurrentValues = [ComboBox(self.panel,size=(160,-1),style=style) for i in range(0,N)]
self.SavedValues = [ComboBox(self.panel,size=(160,-1),style=style) for i in range(0,N)]
# Callbacks
self.Configuration.Bind(wx.EVT_TEXT_ENTER,self.OnConfiguration)
self.Configuration.Bind(wx.EVT_COMBOBOX,self.OnConfiguration)
self.SavedToCurrent.Bind(wx.EVT_BUTTON,self.OnSavedToCurrent)
self.CurrentToSaved.Bind(wx.EVT_BUTTON,self.OnCurrentToSaved)
self.Bind(wx.EVT_TEXT_ENTER,self.OnEnter)
self.Bind(wx.EVT_COMBOBOX,self.OnEnter)
self.Bind(wx.EVT_SIZE,self.OnResize)
##self.Bind(wx.EVT_CLOSE,self.OnClose)
# Layout
layout = wx.BoxSizer()
grid = wx.FlexGridSizer(cols=3,hgap=2,vgap=2)
flag = wx.ALIGN_LEFT
grid.Add (self.Configuration,flag=flag)
grid.Add (self.SavedToCurrent,flag=flag)
grid.Add (self.CurrentToSaved,flag=flag)
for i in range(0,N):
grid.Add (self.Descriptions[i],flag=flag)
grid.Add (self.SavedValues[i],flag=flag)
grid.Add (self.CurrentValues[i],flag=flag)
# Leave a 10-pixel wide space around the panel.
border_box = wx.BoxSizer(wx.VERTICAL)
border_box.Add (grid,flag=wx.EXPAND|wx.ALL)
layout.Add (border_box,flag=wx.EXPAND|wx.ALL,border=10)
self.panel.SetSizer(layout)
##self.panel.SetAutoLayout(True)
self.panel.SetupScrolling()
##self.panel.Fit()
##self.Fit()
self.Show()
self.keep_alive()
def keep_alive(self,event=None):
"""Periodically refresh the displayed settings (every second)."""
self.refresh()
self.timer = wx.Timer(self)
self.Bind (wx.EVT_TIMER,self.keep_alive,self.timer)
self.timer.Start(1000,oneShot=True)
def refresh(self,Event=None):
"""Update all controls"""
configuration_names = configurations.configuration_names
if not self.Configuration.Value in configuration_names:
self.Configuration.Value = configurations.current_configuration
self.Configuration.Items = configuration_names
configuration_name = self.Configuration.Value
##self.SavedLabel.Label = configuration_name
descriptions = configurations.parameters.descriptions
values = [str(v) for v in configurations[""]]
saved_values = [str(v) for v in configurations[configuration_name]]
choices = [[str(c) for c in l] for l in configurations.choices]
agree = [v1 == v2 for v1,v2 in zip(values,saved_values)]
N = len(descriptions)
for i in range(0,N):
self.Descriptions[i].Value = descriptions[i]
self.SavedValues[i].Value = saved_values[i]
self.SavedValues[i].Items = choices[i]
self.SavedValues[i].BackgroundColour = (255,255,255) if agree[i] else (255,190,190)
self.SavedValues[i].ForegroundColour = (100,100,100)
self.CurrentValues[i].Value = values[i]
self.CurrentValues[i].Items = choices[i]
self.Configuration. BackgroundColour = (255,255,255) if all(agree) else (255,190,190)
self.SavedToCurrent.BackgroundColour = (255,255,255) if all(agree) else (255,190,190)
self.SavedToCurrent.Enabled = not all(agree)
self.CurrentToSaved.Enabled = not all(agree)
def OnConfiguration(self,event):
"""Called if the configration is switched"""
self.refresh()
def OnSavedToCurrent(self,event):
"""Make the named saved configuration active"""
name = self.Configuration.Value
configurations[""] = configurations[name]
self.refresh()
def OnCurrentToSaved(self,event):
"""Save the active configuration under the selected name"""
name = self.Configuration.Value
configurations[name] = configurations[""]
self.refresh()
def OnEnter(self,event):
"""Called it a entry is modified"""
N = len(configurations.parameters.descriptions)
name = self.Configuration.Value
configurations[name] = [eval(self.SavedValues [i].Value) for i in range(0,N)]
configurations[""] = [eval(self.CurrentValues[i].Value) for i in range(0,N)]
self.refresh()
def OnResize(self,event):
event.Skip()
self.size = tuple(self.Size)
def OnClose(self,event):
"""Handle Window closed event"""
self.Destroy()
def eval(x):
"""Convert x to a built-in Python data type, by default to string"""
try: return __builtins__.eval(x)
except: return str(x)
if __name__ == '__main__': # for testing
from pdb import pm
app = wx.App(redirect=False)
win = ConfigurationPanel()
app.MainLoop()
<file_sep>"""
Raster scan of a sample holder containing multiple crystals.
The sample holder is a flattened Mylar tubing of about 2 mm width, mounted
horizontally, facing the X-ray beam, with a 30-degree tilt with respect the
vertical.
The scan identifies the location of the crystals based on their X-ray
diffraction properties.
<NAME>, Feb 13, 2017 - Oct 5, 2017
"""
from instrumentation import *
__version__ = "1.3.7" # stepsize
from rayonix_detector_continuous_1 import ccd # use old version
from Ensemble import ensemble
from ms_shutter import ms_shutter
from logging import debug,info,warn,error
import glogging as g
class Image_Scan(object):
name = "image_scan"
from persistent_property import persistent_property
from numpy import sin,cos,radians
cx = persistent_property("cx",0.0) # center [mm]
cy = persistent_property("cy",0.0) # center [mm]
cz = persistent_property("cz",0.0) # center [mm]
dx = persistent_property("dx",0.03) # step size [mm] (0.03 -> 0.02)
dy = persistent_property("dy",0.03) # step size [mm] (0.03 -> 0.02)
width = persistent_property("width", 0.3) # range [mm] (0.3 -> 0.12)
height = persistent_property("height",0.9) # range [mm] (0.9 -> 0.6)
# sample carrier tilt to X-ray beam in deg (0 = normal)
phi = persistent_property("phi",-30)
# acquisition rate: timing_system.hlct*2 for ca 40 Hz
##dt = persistent_property("dt",0.0244388571428)
control_ms_shutter = persistent_property("control_ms_shutter",False)
motion_controller_enabled = persistent_property("motion_controller_enabled",True)
trigger_scope = persistent_property("trigger_scope",False)
# Analyze only the central part of the images? Which faction?
ROI_fraction = persistent_property("ROI_fraction",0.333)
peak_detection_threshold = persistent_property("peak_detection_threshold",10.0)
subtract_background = persistent_property("subtract_background",False)
start_time = persistent_property("start_time",0) # last time scan was run
cancelled = persistent_property("cancelled",False)
Nanalyzed = 0 # how many images have been processed?
def get_center(self): return self.cx,self.cy,self.cz
def set_center(self,value): self.cx,self.cy,self.cz = value
center = property(get_center,set_center)
def get_position(self): return SampleX.value,SampleY.value,SampleZ.value
def set_position(self,value):
SampleX.value,SampleY.value,SampleZ.value = value
position = property(get_position,set_position)
def get_stepsize(self): return self.dx
def set_stepsize(self,value): self.dx = self.dy = value
stepsize = property(get_stepsize,set_stepsize)
def get_directory(self):
"""location to store files"""
import lauecollect; lauecollect.reload_settings()
directory = lauecollect.param.path+"/alignment"
return directory
def set_directory(self,value):
import lauecollect
lauecollect.param.path = value.replace("/alignment","")
lauecollect.save_settings()
directory = property(get_directory,set_directory)
def get_dt(self):
import lauecollect; lauecollect.reload_settings()
return lauecollect.align.waitt
def set_dt(self,value):
import lauecollect
lauecollect.align.waitt = value
lauecollect.save_settings()
dt = property(get_dt,set_dt)
def get_xray_detector_enabled(self):
import lauecollect; lauecollect.reload_settings()
return lauecollect.options.xray_detector_enabled
def set_xray_detector_enabled(self,value):
import lauecollect
lauecollect.options.xray_detector_enabled = value
lauecollect.save_settings()
xray_detector_enabled = property(get_xray_detector_enabled,
set_xray_detector_enabled)
@property
def motors(self):
"""axis names"""
motors = ["X","Y","Z"]
if self.control_ms_shutter: motors += ["msShut_ext"]
return motors
def DX(self,I):
"""Horizontal offset relative to center in mm,
negative = left, positive = right
I: 0-based pixel coordinate, from left, may be an array"""
DX = (I-0.5*(self.NX-1))*self.dx
return DX
def I(self,DX):
"""0-based horizontal pixel coordinate, from left
DX: horizontal offset relative to center in mm,
negative = left, positive = right
may be an array
"""
I = DX/self.dx + 0.5*(self.NX-1)
return I
def DY(self,J):
"""Vertical offset relative to center in mm,
negative = down, positive = up
J: 0-based pixel coordinate, from top, may be an array"""
DY = -(J-0.5*(self.NY-1))*self.dy
return DY
def J(self,DY):
"""0-based vertical pixel coordinate, from top
DY: vertical offset relative to center in mm,
negative = down, positive = up
may be an array
"""
J = -DY/self.dy + 0.5*(self.NY-1)
return J
@property
def scan_IJ(self):
"""list of arrays of integer coordinates for a scan
I: 0-based horozontal pixel coordinate, from left
J: 0-based vertical pixel coordinate, from top
"""
from numpy import array,arange
IP,JP = arange(0,self.NX),arange(0,self.NY)
# In the horizontal direction, alternate direction from line to line.
I = [(IP if j%2==0 else IP[::-1]) for j in range(0,self.NY)]
J = [[j]*self.NX for j in JP]
I,J = array(I).flatten(),array(J).flatten()
IJ = array([I,J])
return IJ
@property
def scan_DXDY(self):
"""list of arrays of DX and DY coordinates for a scan
DY: horizontal direction, orthogonal to X-ray beam
DY: vertical direction, orthogonal to X-ray beam
"""
from numpy import array
I,J = self.scan_IJ
DXDY = array([self.DX(I),self.DY(J)])
return DXDY
@property
def grid_VXVY(self):
"""Scanning velocities at each grid point
VY: horizontal direction, orthogonal to X-ray beam
VY: vertical direction, orthogonal to X-ray beam
"""
from numpy import array
vx = self.dx/self.dt
# In the horizontal direction, alternate direction from line to line.
VX = [[vx if i%2==0 else -vx]*self.NX for i in range(0,self.NY)]
VY = [[0]*self.NX for i in range(0,self.NY)]
VX,VY = array(VX).flatten(),array(VY).flatten()
VX[0] = VX[-1] = 0
VXVY = array([VX,VY])
return VXVY
@property
def scan_XYZ(self):
"""list of arrays of x,y and z coordinates"""
XYZ = self.XYZ(self.scan_DXDY)
return XYZ
def XYZ(self,(DX,DY)):
"""Transform fro m2D to 3D coordinates
DX: horizontal offset relative to center in mm,
negative = left, positive = right; may be an array
DY: vertical offset relative to center in mm,
negative = down, positive = up; may be an array
"""
from numpy import sin,cos,radians,array
X = self.cx+DY*sin(radians(self.phi))
Y = self.cy+DY*cos(radians(self.phi))
Z = self.cz+DX
XYZ = array([X,Y,Z])
return XYZ
@property
def scan_VXVYVZ(self):
"""list of arrays of x,y and z coordinates"""
from numpy import sin,cos,radians,array
VXG,VYG = self.grid_VXVY
VX = VYG*sin(radians(self.phi))
VY = VYG*cos(radians(self.phi))
VZ = VXG
VXVYVZ = array([VX,VY,VZ])
return VXVYVZ
@property
def scan_N(self):
"""How many scan points are there?"""
return self.NX*self.NY
@property
def NX(self):
"""How many scan points are there in the horizontal direction?"""
from numpy import rint
eps = 1e-6
NX = int(rint((self.width+eps)/self.dx)) + 1
return NX
@property
def NY(self):
"""How many scan points are there in the vertical direction?"""
from numpy import rint
eps = 1e-6
NY = int(rint((self.height+eps)/self.dy)) + 1
return NY
@property
def scan_T(self):
"""Time for each scan point"""
from numpy import arange
T = self.dt*arange(0,self.scan_N)
return T
@property
def x_PVT(self):
"""Position, velocity and time"""
P,V,T = self.scan_XYZ[0],self.scan_VXVYVZ[0],self.scan_T
return P,V,T
@property
def y_PVT(self):
"""Position, velocity and time"""
P,V,T = self.scan_XYZ[1],self.scan_VXVYVZ[1],self.scan_T
return P,V,T
@property
def z_PVT(self):
"""Position, velocity and time"""
P,V,T = self.scan_XYZ[2],self.scan_VXVYVZ[2],self.scan_T
return P,V,T
@property
def PVT(self):
PVTs = [self.x_PVT,self.y_PVT,self.z_PVT]
if self.control_ms_shutter: PVTs += [ms_shutter.PVT(self.scan_T)]
PVT = self.conbine_trajectories(PVTs)
return PVT
@staticmethod
def conbine_trajectories(PVTs):
from numpy import concatenate,sort,unique,array
# common time points
T = unique(sort(concatenate([PVT[2] for PVT in PVTs])))
P,V = [],[]
for PVT in PVTs:
p,v = self.PV(PVT)
P += [p(T)]
V += [v(T)]
P,V = array(P),array(V)
return P,V,T
@staticmethod
def PV(PVT):
"""Position and velocity as continous functions of time
PVT: tuple of 1-d vectors, positino, velocity, time
return value: tuple of two interpolation functions
"""
from scipy.interpolate import interp1d
from numpy import nan,concatenate
P,V,T = PVT
dt = 1e-3
P2 = interl(P,P+V*dt)
T2 = interl(T,T+dt)
T2 = concatenate(([-1e3],T2,[1e3]))
P2 = concatenate(([P2[0]],P2,[P2[-1]]))
p = interp1d(T2,P2,bounds_error=False,fill_value=nan)
T = concatenate(([-1e3],T,[1e3]))
V = concatenate(([V[0]],V,[V[-1]]))
v = interp1d(T,V,kind="linear",bounds_error=False,fill_value=nan)
return p,v
def acquire(self):
"""Perform image scan"""
self.clear()
self.start()
info("Scanning...")
self.wait()
info("Scan completed")
self.finish()
def scan(self):
"""Perform image scan and analyze result"""
self.acquire()
self.analyze()
def start(self):
"""Initial setup for image scan"""
from time import time
self.start_time = time()
self.prepare()
self.acquisition_start()
def clear(self):
"""Remove all iamge files"""
from os.path import exists
from shutil import rmtree
if exists(self.directory):
try: rmtree(self.directory)
except Exception,msg: warn("rmtree: %s: %s" % (self.directory,msg))
def prepare(self):
"""Initial setup for image scan"""
self.motion_controller_start()
self.xray_detector_start()
self.diagnostics_start()
self.timing_system_start()
def timing_system_acquiring(self):
"""Has the timing system started acquiring data?"""
return timing_system.image_number.count > 0 \
or timing_system.pass_number.count > 0
def motion_controller_start(self):
"""Configure motion controller for scan"""
self.jog_xray_shutter()
info("Setting up motion controller...")
if self.motion_controller_enabled: self.start_program()
def jog_xray_shutter(self):
# Because of settling of particles in the ferrofluiidic feed-through
# of te X-ray ms shutter, the first operation might have execessive
# positino error, not compensated by the servo feedback loop
# (ca 3 degreees), leading to only partial transmission of the X-ray
# beam.
# By "jogging" the shutter before first use, the ferro fluid is
# "loosened up" again.
from time import sleep
info("Jogging X-ray shutter")
from ms_shutter import ms_shutter
pos = msShut.value
if pos > ms_shutter.open_pos: step = +10
else: step = -10
msShut.value = pos + step
##while msShut.moving: sleep(0.01)
msShut.value = pos
while msShut.moving: sleep(0.01)
def timing_system_start(self):
"""Configure timing system for scan"""
info("Setting up timing system...")
import lauecollect; lauecollect.reload_settings()
# Timing calibration for X-ray shutter is different from Lauecollect
timing_sequencer.ms.offset = 0.0105 # 0.0095,0.010,0.0105,0.011,0.0115,[0.012]
timing_sequencer.trans.offset = 0.005 # 0.005
timing_sequencer.cache_size = 0
nimages = self.scan_N
image_numbers = range(1,self.scan_N+1)
timing_sequencer.queue_active = False # hold off exection till setup complete
timing_system.image_number.count = 0
timing_system.pass_number.count = 0
timing_system.pulses.count = 0
# The detector trigger pulse at the beginning of the first image is to
# dump zingers that may have accumuated on the CCD. This image is discarded.
# An extra detector trigger is required after the last image,
# to save the last image.
waitt = [self.dt]*nimages+[self.dt]
burst_waitt = [self.dt]*nimages+[self.dt]
burst_delay = [0]*nimages+[0]
npulses = [lauecollect.align.npulses]*nimages+[lauecollect.align.npulses]
laser_on = [0]*nimages+[0]
ms_on = [1]*nimages+[0]
xatt_on = [lauecollect.align.attenuate_xray]*nimages+[lauecollect.align.attenuate_xray]
trans_on = [1]*nimages+[0]
xdet_on = [1]*nimages+[1]
xosct_on = [1]*nimages+[0]
image_numbers = image_numbers+[image_numbers[-1]]
timing_sequencer.acquire(
waitt=waitt,
burst_waitt=burst_waitt,
burst_delay=burst_delay,
npulses=npulses,
laser_on=laser_on,
ms_on=ms_on,
xatt_on=xatt_on,
trans_on=trans_on,
xdet_on=xdet_on,
xosct_on=xosct_on,
image_numbers=image_numbers,
)
def xray_detector_start(self):
"""Configure X-ray area detector
image_numbers: list of 1-based integers
e.g. image_numbers = alignment_pass(1)"""
info("Setting up X-ray detector...")
import lauecollect; lauecollect.load_settings()
from ImageViewer import show_images
if self.xray_detector_enabled:
filenames = self.image_filenames
show_images(filenames)
ccd.bin_factor = lauecollect.align.ccd_bin_factor # Speeds up the acquisition time
def acquisition_start(self):
from time import sleep
filenames = self.image_filenames
xdet_on = timing_sequencer.xdet_on
info("X-ray detector continuously triggered: %r" % xdet_on)
# If the X-ray detector is not continuously triggered...
if not xdet_on: xdet_count = timing_system.xdet_count.count+2 # discard first dummy image
timing_sequencer.queue_active = True
info("Timing system: Waiting for acquisition to start...")
while not self.timing_system_acquiring(): sleep(0.01)
info("Timing system: Acquisition started.")
if xdet_on: xdet_count = timing_system.xdet_count.count+1
info("First image: xdet_count=%r" % xdet_count)
ccd.acquire_images_triggered(filenames,start=xdet_count)
def diagnostics_start(self):
"""Configure diagnostics"""
info("Setting up X-ray oscilloscope...")
if self.scan_N > 1: xray_trace.acquire_sequence(self.scan_N)
xray_trace.acquire_waveforms([self.directory+"/xray_trace.trc"])
def wait(self):
"""Wait for scan to complete
image_numbers: list of 1-based integers, e.g. image_numbers = alignment_pass(1)"""
from time import sleep
while self.running and not self.cancelled: sleep(0.01)
@property
def running(self):
"""Is scan complete?
image_numbers: list of 1-based integers, e.g. image_numbers = alignment_pass(1)"""
if self.timing_system_running: running = True
elif self.xray_detector_running: running = True
elif self.motion_controller_running: running = True
else: running = False
return running
@property
def timing_system_running(self):
"""Is scan complete?"""
i = timing_system.image_number.count
p = timing_system.pulses.count
info("acquiring image %3d, %d pulses" % (i,p))
running = i < self.scan_N and self.scan_N > 0
return running
@property
def xray_detector_running(self):
"""Is scan complete?"""
if self.xray_detector_enabled:
nimages = ccd.nimages
info("X-ray detector: %s images left to save" % nimages)
running = (nimages > 0)
else: running = False
return running
@property
def motion_controller_running(self):
"""Is scan complete?"""
if self.motion_controller_enabled:
running = ensemble.program_filename == self.program_filename
else: running = False
return running
def finish(self):
"""End scan"""
self.motion_controller_finish()
self.xray_detector_finish()
self.timing_system_finish()
##self.diagnostics_finish()
def motion_controller_finish(self):
# Return to the center
if self.motion_controller_enabled:
SampleX.value,SampleY.value,SampleZ.value = self.cx,self.cy,self.cz
info("Restarting program 'ms-shutter.ab'")
ensemble.program_filename = "ms-shutter.ab"
def xray_detector_finish(self):
pass
def timing_system_finish(self):
timing_sequencer.queue_active = False
timing_sequencer.queue_length = 0
# Timing calibration for X-ray shutter is different from Lauecollect
timing_sequencer.ms.offset = 0.013
timing_sequencer.trans.offset = 0.005
timing_sequencer.buffer_size = 0
def diagnostics_finish(self):
"""diagnostics"""
info("Restoring X-ray oscilloscope...")
xray_trace.sampling_mode = "RealTime"
xray_trace.trigger_mode = "Normal"
def start_program(self):
from os.path import basename
from time import sleep
program = dos_text(self.program_code)
old_program = file(self.program_filename).read()
if program != old_program:
info("Updating file %r..." % basename(self.program_filename))
file(self.program_filename,"wb").write(program)
ensemble.program_filename = "" # stop program if already running
while ensemble.program_filename: sleep(0.1)
ensemble.program_filename = basename(self.program_filename)
while not ensemble.program_filename: sleep(0.1) # compilation and loading
@property
def program_filename(self):
"""AeroBasic program"""
from normpath import normpath
filename = normpath(ensemble.program_directory)+"/image_scan.ab"
return filename
@property
def program_code(self):
"""AeroBasic program"""
from numpy import maximum,arange
from datetime import datetime
P,V,T = self.PVT
if min(T) < 0: T -= min(T) # negative TIME not allowed for PVT
T = maximum(T,0.001) # TIME 0 not allowed for PVT
t = str(datetime.now())
DIN = "X,1,0" # sample tranlation digital input
if self.control_ms_shutter: DIN = "msShut_ext,0,1" # ms shutter trigger
s = ""
s += "'Automatically generated by image_scan.py %s\n" % __version__
s += "PROGRAM\n"
s += " PLANE 1\n"
s += " RECONCILE "+" ".join(self.motors)+"\n"
s += " RAMP MODE RATE\n"
s += " RAMP RATE 200\n"
s += " LINEAR "+" ".join(["%s %.3f" % (m,p) for (m,p) in zip(self.motors,P[:,0])])+"\n"
s += " WAIT MOVEDONE "+" ".join(self.motors)+"\n"
s += " ABS 'Positions specified in absolute coordinates\n"
s += " VELOCITY ON\n"
s += " WHILE DIN(%s)=0 'wait for next low-to-high transition.\n" % DIN
s += " DWELL 0.00025\n"
s += " WEND\n"
if self.trigger_scope: s += " SCOPETRIG ' for diagnostics\n"
s += " PVT INIT TIME ABS\n"
for i in range(0,len(T)):
s += " PVT "
s += " ".join(["%s %.8f,%g" % (m,p,v) for (m,p,v) in zip(self.motors,P[:,i],V[:,i])])
s += " TIME %.6g\n" % T[i]
s += " WAIT MOVEDONE "+" ".join(self.motors)+"\n"
s += " PLANE 0\n"
s += " RECONCILE "+" ".join(self.motors)+"\n"
s += " 'Return to starting point\n"
motors = self.motors[0:3]; xyz = self.cx,self.cy,self.cz
s += " LINEAR "+" ".join(["%s %.3f" % (m,p) for (m,p) in zip(motors,xyz)])+"\n"
s += " WAIT MOVEDONE "+" ".join(motors)+"\n"
s += "END PROGRAM"
return s
@property
def image_filenames(self):
I,J = self.scan_IJ
X,Y,Z = self.scan_XYZ
dir = self.directory
image_filenames = [
dir+"/%02d,%02d_%+.3f,%+.3f,%+.3f.mccd" % (i,j,x,y,z)
for i,j,x,y,z in zip(I,J,X,Y,Z)]
return image_filenames
@property
def logfile(self):
from table import table
from os.path import basename,exists
from time_string import date_time
if exists(self.log_filename): logfile = table(self.log_filename)
else:
logfile = table()
logfile["date time"] = [date_time(t) for t in self.start_time+self.scan_T]
logfile["filename"] = [basename(f) for f in self.image_filenames]
DX,DY = self.scan_DXDY
logfile["X[mm]"] = DX
logfile["Y[mm]"] = DY
logfile.filename = self.log_filename
return logfile
def generate_logfile(self):
"""Save scan log file"""
self.logfile.save()
@property
def log_filename(self):
filename = self.directory+"/image_scan.log"
return filename
def acquire_camera_image(self):
filename = self.camera_image_filename.replace("/net/","//")
self.camera.acquire_sequence(filenames=[filename])
@property
def camera(self):
from GigE_camera_client import Camera
camera = Camera("MicroscopeCamera")
return camera
@property
def camera_image_filename(self):
filename = self.directory+"/image.jpg"
return filename
def analyze(self):
"""Process the acquired images"""
self.calculate_FOM()
self.generate_FOM_image()
self.generate_plot()
##self.generate_spot_mask()
def calculate_FOM(self):
"""Process the acquired images"""
from numpy import zeros,sum
from numimage import numimage
from peak_integration import peak_integration_mask
images = self.images
FOM = zeros(self.scan_N)
for self.Nanalyzed in range(0,self.scan_N):
if self.Nanalyzed % 10 == 0:
info("analysis %.f%%" % (float(self.Nanalyzed)/self.scan_N*100))
image = images[self.Nanalyzed]
FOM[self.Nanalyzed] = sum(peak_integration_mask(image)*image)
logfile = self.logfile
logfile["FOM"] = FOM
logfile.save()
def calculate_FOM_Fast(self):
"""Process the acquired images"""
from numpy import zeros,sum,uint32
from peak_integration import peak_integration_mask
images = self.images
sum_image = sum(images.astype(uint32),axis=0)
info("Peak mask of summed image...")
mask = peak_integration_mask(sum_image)
info("FOM...")
FOM = zeros(self.scan_N)
for self.Nanalyzed in range(0,self.scan_N):
FOM[self.Nanalyzed] = sum(mask*images[self.Nanalyzed])
info("FOM done.")
logfile = self.logfile
logfile["FOM"] = FOM
logfile.save()
Nsvd = persistent_property("Nsvd",5)
SVD_rotation = persistent_property("SVD_rotation",False)
@property
def SVD_bases(self):
from numpy.linalg import svd
from numpy import zeros,nan,diag,dot
from SVD_rotation import SVD_rotation_max_V_2D_auto_correlation
images = self.images_ordered
NX,NY,w,h = images.shape
image_data = images.reshape((NX*NY,w*h))
info("SVD...")
U,s,V = svd(image_data.T,full_matrices=False)
# Discard insignificant vectors.
s_all = s
U,s,V = U[:,0:self.Nsvd],s[0:self.Nsvd],V[0:self.Nsvd]
if self.SVD_rotation:
info("SVD rotation...")
US,V = SVD_rotation_max_V_2D_auto_correlation(U,s,V,(self.NX,self.NY),
diagnostics=self.directory+"/SVD rotation scan auto-correlation")
else: US = dot(U,diag(s))
info("SVD done.")
# Restore original shapes.
base_images = US.T.reshape((self.Nsvd,w,h))
base_maps = V.reshape((self.Nsvd,self.NX,self.NY))
return base_maps,s_all,base_images
@property
def SVD_bases(self):
from numpy.linalg import svd
from numpy import zeros,nan,diag,dot
from SVD_rotation import SVD_rotation_min_V_cross_correlation
images = self.images_ordered
NX,NY,w,h = images.shape
image_data = images.reshape((NX*NY,w*h))
info("SVD...")
U,s,V = svd(image_data,full_matrices=False)
# Discard insignificant vectors.
s_all = s
U,s,V = U[:,0:self.Nsvd],s[0:self.Nsvd],V[0:self.Nsvd]
if self.SVD_rotation:
info("SVD rotation...")
U,SV = SVD_rotation_min_V_cross_correlation(U,s,V,
diagnostics=self.directory+"/SVD rotation image cross-correlation")
else: SV = dot(diag(s),V)
info("SVD done.")
# Restore original shapes.
base_maps = U.T.reshape((self.Nsvd,self.NX,self.NY))
base_images = SV.reshape((self.Nsvd,w,h))
return base_maps,s_all,base_images
def generate_SVD_plot(self):
import matplotlib; matplotlib.use("PDF",warn=False) # Turn off Tcl/Tk GUI.
from matplotlib.backends.backend_pdf import PdfPages
from pylab import figure,imshow,plot,title,grid,xlabel,ylabel,xlim,ylim,\
xticks,yticks,legend,gca,rc,cm,colorbar,annotate,subplot,close,\
tight_layout,loglog
from numpy import clip,amin,amax,average,sum
from matplotlib.colors import ListedColormap
maps,s,images = self.SVD_bases
info("Plotting...")
PDF_file = PdfPages(self.directory+"/SVD.pdf")
fig = figure(figsize=(5,5))
loglog(range(1,self.Nsvd+1),s[0:self.Nsvd],".",color="red")
loglog(range(self.Nsvd+1,len(s)+1),s[self.Nsvd:],".",color="blue")
grid()
xlabel("base number")
ylabel("singular value")
tight_layout()
PDF_file.savefig(fig)
for (i,(map,image)) in enumerate(zip(maps,images)):
# SVD components map have abitrary sign.
if abs(amin(map)) > amax(map): map *= -1; image *= -1
fig = figure(figsize=(5,7))
subplot(2,1,1)
title("%d" % (i+1))
imshow(map.T,cmap=cm.gray,interpolation='nearest')
colorbar()
xlim(-0.5,self.NX-0.5)
ylim(-0.5,self.NY-0.5)
subplot(2,1,2)
Imin,Imax = 0.02*amin(image),0.02*amax(image)
imshow(clip(image,Imin,Imax).T,cmap=cm.gray,interpolation='nearest')
colorbar()
PDF_file.savefig(fig)
PDF_file.close()
close("all")
info("Plotting done.")
def generate_FOM_image(self):
"""Save the ccan result in the form of an image"""
self.FOM_image.save()
@property
def FOM_image(self):
"""Scan result presented as image"""
from numimage import numimage
from numpy import rint
logfile = self.logfile
X,Y,FOM = logfile.X,logfile.Y,logfile.FOM
I = rint(self.I(X)).astype(int)
J = rint(self.J(Y)).astype(int)
image = numimage((self.NX,self.NY))
image[I,J] = FOM
image.pixelsize = self.dx
image.filename = self.FOM_image_filename
return image
@property
def FOM_image_filename(self):
filename = self.directory+"/FOM_image.tiff"
return filename
@property
def images_ordered(self):
"""Image data to use for analysis, reordered from scan order to X,Y
order, as 4D numpy array, shape NX x NY x W x H"""
from numpy import zeros,nan
images = self.images
info("Reordering images...")
N,w,h = images.shape
images_ordered = zeros((self.NX,self.NY,w,h))+nan
I,J = self.scan_IJ
for i in range(0,N): images_ordered[I[i],J[i]] = images[i]
return images_ordered
@property
def images(self):
"""Image data to use for analysis in collection order
All images as 3D numpy array, shape Nimages x W x H"""
if self.subtract_background: images = self.background_subtracted_images
else: images = self.image_ROIs
return images
@property
def image_ROIs(self):
"""Image data to use for analysis
All iamges as 3D numpy array, shape Nimage x W x H"""
from numimage import numimage
from numpy import array
info("Mapping images...")
images = [numimage(f) for f in self.image_filenames]
images = [self.ROI(image) for image in images]
info("Loading images...")
images = array(images)
info("Loading images done.")
return images
def ROI(self,image):
"""Region of interest for analysis
image: 2D numpy array"""
from numpy import rint
w,h = image.shape
x = self.ROI_fraction # real number between 0 and 1.0, e.g. 0.333
imin,imax = int(rint(w/2*(1-x))),int(rint(w/2*(1+x)))
ROI = image[imin:imax,imin:imax]
return ROI
def generate_spot_mask(self):
"""Save spot mask from FOM calculation in the form of an image"""
self.spot_mask.save()
@property
def spot_mask(self):
from numpy import zeros,sum,uint32
from peak_integration import spot_mask
from numimage import numimage
images = self.images
sum_image = sum(images.astype(uint32),axis=0)
info("Peak mask of summed image...")
mask = spot_mask(sum_image)
mask = numimage(mask)
mask.filename = self.spot_mask_filename
return mask
@property
def spot_mask_filename(self):
filename = self.directory+"/spot_mask.tiff"
return filename
@property
def crystal_mask(self):
"""bitmap showing location of crystals. 1 = crystal, 0 = no crystal"""
from peak_integration import spot_mask
FOM = self.FOM_image
mask = spot_mask(FOM,self.peak_detection_threshold)
return mask
@property
def crystal_IJ(self):
"""coordinates of crystal centers
I: 0-based horizontal pixel coordinates, from left
J: 0-based vertical pixel coordinates, from top
"""
from scipy.ndimage.measurements import label
from numpy import fromfunction,average,zeros,where,array
mask = self.crystal_mask
FOM = self.FOM_image
# Find clusters
labelled_mask,n = label(mask)
Is = fromfunction(lambda i,j:i,mask.shape)
Js = fromfunction(lambda i,j:j,mask.shape)
I,J = zeros(n),zeros(n)
for i in range(0,n):
pixels = where(labelled_mask==i+1)
I[i] = average(Is[pixels],weights=FOM[pixels])
J[i] = average(Js[pixels],weights=FOM[pixels])
return array([I,J])
@property
def crystal_DXDY(self):
"""Coordinates of crystal centers as DX,DY"""
I,J = self.crystal_IJ
DX,DY = self.DX(I),self.DY(J)
return DX,DY
@property
def crystal_XYZ(self):
"""X,Y,Z coordinates of crystal centers"""
DX,DY = self.crystal_DXDY
XYZ = self.XYZ((DX,DY))
return XYZ
def generate_plot(self):
import matplotlib; matplotlib.use("PDF",warn=False) # Turn off Tcl/Tk GUI.
from matplotlib.backends.backend_pdf import PdfPages
from pylab import figure,imshow,plot,title,grid,xlabel,ylabel,xlim,ylim,\
xticks,yticks,legend,gca,rc,cm,colorbar,annotate,close
from matplotlib.colors import ListedColormap
image = self.FOM_image
mask = self.crystal_mask
I,J = self.crystal_IJ
PDF_file = PdfPages(self.directory+"/plot.pdf")
fig = figure(figsize=(5,5))
imshow(image.T,cmap=cm.gray,interpolation='nearest')
colorbar()
cmap = ListedColormap([[0,0,0],[1,0,0]])
imshow(mask.T,alpha=0.5,cmap=cmap,interpolation='nearest')
plot(I,J,"ro")
for n in range(0,len(I)): annotate(str(n),xy=(I[n],J[n]),color="yellow")
xlim(-0.5,self.NX-0.5)
ylim(-0.5,self.NY-0.5)
xlabel("I")
ylabel("J")
PDF_file.savefig(fig)
PDF_file.close()
close("all")
def goto_crystal(self,i):
SampleX.value,SampleY.value,SampleZ.value = self.crystal_XYZ[:,i]
def goto_ij(self,i,j):
SampleX.value,SampleY.value,SampleZ.value = self.XYZ([self.DX(i),self.DY(j)])
@property
def background_subtracted_images(self):
"""Image data to use for analysis
All iamges as 3D numpy array, shape Nimage x W x H"""
from numimage import numimage
from background_image import background_subtracted
from os.path import exists
from numpy import array,where
info("Mapping images...")
filenames = self.image_filenames
images = []
for i in range(0,len(filenames)):
filename = filenames[i]
background_subtracted_filename = filename.replace("/alignment/",
"/alignment/background_subtracted/%r/" % self.ROI_fraction)
if not exists(background_subtracted_filename):
image = self.ROI(numimage(filename))
image = background_subtracted(image)
numimage(image+10).save(background_subtracted_filename)
images += [numimage(background_subtracted_filename)]
info("Loading images...")
images = array(images)
info("Loading images done.")
# offset 10 = 0 counts
images = where(images!=0,images-10.0,0.0)
return images
image_scan = Image_Scan()
def dos_text(text):
"""Convert UNIX to DOS text"""
return text.replace("\n","\r\n")
def interl(a,b):
"""Combine two arrays of the same length alternating their elements"""
from numpy import column_stack,ravel
return ravel(column_stack((a,b)))
if __name__ == "__main__":
self = image_scan # for debugging
import logging
logging.basicConfig(level=logging.INFO,
format="%(asctime)s %(levelname)s: %(message)s")
g.filename = self.directory+"/debug.pdf"
print('self.center = %.3f,%.3f,%.3f' % self.center)
print('self.center = self.position')
print('self.width,self.height = %.3f,%.3f # 0.500,0.700' % (self.width,self.height))
##print('self.dx,self.dy = %.3f,%.3f' % (self.dx,self.dy))
print('self.stepsize = %.3f' % self.stepsize)
print('self.scan_N = %r' % self.scan_N)
print('self.dt = %r # timing_system.hlct*2' % self.dt)
##print('ms_shutter.dt = %r # 0.008' % ms_shutter.dt)
##print('self.trigger_scope = %r' % self.trigger_scope)
print('ensemble.program_directory = %r' % ensemble.program_directory)
print('self.directory = %r' % self.directory)
print('')
##print('self.subtract_background = %r' % self.subtract_background)
##print('self.ROI_fraction = %r # 0.1667' % self.ROI_fraction)
##print('self.peak_detection_threshold = %r' % self.peak_detection_threshold)
##print('')
##print('self.acquire_camera_image()')
print('self.acquire()')
##print('self.analyze()')
##print('self.scan()')
##print('self.crystal_XYZ')
##print('self.goto_crystal(0)')
##print('self.crystal_IJ')
##print('self.goto_ij(0,0)')
##print('self.goto_IJ(11,4)')
##print('self.Nsvd = %r' % self.Nsvd)
##print('self.SVD_rotation = %r' % self.SVD_rotation)
##print('self.generate_SVD_plot()')
##print('images = self.background_subtracted_images')
##print('images = self.images')
from os.path import exists
<file_sep>"""
Run on "mond" node "daq-xpp-mon05.pcdsn" or "daq-xpp-mon06.pcdsn".
Only one instance can run per node.
Setup:
ssh daq-xpp-mon06.pcdsn
source /reg/g/psdm/etc/ana_env.sh
mpirun -n 4 python daq_image_mpi_test.py
DAQ Control - (uncheck) Record Run - Begin Running
<NAME>, Jan 22, 2016
"""
from psana import *
from numpy import *
from logging import info,warn,debug
ds = DataSource('shmem=XPP.0:stop=no')
src = Source('rayonix')
from mpi4py import MPI
comm = MPI.COMM_WORLD
rank = comm.Get_rank()
size = comm.Get_size()
fiducials = []
for nevent,evt in enumerate(ds.events()):
if nevent%size==rank: # different ranks look at different events
raw = evt.get(Camera.FrameV1,src)
if raw is None: continue
fiducials.append(evt.get(EventId).fiducials())
if nevent == 100: break
all_fiducials = comm.gather(fiducials) # from all ranks
if rank==0:
all_fiducials = sort(concatenate((all_fiducials[:]))) # put in one long list
print all_fiducials
MPI.Finalize()
<file_sep>"""
Optical Scattering client wrapper
Authors: <NAME>
Date created: 26 Feb 2018 - original optical freeze detection agent
Date last modified: March 2 2019
Utilizes center 50x50 pixels to measure mean value within
"""
__version__ = "1.0" # write a comment
from CAServer import casput,casdel, casget
from CA import caget
from datetime import datetime
from thread import start_new_thread
from pdb import pm
import os
from time import sleep,time
from persistent_property import persistent_property
from numpy import nan
from logging import debug,info,warn,error
import traceback
import matplotlib.pyplot as plt
class Optical_Scattering(object):
prefix = persistent_property('prefix','NIH:OPTICAL_SCATTERING')
def __init__(self):
pass
@property
def mean(self):
from CA import caget
value = caget(self.prefix+'.MEAN')
return value
@property
def stdev(self):
from CA import caget
value = caget(self.prefix+'.STDEV')
return value
def get_region_size_x(self):
from CA import caget
value = caget(self.prefix+'.region_size_x')
return value
def set_region_size_x(self,value):
from CA import caput
caput(self.prefix+'.region_size_x',int(value))
region_size_x = property(get_region_size_x,set_region_size_x)
def get_region_size_y(self):
from CA import caget
value = caget(self.prefix+'.region_size_y')
return value
def set_region_size_y(self,value):
from CA import caput
caput(self.prefix+'.region_size_y',int(value))
region_size_y = property(get_region_size_y,set_region_size_y)
@property
def get_region_size_xy(self):
value = (self.region_size_x,self.region_size_y)
return value
def get_region_offset_x(self):
from CA import caget
value = caget(self.prefix+'.region_offset_x')
return value
def set_region_offset_x(self,value):
from CA import caput
caput(self.prefix+'.region_offset_x',int(value))
region_offset_x = property(get_region_offset_x,set_region_offset_x)
def get_region_offset_y(self):
from CA import caget
value = caget(self.prefix+'.region_offset_y')
return value
def set_region_offset_y(self,value):
from CA import caput
caput(self.prefix+'.region_offset_y',int(value))
region_offset_y = property(get_region_offset_y,set_region_offset_y)
@property
def region_offset_xy(self):
value = (self.region_offset_x,self.region_offset_y)
return value
@property
def list_all_pvs(self):
from CA import caget
value = caget(self.prefix+'.LIST_ALL_PVS')
return value
def shutdown_server(self):
from CA import caput
caput(self.prefix+'.KILL','shutdown')
def is_boolean(self,value):
import types
return type(value) == types.BooleanType
optical_scattering = Optical_Scattering()
if __name__ == "__main__":
import logging
from tempfile import gettempdir
logging.basicConfig(level=logging.INFO,
format="%(asctime)s %(levelname)s: %(message)s",
filename=gettempdir()+"/scattering_optical.log",
)
self = optical_scattering # for testing
print('optical_scattering.mean')
print('optical_scattering.stdev')
<file_sep>"""
This is to remote control the sample translation stage for high repetinion
rate time-resolved WAXS experiments.
The stage is a linear motor with 25 mm travel, controlled by an Aerotech
Soloist MP server motor controller with an Etherner interface.
Communication is via TCP/IP port 8000. Using ASCII text commands terminated
with newline (ASCII 10). The connection is closed automatically by the operating
system after 10 seconds of inactivity. Several connections ay be active at one
time. However, the data send by the Soloist contorller is partitoned randomly
among the concurrently open connections.
The timeout can be changed with the parameter "InetSock1ActiveTimeSec"
(default: 10)
<NAME>, NIH, 24 Sep 2008 - 6 Mar 2013
"""
__version__ = "2.5.3"
import socket # TCP/IP communication
from numpy import nan
from DB import dbput,dbget
from logging import debug
class SampleStage(object):
"""Linear motor sample translations stage for time-resolved WAXS"""
version = __version__
unit = "mm"
name = "sample stage"
verbose_logging = True
retries = 2
def __init__(self):
"""ip_address may be given as address:port. If :port is omitted, port
number 8000 is assumed."""
object.__init__(self)
self.connection = None
def get_address(self):
"""Internet address, followed by TCP port number,separated with colon,
e.g. 'id14b-samplex:8000'"""
return self.ip_address+":"+str(self.port)
def set_address(self,address):
if address.find(":") >= 0:
self.ip_address = address.split(":")[0]
self.port = int(address.split(":")[1])
else: self.ip_address = address; self.port = 8000
address = property(get_address,set_address)
def get_ip_address(self):
"""Network address of Soloist constroller, as DNS name or numeric as
string"""
ip_address = dbget("sample_translation/ip_address")
if ip_address == "": ip_address = "id14b-samplex.cars.aps.anl.gov"
return ip_address
def set_ip_address(self,value):
dbput("sample_translation/ip_address",value)
ip_address = property(get_ip_address,set_ip_address)
def get_port(self):
"""TCP port number rof network connection"""
try: return int(dbget("sample_translation/port"))
except ValueError: return 8000
def set_port(self,value):
dbput("sample_translation/port",repr(value))
port = property(get_port,set_port)
def send(self,command):
"""Sends a ASCII text command"""
# Command should be terminated with a newline character.
if len(command) == 0 or command[-1] != "\n": command += "\n"
for attempt in range(0,self.retries):
if self.connection == None:
self.connection = socket.socket()
self.connection.settimeout(1)
try: self.connection.connect((self.ip_address,self.port))
except Exception,message:
self.log_error("send %r connect attempt %d/%d failed: %s" %
(command,attempt+1,self.retries,message))
self.connection = None
continue
try: self.connection.sendall(command)
except Exception,message:
self.log_error("send %r send attempt %d/%d failed: %s" %
(command,attempt+1,self.retries,message))
self.connection = None
continue
self.log("send %r" % command)
break
self.disconnect() # Needed?
def query(self,command):
"""To send a command that generates a reply. Returns the reply
without trailing carriage return."""
# Command should be terminated with a newline character.
if len(command) == 0 or command[-1] != "\n": command += "\n"
reply = ""
for attempt in range(0,self.retries):
if self.connection == None:
self.connection = socket.socket()
self.connection.settimeout(1)
try: self.connection.connect((self.ip_address,self.port))
except Exception,message:
self.log_error("query %r connect attempt %d/%d failed: %s" %
(command,attempt+1,self.retries,message))
self.connection = None
continue
# Clear receive buffer of old replies.
self.connection.settimeout(0.05)
while True:
try: received = self.connection.recv(1024)
except socket.timeout: break
except Exception,message:
self.log_error("query %r empty queue attempt %d/%d failed: %s" %
(command,attempt+1,self.retries,message))
self.connection = None
break
if self.connection == None: continue
try: self.connection.sendall(command)
except Exception,message:
self.log_error("query %r send attempt %d/%d failed: %s" %
(command,attempt+1,self.retries,message))
self.connection = None
continue
self.log("send %r" % command)
reply = ""
self.connection.settimeout(1)
try: received = self.connection.recv(1024)
except socket.timeout:
self.log_error("query %r read attempt %d/%d timed out" %
(command,attempt+1,self.retries))
continue
except Exception,message:
self.log_error("query %r read attempt %d/%d failed: %s" %
(command,attempt+1,self.retries,message))
self.connection = None
continue
reply += received
self.connection.settimeout(0.05)
while len(received) > 0:
try: received = self.connection.recv(1024)
except socket.timeout: received = ""
reply += received
reply = reply.strip("\n")
self.log("recv %r" % reply)
break
##self.disconnect()
return reply
def disconnect(self):
"""Close TCP/IP connection to controller
(will close automatically after 10 s of no communication)"""
self.connection = None
def get_position(self):
"""Current position in mm"""
reply = self.query("Current position?")
if reply.find("Current position is ") != 0: return nan
try: return float(reply.strip("Current position is mm."))
except ValueError: return nan
def set_position(self,position):
self.query("Go to %.5f mm." % position)
position = property(get_position,set_position,
doc="""current position in mm, moves the stage if assigned""")
value = position
def get_command_position(self):
"""Nominal target position in mm, is different from actual position
while moving"""
reply = self.query("Command position?")
if reply.find("Command position is ") != 0: return nan
try: return float(reply.strip("Command position is mm."))
except ValueError: return nan
command_position = property(get_command_position,set_position,
doc="""current position in mm, moves the stage if assigned""")
def get_software_command_position(self):
"""Nominal target position in mm maintained in a floating point
variable, independently from the controllers 'command position'."""
reply = self.query("Software command position?")
if reply.find("Software command position is ") != 0: return nan
try: return float(reply.strip("Software command position is mm."))
except ValueError: return nan
software_command_position = property(get_software_command_position,
set_position,
doc="""current position in mm, moves the stage if assigned""")
def is_moving(self):
reply = self.query("Is the stage moving?")
if reply == "The stage is moving.": return True
else: return False
def set_moving(self,moving):
if not moving: stop()
moving = property(is_moving,set_moving,doc="""Tell whether the stage is
currently moving. If assigned False, stops the stage.""")
def stop(self):
"""Cancels current move (and disables external trigger)."""
self.query("Stop.")
def get_calibrated(self):
reply = self.query("Is the stage calibrated?")
if reply == "The stage is calibrated.": return True
else: return False
def set_calibrated(self,calibrate):
if calibrate and not self.is_calibrated(): self.calibrate()
calibrated = property(get_calibrated,set_calibrated,
doc="Has the encoder has been set to zero at the home switch? "+
"Runs calibration if False and assigned the value True.")
def calibrate(self):
"""Drives stage to the home switch and sets enoder to zero"""
self.query("Calibrate the stage.")
def is_at_high_limit(self):
reply = self.query("Is the stage at high limit?")
if reply == "The stage is at high limit.": return True
else: return False
at_high_limit = property(fget=is_at_high_limit,
doc="Is the stage at end of travel?")
def is_at_low_limit(self):
reply = self.query("Is the stage at low limit?")
if reply == "The stage is at low limit.": return True
else: return False
at_low_limit = property(fget=is_at_low_limit,
doc="Is the stage at end of travel?")
def get_controller_stepsize(self):
"""Amplitude of motion executed on external trigger"""
reply = self.query("Step size?")
if reply.find("Step size is ") != 0: return nan
try: return float(reply.strip("Step size is ."))
except ValueError: return nan
def set_controller_stepsize(self,value):
self.query("Step size is %.5f." % value)
controller_stepsize = property(get_controller_stepsize,
set_controller_stepsize)
def get_trigger_enabled(self):
"""Move stage on rising edge of digital input?"""
reply = self.query("Is trigger enabled?")
if reply == "Trigger is enabled.": return True
else: return False
def set_trigger_enabled(self,enabled):
if enabled: self.query("Enable trigger.")
else: self.query("Disable trigger.")
trigger_enabled = property(get_trigger_enabled,set_trigger_enabled)
def get_timer_enabled(self):
"""Move the stage periodically, based on an internal timer?"""
reply = self.query("Is timer enabled?")
if reply == "Timer is enabled.": return True
else: return False
def set_timer_enabled(self,enabled):
if enabled: self.query("Enable timer.")
else: self.query("Disable timer.")
timer_enabled = property(get_timer_enabled,set_timer_enabled)
def get_timer_period(self):
"""At which frequency to move based on internal timer?"""
reply = self.query("Timer period?")
if reply.find("Timer period is ") != 0: return nan
try: return float(reply.strip("Timer period is s."))
except ValueError: return nan
def set_timer_period(self,value):
self.query("Timer period is %.3f." % value)
timer_period = property(get_timer_period,set_timer_period)
def get_auto_return(self):
reply = self.query("Does the stage return to start at end of travel?")
if reply == "The stage returns to start at end of travel.": return True
else: return False
def set_auto_return(self,enabled):
if enabled: self.query("Return to start at end of travel.")
else: self.query("Do not return to start at end of travel.")
auto_return = property(get_auto_return,set_auto_return,doc="On exernal"+
" trigger, does the stage return to start when it reaches a travel limit?")
def get_return_time(self):
"""Time needed to move from the end to the start position or the travel
range"""
from math import sqrt
a = self.acceleration
start,end = self.start_position,self.end_position
s = abs(end-start)
return 2*sqrt(s/a)
def set_return_time(self,t):
"""Change the acceleration to acheive the specified return time"""
from numpy import nan
start,end = self.start_position,self.end_position
s = abs(end-start)
a = 4*s/t**2
##debug("sample stage: acceleration = %r" % a)
self.acceleration = a
return_time = property(get_return_time,set_return_time)
def travel_time(self,start,end):
"""How long does it take to move from start to end?"""
from math import sqrt
a = self.acceleration
s = abs(end-start)
return 2*sqrt(s/a)
def get_controller_auto_reverse(self):
"""On exernal trigger, does the stage change stepping direction when it
reaches a travel limit?"""
reply = self.query("Does the stage change direction at travel limits?")
if reply == "The stage changes direction at travel limits.": return True
else: return False
def set_controller_auto_reverse(self,enabled):
if enabled: self.query("Change direction at travel limits.")
else: self.query("Do not change direction.")
controller_auto_reverse = property(get_controller_auto_reverse,
set_controller_auto_reverse)
def get_controller_start_position(self):
"""Start of scan range in external trigger mode"""
reply = self.query("Start position?")
if reply.find("Start position is ") != 0: return nan
reply = reply.strip("Start position is mm.")
try: return float(reply)
except ValueError: return nan
def set_controller_start_position(self,value):
self.query("Start position %g mm." % value)
controller_start_position = property(get_controller_start_position,
set_controller_start_position)
def get_controller_end_position(self):
"""End of scan range in external trigger mode"""
"""Start of scan range in external trigger mode"""
reply = self.query("End position?")
if reply.find("End position is ") != 0: return nan
reply = reply.strip("End position is mm.")
try: return float(reply)
except ValueError: return nan
def set_controller_end_position(self,value):
self.query("End position %g mm." % value)
controller_end_position = property(get_controller_end_position,set_controller_end_position)
def is_drive_enabled(self):
reply = self.query("Is the drive enabled?")
if reply == "The drive is enabled.": return True
else: return False
def set_drive_enabled(self,enabled):
if enabled: self.query("Enable drive.")
else: self.query("Disable drive.")
drive_enabled = property(is_drive_enabled,set_drive_enabled,
doc="Is feedback active and holing current applied?")
def get_speed(self):
reply = self.query("Top speed?")
if reply.find("Top speed ") != 0: return nan
try: return float(reply.strip("Top speed is mm/s."))
except ValueError: return nan
def set_speed(self,speed):
self.query("Top speed %g." % speed)
speed = property(get_speed,set_speed,doc="Maximum speed in mm/s")
def get_controller_acceleration(self):
"""Acceleration in non-triggered mode in mm/s"""
reply = self.query("Acceleration?")
if reply.find("The acceleration is ") != 0: return nan
reply = reply[len("The acceleration is "):]
try: return float(reply.split()[0])
except ValueError: return nan
def set_controller_acceleration(self,value):
from numpy import isnan,isinf
if isnan(value) or isinf(value) or value <= 0: return
self.query("Acceleration %g." % value)
controller_acceleration = property(get_controller_acceleration,
set_controller_acceleration)
def get_acceleration_in_triggered_mode(self):
reply = self.query("Acceleration in triggered mode?")
if reply.find("The acceleration in triggered mode is ") != 0: return nan
reply = reply[len("The acceleration in triggered mode is "):]
try: return float(reply.split()[0])
except ValueError: return nan
def set_acceleration_in_triggered_mode(self,value):
self.query("Acceleration in triggered mode %g." % value)
acceleration_in_triggered_mode = property(get_acceleration_in_triggered_mode,
set_acceleration_in_triggered_mode,
doc="Acceleration in triggered mode in mm/s")
def get_low_limit(self):
"""end of travel in negative direction in mm"""
reply = self.query("Low limit?")
if reply.find("The low limit is ") != 0: return nan
try: return float(reply.strip("The low limit is mm."))
except ValueError: return nan
def set_low_limit(self,value):
self.query("Set the low limit to %.5f mm." % value)
low_limit = property(get_low_limit,set_low_limit)
def get_high_limit(self):
"""end of travel in positive direction in mm"""
reply = self.query("High limit?")
if reply.find("The high limit is ") != 0: return nan
try: return float(reply.strip("The high limit is mm."))
except ValueError: return nan
def set_high_limit(self,value):
self.query("Set the high limit to %.5f mm." % value)
high_limit = property(get_high_limit,set_high_limit)
def get_limits(self):
"""travel range in mm"""
return self.low_limit,self.high_limit
def set_limits(self,limits):
self.low_limit = limits[0]
self.high_limit = limits[1]
limits = property(get_limits,set_limits)
def get_trigger_count(self):
"""Number if trigger pulses detected"""
reply = self.query("Trigger count?")
if reply.find("The trigger count is ") != 0: return nan
try: return int(reply.strip("The trigger count is."))
except ValueError: return nan
def set_trigger_count(self,value):
self.query("Trigger count %d." % value)
trigger_count = property(get_trigger_count,set_trigger_count,
doc="""Number if trigger pulses detected""")
def get_step_count(self):
"""Number of triggered motions executed"""
reply = self.query("Step count?")
if reply.find("The step count is ") != 0: return nan
try: return int(reply.strip("The step count is."))
except ValueError: return nan
def set_step_count(self,value):
self.query("Step count %d." % value)
step_count = property(get_step_count,set_step_count,
doc="""Number of triggered motions executed.""")
def save_parameters(self):
"""Saves start position, end position and stepsize in the non-
volatile memory of the controller as defaults."""
self.query("Save parameters.")
def get_firmware_version(self):
reply = self.query("Software version?")
version = reply.strip("Software version is .")
return version
firmware_version = property(get_firmware_version,
doc="""Release number of software running on motion controller""")
def get_status(self):
"""Informational message for diagnostics."""
# Is connection still active?
if self.connection != None:
try: self.connection.getpeername()
except Exception: self.connection = None
if self.connection == None:
self.connection = socket.socket()
self.connection.settimeout(1)
try: self.connection.connect((self.ip_address,self.port))
except socket.gaierror:
self.connection = None
return "IP address '%s' does not exist." % self.ip_address
except socket.timeout:
self.connection = None
return "unresponsive"
except socket.error:
self.connection = None
return "Is %d the correct port number?" % self.port
except Exception,message:
self.connection = None
return "connect: %s" % message
try: self.connection.sendall("Software version?\n")
except socket.timeout:
return "timed out"
except Exception,message:
self.connection = None
return "send: %s" % message
self.log("send %r" % "Software version?\n")
reply = ""
self.connection.settimeout(1)
try: received = self.connection.recv(1024)
except socket.timeout:
self.connection = None
return "Is server program running on controller?"
except Exception,message:
self.connection = None
return "receive %s" % message
reply += received
self.connection.settimeout(0.05)
while len(received) > 0:
try: received = self.connection.recv(1024)
except socket.timeout: received = ""
reply += received
reply = reply.strip("\n")
self.log("recv %r" % reply)
return "OK"
status = property(get_status)
def update(self):
"""Update the step size and travel range for the current temperature"""
self.controller_start_position = self.start_position
self.controller_end_position = self.end_position
self.controller_stepsize = self.stepsize
self.controller_acceleration = self.acceleration
self.controller_auto_reverse = self.auto_reverse
def get_start_position(self):
"""Amplitude of motion executed on external trigger"""
if not self.temperature_correction: return self.normal_start_position
else: return self.temperature_corrected_start_position
def set_start_position(self,value):
if not self.temperature_correction: self.normal_start_position = value
else: self.temperature_corrected_start_position = value
start_position = property(get_start_position,set_start_position)
def get_end_position(self):
"""Amplitude of motion executed on external trigger"""
if not self.temperature_correction: return self.normal_end_position
else: return self.temperature_corrected_end_position
def set_end_position(self,value):
if not self.temperature_correction: self.normal_end_position = value
else: self.temperature_corrected_end_position = value
end_position = property(get_end_position,set_end_position)
def get_travel(self):
"""On exernal trigger, the stage is stepping between these two
positions. (start,end) tuple"""
return self.start_position,self.end_position
def set_travel(self,(start,end)):
self.start_position,self.end_position = start,end
travel = property(get_travel,set_travel)
def get_stepsize(self):
"""Amplitude of motion executed on external trigger"""
if self.steps == 0: return 0.2
if self.end_position == self.start_position: return 0.2
return (self.end_position-self.start_position)/self.steps
def set_stepsize(self,stepsize):
from numpy import isnan,floor
if isnan(stepsize): return
if stepsize == 0: return
self.steps = floor((self.end_position-self.start_position)/stepsize)
stepsize = property(get_stepsize,set_stepsize)
def get_home_position(self):
"""Used for setup and alignment"""
try: return float(dbget("sample_translation/home"))
except ValueError: return 0.0
def set_home_position(self,value):
dbput("sample_translation/home",repr(value))
home_position = property(get_home_position,set_home_position)
def get_park_position(self):
"""Predefined position used for data collection"""
try: return float(dbget("sample_translation/park"))
except ValueError: return -12.5
def set_park_position(self,value):
dbput("sample_translation/park",repr(value))
park_position = property(get_park_position,set_park_position)
def get_normal_start_position(self):
"""Start position at calibration temperature"""
try: return float(dbget("sample_translation/start_position"))
except ValueError: return -2.0
def set_normal_start_position(self,value):
dbput("sample_translation/start_position",repr(value))
normal_start_position = property(get_normal_start_position,
set_normal_start_position)
def get_normal_end_position(self):
"""Start position at calibration temperature"""
try: return float(dbget("sample_translation/end_position"))
except ValueError: return 10.0
def set_normal_end_position(self,value):
dbput("sample_translation/end_position",repr(value))
normal_end_position = property(get_normal_end_position,
set_normal_end_position)
def get_acceleration(self):
"""Acceleration in non-triggered mode in mm/s"""
try: return float(dbget("sample_translation/acceleration"))
except ValueError: return 1372.8
def set_acceleration(self,value):
dbput("sample_translation/acceleration",repr(value))
acceleration = property(get_acceleration,set_acceleration)
def get_steps(self):
"""Start position at calibration temperature"""
try: return int(dbget("sample_translation/steps"))
except ValueError: return 50
def set_steps(self,value):
from numpy import rint
value = int(rint(value))
dbput("sample_translation/steps",repr(value))
steps = nsteps = property(get_steps,set_steps)
def get_auto_reverse(self):
try: return bool(int(dbget("sample_translation/auto_reverse")))
except ValueError: return False
def set_auto_reverse(self,value):
dbput("sample_translation/auto_reverse",repr(int(value)))
auto_reverse = property(get_auto_reverse,set_auto_reverse)
def get_move_when_idle(self):
"""Keep moving te stage when not triggered"""
try: return bool(int(dbget("sample_translation/move_when_idle")))
except ValueError: return False
def set_move_when_idle(self,value):
dbput("sample_translation/move_when_idle",repr(int(value)))
move_when_idle = property(get_move_when_idle,set_move_when_idle)
def get_temperature_correction(self):
"""Use temperatrue to adjust start and end position and stepsize?"""
try: return bool(int(dbget("sample_translation/temperature_correction")))
except ValueError: return False
def set_temperature_correction(self,value):
dbput("sample_translation/temperature_correction",repr(int(value)))
temperature_correction = property(get_temperature_correction,
set_temperature_correction)
def get_calibration_temperature_1(self):
"""Temperature at which 'calibrated stepsize' and
'calibrated starting position' are the actual stepsize and starting
positions"""
try: return float(dbget("sample_translation/calibration_temperature_1"))
except ValueError: return 20.0
def set_calibration_temperature_1(self,value):
dbput("sample_translation/calibration_temperature_1",repr(value))
calibration_temperature_1 = property(get_calibration_temperature_1,
set_calibration_temperature_1)
def get_calibrated_start_position_1(self):
"""Start position at calibration temperature"""
try: return float(dbget("sample_translation/calibrated_start_position_1"))
except ValueError: return -2.0
def set_calibrated_start_position_1(self,value):
dbput("sample_translation/calibrated_start_position_1",repr(value))
calibrated_start_position_1 = property(get_calibrated_start_position_1,
set_calibrated_start_position_1)
def get_calibrated_end_position_1(self):
"""Start position at calibration temperature"""
try: return float(dbget("sample_translation/calibrated_end_position_1"))
except ValueError: return 10.0
def set_calibrated_end_position_1(self,value):
dbput("sample_translation/calibrated_end_position_1",repr(value))
calibrated_end_position_1 = property(get_calibrated_end_position_1,
set_calibrated_end_position_1)
def get_calibration_temperature_2(self):
"""Temperature at which 'calibrated stepsize' and
'calibrated starting position' are the actual stepsize and starting
positions"""
try: return float(dbget("sample_translation/calibration_temperature_2"))
except ValueError: return 40.0
def set_calibration_temperature_2(self,value):
dbput("sample_translation/calibration_temperature_2",repr(value))
calibration_temperature_2 = property(get_calibration_temperature_2,
set_calibration_temperature_2)
def get_calibrated_start_position_2(self):
"""Start position at calibration temperature"""
try: return float(dbget("sample_translation/calibrated_start_position_2"))
except ValueError: return -2.0
def set_calibrated_start_position_2(self,value):
dbput("sample_translation/calibrated_start_position_2",repr(value))
calibrated_start_position_2 = property(get_calibrated_start_position_2,
set_calibrated_start_position_2)
def get_calibrated_end_position_2(self):
"""Start position at calibration temperature"""
try: return float(dbget("sample_translation/calibrated_end_position_2"))
except ValueError: return 10.0
def set_calibrated_end_position_2(self,value):
dbput("sample_translation/calibrated_end_position_2",repr(value))
calibrated_end_position_2 = property(get_calibrated_end_position_2,
set_calibrated_end_position_2)
def get_temperature(self):
"""In degrees Celsius. Measured by temperature controller"""
from temperature_controller import temperature_controller
# Use the set point for reproducebilty rather than te measured
# temperature.
return temperature_controller.setT.value
def set_temperature(self,value):
from temperature_controller import temperature_controller
temperature_controller.setT.value = value
temperature = property(get_temperature,set_temperature)
def get_temperature_corrected_start_position(self):
"""Interpolated start_position for the current temperature"""
T = self.temperature
T1,T2 = self.calibration_temperature_1,self.calibration_temperature_2
x1,x2 = self.calibrated_start_position_1,self.calibrated_start_position_2
x = x1+(x2-x1)/(T2-T1)*(T-T1)
return x
def set_temperature_corrected_start_position(self,x):
offset = x - self.temperature_corrected_start_position
self.calibrated_start_position_1 += offset
self.calibrated_start_position_2 += offset
temperature_corrected_start_position = property(
get_temperature_corrected_start_position,
set_temperature_corrected_start_position)
def get_temperature_corrected_end_position(self):
"""Interpolated start_position for the current temperature"""
T = self.temperature
T1,T2 = self.calibration_temperature_1,self.calibration_temperature_2
x1,x2 = self.calibrated_end_position_1,self.calibrated_end_position_2
x = x1+(x2-x1)/(T2-T1)*(T-T1)
return x
def set_temperature_corrected_end_position(self,x):
offset = x - self.temperature_corrected_end_position
self.calibrated_end_position_1 += offset
self.calibrated_end_position_2 += offset
temperature_corrected_end_position = property(
get_temperature_corrected_end_position,
set_temperature_corrected_end_position)
def log_error(self,message):
"""For error messages.
Display the message and append it to the error log file.
If verbose logging is enabled, it is also added to the transcript."""
from sys import stderr
if len(message) == 0 or message[-1] != "\n": message += "\n"
t = timestamp()
file(self.error_logfile,"a").write("%s: %s" % (t,message))
##stderr.write("%s: %s: %s" % (t,self.ip_address,message))
##self.log(message)
def get_error_logfile(self):
"""File name error messages."""
from tempfile import gettempdir
return gettempdir()+"/sample_translation_error.log"
error_logfile = property(get_error_logfile)
def log(self,message):
"""For non-critical messages.
Append the message to the transcript, if verbose logging is enabled."""
if not self.verbose_logging: return
if len(message) == 0 or message[-1] != "\n": message += "\n"
t = timestamp()
file(self.logfile,"a").write("%s: %s" % (t,message))
def get_logfile(self):
"""File name for transcript if verbose logging is enabled."""
from tempfile import gettempdir
return gettempdir()+"/sample_translation.log"
logfile = property(get_logfile)
def timestamp():
"""Current date and time as formatted ASCII text, precise to 1 ms"""
from datetime import datetime
timestamp = str(datetime.now())
return timestamp[:-3] # omit microsconds
sample_stage = SampleStage()
cancelled = True # to top "run_test"
delay_time = 2.5 # to simulate detector readout
repeat_count = 4 # number of strokes before delay
def run_test():
"""Stand-alone operation simulating Lauecollect"""
from id14 import transon,tmode,waitt,pulses,mson,laseron
from time import sleep,time
from numpy import rint
global cancelled; cancelled = False
# Make sure laser and X-ray are not firing
old_laseron = laseron.value; old_mson = mson.value; old_tmode = tmode.value
laseron.value = False; mson.value = False
tmode.value = 1 # counted
transon.value = 1 # Tell FPGA to output trigger pulses for stage.
sample_stage.trigger_enabled = True
sample_stage.step_count = 0
while not cancelled:
sample_stage.timer_enabled = False
for repeat in range(0,repeat_count):
sample_stage.position = sample_stage.start_position
sample_stage.update()
while sample_stage.moving: sleep(0.05)
pulses.value = sample_stage.nsteps+1 # Start triggering
wait_time = sample_stage.nsteps*waitt.value + sample_stage.return_time
t0 = time()
while time()-t0 < wait_time and not cancelled: sleep(0.02)
# Either keep moving or park the stage.
if delay_time > 0:
if sample_stage.move_when_idle: sample_stage.timer_enabled = True
else: sample_stage.position = sample_stage.park_position
# Simulate delay for detector readout.
t0 = time()
while time()-t0 < delay_time and not cancelled: sleep(0.02)
sample_stage.trigger_enabled = False
pulses.value = 0
sample_stage.position = sample_stage.park_position
laseron.value = old_laseron; mson.value = old_mson; tmode.value = old_tmode
def start_test():
"""Start stand-alone operation simlating Lauecollect"""
global cancelled
cancelled = False
from thread import start_new_thread
start_new_thread(run_test,())
def stop_test():
"""Stop stand-alone operation simlating Lauecollect"""
global cancelled
cancelled = True
def test_running():
return not cancelled
if __name__ == '__main__': # test program
from pdb import pm
import logging
##logging.basicConfig(level=logging.DEBUG,format="%(asctime)s: %(message)s")
self = sample_stage
<file_sep>"""
Optical Freeze detector agent
Authors: <NAME>
Date created: 26 Feb 2018
Date last modified: 25 May 2018
-added retract -> iglobal =1 -> insert sequence that waits for previous one
to be executed first
"""
__version__ = "1.7"
from CAServer import casput,casdel, casget
from CA import caget
from datetime import datetime
from thread import start_new_thread
from pdb import pm
import os
from Ensemble_client import ensemble
from time import sleep,time
from thread import start_new_thread
from persistent_property import persistent_property
from temperature_controller import temperature_controller
from logging import debug,info,warn,error
if __name__ == "__main__":
pass
<file_sep>title = "Timing System Configuration"
icon = "timing-system"
EPICS_Record.value = 'timing_system.prefix'
EPICS_Record.properties = {
'Enabled': 'True',
'Items': 'timing_system.prefixes',
}
IP_Address.properties = {
'Enabled': 'False',
'Value': '"Address "+timing_system.ip_address if timing_system.ip_address else "offline"',
}
Configuration.value = 'timing_system.configuration'
Configuration.properties = {
'Enabled': 'timing_system.online',
'Items': 'timing_system.configurations',
}
Load.action = {
True: 'timing_system.load_configuration()'
}
##Load.value = 'timing_system.save_configuration()'
Load.properties = {
'Enabled': 'timing_system.online',
'Label': '"Load Configuration"',
}
Save.action = {
True: 'timing_system.save_configuration()'
}
##Save.value = 'timing_system.save_configuration()'
Save.properties = {
'Enabled': 'timing_system.online',
'Label': '"Save Configuration"',
}
<file_sep>#!/usr/bin/env python
from Timing_Panel import *
if __name__ == '__main__':
import Timing_Panel as module
from inspect import getfile
file = getfile(module).replace(".pyc",".py")
execfile(file)
<file_sep>"""Client-side interface for Temperature System Level (SL) Server
Capabilities:
- Time-based Temperature ramping
Authors: <NAME>, <NAME>
Date created: 2019-05-08
Date last modified: 2019-05-31
"""
__version__ = "1.3" # added monitor,monitor_clear
from logging import debug,warn,info,error
from EPICS_motor import EPICS_motor
class Temperature(EPICS_motor):
"""Temperature System Level (SL)"""
from PV_property_client import PV_property_client
from PV_property import PV_property
time_points = PV_property("time_points",[])
temp_points = PV_property("temp_points",[])
P_default = PV_property_client("P_default",0.0)
I_default = PV_property_client("I_default",0.0)
D_default = PV_property_client("D_default",0.0)
lightwave_prefix = PV_property_client("lightwave_prefix",'')
T_threshold = PV_property_client("temperature_oasis_switch",0.0)
idle_temperature_oasis = PV_property_client("idle_temperature_oasis",0.0)
temperature_oasis_limit_high = PV_property_client("temperature_oasis_limit_high",0.0)
oasis_headstart_time = PV_property_client("oasis_headstart_time",0.0)
oasis_prefix = PV_property_client("oasis_prefix",'')
oasis_slave = PV_property_client("oasis_slave",0.0)
def monitor(self,callback,new_thread=True):
"""Have the routine 'callback' be called every the time value
of the PV changes.
callback: function that takes three parameters:
PV_name, value, char_value
"""
from CA import camonitor
camonitor(self.prefix+".RBV",callback=callback,new_thread=new_thread)
def monitor_clear(self,callback=None):
"""Undo 'monitor'."""
from CA import camonitor_clear
camonitor_clear(self.prefix+".RBV",callback=callback)
@property
def name(self): return self.prefix+".RBV"
temperature = Temperature(prefix="NIH:TEMP",name="temperature")
if __name__ == "__main__":
import logging
logging.basicConfig(level=logging.DEBUG,
format="%(asctime)s %(levelname)s %(module)s.%(funcName)s: %(message)s",
)
from collect import collect
print('collect.temperature_start()')
print('collect.temperature_stop()')
print('')
from numpy import nan
print('temperature.VAL = %r' % temperature.VAL)
print('temperature.RBV = %r' % temperature.RBV)
print('temperature.time_points = %r' % temperature.time_points)
print('temperature.temp_points = %r' % temperature.temp_points)
print('')
print('temperature.P_default = %r' % temperature.P_default)
print('')
from timing_sequencer import timing_sequencer
print("timing_sequencer.queue_active = %r" % timing_sequencer.queue_active)
print("timing_sequencer.queue_active = False # cancel acquistion")
print("timing_sequencer.queue_repeat_count = 0 # restart acquistion")
print("timing_sequencer.queue_active = True # simulate acquistion")
print ('')
def callback(PV_name,value,string_value): info("%s=%r" % (PV_name,value))
print ('temperature.monitor(callback)')
self = temperature # for debugging
<file_sep>title = 'Test Bench Camera'
zoom_level = 1.0<file_sep>#!/usr/bin/env python
# <NAME>, 1 Oct 2014 - 6 Jul 2017
from inspect import getfile
from os.path import dirname
def f(): pass
dir=dirname(getfile(f))
if dir == "": dir = "."
execfile(dir+"/MicroscopeCamera.py")
<file_sep>"""Delay line linearity characterization
<NAME>, Jul 22, 2015 - Apr 27, 2015
Setup:
Ramsay-100B RF Generator, 351.93398 MHz +10 dBm -> FPGA RF IN
FPGA 1: X-scope trig -> CH1, DC50, 500 mV/div
FPGA 13: ps L oscill -> DC block -> 90-MHz low-pass -> CH2, DC50, 500 mV/div
Timebase 5 ns/div
Measurement P1 CH2, time@level, Absolute, 0, Slope Pos, Gate Start 4.5 div,
Stop 5.5 div
Waitting time: 97.8 ms
"""
__version__ = "3.4"
from instrumentation import timing_system,timing_sequencer,round_next
from instrumentation import actual_delay,lecroy_scope
from LokToClock import LokToClock
from timing_sequence import lxd,Sequence
from scan import rscan,timescan as tscan
from motor_wrapper import motor_wrapper
from sleep import sleep
from numpy import arange
locked = motor_wrapper(LokToClock,"locked")
clk_shift_count = motor_wrapper(timing_system.clk_shift,"count")
delay = actual_delay
dt = timing_system.clk_shift.stepsize*32
tmax = round_next(5*timing_system.bct,dt)
nsteps = tmax/dt
def scan():
tmax = round_next(5*timing_system.bct,dt)
nsteps = tmax/dt
lxd.value = 0
data = rscan([lxd,locked],[0,1],[tmax,1],nsteps,[clk_shift_count,delay],
averaging_time=1.0,logfile="logfiles/scan.log")
def scan_delayline():
tmax = timing_system.clk_shift.max_dial
nsteps = tmax/dt
timing_sequencer.running = False
timing_system.xosct.enable.count = 1
timing_system.clk_shift.dial = 0
data = rscan([timing_system.clk_shift,delay.gate.start,delay.gate.stop],
[0,0,0],[tmax,tmax,tmax],nsteps,[clk_shift_count,delay],
averaging_time=10.0,logfile="logfiles/scan_delayline.log")
def timescan():
data = tscan(delay,averaging_time=10.0,logfile="logfiles/timescan.log")
def register_counts():
trange = arange(0,tmax,tmax/50)
pso = [Sequence(ps_lxd=t).register_counts[1][16][0] for t in trange]
clk_shift = [Sequence(ps_lxd=t).register_counts[1][17][0] for t in trange]
return pso,clk_shift
def reset_dcm():
timing_system.clk_shift_reset.count = 1
sleep(0.2)
timing_system.clk_shift_reset.count = 0
def peridiocally_reset_dcm(wait_time=60):
while True:
try:
reset_dcm()
sleep(wait_time)
except KeyboardInterrupt:
timing_system.clk_shift_reset.count = 0
break
if __name__ == "__main__":
print('timing_system.ip_address = %r' % timing_system.ip_address)
print('delay.scope.ip_address = %r' % delay.scope.ip_address)
print('reset_dcm()')
print('scan_delayline()')
print('scan()')
<file_sep>"""marccd decoding. <NAME>, Jan 24 2015
HS High Speed Series X-ray Detector Manual by <NAME> and <NAME>
Rayonix_HS_detector_manual-0.3a.pdf
"""
__version__ = "1.0"
def read_mccd(filename):
"""read mccd file and get data"""
import mmap
with open(filename,"rb") as f:
# try to map to reduce any overhead to read file.
content = mmap.mmap(f.fileno(),0,prot=mmap.ACCESS_READ) #PROT_READ) #2048+512
f.close()
#content = file(filename,"rb").read()
fileparam_offset = content.find("MarCCD X-ray Image File")
fileparam = content[fileparam_offset:fileparam_offset+1024]
detectorparam_offset = fileparam_offset-256 #
head_offset = 1024
#print fileparam_offset, detectorparam_offset, head_offset
detectorparam = content[detectorparam_offset:detectorparam_offset+128]
headparam = content[head_offset:head_offset+256]
data = content[4096:]
from struct import unpack
head_nfast, = unpack("i",headparam[80:84])
head_nslow, = unpack("i",headparam[84:88])
#print head_nfast, head_nslow
detector_type, = unpack("i",detectorparam[0:4])
pixelsize_x, = unpack("i",detectorparam[4:8])
pixelsize_y, = unpack("i",detectorparam[8:12])
from numpy import frombuffer,int16
data = frombuffer(data,int16)
data = data.reshape((head_nfast,head_nslow))
return data
def timestamp_mccd(filename):
"""read mccd file and decode information"""
import mmap
with open(filename,"rb") as f:
# try to map to reduce any overhead to read file.
content = mmap.mmap(f.fileno(),0,prot=mmap.ACCESS_READ) #PROT_READ) #2048+512
f.close()
fileparam_offset = content.find("MarCCD X-ray Image File")
fileparam = content[fileparam_offset:fileparam_offset+1024]
from struct import unpack
acquire_timestamp = fileparam[320:352]
header_timestamp = fileparam[352:384]
save_timestamp = fileparam[384:416]
months = int(acquire_timestamp[:2])
days = int(acquire_timestamp[2:4])
hours = int(acquire_timestamp[4:6])
mins = int(acquire_timestamp[6:8])
year = int(acquire_timestamp[8:12])
seconds = int(acquire_timestamp[13:15])
# old version rayonix mccd file on before Feb 6 2015 does not have microseconds
try:
microseconds = int(acquire_timestamp[16:22])
except ValueError: microseconds = 0
from datetime import datetime
date_time = datetime(year,months,days,hours,mins,seconds,microseconds)
#print date_time
#ts_format = date_time.strftime("%d-%b-%y %H:%M:%S.%f")
ts = toseconds(date_time)
return ts
def toseconds(dt):
"""convert datetime format (dt) to seconds"""
import datetime
from time import mktime
return mktime(dt.timetuple()) + dt.microsecond*1.e-6
def todatetime(ts):
import datetime
return datetime.datetime.fromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S.%f')
if __name__ == "__main__": # for testing
#filename = "/Mirror/Femto/C/Data/2014.08/Setup/Beamstop/3mm/Sapphire_3mm_24bunch_001.mccd"
#filename = "/Mirror/Femto/C/Data/2014.03/WAXS/GB3/GB3-1/GB3-1_offBT1_003.mccd"
#filename = "/Volumes/data-1/pub/rob/testing/testing.mccd"
filename = "/data/anfinrud_1502/Data/WAXS/Reference/Reference1/Reference1_offWT1_100.mccd"
#filename = "/data/anfinrud_1502/Test/Test19/Test19_64.mccd"
ts = timestamp_mccd(filename)
data = read_mccd(filename)
print "%6f" % ts
<file_sep>from Ensemble_SAXS_pp import Ensemble_SAXS, Sequence, Sequences
<file_sep>#!/usr/bin/env python
"""Rayonix detector control panel for continuous operation
Author: <NAME>
Date created: 2017-05-10
Date last modified: 2019-06-02
"""
from rayonix_detector_client import rayonix_detector
from Panel import BasePanel,PropertyPanel,ButtonPanel,TogglePanel,TweakPanel
import wx
from numpy import inf
__version__ = "3.4" # Do not disable down temp file cleanup on close
class Rayonix_Detector_Panel(BasePanel):
name = "Rayonix_Detector_Panel"
title = "Rayonix Detector [new]"
standard_view = [
"Acquisition",
"X-ray detector image count",
"Image",
"Images left to save",
"Scratch directory",
"Bin factor",
"Server IP Address",
"Detector IP Address",
]
dirs = ["/net/mx340hs/data/tmp","/net/femto-data/C/Data/tmp","//femto-data/C/Data/tmp",
"/Mirror/femto-data/C/Data/tmp"]
server_ip_address_choices = [
"localhost:2223",
"id14b4.cars.aps.anl.gov:2223",
"pico5.cars.aps.anl.gov:2223",
"pico5.niddk.nih.gov:2223",
"pico8.niddk.nih.gov:2223",
"pico20.niddk.nih.gov:2223",
]
detector_ip_address_choices = [
"mx340hs.cars.aps.anl.gov:2222",
"pico5.cars.aps.anl.gov:2222",
"localhost:2222",
"pico5.niddk.nih.gov:2222",
"pico8.niddk.nih.gov:2222",
"pico20.niddk.nih.gov:2222",
]
parameters = [
[[PropertyPanel,"Status",rayonix_detector,"online"],{"type":"Offline/Online","read_only":True,"refresh_period":1.0}],
[[TogglePanel, "Acquisition",rayonix_detector,"acquiring"],{"type":"Start/Cancel","refresh_period":1.0}],
[[PropertyPanel,"X-ray detector image count",rayonix_detector,"last_image_number"],{"refresh_period":0.25}],
[[PropertyPanel,"Image",rayonix_detector,"current_image_basename"],{"read_only":True,"refresh_period":1.0}],
[[PropertyPanel,"Images left to save",rayonix_detector,"nimages"],{"read_only":True,"refresh_period":1.0}],
[[PropertyPanel,"Scratch image",rayonix_detector,"last_filename"],{"read_only":True,"refresh_period":1.0}],
[[PropertyPanel,"Bin factor",rayonix_detector,"bin_factor"],{"choices":[1,2,3,4,5,6,8],"refresh_period":1.0}],
[[PropertyPanel,"Scratch directory",rayonix_detector,"scratch_directory"],{"choices":dirs,"refresh_period":1.0}],
[[PropertyPanel,"Images to keep",rayonix_detector,"nimages_to_keep"],{"choices":[3,5,10,20],"refresh_period":1.0}],
[[PropertyPanel,"Server IP address",rayonix_detector,"ip_address"],{"choices":server_ip_address_choices,"refresh_period":1.0}],
[[PropertyPanel,"Detector IP address",rayonix_detector,"detector_ip_address"],{"choices":detector_ip_address_choices,"refresh_period":1.0}],
[[PropertyPanel,"Timing mode",rayonix_detector,"timing_mode"],{"choices":rayonix_detector.timing_modes,"refresh_period":1.0}],
[[PropertyPanel,"ADXV live image",rayonix_detector,"ADXV_live_image"],{"type":"Off/On","refresh_period":1.0}],
[[PropertyPanel,"Live image",rayonix_detector,"live_image"],{"type":"Off/On","refresh_period":1.0}],
[[PropertyPanel,"Limit images to keep",rayonix_detector,"limit_files_enabled"],{"type":"Off/On","refresh_period":1.0}],
[[PropertyPanel,"Auto-start",rayonix_detector,"auto_start"],{"type":"Off/On","refresh_period":1.0}],
]
def __init__(self,parent=None):
BasePanel.__init__(self,
parent=parent,
name=self.name,
title=self.title,
icon="Rayonix Detector",
parameters=self.parameters,
standard_view=self.standard_view,
label_width=180,
refresh=False,
live=False,
)
self.Bind(wx.EVT_CLOSE,self.OnClose)
rayonix_detector.limit_files_enabled = True
if __name__ == '__main__':
from pdb import pm # for debugging
from redirect import redirect
redirect("Rayonix_Detector_Panel",level="INFO")
import wx
app = wx.App(redirect=False)
panel = Rayonix_Detector_Panel()
app.MainLoop()
<file_sep>#!/bin/env python
"""Setup: source /reg/g/psdm/etc/ana_env.sh"""
import zmq
import numpy as np
from time import sleep
context = zmq.Context()
socket = context.socket(zmq.PUB)
socket.bind("tcp://*:12300")
arr = np.zeros([512,512])
i = 0
while True:
print i
socket.send('rayonix',zmq.SNDMORE)
socket.send_pyobj(i,zmq.SNDMORE)
socket.send_pyobj(arr)
i += 1
arr += 1
sleep(1)
<file_sep>#!/usr/bin/env python
"""
Grapical User Interface for FPGA Timing System.
Author: <NAME>
Date created: 2019-03-26
Date last modified: 2019-03-26
"""
__version__ = "1.0"
from logging import debug,info,warn,error
from SavedPositionsPanel_2 import SavedPositionsPanel
class PP_Modes_Panel(SavedPositionsPanel):
name = "timing_modes"
if __name__ == '__main__':
from pdb import pm # for debugging
from redirect import redirect
redirect("PP_Modes_Panel")
import wx
app = wx.App(redirect=False)
panel = PP_Modes_Panel()
app.MainLoop()
<file_sep>import time
import zmq
import numpy as np
context = zmq.Context()
sender = context.socket(zmq.PUSH)
sender.connect("tcp://127.0.0.1:12321")
arr = np.zeros([512,512])
for num in range(1000):
sender.send_pyobj(arr)
arr+=1
time.sleep(1)
<file_sep>CH2.temperature.filename = '//mx340hs/data/anfinrud_1903/Archive/NIH.DI245.CH2.temperature.txt'
CH4.temperature.filename = '//mx340hs/data/anfinrud_1903/Archive/NIH.DI245.CH4.temperature.txt'
pressure_upstream.filename = '//mx340hs/data/anfinrud_1906/Archive/NIH.DI245.pressure_upstream.txt'
pressure_downstream.filename = '//mx340hs/data/anfinrud_1906/Archive/NIH.DI245.pressure_downstream.txt'
temperature_hutch.filename = '//mx340hs/data/anfinrud_1906/Archive/NIH.DI245.temperature_hutch.txt'
pressure_barometric.filename = '/net/mx340hs/data/anfinrud_1906/Archive/NIH.DI245.pressure_barometric.txt'<file_sep>import wx
app = wx.App()
window = wx.Frame(None, title = "wxPython Frame", size = (300,200))
panel = wx.Panel(window)
label = wx.StaticText(panel, label = "<NAME>", pos = (100,50))
window.Show(True)
app.MainLoop()
<file_sep>"""
Motorized variable neutral density filter to control the laser power
for power titration experiments.
This attunator is controlled by a Thorlabs Z612 actuator. A circulator
gardient filter is mounter directly only the lead screw to rotate the
filter. With a screw pitch of 0.5 mm, 0.5 mm of linear translation corresponds
to 360 deg of rotation.
<NAME>, 22 Feb 2008 - 27 Oct 2016
"""
__version__ = "1.5.1" # motor name
from math import log10
nan = 1e1000/1e1000 # Not a Number
def isnan(x): return x!=x
class variable_attenuator(object):
"""Motorized variable neutral density filter for controling the laser power
for power titration experiments.
"""
def __init__(self,motor,OD_range=[0,2.66],motor_range=[15,345],
motor_min=None,OD_min=None,motor_max=None,OD_max=None):
"""'motor' is motor controlled by an EPICS motor record
'motor_range=[15,345]',OD_range=[0,2.66]' means that
The attenuation varies from 0 to 2.66 (2.7-0.04) over a range of 330 deg,
which starts at 15 deg.
"""
self.motor = motor
self.unit = ""
self.motor_range = motor_range
self.OD_range = OD_range
if motor_min == None: self.motor_min = motor_range[0]
if motor_max == None: self.motor_max = motor_range[1]
if OD_min == None: self.OD_min = OD_range[0]
if OD_max == None: self.OD_max = OD_range[1]
def get_value(self):
"""Calculates the transmission from the motor position"""
return self.transmission(self.motor.value)
def set_value(self,transmission):
"""Rotates the filter to a new orienation, based on the desired
transmission"""
position = self.position_of_transmission(transmission)
if position != self.motor.command_value: self.motor.value = position
value = property(fset=set_value,fget=get_value,
doc="transmission of filter, range 0 to 1")
def get_angle(self):
"Motor position"
return self.motor.value
def set_angle(self,position):
"Drives the motor to a new position"
self.motor.value = position
angle = property(get_angle,set_angle,doc="Orientation of wheel")
position = property(get_angle,set_angle,doc="same as angle")
def transmission(self,position):
"""Calculates the transmission from the motor position in mm"""
if isnan(position): return nan
if position == self.motor_max: return pow(10,-self.OD_max)
if position == self.motor_min: return pow(10,-self.OD_min)
pmin = self.motor_range[0]; pmax = self.motor_range[1]
# Assume the transmission is flat outside the angular range
if position < min(pmin,pmax): position = min(pmin,pmax)
if position > max(pmin,pmax): position = max(pmin,pmax)
# Inside the angular range, assume that there is a linear gradient of OD
OD = self.OD_range[0] + (position-pmin)/(pmax-pmin)*self.OD_range[1]
transmission = pow(10,-OD)
return transmission
def position_of_transmission(self,transmission):
"""Calculates the motor position in mm for a desired transmission"""
if transmission <= 0: transmission = 1e-6
OD = -log10(transmission)
if OD >= self.OD_max: return self.motor_max
if OD <= self.OD_min: return self.motor_min
pmin = self.motor_range[0]; pmax = self.motor_range[1]
position = pmin + (OD-self.OD_range[0])/self.OD_range[1]*(pmax-pmin)
# Assume the transmission is flat outside the angular range
if position < min(pmin,pmax): position = min(pmin,pmax)
if position > max(pmin,pmax): position = max(pmin,pmax)
return position
def set_moving(self,value): self.motor.moving = value
moving = property(lambda self: self.motor.moving,set_moving,
doc="Is filter currently moving?")
def __repr__(self):
return "variable_attenuator(%r,OD_range=[%g,%g],motor_range=[%g,%g])" \
% (self.motor,self.OD_range[0],self.OD_range[1],
self.motor_range[0],self.motor_range[1])
if __name__ == "__main__": # for testing - remove when done
from EPICS_motor import motor # EPICS-controlled motors
# Laser beam attenuator wheel in 14ID-B X-ray hutch
VNFilter = motor("14IDB:m32",name="VNFilter")
VNFilter.readback_slop = 0.1 # [deg] otherwise Thorlabs motor gets hung in "Moving" state
VNFilter.min_step = 0.050 # [deg] otherwise Thorlabs motor gets hung in "Moving" state"
# This filter is mounted such that when the motor is homed (at 0) the
# attuation is minimal (OD 0.04) and increasing to 2.7 when the motor
# moves in positive direction.
# Based on measurements by <NAME> and <NAME>, made 7 Dec 2009
trans = variable_attenuator(VNFilter,motor_range=[5,285],OD_range=[0,2.66])
trans.motor_min=-5
trans.OD_min=0
trans.motor_max=300
trans.OD_max=2.66
# 14-ID Laser Lab
VNFilter1 = motor("14IDLL:m8",name="VNFilter1")
VNFilter1.readback_slop = 0.030 # otherwise Thorlabs motor gets hung in "Moving" state
VNFilter1.min_step = 0.030 # otherwise Thorlabs motor gets hung in "Moving" state"
# This filter is mounted such that when the motor is homed (at 0) the
# attuation is minimal (OD 0.04) and increasing to 2.7 when the motor
# moves in positive direction.
trans1 = variable_attenuator(VNFilter1,motor_range=[15,295],OD_range=[0,2.66])
trans1.motor_min=0
trans1.OD_min=0
trans1.motor_max=315
trans1.OD_max=2.66
<file_sep>RBV.filename = '//mx340hs/data/anfinrud_1906/Archive/NIH.LIGHTWAVE.RBV.txt'
VAL.filename = '//mx340hs/data/anfinrud_1906/Archive/NIH.LIGHTWAVE.VAL.txt'
I.filename = '//Volumes/C/All Projects/APS/Experiments/2019.05/Test/Archive/NIH.LIGHTWAVE.I.txt'<file_sep>"""Simulate motors of 14-IDB beamline
Author: <NAME>,
Date created: 2016-06-25
Date last modified: 2019-05-26
"""
__version__ = "1.8" # Slit1H,Slit1V: readback
class sim_id14:
name = "sim_id14"
from sim_motor import sim_EPICS_motor as motor
from sim_safety_shutter import sim_EPICS_safety_shutter
current = motor("S:SRcurrentAI",name="current",description="Ring current")
sbcurrent = motor("BNCHI:BunchCurrentAI",name="sbcurrent",description="Bunch current")
# Undulators
U23 = motor("ID14ds:Gap",name="U23",description="U23 gap")
U27 = motor("ID14us:Gap",name="U27",description="U23 gap")
# Safety shutter
FE_shutter_enabled = motor("ACIS:ShutterPermit",
name="FE_shutter_enabled",description="Shutter 14IDA enabled")
ID14A_shutter = sim_EPICS_safety_shutter(
name="ID14A_shutter",
description="Shutter 14IDA",
command_value="14IDA:shutter_in1.VAL",
value="PA:14ID:STA_A_FES_OPEN_PL.VAL",
auto_open="14IDA:shutter_auto_enable1.VAL",
)
ID14A_shutter.IOC.transform_functions["command_value"] = lambda x:1-x,lambda x:1-x
# (old version)
ID14A_shutter_open = motor("PA:14ID:STA_A_FES_OPEN_PL",
name="ID14A_shutter_open",description="Shutter 14IDA open")
ID14A_shutter_auto = motor("14IDA:shutter_auto_enable1",
name="ID14A_shutter_auto",description="Shutter 14IDA auto")
# white beam slits (at 28 m)
Slit1H = motor("14IDA:Slit1Hsize",name="Slit1H",description="White beam slits H gap",
readback="14IDA:Slit1Ht2.C")
Slit1V = motor("14IDA:Slit1Vsize",name="Slit1V",description="White beam slits V gap",
readback="14IDA:Slit1Vt2.C")
# Heatload chopper
HLC = motor("14IDA:m5",name="HLC",description="Heatload chopper")
# Vertical deflecting mirror
# Incidence angle
mir1Th = motor("14IDC:mir1Th",name="mir1Th",description="Vert. mirror angle",unit="mrad")
# Piezo DAC voltage (0-10 V)
MirrorV = motor("14IDA:DAC1_4",name="MirrorV",description="Vert. beam stearing",unit="V")
mir1bender = motor("14IDC:m6",name="mir1bender",description="Vert. mirror bender")
# Horizontal deflecting mirror
# Upstream
mir2X1 = motor("14IDC:m12",name="mir2X1",description="Horiz. mirror jack 1")
# Downstream (distance 1.045 m)
mir2X2 = motor("14IDC:m13",name="mir2X2",description="Horiz. mirror jack 2")
mir2bender = motor("14IDC:m14",name="mir2bender",description="Horiz. mirror bender")
# Safety shutter
ID14C_shutter = sim_EPICS_safety_shutter(
name="ID14C_shutter",
description="Shutter 14IDC",
command_value="14IDA:shutter_in2.VAL",
value="PA:14ID:STA_B_SCS_OPEN_PL.VAL",
auto_open="14IDA:shutter_auto_enable2.VAL",
)
ID14C_shutter.IOC.transform_functions["command_value"] = lambda x:1-x,lambda x:1-x
# (old version)
ID14C_shutter_open = motor("PA:14ID:STA_B_SCS_OPEN_PL",
name="ID14C_shutter_open",description="Shutter 14IDC open")
ID14C_shutter_auto = motor("14IDA:shutter_auto_enable2",
name="ID14C_shutter_auto",description="Shutter 14IDC auto")
# JJ1 slits (upstream)
s1hg = motor("14IDC:m39",name="s1hg",description="JJ1 slits horiz. gap)")
s1ho = motor("14IDC:m40",name="s1ho",description="JJ1 slits horiz. offset")
s1vg = motor("14IDC:m37",name="s1vg",description="JJ1 slits vert. gap)")
s1vo = motor("14IDC:m38",name="s1vo",description="JJ1 slits vert. offset")
# High-speed X-ray Chopper
ChopX = motor("14IDB:m1",name="ChopX",description="High-speed chopper X")
ChopY = motor("14IDB:m2",name="ChopY",description="High-speed chopper Y")
# JJ2 Sample slits
shg = motor("14IDB:m25",name="shg",description="Sample slits horiz. gap")
sho = motor("14IDB:m26",name="sho",description="Sample slits horiz. offset")
svg = motor("14IDB:m27",name="svg",description="Sample slits vert. gap")
svo = motor("14IDB:m28",name="svo",description="Sample slits vert. offset")
# KB mirror
KB_Vpitch = motor("14IDC:pm4",name="KB_Vpitch", description="KB vert. pitch")
KB_Vheight = motor("14IDC:pm3",name="KB_Vheight", description="KB vert. height")
KB_Vcurvature = motor("14IDC:pm1",name="KB_Vcurvature",description="KB vert. curv.")
KB_Vstripe = motor("14IDC:m15",name="KB_Vstripe", description="KB vert. stripe")
KB_Hpitch = motor("14IDC:pm8",name="KB_Hpitch", description="KB horiz. pitch")
KB_Hheight = motor("14IDC:pm7",name="KB_Hheight", description="KB horiz. height")
KB_Hcurvature = motor("14IDC:pm5",name="KB_Hcurvature",description="KB horiz. curv.")
KB_Hstripe = motor("14IDC:m44",name="KB_Hstripe", description="KB horiz. stripe")
# Collimator
CollX = motor("14IDB:m35",name="CollX",description="Collimator X")
CollY = motor("14IDB:m36",name="CollY",description="Collimator Y")
# Alio diffractometer
GonX = motor("14IDB:m152",name="GonX",description="Alio X")
GonY = motor("14IDB:m153",name="GonY",description="Alio Y")
GonZ = motor("14IDB:m150",name="GonZ",description="Alio Z")
Phi = motor("14IDB:m151",name="Phi",description="Alio Phi")
# Sample-to-detector distance
DetZ = motor("14IDB:m3",name="DetZ",description="Detector distance")
# Laser safety shutter
laser_safety_shutter = sim_EPICS_safety_shutter(
name="laser_safety_shutter",
description="Laser Safety Shutter",
command_value="14IDB:lshutter.VAL",
value="14IDB:B1Bi0.VAL",
auto_open="14IDB:lshutter_auto.VAL",
)
laser_safety_shutter.IOC.transform_functions["value"] = lambda x:1-x,lambda x:1-x
# (old version)
laser_safety_shutter_open = motor("14IDB:B1Bi0",
name="laser_safety_shutter",description="Laser Safety Shutter")
laser_safety_shutter_auto = motor("14IDB:lshutter_auto",
name="laser_safety_shutter_auto",description="Laser Safety Shutter auto")
# Laser beam attenuator wheel in 14ID-B X-ray hutch
VNFilter = motor("14IDB:m32",name="VNFilter",description="Laser att. X-Ray hutch")
<file_sep>intervention_enabled = False
orientation = 'on-axis-h'
retracted_time = 15.0
scattering_threshold = 600
box_dimensions = 10
warning_threshold = 500.0
region_offset_x = 0
region_offset_y = 0
region_size_x = 10
region_size_y = 10<file_sep>#!/bin/env python
"""<NAME>, Jun 17, 2016 - Aug 14, 2017
"""
__version__ = "1.2.2" # Windows UNC pathnames, normpath
from logging import debug,info,warn,error
class Rayonix_Detector(object):
from persistent_property import persistent_property
bin_factor = persistent_property("bin_factor",2)
npixels = 7680
bkg_image_size = 0
external_trigger = persistent_property("external_trigger",False)
# Simulate trigger coming at this interval (in seconds).
nominal_trigger_period = persistent_property("nominal_trigger_period",1.0)
last_filename = ""
# listen port number of this server script
port = persistent_property("port",2222)
trigger_times = []
@property
def state(self):
if self.acquiring_series: return 0x02000000
return 0
@property
def image_size(self):
return self.npixels/self.bin_factor
def handle_trigger(self):
if self.acquiring_series:
if not self.series_triggered:
info("rayonix: Ignoring first trigger")
self.series_triggered = True
else: self.acquire_image()
self.register_trigger_time()
def register_trigger_time(self):
from time import time
self.trigger_times = self.trigger_times[-9:]+[time()]
@property
def measured_trigger_period(self):
from numpy import nan
from time import time
self.monitoring_trigger = True
t = self.trigger_times
if len(t) >= 2 and time()-t[-1] <= t[-1]-t[-2]+5:
T = t[-1]-t[-2]
else: T = nan
return T
def get_trigger_period(self):
if self.external_trigger: return self.measured_trigger_period
else: return self.nominal_trigger_period
def set_trigger_period(self,value):
self.nominal_trigger_period = value
trigger_period = property(get_trigger_period,set_trigger_period)
def acquire_image(self):
from numimage import numimage
from numpy import uint16
from os.path import basename
from thread import start_new_thread
if self.acquiring_series:
filename = "%s%0*d%s" % \
(self.filename_base,self.number_field_width,
self.frame_number,self.filename_suffix)
I = numimage((self.image_size,self.image_size),dtype=uint16,
pixelsize=self.pixelsize)
##info("rayonix: Saving image %r %r" % (basename(filename),I.shape))
start_new_thread(I.save,(filename,))
self.last_filename = filename
self.frame_number += 1
if self.frame_number > self.last_frame_number:
self.acquiring_series = False
@property
def pixelsize(self):
pixelsize = 0.02*self.bin_factor
return pixelsize
def acquire_series(self):
if self.external_trigger: self.acquire_series_on_trigger()
self.acquire_series_on_timer()
def acquire_series_on_trigger(self):
from time import sleep
self.monitoring_trigger = True
while self.acquiring_series: sleep(0.05)
__monitoring_trigger__ = False
def get_monitoring_trigger(self):
return self.__monitoring_trigger__
def set_monitoring_trigger(self,value):
from CA import camonitor,camonitor_clear
if value: camonitor(self.trigger_PV,callback=self.trigger_callback)
else: camonitor_clear(self.trigger_PV,callback=self.trigger_callback)
self.__monitoring_trigger__ = value
monitoring_trigger = property(get_monitoring_trigger,set_monitoring_trigger)
__trigger_PV__ = persistent_property("trigger_PV","NIH:TIMING.registers.xdet_state")
def get_trigger_PV(self): return self.__trigger_PV__
def set_trigger_PV(self,value):
if value != self.__trigger_PV__:
from CA import camonitor,camonitor_clear
camonitor_clear(self.__trigger_PV__,callback=self.trigger_callback)
self.trigger_times = []
self.__trigger_PV__ = value
camonitor(self.__trigger_PV__,callback=self.trigger_callback)
trigger_PV = property(get_trigger_PV,set_trigger_PV)
@property
def trigger_PV_OK(self):
from CA import caget
return caget(self.trigger_PV) is not None
def trigger_callback(self,PV_name,value,formatted_value):
##info("rayonix: trigger_callback: %s=%s(%s)" % (PV_name,value,formatted_value))
if value == 1: self.handle_trigger()
def acquire_series_on_timer(self):
from time import sleep
sleep(self.trigger_period)
while self.acquiring_series:
self.handle_trigger()
sleep(self.trigger_period)
def process_command(self,query):
"""Process a command"""
if query == "get_state": return str(self.state)
elif query.startswith("start_series,"):
start_series,n_frames,first_frame_number,integration_time,\
interval_time,frame_trigger_type,series_trigger_type,\
filename_base,filename_suffix,number_field_width \
= query.split(",")
self.start_series(int(n_frames),int(first_frame_number),
float(integration_time),float(interval_time),
int(frame_trigger_type),int(series_trigger_type),
filename_base,filename_suffix,int(number_field_width))
elif query == "get_bin":
return str(self.bin_factor)+","+str(self.bin_factor)
elif query.startswith("set_bin,"):
set_bin,bin_factor,bin_factor = query.split(",")
self.bin_factor = int(bin_factor)
elif query == "get_size":
return str(self.image_size)+","+str(self.image_size)
elif query == "get_size_bkg":
return str(self.bkg_image_size)+","+str(self.bkg_image_size)
elif query.startswith("trigger,"): self.handle_trigger()
elif query == "abort": self.abort()
def start_series(self,n_frames=None,first_frame_number=None,
integration_time=None,interval_time=None,frame_trigger_type=None,
series_trigger_type=None,
filename_base=None,filename_suffix=None,number_field_width=None):
"""Start acqisition of image series."""
from normpath import normpath
if n_frames is not None:
self.n_frames = n_frames
if first_frame_number is not None:
self.first_frame_number = first_frame_number
if filename_base is not None:
self.filename_base = normpath(filename_base)
if filename_suffix is not None:
self.filename_suffix = filename_suffix
if number_field_width is not None:
self.number_field_width = number_field_width
info("rayonix: Starting series of %d images..." % self.n_frames)
self.frame_number = self.first_frame_number
self.acquiring_series = True
self.series_triggered = False # trigger pulse seen?
from thread import start_new_thread
start_new_thread(self.acquire_series,())
n_frames = persistent_property("n_frames",10)
first_frame_number = persistent_property("first_frame_number",0)
filename_base = persistent_property("filename_base","/tmp/")
filename_suffix = persistent_property("filename_suffix",".rx")
number_field_width = persistent_property("number_field_width",6)
frame_number = 0
acquiring_series = False
series_triggered = False
@property
def last_frame_number(self):
return self.first_frame_number+self.n_frames-1
def abort(self):
"""End acqisition of image series."""
info("rayonix: Aborting acqisition.")
self.acquiring_series = False
def get_acquiring(self):
"""Is image series acqisition in progress?"""
return self.acquiring_series
def set_acquiring(self,value):
if value: self.start_series()
else: self.abort()
acquiring = property(get_acquiring,set_acquiring)
@property
def readout_time(self):
"""Estimated readout time in seconds. Changes with 'bin_factor'."""
return self.readout_time_of_bin_factor(self.bin_factor)
def readout_time_of_bin_factor(self,bin_factor):
"""Estimated readout time in seconds as function of bin factor."""
safetyFactor = 1
from numpy import nan
# Readout rate in frames per second as function of bin factor:
readout_rate = {1: 2, 2: 10, 3: 15, 4: 25, 5: 40, 6: 60, 8: 75, 10: 120}
if bin_factor in readout_rate: read_time = 1.0/readout_rate[bin_factor]
else: read_time = nan
return read_time*safetyFactor
def get_server_running(self):
return getattr(self.server,"active",False)
def set_server_running(self,value):
if self.server_running != value:
if value: self.start_server()
else: self.stop_server()
server_running = property(get_server_running,set_server_running)
server = None
def start_server(self):
# make a threaded server, listen/handle clients forever
try:
self.server = self.ThreadingTCPServer(("",self.port),self.ClientHandler)
self.server.active = True
info("rayonix: server version %s started, listening on port %d." % (__version__,self.port))
from threading import Thread
self.thread = Thread(target=self.run_server)
self.thread.start() # Stop with: "self.server.shutdown()"
except Exception,msg: error("rayonix: start_server: %r" % msg)
def stop_server(self):
if getattr(self.server,"active",False):
self.server.server_close()
self.server.active = False
def run_server(self):
try: self.server.serve_forever()
except Exception,msg: info("rayonix: server: %s" % msg)
info("rayonix: server shutting down")
# By default, the "ThreadingTCPServer" class binds to the sever port
# without the option SO_REUSEADDR. The consequence of this is that
# when the server terminates you have to let 60 seconds pass, for the
# socket to leave to "CLOSED_WAIT" state before it can be restarted,
# otherwise the next bind call would generate the error
# 'Address already in use'.
# Setting allow_reuse_address to True makes "ThreadingTCPServer" use to
# SO_REUSEADDR option when calling "bind".
import SocketServer
class ThreadingTCPServer(SocketServer.ThreadingTCPServer):
allow_reuse_address = True
class ClientHandler(SocketServer.BaseRequestHandler):
def handle(self):
"""Called when a client connects. 'self.request' is the client socket"""
info("rayonix: accepted connection from "+self.client_address[0])
import socket
input_queue = ""
while self.server.active:
# Commands from a client are not necessarily received as one packet
# but each command is terminated by a newline character.
# If 'recv' returns an empty string it means client closed the
# connection.
while input_queue.find("\n") == -1:
self.request.settimeout(1.0)
received = ""
while self.server.active:
try: received = self.request.recv(2*1024*1024)
except socket.timeout: continue
except Exception,x: error("rayonix: %r %r" % (x,str(x)))
if received == "": info("rayonix: client disconnected")
break
if received == "": break
input_queue += received
if input_queue == "": break
if input_queue.find("\n") != -1:
end = input_queue.index("\n")
query = input_queue[0:end]
input_queue = input_queue[end+1:]
else: query = input_queue; input_queue = ""
query = query.strip("\r ")
error("rayonix: evaluating query: '%s'" % query)
try: reply = det.process_command(query)
except Exception,x: error("rayonix: %r %r" % (x,str(x))); reply = ""
if reply:
reply = reply.replace("\n","") # "\n" = end of reply
reply += "\n"
info("rayonix: sending reply: "+repr(reply))
self.request.sendall(reply)
info("rayonix: closing connection to "+self.client_address[0])
self.request.close()
det = Rayonix_Detector()
def timestamp():
"""Current date and time as formatted ASCCI text, precise to 1 ms"""
from datetime import datetime
timestamp = str(datetime.now())
return timestamp[:-3] # omit microseconds
if __name__ == "__main__":
import logging
logging.basicConfig(level=logging.DEBUG,
format="%(asctime)s %(levelname)s: %(message)s")
self = det # for debugging
from CA import camonitor,camonitor_clear,caget
##print('camonitor(self.trigger_PV,callback=self.trigger_callback)')
##print('camonitor_clear(self.trigger_PV,callback=self.trigger_callback)')
##print('self.acquiring = True')
print('self.trigger_PV = %r' % self.trigger_PV)
print('self.trigger_PV_OK')
print('self.trigger_period')
print('det.server_running = True')
<file_sep>#!/usr/bin/env python
"""Control panel for all motor controlled by the Aerotech Ensemble EPAQ.
<NAME>, 31 Oct 2013 - Jun 30, 2017"""
__version__ = "1.0.2" # msShut
import wx
from MotorPanel import MotorWindow
# Needed to initialize WX library
if not "app" in globals(): app = wx.App(redirect=False)
from instrumentation import SampleX,SampleY,SampleZ,SamplePhi,PumpA,PumpB,msShut
window = MotorWindow([SampleX,SampleY,SampleZ,SamplePhi,PumpA,PumpB,msShut],
title="Ensemble")
app.MainLoop()
<file_sep>#!/bin/bash -l
# Mac OS X startup script for Time-resolved Wide-Angle X-ray scattering software
# This needs to be located in the directory basename.app/Contents/MacOS
# The basename.app directory is created with the "Build Applet" utility
# include in MacPython.
# The -l (login) option makes sure that the environment is the same as for
# an interactive shell.
# If MacPython is installed it modifies the PATH environment variable in
# ~/.bash_profile such that "python" refers to the MacPython version, rather
# than Mac OS X's built-in version of Python.
# Use this to check which version of python is used:
# which python > /tmp/ImageViewer.log
# <NAME>, 24 Jan 2009
dir=`dirname "$0"`/../../..
prog=`basename "$0"`
PYTHONPATH="${dir}:$PYTHONPATH"
exec python "$dir/$prog.py" "$1" "$2" 2>&1 > /tmp/ImageViewer.log
# Append this is inspect error messages: 2>&1 > /tmp/ImageViewer.log
<file_sep>#!/usr/bin/env python
"""Controls when data collection is suspended, in case the X-ray beam is
down
<NAME>,
Date created: 2017-02-24
Date last modified: 2018-03-15
"""
__version__ = "1.2.9" # logging
from checklist import checklist
import wx, wx3_compatibility
from EditableControls import TextCtrl,ComboBox
from logging import debug,info,warn,error
class ChecklistPanel(wx.Frame):
name = "ChecklistPanel"
from persistent_property import persistent_property
from collections import OrderedDict as odict
AllView = range(0,20)
CustomView = persistent_property("CustomView",range(0,20))
views = odict([("All","AllView"),("Custom","CustomView")])
view = persistent_property("view","All")
attributes = ["OK"]
refresh_period = 1.0 # s
def __init__(self,parent=None,title="Suspend Checklist"):
wx.Frame.__init__(self,parent=parent,title=title)
from Icon import SetIcon
SetIcon(self,"Checklist")
# Controls
self.panel = wx.Panel(self)
self.controls = []
# Menus
menuBar = wx.MenuBar()
self.ViewMenu = wx.Menu()
for i in range(0,len(self.views)):
self.ViewMenu.AppendCheckItem(10+i,self.views.keys()[i])
self.ViewMenu.AppendSeparator()
menuBar.Append (self.ViewMenu,"&View")
menu = wx.Menu()
menu.AppendCheckItem(200,"Setup")
menu.AppendSeparator()
menu.Append(201,"Add Line")
menu.Append(202,"Remove Line")
menuBar.Append(menu,"&More")
menu = wx.Menu()
menu.Append(wx.ID_ABOUT,"About...")
menuBar.Append(menu,"&Help")
self.SetMenuBar(menuBar)
# Callbacks
self.Bind(wx.EVT_MENU_OPEN,self.OnOpenView)
for i in range(0,len(self.views)):
self.Bind(wx.EVT_MENU,self.OnSelectView,id=10+i)
self.Bind(wx.EVT_MENU,self.OnSetup,id=200)
self.Bind(wx.EVT_MENU,self.OnAdd,id=201)
self.Bind(wx.EVT_MENU,self.OnRemove,id=202)
self.Bind(wx.EVT_MENU,self.OnAbout,id=wx.ID_ABOUT)
self.Bind(wx.EVT_CLOSE,self.OnClose)
# Layout
self.sizer = wx.BoxSizer(wx.VERTICAL)
self.panel.SetSizer(self.sizer)
self.update_controls()
self.Show()
# Refresh
from numpy import nan
self.values = {"OK": nan}
self.old_values = {}
self.Bind(wx.EVT_TIMER,self.OnUpdate)
from threading import Thread
self.thread = Thread(target=self.keep_updated,name=self.name)
self.thread.start()
def keep_updated(self):
"""Periodically refresh the displayed settings."""
from time import time,sleep
while True:
try:
t0 = time()
while time() < t0+self.refresh_period: sleep(0.1)
if self.Shown:
self.update_data()
if self.data_changed:
event = wx.PyCommandEvent(wx.EVT_TIMER.typeId,self.Id)
# call OnUpdate in GUI thread
wx.PostEvent(self.EventHandler,event)
except wx.PyDeadObjectError: break
def refresh(self):
"""Force update"""
from threading import Thread
self.thread = Thread(target=self.refresh_background,name=self.name+".refresh")
self.thread.start()
def refresh_background(self):
"""Force update"""
self.update_data()
if self.data_changed:
event = wx.PyCommandEvent(wx.EVT_TIMER.typeId,self.Id)
wx.PostEvent(self.EventHandler,event) # call OnUpdate in GUI thread
def update_data(self):
"""Retreive status information"""
self.old_values = dict(self.values) # make a copy
for n in self.attributes: self.values[n] = getattr(checklist,n)
@property
def data_changed(self):
"""Did the last 'update_data' change the data to be plotted?"""
changed = (self.values != self.old_values)
return changed
def OnUpdate(self,event):
"""Periodically refresh the displayed settings."""
self.refresh_status()
def refresh_status(self,event=None):
"""Update title to show whether all checks passed"""
from numpy import isnan
OK = self.values["OK"]
status = "?" if isnan(OK) else "OK" if OK else "not OK"
self.Title = self.Title.split(":")[0]+": %s" % status
def update_controls(self):
if len(self.controls) != checklist.N:
for control in self.controls: control.Destroy()
##self.sizer.DeleteWindows() # not compatible with wx 4.0
self.controls = []
for i in range(checklist.N):
self.controls += [ChecklistControl(self.panel,i)]
for i in range(0,len(self.controls)):
self.sizer.Add(self.controls[i],flag=wx.ALL|wx.EXPAND,proportion=1)
self.panel.Sizer.Fit(self)
if not self.view in self.views: self.view = self.views.keys()[0]
self.View = getattr(self,self.views[self.view])
def get_View(self):
"""Which control to show? List of 0-based integers"""
view = [i for (i,c) in enumerate(self.controls) if c.Shown]
return view
def set_View(self,value):
currently_shown = [c.Shown for c in self.controls]
shown = [False]*len(self.controls)
for i in value:
if i < len(shown): shown[i] = True
if shown != currently_shown:
for i in range(0,len(self.controls)):
self.controls[i].Shown = shown[i]
self.panel.Sizer.Fit(self)
View = property(get_View,set_View)
def OnOpenView(self,event):
"""Called if the "View" menu is selected"""
for i in range(0,len(self.views)):
self.ViewMenu.Check(10+i,self.views.keys()[i] == self.view)
for i in range(0,len(self.controls)):
try: self.ViewMenu.Remove(100+i)
except: pass
self.ViewMenu.AppendCheckItem(100+i,self.controls[i].Title)
self.ViewMenu.Check(100+i,self.controls[i].Shown)
self.ViewMenu.Enable(100+i,self.view != "All")
self.Bind(wx.EVT_MENU,self.OnView,id=100+i)
def OnSelectView(self,event):
"""Called if the view is toogled between 'All' and 'Custome'
from the 'View ' menu."""
n = event.Id-10
self.view = self.views.keys()[n]
self.View = getattr(self,self.views.values()[n])
def OnView(self,event):
"""Called if one of the items of the "View" menu is checked or
unchecked."""
n = event.Id-100
self.controls[n].Shown = event.Checked()
self.panel.Sizer.Fit(self)
setattr(self,self.views[self.view],self.View) # save modified view
def OnSetup(self,event):
"""Enable 'setup' mode, allowing the panel to be configured"""
for control in self.controls: control.setup = event.Checked()
self.panel.Sizer.Fit(self)
def OnAdd(self,event):
checklist.N += 1
self.update_controls()
def OnRemove(self,event):
if checklist.N > 0: checklist.N -= 1
self.update_controls()
def OnAbout(self,event):
"""Show panel with additional parameters"""
from os.path import basename
from inspect import getfile
from os.path import getmtime
from datetime import datetime
filename = getfile(lambda x: None)
info = basename(filename)+" "+__version__
import checklist as module
filename = getfile(module)
if hasattr(module,"__source_timestamp__"):
timestamp = module.__source_timestamp__
filename = filename.replace(".pyc",".py")
else: timestamp = getmtime(getfile(module))
info += "\n"+basename(filename)+" "+module.__version__
info += " ("+str(datetime.fromtimestamp(timestamp))+")"
info += "\nwx "+wx.__version__
info += "\n\n"+__doc__
dlg = wx.MessageDialog(self,info,"About",wx.OK|wx.ICON_INFORMATION)
dlg.CenterOnParent()
dlg.ShowModal()
dlg.Destroy()
def OnClose(self,event):
"""Called when the windows's close button is clicked"""
self.Destroy()
class ChecklistControl(wx.Panel):
name = "ChecklistControl"
attributes = "formatted_value","OK","test_code_OK"
refresh_period = 1.0
def __init__(self,parent,n):
self.values = {"formatted_value":"","OK":True,"test_code_OK":False}
self.old_values = {}
wx.Panel.__init__(self,parent)
self.Title = "Test %d" % n
self.n = n
self.myEnabled = wx.CheckBox(self,size=(320,-1))
from wx.lib.buttons import GenButton
self.State = GenButton(self,size=(25,20))
self.Setup = wx.Button(self,size=(60,-1),label="More...")
self.Setup.Shown = False
self.Bind(wx.EVT_CHECKBOX,self.OnEnable,self.myEnabled)
self.Bind(wx.EVT_BUTTON,self.OnSetup,self.State)
self.Bind(wx.EVT_BUTTON,self.OnSetup,self.Setup)
# Layout
self.layout = wx.BoxSizer(wx.HORIZONTAL)
flag = wx.ALL|wx.ALIGN_CENTER_VERTICAL|wx.EXPAND
self.layout.Add(self.myEnabled,flag=flag,proportion=1)
self.layout.Add(self.State,flag=flag)
self.layout.Add(self.Setup,flag=flag)
# Leave a 10 pixel wide border.
self.box = wx.BoxSizer(wx.VERTICAL)
self.box.Add(self.layout,flag=wx.ALL,border=5)
self.SetSizer(self.box)
self.Fit()
self.refresh_label()
# Periodically refresh the displayed settings.
self.Bind(wx.EVT_TIMER,self.OnUpdate)
from threading import Thread
self.thread = Thread(target=self.keep_updated,name=self.name)
self.thread.start()
def keep_updated(self):
"""Periodically refresh the displayed settings."""
from time import time,sleep
while True:
try:
t0 = time()
while time() < t0+self.refresh_period: sleep(0.1)
if self.Shown:
self.update_data()
if self.data_changed:
event = wx.PyCommandEvent(wx.EVT_TIMER.typeId,self.Id)
# call OnUpdate in GUI thread
wx.PostEvent(self.EventHandler,event)
except wx.PyDeadObjectError: break
def refresh(self):
"""Force update"""
from threading import Thread
self.thread = Thread(target=self.refresh_background,name=self.name+".refresh")
self.thread.start()
def refresh_background(self):
"""Force update"""
self.update_data()
if self.data_changed:
event = wx.PyCommandEvent(wx.EVT_TIMER.typeId,self.Id)
wx.PostEvent(self.EventHandler,event) # call OnUpdate in GUI thread
def update_data(self):
"""Retreive status information"""
self.old_values = dict(self.values) # make a copy
for n in self.attributes: self.values[n] = getattr(checklist.test(self.n),n)
@property
def data_changed(self):
"""Did the last 'update_data' change the data to be plotted?"""
changed = (self.values != self.old_values)
return changed
def OnUpdate(self,event):
"""Periodically refresh the displayed settings."""
self.refresh_status()
def refresh_label(self,event=None):
"""Update the controls with current values"""
self.Title = checklist.test(self.n).label
self.myEnabled.Value = checklist.test(self.n).enabled
self.myEnabled.Label = checklist.test(self.n).label
def refresh_status(self,event=None):
"""Update the controls with current values"""
red = (255,0,0)
green = (0,255,0)
gray = (180,180,180)
label = checklist.test(self.n).label
self.myEnabled.Label = "%s: %s" % (label,self.values["formatted_value"])
color = green if self.values["OK"] else red
if not self.values["test_code_OK"]: color = gray
self.State.BackgroundColour = color
self.State.ForegroundColour = color
self.State.Refresh() # work-around for a GenButton bug in Windows
def OnEnable(self,event):
checklist.test(self.n).enabled = event.Checked()
self.refresh()
def get_setup(self):
"""'Setup' mode enabled? (Allows reconfiguring parameters)"""
value = self.Setup.Shown
return value
def set_setup(self,value):
self.Setup.Shown = value
self.Layout()
self.Fit()
setup = property(get_setup,set_setup)
def OnSetup(self,event):
""""""
dlg = SetupPanel(self,self.n)
dlg.CenterOnParent()
dlg.Show()
class SetupPanel(wx.Frame):
def __init__(self,parent,n):
self.n = n
wx.Frame.__init__(self,parent=parent,title="Setup")
self.panel = wx.Panel(self)
# Controls
style = wx.TE_PROCESS_ENTER
self.myLabel = ComboBox(self.panel,size=(320,-1),style=style)
self.Value = ComboBox(self.panel,size=(320,-1),style=style)
self.Format = ComboBox(self.panel,size=(320,-1),style=style)
self.Test = ComboBox(self.panel,size=(320,-1),style=style)
# Callbacks
self.Bind (wx.EVT_COMBOBOX,self.OnLabel,self.myLabel)
self.Bind (wx.EVT_TEXT_ENTER,self.OnLabel,self.myLabel)
self.Bind (wx.EVT_COMBOBOX,self.OnValue,self.Value)
self.Bind (wx.EVT_TEXT_ENTER,self.OnValue,self.Value)
self.Bind (wx.EVT_COMBOBOX,self.OnFormat,self.Format)
self.Bind (wx.EVT_TEXT_ENTER,self.OnFormat,self.Format)
self.Bind (wx.EVT_COMBOBOX,self.OnTest,self.Test)
self.Bind (wx.EVT_TEXT_ENTER,self.OnTest,self.Test)
self.Bind (wx.EVT_SIZE,self.OnResize)
# Layout
self.layout = wx.BoxSizer()
grid = wx.FlexGridSizer(cols=2,hgap=5,vgap=5)
flag = wx.ALIGN_CENTER_VERTICAL|wx.ALL|wx.EXPAND
label = "Label:"
grid.Add(wx.StaticText(self.panel,label=label),flag=flag)
grid.Add(self.myLabel,flag=flag,proportion=1)
label = "Value:"
grid.Add(wx.StaticText(self.panel,label=label),flag=flag)
grid.Add(self.Value,flag=flag,proportion=1)
label = "Format:"
grid.Add(wx.StaticText(self.panel,label=label),flag=flag)
grid.Add(self.Format,flag=flag,proportion=1)
label = "Test:"
grid.Add(wx.StaticText(self.panel,label=label),flag=flag)
grid.Add(self.Test,flag=flag,proportion=1)
# Leave a 10-pixel wide space around the panel.
self.layout.Add(grid,flag=wx.EXPAND|wx.ALL,proportion=1,border=10)
self.panel.SetSizer(self.layout)
self.panel.Fit()
self.Fit()
# Intialization
labels,values,formats,tests = [],[],[],[]
for label in checklist.defaults:
labels += [label]
values += [checklist.defaults[label]["value"]]
formats += [checklist.defaults[label]["format"]]
tests += [checklist.defaults[label]["test"]]
self.myLabel.Items = labels
self.Value.Items = values
self.Format.Items = formats
self.Test.Items = tests
self.refresh()
def refresh(self,Event=0):
self.myLabel.Value = checklist.test(self.n).label
self.Value.Value = checklist.test(self.n).value_code
self.Format.Value = checklist.test(self.n).format
self.Test.Value = checklist.test(self.n).test_code
def OnLabel(self,event):
checklist.test(self.n).label = self.myLabel.Value
self.refresh()
def OnValue(self,event):
checklist.test(self.n).value_code = self.Value.Value
self.refresh()
def OnFormat(self,event):
checklist.test(self.n).format = self.Format.Value
self.refresh()
def OnTest(self,event):
checklist.test(self.n).test_code = self.Test.Value
self.refresh()
def OnResize(self,event):
"""Rearange contents to fit best into new size"""
self.panel.Fit()
event.Skip()
if __name__ == '__main__':
from pdb import pm
import logging
from tempfile import gettempdir
logging.basicConfig(
level=logging.DEBUG,
format="%(asctime)s %(levelname)s %(module)s.%(funcName)s: %(message)s",
filename=gettempdir()+"/ChecklistPanel.log",
)
import autoreload
# Needed to initialize WX library
app = wx.App(redirect=False)
ChecklistPanel()
app.MainLoop()
<file_sep>from os import getcwd,makedirs
from os.path import exists,dirname,basename,getmtime
from logging import info,error,warn # for debugging
import wxversion; wxversion.select("2.8")
import wx
import matplotlib.pyplot as plt
import math
from id14 import *
from alio import *
# Plot motion profile
# Add help
# Hightlight things in read that exceed some limit. velecity is exceded.
# Add button to write values to FPGA
# Fix ramp up distance of X and Y
# Calc freqency.
kHz_clock=1.0126899 # ms (DT)
class param: "Container for data collection parameters"
param.first_hole_x = 0
param.first_hole_y = 0
param.first_hole_z = 0
param.last_hole_x = 0
param.last_hole_y = 0
param.last_hole_z = 0
param.step_size = 0.2 # mm
param.acceleration = 200 # mm/s2
param.repetition_period = 48 # ~ms
param.settle_period = 2
param.continuous = 1
param.translate_x = 0
param.translate_y = 0
param.translate_z = 0
param.velocity = 0
param.acceleration_time = 0
param.acceleration_distance = 0
param.settling_time_at_speed = 0
param.settling_distance_at_speed = 0
param.time_to_first_xray_pulse = 0
param.number_of_data_points = 0
param.distance_of_actual_data_collection = 0
param.total_distance_of_translation = 0
param.time_to_reach_half_the_return_distance =0
param.max_velocity_on_return = 0
param.total_time_to_return = 0
param.total_time_of_translation = 0
param.full_cycle_clock_ticks = 0
param.measure_length = 0
class options:"Container for data collection parameters"
def save_settings():
global settings_file_timestamp
filename = settings_file()
save_settings_to_file(filename)
settings_file_timestamp = getmtime(filename)
settings_file_timestamp = 0
def save_settings_to_file(filename):
if not exists(dirname(filename)): makedirs(dirname(filename))
f = file(filename,"w")
for obj in param,options:
for name in dir(obj):
if name.startswith("__"):continue
line = "%s.%s = %r\n" % (obj.__name__,name,getattr(obj,name))
line = line.replace("-1.#IND","nan") # Needed for Windows Python
line = line.replace("1.#INF","inf") # Needed for Windows Python
f.write(line)
def load_settings(filename=None):
"""Reload last saved parameters."""
if filename == None: filename = settings_file()
if not exists(filename): return
for line in file(filename).readlines():
try: exec(line)
except: warn("ignoring line %r in settings" % line)
def settings_file():
"""Where to save to the default settings"""
filename = settingsdir()+"/alio.py"
return filename
def settingsdir():
"""In which directory to save to the settings file"""
return module_dir()+"/settings"
def module_dir():
"directory of the current module"
from os.path import dirname
module_dir = dirname(module_path())
if module_dir == "": module_dir = "."
return module_dir
def module_path():
"full pathname of the current module"
from sys import path
# from os import getcwd
# from os.path import basename,exists
from inspect import getfile
# 'getfile' retreives the source file name name compiled into the .pyc file.
pathname = getfile(lambda x: None)
if exists(pathname): return pathname
# The module might have been compiled on a different machine or in a
# different directory.
pathname = pathname.replace("\\","/")
filename = basename(pathname)
dirs = [dir for dir in [getcwd()]+path if exists(dir+"/"+filename)]
if len(dirs) == 0: warn("pathname of file %r not found" % filename)
dir = dirs[0] if len(dirs) > 0 else "."
pathname = dir+"/"+filename
return pathname
def translation_range():
param.translate_x=param.last_hole_x-param.first_hole_x
param.translate_y=param.last_hole_y-param.first_hole_y
param.translate_z=param.last_hole_z-param.first_hole_z
def velocity():
try: param.velocity=param.step_size/(param.repetition_period*kHz_clock)*1000
except:
print "Velocity calc error" #Should put an error in the log file.
def acceleration_time():
param.acceleration_time=param.velocity/param.acceleration
def acceleration_distance():
param.acceleration_distance=param.acceleration*param.acceleration_time**2 / 2
def settling_time_at_speed():
param.settling_time_at_speed=param.settle_period*param.repetition_period*kHz_clock/1000
def settling_distance_at_speed():
param.settling_distance_at_speed=param.settling_time_at_speed*param.velocity
def time_to_first_xray_pulse():
time_to_first_xray_pulse_initial=param.acceleration_time+param.settling_time_at_speed
#print time_to_first_xray_pulse_initial
time_to_first_xray_pulse_divided_by_12=time_to_first_xray_pulse_initial*1000/12
#print time_to_first_xray_pulse_divided_by_12
time_to_first_xray_pulse_rounded_up=math.ceil(float(time_to_first_xray_pulse_divided_by_12))
#print time_to_first_xray_pulse_rounded_up
param.time_to_first_xray_pulse =time_to_first_xray_pulse_rounded_up*12
def distance_of_actual_data_collection():
distance_of_actual_data_collection_initial=param.translate_z-param.settling_distance_at_speed
#print distance_of_actual_data_collection_initial
# We might be able to remove this -1. I think this was to be safe so that we were not collecting during the deceleration
try: param.number_of_data_points = (distance_of_actual_data_collection_initial/param.velocity)/(param.repetition_period*kHz_clock/1000)-1
except ZeroDivisionError: pass
#print param.number_of_data_points
param.distance_of_actual_data_collection = param.number_of_data_points*param.repetition_period*kHz_clock*param.velocity/1000
def total_distance_of_translation():
param.total_distance_of_translation=param.translate_z+2*param.acceleration_distance
def time_to_reach_half_the_return_distance():
param.time_to_reach_half_the_return_distance=math.sqrt(param.total_distance_of_translation/param.acceleration)
def max_velocity_on_return():
param.max_velocity_on_return=param.acceleration*param.time_to_reach_half_the_return_distance
def total_time_to_return():
param.total_time_to_return=param.time_to_reach_half_the_return_distance*2
def total_time_of_translation():
try: param.total_time_of_translation=param.acceleration_time*2+param.translate_z/param.velocity+param.total_time_to_return
except ZeroDivisionError: pass
def full_cycle_clock_ticks():
full_cycle_clock_ticks_initial=param.total_time_of_translation/(param.repetition_period*kHz_clock/1000)
#print full_cycle_clock_ticks_initial
param.full_cycle_clock_ticks=math.ceil(full_cycle_clock_ticks_initial)
def measure_length():
param.measure_length=param.full_cycle_clock_ticks*param.repetition_period
def update_plot():
ad=param.acceleration_distance
sdap=param.settling_distance_at_speed
v=param.velocity
doadc=param.distance_of_actual_data_collection
rv=param.max_velocity_on_return
#plt.plot([0,ad,ad+sdap,ad+sdap+ad],[0,v,v,0],color='g')
plt.plot([0,ad],[0,v],'r') # Acceleration
plt.plot([ad,ad+sdap],[v,v],'b') # Settling time
plt.plot([ad+sdap,ad+sdap+doadc],[v,v],'g') # Actual data collection
plt.plot([ad+sdap+doadc,ad+sdap+doadc+ad],[v,0],'r') # Deceleration
plt.plot([ad+sdap+doadc+ad,(ad+sdap+doadc+ad)/2],[0,-rv],'r') # Return acceleration
plt.plot([(ad+sdap+doadc+ad)/2,0],[-rv,0],'r') # Return deceleration
plt.plot()
plt.show()
class AlioWindow(wx.Frame):
def __init__(self):
wx.Frame.__init__ (self,None,-1,"Alio PP")
self.SetSize((640,400))
main_page = wx.BoxSizer(wx.VERTICAL)
grid=wx.FlexGridSizer(7,7,0,0)
self.input=wx.Panel(self)
# Add a button to save the current position
self.title=wx.StaticText(self.input,-1," Position of first hole (X,Y,Z) ")
self.firstX=wx.TextCtrl(self.input,size=(80,-1),style=wx.TE_PROCESS_ENTER)
self.firstY=wx.TextCtrl(self.input,size=(80,-1),style=wx.TE_PROCESS_ENTER)
self.firstZ=wx.TextCtrl(self.input,size=(80,-1),style=wx.TE_PROCESS_ENTER)
self.units=wx.StaticText(self.input,-1," mm ")
#button = wx.Button(self.GonPanel,label="Save current",pos=(x,y),size=(90,-1)); x+=100
button = wx.Button(self.input,label="Save current",size=(100,-1))
self.Bind (wx.EVT_BUTTON,self.define_first_save,button)
button2 = wx.Button(self.input,label="Go To",size=(80,-1))
self.Bind (wx.EVT_BUTTON,self.define_first_goto,button2)
grid.AddMany([(self.title,0,wx.ALIGN_CENTER_VERTICAL),(self.firstX),(self.firstY),(self.firstZ),\
(self.units,0,wx.ALIGN_CENTER_VERTICAL),(button),(button2)])
# Add a button to save the current position
self.title=wx.StaticText(self.input,-1," Position of last hole (X,Y,Z) ")
self.lastX=wx.TextCtrl(self.input,size=(80,-1),style=wx.TE_PROCESS_ENTER)
self.lastY=wx.TextCtrl(self.input,size=(80,-1),style=wx.TE_PROCESS_ENTER)
self.lastZ=wx.TextCtrl(self.input,size=(80,-1),style=wx.TE_PROCESS_ENTER)
self.units=wx.StaticText(self.input,-1," mm ")
button = wx.Button(self.input,label="Save current",size=(100,-1))
self.Bind (wx.EVT_BUTTON,self.define_last_save,button)
button2 = wx.Button(self.input,label="Go To",size=(80,-1))
self.Bind (wx.EVT_BUTTON,self.define_last_goto,button2)
#self.blank=wx.StaticText(self.input,-1,"")
grid.AddMany([(self.title,0,wx.ALIGN_CENTER_VERTICAL),(self.lastX),(self.lastY),(self.lastZ),\
(self.units,0,wx.ALIGN_CENTER_VERTICAL),(button),(button2)])
self.title=wx.StaticText(self.input,-1," Step size ")
self.step_size=wx.TextCtrl(self.input,size=(80,-1),style=wx.TE_PROCESS_ENTER)
self.units=wx.StaticText(self.input,-1," mm ")
self.blank=wx.StaticText(self.input,-1,"")
grid.AddMany([(self.title,0,wx.ALIGN_CENTER_VERTICAL),(self.step_size),(self.units,0,wx.ALIGN_CENTER_VERTICAL),\
(self.blank),(self.blank),(self.blank),(self.blank)])
self.title=wx.StaticText(self.input,-1," Acceleration ")
self.acceleration=wx.TextCtrl(self.input,size=(80,-1),style=wx.TE_PROCESS_ENTER)
self.units=wx.StaticText(self.input,-1," mm/s2 ")
grid.AddMany([(self.title,0,wx.ALIGN_CENTER_VERTICAL),(self.acceleration),(self.units,0,wx.ALIGN_CENTER_VERTICAL),\
(self.blank),(self.blank),(self.blank),(self.blank)])
# Force this value to be an integer
# Show what the frequency would be
self.title=wx.StaticText(self.input,-1," Repetition Period (dt) ")
self.title.SetToolTip(wx.ToolTip("X-ray repetition period. Inverse of frequency. Example: 48 is 20 Hz"))
self.repetition_period=wx.TextCtrl(self.input,size=(80,-1),style=wx.TE_PROCESS_ENTER)
self.units=wx.StaticText(self.input,-1," ~ms ")
grid.AddMany([(self.title,0,wx.ALIGN_CENTER_VERTICAL),(self.repetition_period),\
(self.units,0,wx.ALIGN_CENTER_VERTICAL),(self.blank),(self.blank),(self.blank),(self.blank)])
self.title=wx.StaticText(self.input,-1," Period to settle at speed ")
self.title.SetToolTip(wx.ToolTip("Time, after ramp up, to allow the stage to stabilize before collecting data"))
self.settle_period=wx.TextCtrl(self.input,size=(80,-1),style=wx.TE_PROCESS_ENTER)
#self.units=wx.StaticText(self,-1," ~ms ")
grid.AddMany([(self.title,0,wx.ALIGN_CENTER_VERTICAL),(self.settle_period),(self.blank),(self.blank),\
(self.blank),(self.blank),(self.blank)])
# Need to implement this part
self.title=wx.StaticText(self.input,-1," Continuous (1) or Stepping (#) (NA) ")
self.title.SetToolTip(wx.ToolTip("Use 1 for now. Stepping mode not enabled."))
self.continuous=wx.TextCtrl(self.input,size=(80,-1),style=wx.TE_PROCESS_ENTER)
#self.units=wx.StaticText(self,-1," ~ms ")
grid.AddMany([(self.title,0,wx.ALIGN_CENTER_VERTICAL),(self.continuous),(self.blank),(self.blank),\
(self.blank),(self.blank),(self.blank)])
self.input.SetSizer(grid)
self.input.Fit()
main_page.Add(self.input)
#line=wx.StaticLine(self,wx.ID_ANY,size=(20,-1),style=wx.LI_HORIZONTAL)
line=wx.StaticLine(self,style=wx.LI_HORIZONTAL)
main_page.AddSpacer(10)
main_page.Add(line,0,wx.GROW,5)
main_page.AddSpacer(10)
grid2=wx.FlexGridSizer(7,5,0,0)
self.output=wx.Panel(self)
self.title=wx.StaticText(self.output,-1," Translation range (X, Y, Z) ")
self.translate_x=wx.TextCtrl(self.output,size=(80,-1),style=wx.TE_READONLY)
self.translate_y=wx.TextCtrl(self.output,size=(80,-1),style=wx.TE_READONLY)
self.translate_z=wx.TextCtrl(self.output,size=(80,-1),style=wx.TE_READONLY)
self.units=wx.StaticText(self.output,-1," mm ")
grid2.AddMany([(self.title,0,wx.ALIGN_CENTER_VERTICAL),(self.translate_x),(self.translate_y),(self.translate_z),(self.units,0,wx.ALIGN_CENTER_VERTICAL)])
self.title=wx.StaticText(self.output,-1," Velocity ")
self.title.SetToolTip(wx.ToolTip("Velecity at full speed. mm/s"))
self.velocity=wx.TextCtrl(self.output,size=(80,-1),style=wx.TE_READONLY)
self.units=wx.StaticText(self.output,-1," mm/s ")
grid2.AddMany([(self.title,0,wx.ALIGN_CENTER_VERTICAL),(self.velocity),(self.units,0,wx.ALIGN_CENTER_VERTICAL),(self.blank),(self.blank)])
self.title=wx.StaticText(self.output,-1," Acceleration time ")
self.acceleration_time=wx.TextCtrl(self.output,size=(80,-1),style=wx.TE_READONLY)
self.units=wx.StaticText(self.output,-1," s ")
grid2.AddMany([(self.title,0,wx.ALIGN_CENTER_VERTICAL),(self.acceleration_time),(self.units,0,wx.ALIGN_CENTER_VERTICAL),(self.blank),(self.blank)])
self.title=wx.StaticText(self.output,-1," Acceleration distance ")
self.acceleration_distance=wx.TextCtrl(self.output,size=(80,-1),style=wx.TE_READONLY)
self.units=wx.StaticText(self.output,-1," mm ")
grid2.AddMany([(self.title,0,wx.ALIGN_CENTER_VERTICAL),(self.acceleration_distance),(self.units,0,wx.ALIGN_CENTER_VERTICAL),(self.blank),(self.blank)])
self.title=wx.StaticText(self.output,-1," Settling time at speed ")
self.settling_time_at_speed=wx.TextCtrl(self.output,size=(80,-1),style=wx.TE_READONLY)
self.units=wx.StaticText(self.output,-1," s ")
grid2.AddMany([(self.title,0,wx.ALIGN_CENTER_VERTICAL),(self.settling_time_at_speed),(self.units,0,wx.ALIGN_CENTER_VERTICAL),(self.blank),(self.blank)])
self.title=wx.StaticText(self.output,-1," Settling distance at speed ")
self.settling_distance_at_speed=wx.TextCtrl(self.output,size=(80,-1),style=wx.TE_READONLY)
self.units=wx.StaticText(self.output,-1," mm ")
grid2.AddMany([(self.title,0,wx.ALIGN_CENTER_VERTICAL),(self.settling_distance_at_speed),(self.units,0,wx.ALIGN_CENTER_VERTICAL),(self.blank),(self.blank)])
self.title=wx.StaticText(self.output,-1," Time to first X-ray pulse (t0) ")
self.time_to_first_xray_pulse=wx.TextCtrl(self.output,size=(80,-1),style=wx.TE_READONLY)
self.units=wx.StaticText(self.output,-1," ms ")
grid2.AddMany([(self.title,0,wx.ALIGN_CENTER_VERTICAL),(self.time_to_first_xray_pulse),(self.units,0,wx.ALIGN_CENTER_VERTICAL),(self.blank),(self.blank)])
self.title=wx.StaticText(self.output,-1," Number of data points (N)")
self.number_of_data_points=wx.TextCtrl(self.output,size=(80,-1),style=wx.TE_READONLY|wx.TE_RICH)
#self.units=wx.StaticText(self.output,-1," ms ")
grid2.AddMany([(self.title,0,wx.ALIGN_CENTER_VERTICAL),(self.number_of_data_points),(self.blank),(self.blank),(self.blank)])
self.title=wx.StaticText(self.output,-1," Distance of actual data collection ")
self.distance_of_actual_data_collection=wx.TextCtrl(self.output,size=(80,-1),style=wx.TE_READONLY)
self.units=wx.StaticText(self.output,-1," mm ")
grid2.AddMany([(self.title,0,wx.ALIGN_CENTER_VERTICAL),(self.distance_of_actual_data_collection),(self.units,0,wx.ALIGN_CENTER_VERTICAL),(self.blank),(self.blank)])
self.title=wx.StaticText(self.output,-1," Total distance of translation ")
self.total_distance_of_translation=wx.TextCtrl(self.output,size=(80,-1),style=wx.TE_READONLY)
self.units=wx.StaticText(self.output,-1," mm ")
grid2.AddMany([(self.title,0,wx.ALIGN_CENTER_VERTICAL),(self.total_distance_of_translation),(self.units,0,wx.ALIGN_CENTER_VERTICAL),(self.blank),(self.blank)])
self.title=wx.StaticText(self.output,-1," Time to reach half the return distance ")
self.time_to_reach_half_the_return_distance=wx.TextCtrl(self.output,size=(80,-1),style=wx.TE_READONLY)
self.units=wx.StaticText(self.output,-1," s ")
grid2.AddMany([(self.title,0,wx.ALIGN_CENTER_VERTICAL),(self.time_to_reach_half_the_return_distance),(self.units,0,wx.ALIGN_CENTER_VERTICAL),(self.blank),(self.blank)])
self.title=wx.StaticText(self.output,-1," Max velocity on return ")
self.max_velocity_on_return=wx.TextCtrl(self.output,size=(80,-1),style=wx.TE_READONLY)
self.units=wx.StaticText(self.output,-1," mm/s ")
grid2.AddMany([(self.title,0,wx.ALIGN_CENTER_VERTICAL),(self.max_velocity_on_return),(self.units,0,wx.ALIGN_CENTER_VERTICAL),(self.blank),(self.blank)])
self.title=wx.StaticText(self.output,-1," Total time to return ")
self.total_time_to_return=wx.TextCtrl(self.output,size=(80,-1),style=wx.TE_READONLY)
self.units=wx.StaticText(self.output,-1," s ")
grid2.AddMany([(self.title,0,wx.ALIGN_CENTER_VERTICAL),(self.total_time_to_return),(self.units,0,wx.ALIGN_CENTER_VERTICAL),(self.blank),(self.blank)])
self.title=wx.StaticText(self.output,-1," Total time of translation ")
self.total_time_of_translation=wx.TextCtrl(self.output,size=(80,-1),style=wx.TE_READONLY)
self.units=wx.StaticText(self.output,-1," s ")
grid2.AddMany([(self.title,0,wx.ALIGN_CENTER_VERTICAL),(self.total_time_of_translation),(self.units,0,wx.ALIGN_CENTER_VERTICAL),(self.blank),(self.blank)])
self.title=wx.StaticText(self.output,-1," Full cycle clock ticks ")
self.full_cycle_clock_ticks=wx.TextCtrl(self.output,size=(80,-1),style=wx.TE_READONLY)
#self.units=wx.StaticText(self.output,-1," s ")
grid2.AddMany([(self.title,0,wx.ALIGN_CENTER_VERTICAL),(self.full_cycle_clock_ticks),(self.blank),(self.blank),(self.blank)])
self.title=wx.StaticText(self.output,-1," Measure length (period) ")
self.measure_length=wx.TextCtrl(self.output,size=(80,-1),style=wx.TE_READONLY)
self.units=wx.StaticText(self.output,-1," clock cycles ")
grid2.AddMany([(self.title,0,wx.ALIGN_CENTER_VERTICAL),(self.measure_length),(self.units,0,wx.ALIGN_CENTER_VERTICAL),(self.blank),(self.blank)])
self.output.SetSizer(grid2)
self.output.Fit()
main_page.Add(self.output)
#line=wx.StaticLine(self,style=wx.LI_HORIZONTAL)
#main_page.AddSpacer(10)
#main_page.Add(line,0,wx.GROW,5)
#main_page.AddSpacer(10)
self.buttons=wx.Panel(self)
self.button = wx.Button(self.buttons,label="Send to Alio",size=(100,25),pos=(5,-1))
self.Bind (wx.EVT_BUTTON,self.send_to_alio,self.button)
#self.button2 = wx.Button(self.buttons,label="Send to FPGA",size=(100,25),pos=(100,-1))
#self.Bind (wx.EVT_BUTTON,self.send_to_fpga,self.button2)
main_page.Add(self.buttons)
self.SetSizer(main_page)
# main_page.Add(grid2)
self.Fit()
self.Bind(wx.EVT_TEXT_ENTER,self.on_input)
self.update_parameters()
self.timer = wx.Timer(self)
self.Bind (wx.EVT_TIMER,self.OnTimer)
self.OnTimer()
self.Show()
def OnTimer(self,event=None):
"""Periodically update the panel"""
#self.update_parameters()
self.on_input(self)
self.timer.Start(1000,oneShot=True) # Need to restart the Timer
def define_first_save(self, event):
"""Reads the current position of GonX,GonY,GonZ as starting of
translation"""
param.first_hole_x = round(GonX.value,3)
param.first_hole_y = round(GonY.value,3)
param.first_hole_z = round(GonZ.value,3)
self.update_parameters()
save_settings()
def define_first_goto(self, event):
"""Reads the current position of GonX,GonY,GonZ as starting of
translation"""
GonX.value = param.first_hole_x
GonY.value = param.first_hole_y
GonZ.value = param.first_hole_z
self.update_parameters()
def define_last_save(self, event):
"""Reads the current position of GonX,GonY,GonZ as starting of
translation"""
param.last_hole_x = round(GonX.value,3)
param.last_hole_y = round(GonY.value,3)
param.last_hole_z = round(GonZ.value,3)
self.update_parameters()
save_settings()
def define_last_goto(self, event):
"""Reads the current position of GonX,GonY,GonZ as starting of
translation"""
GonX.value = param.last_hole_x
GonY.value = param.last_hole_y
GonZ.value = param.last_hole_z
self.update_parameters()
def send_to_alio(self, event):
"""Sends calculated values to Alio"""
alio.speed=param.velocity
alio.accel=param.acceleration_time*1000 # Needs to be converted to msec
alio.z_step_size=param.translate_z
alio.x_step_size=param.translate_x
alio.y_step_size=param.translate_y
alio.z_starting=param.first_hole_z-param.acceleration_distance
alio.x_starting=param.first_hole_x
alio.y_starting=param.first_hole_y
def send_to_fpga(self, event):
"""Sends calculated values to FPGA"""
pass
def update_parameters(self):
try:
self.firstX.SetValue(str(param.first_hole_x))
self.firstY.SetValue(str(param.first_hole_y))
self.firstZ.SetValue(str(param.first_hole_z))
self.lastX.SetValue(str(param.last_hole_x))
self.lastY.SetValue(str(param.last_hole_y))
self.lastZ.SetValue(str(param.last_hole_z))
self.step_size.SetValue(str(param.step_size))
self.acceleration.SetValue(str(param.acceleration))
self.repetition_period.SetValue(str(param.repetition_period))
self.settle_period.SetValue(str(param.settle_period))
self.continuous.SetValue(str(param.continuous))
except:
print "Problem loading parameters"
def on_input(self,event):
try:
param.first_hole_x = float(eval(self.firstX.GetValue()))
param.first_hole_y = float(eval(self.firstY.GetValue()))
param.first_hole_z = float(eval(self.firstZ.GetValue()))
param.last_hole_x = float(eval(self.lastX.GetValue()))
param.last_hole_y = float(eval(self.lastY.GetValue()))
param.last_hole_z = float(eval(self.lastZ.GetValue()))
param.step_size = float(eval(self.step_size.GetValue()))
param.acceleration = float(eval(self.acceleration.GetValue()))
param.repetition_period = float(eval(self.repetition_period.GetValue()))
param.settle_period = float(eval(self.settle_period.GetValue()))
param.continuous = float(eval(self.continuous.GetValue()))
except: pass
translation_range()
self.translate_x.SetValue(str(param.translate_x))
#self.translate_x.SetLabel(str(param.translate_x))
self.translate_y.SetValue(str(param.translate_y))
self.translate_z.SetValue(str(param.translate_z))
velocity()
self.velocity.SetValue(str(param.velocity))
acceleration_time()
self.acceleration_time.SetValue(str(param.acceleration_time))
acceleration_distance()
self.acceleration_distance.SetValue(str(param.acceleration_distance))
settling_time_at_speed()
self.settling_time_at_speed.SetValue(str(param.settling_time_at_speed))
settling_distance_at_speed()
self.settling_distance_at_speed.SetValue(str(param.settling_distance_at_speed))
time_to_first_xray_pulse()
self.time_to_first_xray_pulse.SetValue(str(param.time_to_first_xray_pulse))
distance_of_actual_data_collection()
self.distance_of_actual_data_collection.SetValue(str(param.distance_of_actual_data_collection))
total_distance_of_translation()
self.number_of_data_points.SetValue(str(param.number_of_data_points))
self.total_distance_of_translation.SetValue(str(param.total_distance_of_translation))
time_to_reach_half_the_return_distance()
self.time_to_reach_half_the_return_distance.SetValue(str(param.time_to_reach_half_the_return_distance))
max_velocity_on_return()
self.max_velocity_on_return.SetValue(str(param.max_velocity_on_return))
total_time_to_return()
self.total_time_to_return.SetValue(str(param.total_time_to_return))
total_time_of_translation()
self.total_time_of_translation.SetValue(str(param.total_time_of_translation))
full_cycle_clock_ticks()
self.full_cycle_clock_ticks.SetValue(str(param.full_cycle_clock_ticks))
measure_length()
self.measure_length.SetValue(str(param.measure_length))
a=round(param.number_of_data_points,10)
if a.is_integer():
self.number_of_data_points.SetForegroundColour(wx.NullColor)
else:
self.number_of_data_points.SetForegroundColour(wx.RED)
#print param.number_of_data_points
save_settings()
#update_plot()
def Alio_PP():
global win
wx.app = wx.App(redirect=False)
win = AlioWindow()
wx.app.MainLoop()
load_settings()
if __name__ == '__main__':
#P250.value="0" # Tell ALIO to not accept triggers.
Alio_PP()
<file_sep>show_in_list = True
title = 'Diagnostics Configuration'
motor_names = ['diagnostics.list']
names = ['diagnostics']
motor_labels = ['diagnostics']
widths = [300]
line0.description = 'SAXS/WAXS'
line1.description = 'NIH:Channel-Cut-Scan'
line0.updated = '25 Oct 17:31'
line1.updated = '25 Oct 17:31'
line0.diagnostics.list = 'ring_current, bunch_current, temperature'
line1.diagnostics.list = 'xscope.P1, xscope.P2'
command_row = 0
show_define_buttons = False
command_rows = [0]
nrows = 4
line2.description = 'NIH:Slit-Scan'
line2.diagnostics.list = 'xscope.P3'
line2.updated = '2019-01-28 19:21:13'
line3.description = '<NAME>'
description_width = 170
line3.diagnostics.list = 'xscope.P1'
line3.updated = '2019-02-04 11:31:36'<file_sep>#!/usr/bin/env python
"""
Control panel for variable laser attenuator
<NAME>, APS, Jun 8, 2009 - Nov 2, 2017
"""
import wx
from EditableControls import ComboBox
__version__ = "1.2.2" #wx.Colour
class LaserAttenuatorPanel (wx.Frame):
"""variable laser attenuator control panel"""
def __init__(self,trans,title="Laser Attenuator"):
"""trans: attenautor objects"""
self.trans = trans
wx.Frame.__init__(self,parent=None,title=title)
# Highlight an Edit control if its contents have been modified
# but not applied yet by hitting the Enter key.
self.edited = wx.Colour(255,255,220)
panel = wx.Panel(self)
# Controls
style = wx.TE_PROCESS_ENTER
size = (100,-1)
choices = ["0"]
self.Angle = ComboBox(panel,choices=choices,size=size,style=style)
choices = ["1","0.5","0.2","0.1","0.05","0.02","0.01"]
self.Transmission = ComboBox(panel,choices=choices,size=size,style=style)
self.LiveCheckBox = wx.CheckBox (panel,label="Live")
self.RefreshButton = wx.Button (panel,label="Refresh")
# Callbacks
self.Angle.Bind(wx.EVT_CHAR,self.OnEditAngle)
self.Bind (wx.EVT_TEXT_ENTER,self.OnEnterAngle,self.Angle)
self.Bind (wx.EVT_COMBOBOX,self.OnEnterAngle,self.Angle)
self.Transmission.Bind(wx.EVT_CHAR,self.OnEditTransmission)
self.Bind (wx.EVT_TEXT_ENTER,self.OnEnterTransmission,self.Transmission)
self.Bind (wx.EVT_COMBOBOX,self.OnEnterTransmission,self.Transmission)
self.Bind (wx.EVT_CHECKBOX,self.OnLive,self.LiveCheckBox)
self.Bind (wx.EVT_BUTTON,self.OnRefresh,self.RefreshButton)
# Layout
layout = wx.GridBagSizer(1,1)
a = wx.ALIGN_CENTRE_VERTICAL
e = wx.EXPAND
# Specified a label length to prevent line wrapping.
# This is a bug in the Linux version of wxPython 2.6, fixed in 2.8.
size=(160,-1)
t = wx.StaticText(panel,label="Angle [deg]:",size=size)
layout.Add (t,(0,0),flag=a)
layout.Add (self.Angle,(0,1),flag=a|e)
t = wx.StaticText(panel,label="Transmission:",size=size)
layout.Add (t,(1,0),flag=a)
layout.Add (self.Transmission,(1,1),flag=a|e)
# Leave a 10 pixel wide border.
box = wx.BoxSizer(wx.VERTICAL)
box.Add (layout,flag=wx.ALL,border=5)
buttons = wx.BoxSizer(wx.HORIZONTAL)
buttons.Add (self.LiveCheckBox,flag=wx.ALIGN_CENTER_VERTICAL)
buttons.AddSpacer((5,5))
buttons.Add (self.RefreshButton,flag=wx.ALL|wx.ALIGN_CENTER_HORIZONTAL,border=5)
box.Add (buttons,flag=wx.ALL|wx.ALIGN_CENTER_HORIZONTAL,border=5)
panel.SetSizer(box)
panel.Fit()
self.Fit()
self.Show()
# Initialization
self.refresh()
def refresh(self):
"""Updates the controls with current values"""
self.Angle.SetValue("%.1f" % self.trans.angle)
self.Transmission.SetValue("%.3g" % self.trans.value)
def OnLive(self,event):
"""Called when the 'Live' checkbox is either checked or unchecked."""
self.RefreshButton.Enabled = not self.LiveCheckBox.Value
if self.LiveCheckBox.Value == True: self.keep_alive()
def keep_alive(self,event=None):
"""Periodically refresh te displayed settings (every second)."""
if self.LiveCheckBox.Value == False: return
self.refresh()
self.timer = wx.Timer(self)
self.Bind (wx.EVT_TIMER,self.keep_alive,self.timer)
self.timer.Start(1000,oneShot=True)
def OnEditAngle(self,event):
"Called when typing in the position field."
self.Angle.SetBackgroundColour(self.edited)
# Pass this event on to further event handlers bound to this event.
# Otherwise, the typed text does not appear in the window.
event.Skip()
def OnEnterAngle(self,event):
"Called when typing Enter in the position field."
self.Angle.SetBackgroundColour(wx.WHITE)
text = self.Angle.GetValue()
try: value = float(eval(text))
except: self.refresh(); return
self.trans.angle = value
self.refresh()
def OnEditTransmission(self,event):
"Called when typing in the position field."
self.Transmission.SetBackgroundColour(self.edited)
# Pass this event on to further event handlers bound to this event.
# Otherwise, the typed text does not appear in the window.
event.Skip()
def OnEnterTransmission(self,event):
"Called when typing Enter in the position field."
self.Transmission.SetBackgroundColour(wx.WHITE)
text = self.Transmission.GetValue()
try: value = float(eval(text))
except: self.refresh(); return
self.trans.value = value
self.refresh()
def OnRefresh(self,event=None):
"Check whether the network connection is OK."
# Reset pending status of entered new position
self.Angle.SetBackgroundColour(wx.WHITE)
self.Transmission.SetBackgroundColour(wx.WHITE)
self.refresh()
if __name__ == '__main__':
# Needed to initialize WX library
from id14 import trans
wx.app = wx.App(redirect=False)
panel = LaserAttenuatorPanel(trans,title="Laser Attenuator")
wx.app.MainLoop()
<file_sep>This directory is used by Mac OS X as an "Application Bundle".
An application bundle is needed to launch a Python program from the Finder or Dock
and to associate file extension with an application to open a file.
This directory was automatically created from a .py file using the "Build Applet"
utility coming with "MacPython".
I edited the script in the subdirectory "Contents/MacOS" to launch the orignal
.py file, rather than the copy "Build Applet" placed in the "Contents/Resources"
subdirectory.
<NAME>, 26 Jan 2009<file_sep>#!/usr/bin/env python
"""
Trigger of:
- X-ray shutter: R32 #1 J3 Event code 90 ch1
- X-ray attenuator: R32 #2 J4 Event code 91 ch2
- Sample translation: R31 #2 ETR-04 Event code 92 ch3
- Laser shutter: R31 #3 Event code 93 (ch3)
- X-ray area detector: R31 #1 ETR-03 Event code 94 ch4
- Data acquisition: Event code 95
- Timing tool reference Event code 96
Using LCLS event sequencer and event reveiver (EVR)
Two patterns:
- Data collection
- Alignment
<NAME>, 25 Nov 2013 - 2 Dec 2013
"""
__version__ = "1.0.4"
from CA import caget,caput,PV
from numpy import array,nan
from time import sleep
triggers = [
{"name": "X-ray shutter", "EVR": "XPP:R32:EVR:32", "row":1, "channel": 1, "event_code":90},
{"name": "X-ray attenuator", "EVR": "XPP:R32:EVR:32", "row":2, "channel": 2, "event_code":91},
{"name": "Sample translation", "EVR": "XPP:R31:EVR:21", "row":1, "channel": 2, "event_code":92},
{"name": "Laser shutter", "EVR": "XPP:R31:EVR:21", "row":2, "channel": 3, "event_code":93},
{"name": "X-ray area detector","EVR": "XPP:R31:EVR:21", "row":3, "channel": 1, "event_code":94},
]
# EVR: Event Receiver's EPICS record name
# row: 1-based index of the event row in the EDM screen
# channel: 0-based index of the event receiver
def event_code_name(event_code):
"""event_code: integer between 90 and 98"""
for trigger in triggers:
if trigger["event_code"] == event_code: return trigger["name"]
return ""
def event_receiver_setup():
for trigger in triggers:
caput(trigger["EVR"]+":EVENT%sNAME"%trigger["row"],trigger["name"])
caput(trigger["EVR"]+":EVENT%sCTRL.ENM"%trigger["row"],trigger["event_code"])
caput(trigger["EVR"]+":EVENT%sCTRL.ENAB"%trigger["row"],1)
for row in range(1,15):
caput(trigger["EVR"]+":EVENT%sCTRL.OUT%d"%(row,trigger["channel"]),
row==trigger["row"])
# Reset event counter to zero.
caput(trigger["EVR"]+":EVENT%sCNT"%trigger["row"],0)
# Enable event counter.
caput(trigger["EVR"]+":EVENT%sCRTL.VME"%trigger["row"],1)
# Enable the trigger output
caput(trigger["EVR"]+":CTRL.DG%sE"%trigger["channel"],1)
# Polarity normal
caput(trigger["EVR"]+":CTRL.DG%sP"%trigger["channel"],0)
# Program output pulse length of event receiver to 8.333 ms.
caput(trigger["EVR"]+":CTRL.DG%sW"%trigger["channel"],8400)
caput(trigger["EVR"]+":CTRL.DG%sC"%trigger["channel"],119)
class EventSequencer(object):
"""Trigger generator"""
stop_at_step = PV("ECS:SYS0:3:LEN")
event_code = PV("ECS:SYS0:3:SEQ.A")
delta_beam = PV("ECS:SYS0:3:SEQ.B")
fiducial_delays = PV("ECS:SYS0:3:SEQ.C")
burst_count = PV("ECS:SYS0:3:SEQ.D")
process = PV("ECS:SYS0:3:SEQ.PROC")
base_rate = PV("EVNT:SYS0:1:LCLSBEAMRATE")
events = []
def clear(self): self.events = []
def add_event(self,time_mark,event_code):
for i in range(len(self.events),time_mark+1): self.events += [[]]
if not event_code in self.events[time_mark]:
self.events[time_mark] += [event_code]
def add_burst(self,start_time_mark,end_time_mark,event_code):
"""start_time_mark: first
end_time_mark: not included"""
for i in range(start_time_mark,end_time_mark):
self.add_event(i,event_code)
def update(self):
event_code = []
delta_beam = []
last_time_mark = 0
for i in range(0,len(self.events)):
event_group = self.events[i]
if len(event_group) == 0: continue
event_code += event_group
delta_beam += [i-last_time_mark]
delta_beam += [0]*(len(event_group)-1)
last_time_mark = i
assert len(event_code) == len(delta_beam)
n = len(event_code)
self.stop_at_step.value = n
self.event_code.value = event_code+[0]*(2048-n)
self.delta_beam.value = delta_beam+[0]*(2048-n)
self.fiducial_delays.value = [0]*2048
self.burst_count.value = [0]*2048
# Add labels to MEDM screen
event_code += [0]*(20-len(event_code))
for i in range(0,20):
caput("XPP:ECS:IOC:01:EC_3:%02d.DESC"%i,
event_code_name(event_code[i]))
sleep(0.1) # needed
self.process.value = 1
sleep(0.2) # needed
self.process.value = 1 # needed
@property
def sequence_length(self):
"""interger value in multiples of 120-Hz cycles"""
n = self.stop_at_step.value
delta_beam = self.delta_beam.value
sequence_length = sum(delta_beam[0:n])
return sequence_length
@property
def period(self):
"""Repetion time in seconds"""
rate = tofloat(self.base_rate.value)
if rate == 0: return nan
period = self.sequence_length/rate
return period
def single_shot_setup(self):
self.clear()
self.add_burst( 0, 1,90)# X-ray shutter
self.add_burst( 2, 3,92)# Sample translation
self.add_burst( 2, 3,94)# X-ray detector
self.add_burst( 1, 2,95)# Data Acquisition
self.add_event( 0,96) # Timing tool reference
self.add_event(13,0) # add delay and the end for the rep rate
self.update()
event_receiver_setup()
def collection_setup(self):
self.clear()
self.add_burst( 1,11,90)# X-ray shutter
self.add_burst(14,15,90)# X-ray shutter
self.add_burst( 1,11,91)# X-ray attenuator
self.add_burst( 2, 3,92)# Sample translation
self.add_burst(15,16,92)# Sample translation
self.add_burst(14,15,93)# Laser shutter
self.add_burst(12,13,94)# X-ray detector
self.add_burst(25,26,94)# X-ray detector
self.add_burst( 1,13,95)# Data Acquisition (X-ray shutter+1)
self.add_burst(25,26,95)# Data Acquisition (X-ray shutter+1)
self.add_event(26,0) # add delay and the end for the rep rate
self.update()
event_receiver_setup()
def alignment_setup(self):
self.clear()
self.add_burst( 2,12,90)# X-ray shutter
self.add_burst( 2,12,91)# X-ray attenuator
self.add_burst(13,14,92)# Sample translation
self.add_burst(13,14,94)# X-ray detector
self.add_burst( 3,13,95)# Data Acquisition (X-ray shutter+1)
self.add_burst( 0, 1,95)# Data Acquisition (X-ray shutter+1)
self.add_event(12,0) # add delay and the end for the rep rate
##self.add_event(120,0) # for debugging, slow down to 1 Hz
self.update()
event_receiver_setup()
def test_setup(self):
self.clear()
self.add_event(0,90)
self.add_event(0,91)
self.add_event(0,92)
self.add_event(0,93)
self.add_event(0,94)
self.add_event(24,0)
self.update()
event_sequencer = EventSequencer()
def start():
"""Start event sequencer"""
caput("ECS:SYS0:3:PLYCTL",1)
def stop():
"""Start event sequencer"""
caput("ECS:SYS0:3:PLYCTL",0)
class Pulses(object):
"""Number of pulses per acquisition"""
mode_PV = PV("ECS:SYS0:3:PLYMOD") # 0=Once,1=N times,2=Forever
target_count_PV = PV("ECS:SYS0:3:REPCNT")
run_PV = PV("ECS:SYS0:3:PLYCTL")
count_PV = PV("ECS:SYS0:3:PLYCNT") # counting up to target count
doc = "When read return the number of pulses remaining until the burst"\
"ends. When set trigger a burst with the given number of pulses."
def get_value(self):
"""Number of pulses remaining until the burst ends"""
# PV is counting up from zero to count_PV
count = toint(self.target_count_PV.value) - toint(self.count_PV.value)
return count
def set_value(self,count):
if count > 0:
if self.mode_PV.value != 1:
self.mode_PV.value = 1 # Repeat N Times
if self.target_count_PV.value != count:
self.target_count_PV.value = count
self.run_PV.value = 1
if count == 0:
self.run_PV.value = 0
value = property(get_value,set_value,doc=doc)
pulses = Pulses()
class ContinuousTrigger(object):
"""Is continuous triggering enabled?"""
mode_PV = PV("ECS:SYS0:3:PLYMOD")
run_PV = PV("ECS:SYS0:3:PLYCTL")
def get_value(self):
"""Is continuous triggering enabled?"""
return self.mode_PV.value == 2 and self.run_PV.value == 1
def set_value(self,value):
if bool(value) == True:
if self.mode_PV.value != 2:
self.mode_PV.value = 2 # Repeat Forever
self.run_PV.value = 1
else:
self.run_PV.value = 0
value = property(get_value,set_value)
def __repr__(self): return self.PV.name
continuous_trigger = ContinuousTrigger()
class TMode(object):
def get_value(self): return not continuous_trigger.value
def set_value(self,value): continuous_trigger.value = not value
value = property(get_value,set_value)
tmode = TMode()
class Waitt(object):
"""Waiting time between pulses"""
unit = "s"
stepsize = 1/120.
# The repetiton rate is a subhamonic of 60 Hz.
# Not every subharmonic is allowed. Only the following ones:
frequencies={
0: 60,
1: 30,
2: 10,
3: 5,
4: 1,
5: 0.5,
}
def get_value(self):
"""Time between susequent X-ray pulse in seconds"""
return event_sequencer.period
def set_value(self,waitt): pass
value = property(get_value,set_value)
def get_min(self):
"""Lower limit in seconds"""
return min(1.0/array(self.frequencies.values()))
min = property(get_min)
def get_max(self):
"""Upper limit in seconds"""
return max(1.0/array(self.frequencies.values()))
max = property(get_max)
def get_choices(self):
"""Upper limit in seconds"""
return 1.0/array(self.frequencies.values())
choices = property(get_choices)
def next(self,waitt):
"""Closest allowed value to the given waitting time in s"""
from numpy import inf,array,argmin
waitts = 1.0/array(self.frequencies.values())
i = argmin(abs(waitt-waitts))
return waitts[i]
waitt = Waitt()
class TriggerActive(object):
status_PV = PV("ECS:SYS0:3:PLSTAT") # 0: Stopped, 1:Playing
control_PV = PV("ECS:SYS0:3:PLYCTL") # 0: Stop, 1:Start
def get_value(self):
return self.status_PV.value != 0
def set_value(self,value):
self.control_PV.value = 1 if value else 0
value = property(get_value,set_value)
trigger_active = TriggerActive()
class XRayShutterEnabled(object):
"""X-ray shutter trigger enabled?"""
enabled_PV = PV("XPP:R32:EVR:32:EVENT1CTRL.ENAB")
def get_value(self):
return self.enabled_PV.value
def set_value(self,value):
self.enabled_PV.value = 1 if value else 0
value = property(get_value,set_value)
xray_shutter_enabled = XRayShutterEnabled()
mson = xray_shutter_enabled
class XRayShutterOpen(object):
"""X-ray shutter trigger enabled?"""
polarity_PV = PV("XPP:R32:EVR:32:CTRL.DG1P")
def get_value(self):
level_OK = self.polarity_PV.value == 1
active = xray_shutter_enabled.value and trigger_active.value
return level_OK and not active
def set_value(self,value):
self.polarity_PV.value = 1 if value else 0
value = property(get_value,set_value)
xray_shutter_open = XRayShutterOpen()
class XRayAttenuatorInserted(object):
"""X-ray shutter trigger enabled?"""
polarity_PV = PV("XPP:R32:EVR:32:CTRL.DG2P")
def get_value(self):
level_OK = self.polarity_PV.value == 1
active = xray_attenuator_enabled.value and trigger_active.value
return level_OK and not active
def set_value(self,value):
self.polarity_PV.value = 1 if value else 0
value = property(get_value,set_value)
xray_attenuator_inserted = XRayAttenuatorInserted()
class XRayDetectorTrigger():
class TriggerLevel(object):
"""X-ray detector tigger input high?"""
polarity_PV = PV("XPP:R31:EVR:21:CTRL.DG1P")
def get_value(self):
return self.polarity_PV.value == 1
def set_value(self,value):
self.polarity_PV.value = 1 if value else 0
value = property(get_value,set_value)
trigger_level = TriggerLevel()
def trigger_once(self):
"""Send a single trigger pulse of 100 ms duraction
to the X-ray detector"""
self.trigger_level.value = True
sleep(0.1)
self.trigger_level.value = False
class Count(object):
"""X-ray detector tigger input high?"""
# Was unable to use XPP:R31:EVR:21:EVENT3CNT.
# Count was not counting up. <NAME>, 1 Dec 2013
# Using XPP:IPM:EVR:EVENT2CNT instead.
count_PV = PV("XPP:IPM:EVR:EVENT2CNT")
event_code_PV = PV("XPP:IPM:EVR:EVENT2CTRL.ENM")
enabled_PV = PV("XPP:IPM:EVR:EVENT2CTRL.VME")
name_PV = PV("XPP:IPM:EVR:EVENT2NAME")
offset = 0
def setup(self):
self.event_code_PV.value = 94
self.enabled_PV.value = 1
self.name_PV.value = "X-ray area detector"
def get_value(self):
return toint(self.count_PV.value) + self.offset
def set_value(self,value):
# "caput" does not change the count value.
# Using a user-defined offset instead.
self.offset = value - self.value
##self.count_PV.value = value
value = property(get_value,set_value)
count = Count()
xray_detector_trigger = XRayDetectorTrigger()
class SampleTranslationTrigger():
class Count(object):
"""X-ray detector tigger input high?"""
# Was unable to use XPP:R31:EVR:21:EVENT1CNT.
# Count was not counting up. <NAME>, 26 Nov 2013
# Silke recommeded to use XPP:IPM:EVR:EVENT1CNT instead.
count_PV = PV("XPP:IPM:EVR:EVENT1CNT")
event_code_PV = PV("XPP:IPM:EVR:EVENT1CTRL.ENM")
enabled_PV = PV("XPP:IPM:EVR:EVENT1CTRL.VME")
name_PV = PV("XPP:IPM:EVR:EVENT1NAME")
offset = 0
def setup(self):
self.event_code_PV.value = 92
self.enabled_PV.value = 1
self.name_PV.value = "Sample Translation"
def get_value(self):
return int(self.count_PV.value) + self.offset
def set_value(self,value):
# "caput" does not change the count value.
# Using a user-defined offset instead.
self.offset = value - self.value
##self.count_PV.value = value
value = property(get_value,set_value)
count = Count()
sample_translation_trigger = SampleTranslationTrigger()
def toint(x):
"""Convert x to a floating point number.
If not convertible return zero"""
try: return int(x)
except: return 0
def tofloat(x):
"""Convert x to a floating point number.
If not convertible return 'Not a Number'"""
from numpy import nan
try: return float(x)
except: return nan
if __name__ == "__main__":
self = event_sequencer # for debugging
print "event_receiver_setup()"
print "event_sequencer.single_shot_setup()"
print "event_sequencer.collection_setup()"
print "event_sequencer.alignment_setup()"
print "pulses.value = 1"
print "continuous_trigger.value = 1"
print "sample_translation_trigger.count.value"
print "sample_translation_trigger.count.value = 0"
<file_sep>from pylab import *
from table import table
from datetime import datetime
filename = '//id14bxf/data/anfinrud_1006/Data/Test/Test1/Test1.log'
logfile = table(filename,separator="\t")
def seconds(date_time):
"Convert a date string to number of seconds til 1 Jan 1970."
from time import strptime,mktime
return mktime(strptime(date_time,"%d-%b-%y %H:%M:%S"))
t = map(seconds,logfile.date_time)
nom_delay = logfile.nom_delay
act_delay = logfile.act_delay
dt = act_delay - nom_delay
table(filename,separator="\t")
date = [date2num(datetime.fromtimestamp(x)) for x in t]
figure = figure()
figure.subplots_adjust(bottom=0.2)
plot = figure.add_subplot(111)
plot.plot(date,dt/1e-12,'.')
plot.xaxis_date()
formatter = DateFormatter('%b %d %H:%M')
plot.xaxis.set_major_formatter(formatter)
setp(plot.get_xticklabels(),rotation=90,fontsize=10)
show()
<file_sep>#!/bin/env python
"""X-ray beam stabilization
<NAME>, Nov 22, 2015 - Jun 27, 2017
"""
__version__ = "1.2" # rayonix_detector_continuous
from profile import xy_projections,FWHM,CFWHM,xvals,yvals,overloaded_pixels,SNR
from table import table
from CA import caget,caput,PV
from persistent_property import persistent_property
from EPICS_Channel_Archiver import PV_history
from time import time,sleep
from numpy import average,asarray,where
from thread import start_new_thread
from logging import debug,info,warn,error
from time_string import timestamp,date_time
from logfile import LogFile
from os.path import exists
from normpath import normpath
class Xray_Beam_Stabilization(object):
name = "xray_beam_stabilization"
log = LogFile(name+".log",["date time","filename","x","y","x_control","y_control","image_timestamp"])
if log.filename == "":
log.filename = "//mx340hs/data/anfinrud_1702/Logfiles/xray_beam_stabilization.log"
auto_update = False
x_PV = persistent_property("x_PV","14IDC:mir2Th.VAL") # Piezo control voltage in V
x_read_PV = persistent_property("x_read_PV","14IDC:mir2Th.RBV")
y_PV = persistent_property("y_PV","14IDA:DAC1_4.VAL") # Theta in mrad
y_read_PV = persistent_property("y_read_PV","14IDA:DAC1_4.VAL")
x_gain = persistent_property("x_gain",0.143) # mrad/mm
y_gain = persistent_property("y_gain",2.7) # V/mm was: 1/3.3e-3
x_nominal = persistent_property("x_nominal",175.927) # mm from left, 2016-03-05
y_nominal = persistent_property("y_nominal",174.121) # mm from top, 2016-03-05
history_length = persistent_property("history_length",5)
average_samples = persistent_property("average_samples",5)
x_enabled = False
y_enabled = False
ROI_width = persistent_property("ROI_width",1.0) # mm
x_ROI_center = persistent_property("x_ROI_center",175.9) # mm from left
y_ROI_center = persistent_property("y_ROI_center",174.1) # mm from top
min_SNR = persistent_property("min_SNR",5.0) # signal-to-noise ratio
# Use only images matching this pattern, e.g. "5pulses"
history_filter = persistent_property("history_filter","")
analysis_filter = persistent_property("analysis_filter","")
def __init__(self):
""""""
start_new_thread(self.keep_updated,())
def keep_updated(self):
while True:
try:
if self.auto_update: self.update()
if self.x_enabled: self.apply_x_correction()
if self.y_enabled: self.apply_y_correction()
except Exception,m: info("xray_beam_stabilization: %s" % m); break
sleep(1)
def update(self):
t = self.image_timestamp
if t != 0 and abs(t - self.last_image_timestamp) >= 0.1:
f = self.image_basename
x,y = self.beam_position
xc,yc = self.x_control,self.y_control
self.log.log(f,x,y,xc,yc,t)
@property
def x_average(self): return average(self.x_samples)
@property
def y_average(self): return average(self.y_samples)
@property
def x_history(self): return self.history("x",count=self.history_length)
@property
def y_history(self): return self.history("y",count=self.history_length)
@property
def t_history(self): return self.history("date time",count=self.history_length)
@property
def x_samples(self): return self.history("x",count=self.average_samples)
@property
def y_samples(self): return self.history("y",count=self.average_samples)
@property
def last_image_timestamp(self):
t = self.history("image_timestamp",count=1)
t = t[0] if len(t)>0 else 0
return t
def get_x_control(self): return tofloat(caget(self.x_read_PV))
def set_x_control(self,value): return caput(self.x_PV,value)
x_control = property(get_x_control,set_x_control)
def get_y_control(self): return tofloat(caget(self.y_read_PV))
def set_y_control(self,value): return caput(self.y_PV,value)
y_control = property(get_y_control,set_y_control)
def get_x_control_average(self): return average(self.x_control_samples)
def set_x_control_average(self,value): self.x_control = value
x_control_average = property(get_x_control_average,set_x_control_average)
def get_y_control_average(self): return average(self.y_control_samples)
def set_y_control_average(self,value): self.y_control = value
y_control_average = property(get_y_control_average,set_y_control_average)
@property
def x_control_samples(self):
return self.history("x_control",count=self.average_samples)
@property
def y_control_samples(self):
return self.history("y_control",count=self.average_samples)
@property
def x_control_history(self):
return self.history("x_control",count=self.history_length)
@property
def y_control_history(self):
return self.history("y_control",count=self.history_length)
@property
def x_control_corrected(self):
"""Value for the y control in roder to bring the y position back to
its nominal value"""
x_control = self.x_control_average - \
(self.x_average - self.x_nominal)*self.x_gain
return x_control
@property
def y_control_corrected(self):
"""Value for the y control in roder to bring the y position back to
its nominal value"""
y_control = self.y_control_average - \
(self.y_average - self.y_nominal)*self.y_gain
return y_control
def apply_correction(self):
self.apply_x_correction()
self.apply_y_correction()
def apply_x_correction(self):
if self.image_OK:
self.x_control = self.x_control_corrected
def apply_y_correction(self):
if self.image_OK:
self.y_control = self.y_control_corrected
@property
def x_beam(self): return self.beam_position[0]
@property
def y_beam(self): return self.beam_position[1]
@property
def beam_position_HyunSun(self):
from transmissive_beamstop import beam_center
x,y = beam_center(self.image)
return x,y
@property
def beam_position(self):
xprofile,yprofile = xy_projections(self.image,self.ROI_center,self.ROI_width)
x,y = CFWHM(xprofile),CFWHM(yprofile)
return x,y
@property
def ROI_center(self): return self.x_ROI_center,self.y_ROI_center
@property
def image_OK(self):
if self.image_overloaded: OK = False
elif self.SNR < self.min_SNR: OK = False
elif self.analysis_filter not in self.image_basename: OK = False
else: OK = True
return OK
@property
def image_overloaded(self):
return overloaded_pixels(self.image,self.ROI_center,self.ROI_width)
@property
def SNR(self):
xprofile,yprofile = xy_projections(self.image,self.ROI_center,self.ROI_width)
return (SNR(xprofile)+SNR(yprofile))/2
@property
def image(self):
from numimage import numimage
from numpy import uint16
filename = self.image_filename
if filename: image = numimage(filename)
else: image = self.default_image
return image
@property
def default_image(self):
from numimage import numimage
from numpy import uint16
image = numimage((3840,3840),pixelsize=0.0886,dtype=uint16)+10
return image
@property
def image_timestamp(self):
"""Full pathname of the last recorded image"""
from os.path import getmtime
from normpath import normpath
filename = self.image_filename
t = getmtime(normpath(filename)) if filename else 0
return t
@property
def image_filename(self):
"""Full pathname of the last recorded image"""
image_filenames = self.image_filenames
if len(image_filenames)>0: image_filename = image_filenames[-1]
else: image_filename = ""
self.last_image_filename = image_filename
return image_filename
last_image_filename = ""
@property
def image_filenames(self):
"""Full pathnames of the last recorded images"""
from rayonix_detector_continuous import ccd
return ccd.image_filenames
@property
def image_basename(self):
"""Filename of the last recorded image, with out directory"""
from os.path import basename
return basename(self.image_filename)
def history(self,name,count):
"""Log history filtered by image filename pattern"""
from numpy import array,chararray
filename = self.log.history("filename",count=count)
values = self.log.history(name,count=count)
filename = array(filename,str).view(chararray)
match = filename.find(self.history_filter)>=0
values = array(values)[match]
return values
xray_beam_stabilization = Xray_Beam_Stabilization()
def tofloat(x):
"""Convert to floating point number without throwing exception"""
from numpy import nan
try: return float(x)
except: return nan
if __name__ == "__main__":
from pdb import pm
self = xray_beam_stabilization # for debugging
print('self.log.filename = %r' % self.log.filename)
print('self.history_filter = %r' % self.history_filter)
print('self.history("x",count=10)')
print('self.x_history')
print('self.update()')
<file_sep>#!/usr/bin/env python
"""Grapical User Interface
Author: <NAME>
Date created: 2008-11-23
Date last modified: 2019-03-26
"""
__version__ = "1.10" # subpanels items may be preceeded by labels
import wx, wx3_compatibility
from EditableControls import ComboBox,TextCtrl # customized versions
from logging import debug,info,warn,error
from traceback import format_exc
from numpy import inf
class BasePanel(wx.Frame):
"""Control Panel for FPGA Timing System"""
from persistent_property import persistent_property
from collections import OrderedDict as odict
CustomView = persistent_property("CustomView",[])
views = odict([("Standard","StandardView"),("Custom","CustomView")])
view = persistent_property("view","Standard")
from setting import setting
refresh_period = setting("refresh_period",1.0)
from numpy import inf
refresh_period_choices_all = [0.1,0.2,0.5,1.,2.,5,10.,20.,30.,60.,inf]
@property
def refresh_period_choices(self):
choices = self.refresh_period_choices_all
if not self.refresh_period in choices:
choices = sorted(choices + [self.refresh_period])
return choices
def __init__(self,parent=None,name="BasePanel",title="Base Panel",
component=object,parameters=[],standard_view=[],subpanels=[],buttons=[],
subname=True,layout=[],label_width=150,object=None,
refresh=False,live=False,update=[],
icon=None,
*common_args,**common_kwargs):
wx.Frame.__init__(self,parent=parent)
if hasattr(parent,"Title"): title = parent.Title+" "+title
self.Title = title
self.name = name
self.component = component
self.parameters = parameters
self.StandardView = standard_view
self.subpanels = subpanels
self.buttons = buttons
self.layout = layout
self.object = object if object is not None else self
self.update = update
if subname and hasattr(parent,"name"):
self.name = parent.name+"."+self.name
if self.CustomView == []: self.CustomView = standard_view
# Icon
from Icon import SetIcon
SetIcon(self,icon)
# Controls
self.panel = wx.Panel(self)
self.controls = []
for args,kwargs in self.parameters:
args += common_args
kwargs.update(common_kwargs)
if hasattr(args[0],"WindowStyle"): component = args[0]; args = args[1:]
else: component = self.component
if live or refresh:
if not "refresh_period" in kwargs: kwargs["refresh_period"] = inf
kwargs["label_width"] = label_width
self.controls += [component(self.panel,*args,**kwargs)]
self.components = []
for row in self.layout:
panel = wx.Panel(self.panel)
panel.title = ""
layout = wx.BoxSizer()
self.controls += [panel]
self.components += [[]]
for cell in row:
if type(cell) == str:
component_type,args = wx.StaticText,[]
kwargs = {"label":cell,"size":(label_width,-1)}
panel.title = cell
else:
component_type,args,kwargs = cell
if len(args) < 2 and not "object" in kwargs and component_type is not wx.StaticText:
kwargs["object"] = self.object
if live or refresh:
if not "refresh_period" in kwargs and component_type != wx.StaticText:
kwargs["refresh_period"] = inf
component = component_type(panel,*args,**kwargs)
flag = wx.ALIGN_CENTRE_VERTICAL|wx.EXPAND
layout.Add(component,flag=flag)
self.components[-1] += [component]
panel.SetSizer(layout)
panel.Fit()
self.LiveCheckBox = wx.CheckBox(self.panel,label="Live")
style = wx.BU_EXACTFIT
self.RefreshButton = wx.ToggleButton(self.panel,label="Refresh",style=style)
self.ApplyButton = wx.ToggleButton(self.panel,label="Apply",style=style)
self.Buttons = []
for (i,(label,panel)) in enumerate(self.buttons):
Button = wx.Button(self.panel,label=label,style=style,id=i)
self.Buttons += [Button]
# Menus
menuBar = wx.MenuBar()
# Edit
menu = wx.Menu()
menu.Append(wx.ID_CUT,"Cu&t\tCtrl+X","selection to clipboard")
menu.Append(wx.ID_COPY,"&Copy\tCtrl+C","selection to clipboard")
menu.Append(wx.ID_PASTE,"&Paste\tCtrl+V","clipboard to selection")
menu.Append(wx.ID_DELETE,"&Delete\tDel","clear selection")
menu.Append(wx.ID_SELECTALL,"Select &All\tCtrl+A")
menuBar.Append(menu,"&Edit")
# View
self.ViewMenu = wx.Menu()
for i in range(0,len(self.views)):
self.ViewMenu.AppendCheckItem(10+i,self.views.keys()[i])
self.ViewMenu.AppendSeparator()
for i in range(0,len(self.controls)):
self.ViewMenu.AppendCheckItem(100+i,Title(self.controls[i]))
menuBar.Append(self.ViewMenu,"&View")
# Refresh
self.RefreshMenu = wx.Menu()
menuBar.Append(self.RefreshMenu,"&Refresh")
# More
if len(self.subpanels) > 0:
menu = wx.Menu()
for i in range(0,len(self.subpanels)):
if hasattr(subpanels[i],"__len__"):
title = self.subpanels[i][0]
else:
if hasattr(self.subpanels[i],"title"):
title = self.subpanels[i].title+"..."
elif hasattr(self.subpanels[i],"name"):
title = self.subpanels[i].name.replace("_","").title()+"..."
elif hasattr(self.subpanels[i],"__name__"):
title = self.subpanels[i].__name__.replace("_","").title()+"..."
else: title = "Control Panel..."
menu.Append (200+i,title)
menuBar.Append (menu,"&More")
# Help
menu = wx.Menu()
menu.Append (wx.ID_ABOUT,"About...","Show version number")
menuBar.Append (menu,"&Help")
self.SetMenuBar (menuBar)
# Callbacks
for i in range(0,len(self.views)):
self.Bind(wx.EVT_MENU,self.OnSelectView,id=10+i)
for i in range(0,len(self.controls)):
self.Bind(wx.EVT_MENU,self.OnView,id=100+i)
self.Bind(wx.EVT_MENU_OPEN,self.OnMenuOpen)
##self.ViewMenu.Bind(wx.EVT_MENU_OPEN,self.OnViewMenuOpen)
##self.RefreshMenu.Bind(wx.EVT_MENU_OPEN,self.OnRefreshMenuOpen)
for i in range(0,len(self.refresh_period_choices)):
self.Bind(wx.EVT_MENU,self.OnRefreshPeriod,id=300+i)
self.Bind(wx.EVT_MENU,self.OnRefreshPeriodOther,id=399)
for i in range(0,len(self.subpanels)):
self.Bind(wx.EVT_MENU,self.OnSubpanel,id=200+i)
self.Bind(wx.EVT_MENU,self.OnAbout,id=wx.ID_ABOUT)
self.Bind(wx.EVT_SIZE,self.OnResize)
self.Bind(wx.EVT_CHECKBOX,self.OnLive,self.LiveCheckBox)
self.Bind(wx.EVT_TOGGLEBUTTON,self.OnRefresh,self.RefreshButton)
self.Bind(wx.EVT_TOGGLEBUTTON,self.OnApply,self.ApplyButton)
for Button in self.Buttons: self.Bind(wx.EVT_BUTTON,self.OnButton,Button)
self.Bind(wx.EVT_CLOSE,self.OnClose)
# Layout
layout = wx.BoxSizer(wx.VERTICAL)
flag = wx.ALL|wx.EXPAND
for c in self.controls: layout.Add(c,flag=flag,border=0,proportion=1)
for c in self.controls: c.Shown = Title(c) in self.view
# Leave a 5-pixel wide border.
box = wx.BoxSizer(wx.VERTICAL)
box.Add(layout,flag=flag,border=5,proportion=1)
buttons = wx.BoxSizer(wx.HORIZONTAL)
buttons.Add(self.LiveCheckBox,flag=wx.ALIGN_CENTER_VERTICAL)
buttons.AddSpacer(1)
buttons.Add(self.RefreshButton)
buttons.AddSpacer(1)
buttons.Add (self.ApplyButton)
buttons.AddSpacer(2)
for Button in self.Buttons:
buttons.AddSpacer(1)
buttons.Add(Button)
box.Add (buttons,flag=wx.ALL|wx.ALIGN_CENTER_HORIZONTAL,border=5)
self.RefreshButton.Shown = refresh
self.LiveCheckBox.Shown = live
self.ApplyButton.Shown = True if self.update else False
self.panel.Sizer = box
self.panel.Fit()
self.Fit()
# Initialization
if not self.view in self.views: self.view = self.views.keys()[0]
self.View = getattr(self,self.views[self.view])
self.Show()
# Refresh
self.timer = wx.Timer(self)
self.Bind (wx.EVT_TIMER,self.OnTimer,self.timer)
self.timer.Start(200,oneShot=True)
def OnTimer(self,event):
"""Perform periodic updates"""
if self.Shown:
self.UpdateRefreshButton()
self.timer.Start(200,oneShot=True)
def UpdateRefreshButton(self):
"""Update the refresh button"""
self.RefreshButton.Value = self.refreshing
def OnResize(self,event):
self.panel.Fit()
event.Skip() # call default handler
def get_View(self):
"""Which control to show? List of strings"""
return [Title(c) for c in self.controls if c.Shown]
def set_View(self,value):
for c in self.controls: c.Shown = Title(c) in value
self.panel.Sizer.Fit(self)
View = property(get_View,set_View)
def OnMenuOpen(self,event):
debug("Menu opened: %r" % event.EventObject)
if event.EventObject == self.ViewMenu: self.OnViewMenuOpen(event)
if event.EventObject == self.RefreshMenu: self.OnRefreshMenuOpen(event)
def OnViewMenuOpen(self,event):
"""Handle "View" menu display"""
debug("View menu opened")
for i in range(0,len(self.views)):
self.ViewMenu.Check(10+i,self.views.keys()[i] == self.view)
for i in range(0,len(self.controls)):
self.ViewMenu.Check(100+i,self.controls[i].Shown)
self.ViewMenu.Enable(100+i,self.view != "Standard")
def OnSelectView(self,event):
"""Called if one of the items of the "View" menu is selected"""
n = event.Id-10
self.view = self.views.keys()[n]
self.View = getattr(self,self.views.values()[n])
def OnView(self,event):
"""Called if one of the items of the "View" menu is selected"""
n = event.Id-100
self.controls[n].Shown = not self.controls[n].Shown
self.panel.Sizer.Fit(self)
view = [Title(c) for c in self.controls if c.Shown]
setattr(self,self.views[self.view],view)
def OnRefreshMenuOpen(self,event):
"""Handle "Refresh" menu display"""
debug("Refresh menu opened")
menu = self.RefreshMenu
for item in menu.MenuItems: menu.RemoveItem(item)
from time_string import time_string
for i,choice in enumerate(self.refresh_period_choices):
label = time_string(choice)
menu.AppendCheckItem(300+i,label)
menu.AppendSeparator()
menu.Append(399,"Other...")
def same(x,y):
from numpy import isinf
return (x == y) or (isinf(x) and isinf(y))
for i,choice in enumerate(self.refresh_period_choices):
checked = same(choice,self.refresh_period)
menu.Check(300+i,checked)
def OnRefreshPeriod(self,event):
"""Called if one of the items of the "Refresh" menu is selected"""
debug("Refresh ID=%r selected" % event.Id)
n = event.Id-300
if n in range(0,len(self.refresh_period_choices)):
self.refresh_period = self.refresh_period_choices[n]
debug("refresh_period %r" % self.refresh_period)
def OnRefreshPeriodOther(self,event):
panel = RefreshPeriodPanel(self)
panel.CenterOnParent()
def OnSubpanel(self,event):
n = event.Id-200
if 0 <= n < len(self.subpanels):
if hasattr(self.subpanels[n],"__len__"):
PanelType = self.subpanels[n][1]
else: PanelType = self.subpanels[n]
##panel = PanelType(self)
##panel.CenterOnParent()
from start import start,modulename
start(modulename(PanelType),PanelType.__name__+"()")
def OnAbout(self,event):
"""Show panel with additional parameters"""
from os.path import basename
from inspect import getfile,getmodule
from os.path import getmtime
from datetime import datetime
filename = getfile(type(self))
info = basename(filename)+" "+getmodule(type(self)).__version__
info += "\n\n"+getmodule(type(self)).__doc__
dlg = wx.MessageDialog(self,info,"About",wx.OK|wx.ICON_INFORMATION)
dlg.CenterOnParent()
dlg.ShowModal()
dlg.Destroy()
def OnRefresh(self,event):
"""Handle 'Refresh' button"""
self.refresh()
def OnLive(self,event):
"""Called when the 'Live' checkbox is either checked or unchecked."""
##self.RefreshButton.Enabled = not self.LiveCheckBox.Value
if self.LiveCheckBox.Value == True: self.keep_alive()
def OnApply(self,event):
"""Handle 'Apply' button."""
#for proc in self.update: proc()
self.apply()
def OnButton(self,event):
##debug("Button %r pressed" % event.Id)
n = event.Id
if 0 <= n < len(self.buttons):
PanelType = self.buttons[n][1]
##panel = PanelType(self)
##panel.CenterOnParent()
from start import start,modulename
start(modulename(PanelType),PanelType.__name__+"()")
def apply(self):
"""Handle 'Apply' button."""
if not hasattr(self,"applying"): self.applying = False
if not self.applying:
from wx.lib.newevent import NewEvent
self.ApplyEvent = NewEvent()[1]
self.Bind(self.ApplyEvent,self.UpdateApplyButton)
from threading import Thread
self.apply_thread = Thread(target=self.apply_background,
name=self.name+".apply")
self.apply_thread.daemon = True
self.applying = True
self.apply_thread.start()
def apply_background(self):
"""Handle 'Apply' button."""
try:
for proc in self.update:
try: proc()
except Exception,msg:
error("Apply: %s\n%s" % (msg,format_exc()))
self.applying = False
# Refresh GUI. May be called from non-GUI thread"""
event = wx.PyCommandEvent(self.ApplyEvent.typeId,self.Id)
wx.PostEvent(self.EventHandler,event) # call UpdateApplyButton in GUI thread
except wx.PyDeadObjectError: pass
def UpdateApplyButton(self,event):
"""Handle 'Apply' button."""
self.ApplyButton.Value = self.applying
def refresh(self):
"""Updates the controls with current values"""
for control in self.all_controls:
if control.Shown and hasattr(control,"refresh"): control.refresh()
@property
def refreshing(self):
"""Is any of the controls still in the process of refreshing after a
call of 'refresh'?"""
refreshing = all([c.Shown and getattr(c,"refreshing",False) for c in
self.all_controls])
return refreshing
@property
def all_controls(self):
"""All controls as list of objects"""
controls = []
controls += self.controls
for row in self.components: controls += [comp for comp in row]
return controls
def keep_alive(self,event=None):
"""Periodically refresh the displayed settings (every second)."""
if self.Shown:
if self.LiveCheckBox.Value == True:
self.RefreshButton.Value = True
self.refresh()
self.keep_alive_timer = wx.Timer(self)
self.Bind(wx.EVT_TIMER,self.keep_alive,self.keep_alive_timer)
self.keep_alive_timer.Start(int(self.refresh_period*1000),oneShot=True)
def OnClose(self,event):
"""Called when the windows's close button is clicked"""
self.Show(False)
##for control in self.all_controls: control.Destroy()
##self.Destroy() # might crash under Windows
wx.CallLater(1000,self.Destroy)
class PropertyPanel(wx.Panel):
"""A component for 'BasePanel'"""
def __init__(self,parent=None,title="",object=None,name="",type="",choices=[],format="",
read_only=False,digits=None,refresh_period=1.0,width=120,unit="",label_width=180):
"""title: descriptive label
name: property name of object
"""
wx.Panel.__init__(self,parent)
self.title = title
self.object = object
self.name = name
self.choices = choices
self.type = type
self.format = format
self.unit = unit
self.read_only = read_only
if digits is not None: self.format = "%%.%df" % digits
self.refresh_period = refresh_period
self.changing = False
# Controls
style = wx.TE_PROCESS_ENTER
if not self.read_only:
self.Current = ComboBox(self,size=(width,-1),style=style)
else: self.Current = wx.TextCtrl(self,size=(width,-1),style=wx.TE_READONLY)
# Callbacks
self.Bind(wx.EVT_TEXT_ENTER,self.OnChange,self.Current)
self.Bind(wx.EVT_COMBOBOX,self.OnChange,self.Current)
# Layout
layout = wx.BoxSizer()
av = wx.ALIGN_CENTRE_VERTICAL
e = wx.EXPAND
if self.title:
label = wx.StaticText(self,label=self.title+":",size=(label_width,-1))
layout.Add(label,flag=av)
layout.Add(self.Current,flag=av|e,proportion=1)
self.SetSizer(layout)
self.Fit()
# Refresh
self.attributes = [self.name]
from numpy import nan
self.values = {} ##dict([(n,nan) for n in self.attributes])
self.old_values = {}
from threading import Thread
self.refresh_thread = Thread(target=self.refresh_background,
name=self.name+".refresh")
self.refresh_thread.daemon = True
self.refreshing = False
from wx.lib.newevent import NewEvent
self.EVT_THREAD = NewEvent()[1]
self.Bind(self.EVT_THREAD,self.OnUpdate)
self.thread = Thread(target=self.keep_updated,name=self.name)
self.thread.daemon = True
self.thread.start()
def keep_updated(self):
"""Periodically refresh the displayed settings."""
from time import time,sleep
try:
while True:
t0 = time()
while time() < t0+self.refresh_period: sleep(0.1)
if self.Shown:
self.update_data()
if self.data_changed: self.force_refresh()
except wx.PyDeadObjectError: pass
def refresh(self):
"""Force update"""
from threading import Thread
if not self.refreshing and self.Shown:
self.refresh_thread = Thread(target=self.refresh_background,
name=self.name+".refresh")
self.refresh_thread.daemon = True
self.refreshing = True
self.refresh_thread.start()
def refresh_background(self):
"""Force update"""
try:
self.update_data()
if self.data_changed: self.force_refresh()
self.refreshing = False
except wx.PyDeadObjectError: pass
def force_refresh(self):
"""MAke the control update. May be called from non-GUI thread"""
event = wx.PyCommandEvent(self.EVT_THREAD.typeId,self.Id)
wx.PostEvent(self.EventHandler,event) # call OnUpdate in GUI thread
def update_data(self):
"""Retreive status information"""
from numpy import nan
self.old_values = dict(self.values) # make a copy
self.values[self.name] = self.getattr(self.object,self.name,nan)
from time import time
self.changed = time()
from numpy import nan
@staticmethod
def getattr(object,attribute,default_value=nan):
"""Get a propoerty of an object
attribute: e.g. 'value' or 'member.value'"""
try: return eval("object."+attribute)
except Exception,msg:
error("%s.%s: %s\n%s" % (object,attribute,msg,format_exc()))
return default_value
@property
def data_changed(self):
"""Did the last 'update_data' change the data to be plotted?"""
changed = (self.values != self.old_values)
return changed
def OnUpdate(self,event=None):
"""Periodically refresh the displayed settings."""
self.refresh_status()
def refresh_status(self):
"""Update the displayed value in the indicator"""
value = self.formatted_text(self.values[self.name]) \
if self.name in self.values else ""
if self.changing: value += " > "+self.formatted_text(self.new_value)
choices = self.formatted_choices(self.choices)
if not "" in choices: choices += [""]
self.Current.Items = choices
self.Current.Value = value
self.Current.BackgroundColour = \
(255,200,200) if self.changing else (255,255,255)
def formatted_text(self,value):
"""Value as text"""
if isnan(value): text = ""
elif self.type.startswith("time") or self.type.startswith("frequency"):
from numpy import asarray,concatenate,arange,unique
from time_string import time_string
precision = self.type.split(".")[-1][0]
try: precision = int(precision)
except: precision = 3
if self.type.startswith("time"):
def my_format(x): return time_string(x,precision)
else:
def my_format(x): return to_SI_format(1./x,precision)+"Hz"
text = my_format(value)
elif self.type == "date":
from time_string import date_time
text = date_time(value)
elif self.type == "binary":
text = "%g (%s)"%(value,format(value,"#08b"))
elif self.type == "boolean":
text = "On" if value else "Off"
elif self.type == "integer":
text = "%d" % value
elif self.type == "float":
text = "%g" % value
elif self.type == "list":
text = ",".join([str(x) for x in value])
elif self.type.startswith("{"): # dictionary
try:
map = eval(self.type)
text = map[value]
except: text = str(value)
elif "/" in self.type: # list of names
choices = self.type.split("/")
try: text = choices[int(value)]
except Exception,msg:
debug("PropertyPanel.refresh: %r: type %r, value %r" %
(self.name,self.type,value))
text = str(value)
else:
if isnan(value): text = ""
elif type(value) == str: text = value
elif type(value) == bool: text = "On" if value else "Off"
elif self.format:
try: text = self.format % value
except Exception,msg: text = ""
else: text = str(value)
if self.unit and text: text += " "+self.unit
return text
def formatted_choices(self,choices):
"""Choices as text"""
if hasattr(choices,"__call__"): choices = choices()
if self.type.startswith("time") or self.type.startswith("frequency"):
from numpy import asarray,concatenate,arange,unique
from time_string import time_string
precision = self.type.split(".")[-1][0]
try: precision = int(precision)
except: precision = 3
if self.type.startswith("time"):
def my_format(x): return time_string(x,precision)
else:
def my_format(x): return to_SI_format(1./x,precision)+"Hz"
choices = asarray(choices)
if len(choices) == 0:
choices = concatenate(([0],10**(arange(-11,1,0.25))))
if "delay" in self.name and hasattr(self.object,"next_delay"):
choices = unique([self.object.next_delay(t) for t in choices])
choices = [my_format(t) for t in choices]
elif self.type == "date": pass
elif self.type == "binary": pass
elif self.type == "boolean":
choices = ["On","Off"]
elif self.type == "integer":
choices = ["0"]
elif self.type.startswith("{"): # dictionary
try:
map = eval(self.type)
if not choices: choices = map.values()
except: pass
elif "/" in self.type: # list of names
choices = self.type.split("/")
else:
if len(choices) == 0 and not self.read_only:
if hasattr(self.object,self.name+"s") \
and getattr(self.object,self.name+"s") is not None:
choices = list(getattr(self.object,self.name+"s"))
if len(choices) == 0 and not self.read_only:
if hasattr(self.object,self.name+"_choices") \
and getattr(self.object,self.name+"_choices") is not None:
choices = list(getattr(self.object,self.name+"_choices"))
choices = [str(x) for x in choices]
return choices
def OnChange(self,event):
from numpy import nan,inf # for "eval"
text = str(self.Current.Value)
text = text.replace(self.unit,"")
text = text.rstrip() # ignore trailing blanks
if self.type.startswith("time") or self.type.startswith("frequency"):
if not self.type.startswith("frequency"):
from time_string import seconds
value = seconds(text)
else: value = 1/from_SI_format(text.replace("Hz",""))
elif self.type == "binary":
# If both decimal and binary values are given,
# use the value that has been modified as the nwe value.
if "(0b" in text:
i = text.index("(0b")
text1,text2 = text[0:i],text[i:]
try: value1,value2 = int(eval(text1)),int(eval(text2))
except Exception,msg: debug("%r"%msg); return
old_value = getattr(self.object,self.name)
value = value1 if value1 != old_value else value2
else:
try: value = int(eval(text))
except: return
elif self.type == "boolean": value = (text == "On")
elif self.type == "integer":
if text == "": value = nan
else:
try: value = int(eval(text))
except: return
elif self.type == "float":
if text == "": value = nan
else:
try: value = float(eval(text))
except: return
elif self.type.startswith("{"): # dictionary
try:
map = eval(self.type)
inv_map = {v: k for k, v in map.items()}
value = inv_map[text]
except: return
elif "/" in self.type: # list of choices
choices = self.type.split("/")
try: value = choices.index(text)
except:
try: value = eval(text)
except: return
else:
old_value = getattr(self.object,self.name)
if type(old_value) == str: value = text
elif type(old_value) == bool: value = (text == "On")
else:
try: value = eval(text)
except: return
from threading import Thread
if not self.changing:
self.change_thread = Thread(target=self.change_background,
args=(),name=self.name+".change")
self.change_thread.daemon = True
self.changing = True
self.new_value = value
self.change_thread.start()
self.refresh_status()
def change_background(self):
"""If the control has changed apply the change to the object is
is controlling."""
try:
debug("Starting %r.%s = %r..." % (self.object,self.name,self.new_value))
setattr(self.object,self.name,self.new_value)
debug("Finished %r.%s = %r" % (self.object,self.name,self.new_value))
self.update_data()
debug("Updated %r.%s = %r" % (self.object,self.name,self.values[self.name]))
self.changing = False
self.force_refresh()
except wx.PyDeadObjectError: pass
class TweakPanel(wx.Panel):
"""A component for 'BasePanel'"""
def __init__(self,parent=None,title="",object=None,name="",digits=3,
width=90,refresh_period=1.0,label_width=180,**kwargs):
"""title: descriptive label
name: name of a callable member function of object
"""
wx.Panel.__init__(self,parent)
self.title = title
self.object = object
self.name = name
self.digits = digits
self.refresh_period = refresh_period
# Standardize vertical size of controls
test = wx.ComboBox(self)
w,h = test.Size
test.Destroy()
# Controls
style = wx.TE_PROCESS_ENTER
self.Control = TextCtrl(self,size=(width,h),style=style)
self.TweakControl = wx.SpinButton(self,size=(-1,h))
self.TweakControl.SetRange(-100000,100000)
# Callbacks
self.Bind(wx.EVT_TEXT_ENTER,self.OnChange,self.Control)
self.Bind(wx.EVT_SPIN_DOWN,self.OnTweakDown,self.TweakControl)
self.Bind(wx.EVT_SPIN_UP,self.OnTweakUp,self.TweakControl)
# Layout
layout = wx.BoxSizer()
av = wx.ALIGN_CENTRE_VERTICAL
e = wx.EXPAND
if self.title:
label = wx.StaticText(self,label=self.title+":",size=(label_width,-1))
layout.Add(label,flag=av)
layout.Add(self.Control,flag=av|e,proportion=1)
layout.Add(self.TweakControl,flag=av|e)
self.SetSizer(layout)
self.Fit()
# Refresh
self.refreshing = False
from threading import Thread
from wx.lib.newevent import NewEvent
self.EVT_THREAD = NewEvent()[1]
self.Bind(self.EVT_THREAD,self.OnUpdate)
thread = Thread(target=self.keep_updated,name=self.name+".keep_updated")
thread.daemon = True
thread.start()
def keep_updated(self):
"""Periodically refresh the displayed settings."""
from time import time,sleep
while True:
try:
t0 = time()
while time() < t0+self.refresh_period: sleep(0.1)
if self.Shown:
self.value = getattr(self.object,self.name)
event = wx.PyCommandEvent(self.EVT_THREAD.typeId,self.Id)
wx.PostEvent(self.EventHandler,event)
except wx.PyDeadObjectError: break
def refresh(self):
"""Refresh the displayed settings."""
if not self.refreshing and self.Shown:
from threading import Thread
thread = Thread(target=self.refresh_background,
name=self.name+".refresh")
thread.daemon = True
self.refreshing = True
thread.start()
def refresh_background(self):
"""Refresh the displayed settings."""
self.value = getattr(self.object,self.name)
event = wx.PyCommandEvent(self.EVT_THREAD.typeId,self.Id)
wx.PostEvent(self.EventHandler,event)
self.refreshing = False
def update_data(self):
"""Retreive status information"""
self.old_values = dict(self.values) # make a copy
for n in self.attributes: self.values[n] = getattr(self.object,n)
@property
def data_changed(self):
"""Did the last 'update_data' change the data to be plotted?"""
changed = (self.values != self.old_values)
return changed
def OnUpdate(self,event=None):
"""Refresh the displayed settings."""
text = "%.*f" % (self.digits,self.value)
self.Control.Value = text
def OnChange(self,event):
text = self.Control.Value
try: value = eval(text)
except Exception,msg:
warn("TweakPanel %r: %r: %s" % (self.name,text,msg))
self.refresh()
return
setattr(self.object,self.name,value)
self.refresh()
def OnTweakUp(self,event):
self.Tweak(+1)
def OnTweakDown(self,event):
self.Tweak(-1)
def Tweak(self,sign):
text = str(self.Control.Value)
cursor,end = self.Control.Selection
if cursor == end and cursor>0: cursor -= 1
if cursor == len(text) and len(text)>0: cursor = len(text) - 1
if "." in text:
n = text.find(".")-cursor-1
if n<0: n += 1
else: n = len(text)-cursor-1
##debug("Tweak %+g,%r,cur %r,end %r,digit %r" % (sign,text,cursor,end,n))
incr = 10**n
try: value = eval(text)
except Exception,msg: self.refresh(); return
value += sign*incr
text = "%.*f" % (self.digits,value)
if "." in text:
if n>=0: cursor = text.find(".")-n-1
else: cursor = text.find(".")-n
else: cursor = len(text)-n-1
if cursor<0: cursor = 0
end = cursor+1
##debug("Tweak %+g,%r,cur %r,end %r,digit %r" % (sign,text,cursor,end,n))
setattr(self.object,self.name,value)
self.Control.SetFocus()
self.Control.Value = text
self.Control.SetSelection(cursor,end)
class TogglePanel(wx.Panel):
"""A component for 'BasePanel'"""
def __init__(self,parent=None,title="",object=None,name="",type="Off/On",
width=None,refresh_period=1.0,label="",size=None,label_width=180):
"""title: descriptive label
name: name of a callable member function of object
label: default label, if object.name failes
"""
wx.Panel.__init__(self,parent)
self.title = title
self.object = object
self.name = name
self.type = type
self.refresh_period = refresh_period
self.label = label
self.width = -1
if width is not None: self.width = width
if size is not None: self.width = size[0]
# Standardize vertical size of controls
test = wx.ComboBox(self)
w,h = test.Size
test.Destroy()
# Controls
style = wx.TE_PROCESS_ENTER
self.Control = wx.ToggleButton(self,size=(self.width,h),label=label)
# Callbacks
self.Bind(wx.EVT_TOGGLEBUTTON,self.OnChange,self.Control)
# Layout
layout = wx.BoxSizer()
av = wx.ALIGN_CENTRE_VERTICAL
e = wx.EXPAND
if self.title:
label = wx.StaticText(self,label=self.title+":",size=(label_width,-1))
layout.Add(label,flag=av)
layout.Add(self.Control,flag=av|e,proportion=1)
self.SetSizer(layout)
self.Fit()
# Refresh
self.attributes = [self.name]
from numpy import nan
self.values = dict([(n,nan) for n in self.attributes])
self.old_values = {}
self.refreshing = False
self.changing = False
from wx.lib.newevent import NewEvent
self.EVT_THREAD = NewEvent()[1]
self.Bind(self.EVT_THREAD,self.OnUpdate)
from threading import Thread
self.thread = Thread(target=self.keep_updated,name=self.name)
self.thread.daemon = True
self.thread.start()
def keep_updated(self):
"""Periodically refresh the displayed settings."""
from time import time,sleep
while True:
try:
t0 = time()
while time() < t0+self.refresh_period: sleep(0.1)
if self.Shown:
self.update_data()
if self.data_changed:
event = wx.PyCommandEvent(self.EVT_THREAD.typeId,self.Id)
# call OnUpdate in GUI thread
wx.PostEvent(self.EventHandler,event)
except wx.PyDeadObjectError: break
def refresh(self):
"""Force update"""
from threading import Thread
if not self.refreshing and self.Shown:
self.refresh_thread = Thread(target=self.refresh_background,
name=self.name+".refresh")
self.refresh_thread.daemon = True
self.refreshing = True
self.refresh_thread.start()
def refresh_background(self):
"""Force update"""
try:
self.update_data()
if self.data_changed:
event = wx.PyCommandEvent(self.EVT_THREAD.typeId,self.Id)
wx.PostEvent(self.EventHandler,event) # call OnUpdate in GUI thread
self.refreshing = False
except wx.PyDeadObjectError: pass
def update_data(self):
"""Retreive status information"""
self.old_values = dict(self.values) # make a copy
for n in self.attributes: self.values[n] = getattr(self.object,n)
@property
def data_changed(self):
"""Did the last 'update_data' change the data to be plotted?"""
changed = (self.values != self.old_values)
return changed
def OnUpdate(self,event):
"""Periodically refresh the displayed settings."""
self.refresh_status()
def refresh_status(self):
value = self.values[self.name]
try:
value = int(value)
valid = True
except Exception,msg:
debug("PropertyPanel.refresh: %r: value %r" % (self.name,value))
valid = False
self.Control.Value = value if valid else False
self.Control.Enabled = valid
choices = self.type.split("/")
if valid:
try: text = choices[value]
except Exception,msg:
debug("PropertyPanel.refresh_status: %r: type %r, value %r" %
(self.name,self.type,value))
text = str(value)
else: text = self.label
self.Control.Label = text
def OnChange(self,event):
from threading import Thread
if not self.changing:
self.change_thread = Thread(target=self.change_background,
name=self.name+".change")
self.change_thread.daemon = True
self.changing = True
self.change_thread.start()
def change_background(self):
"""If the control has changed apply the change to the object is
is controlling."""
value = self.Control.Value
setattr(self.object,self.name,value)
self.changing = False
self.refresh()
class ButtonPanel(wx.Panel):
"""A component for 'BasePanel'"""
def __init__(self,parent=None,title="",object=None,name="",label="",
refresh_period=1.0,label_width=180):
"""title: descriptive label
name: name of a callable member function of object
"""
wx.Panel.__init__(self,parent)
self.title = title
self.object = object
self.name = name
self.label = label
# Standardize vertical size of controls
test = wx.ComboBox(self)
w,h = test.Size
test.Destroy()
# Controls
self.Control = wx.ToggleButton(self,size=(120,h),label=self.label)
# Callbacks
self.Bind(wx.EVT_TOGGLEBUTTON,self.OnButton,self.Control)
# Layout
layout = wx.BoxSizer()
av = wx.ALIGN_CENTRE_VERTICAL
e = wx.EXPAND
if self.title:
label = wx.StaticText(self,label=self.title+":",size=(label_width,-1))
layout.Add(label,flag=av)
layout.Add(self.Control,flag=av|e,proportion=1)
self.SetSizer(layout)
self.Fit()
# Refresh
from wx.lib.newevent import NewEvent
self.EVT_THREAD = NewEvent()[1]
self.Bind(self.EVT_THREAD,self.OnUpdate)
self.running = False
def OnButton(self,event):
from threading import Thread
if self.Control.Value:
self.thread = Thread(target=self.run_in_background,name=self.name)
self.thread.daemon = True
self.running = True
self.thread.start()
self.OnUpdate()
def run_in_background(self):
"""Execute the procedure"""
getattr(self.object,self.name)()
self.running = False
event = wx.PyCommandEvent(self.EVT_THREAD.typeId,self.Id)
wx.PostEvent(self.EventHandler,event) # call OnUpdate in GUI thread
def OnUpdate(self,event=None):
"""Update button state to reflect if the procedure is running"""
self.Control.Value = self.running
# for compatibility with other controls
def refresh(self): pass
refreshing = False
class RefreshPeriodPanel(wx.Frame):
title = "Refresh Period"
def __init__(self,parent):
wx.Frame.__init__(self,parent=parent,title=self.title)
panel = wx.Panel(self)
# Controls
style = wx.TE_PROCESS_ENTER
width = 160
choices = getattr(self.Parent,"refresh_period_choices",[])
from time_string import time_string
choices = [time_string(choice) for choice in choices]
self.RefreshPeriod = ComboBox(panel,style=style,choices=choices,
size=(width,-1))
# Callbacks
self.Bind (wx.EVT_TEXT_ENTER,self.OnEnterRefreshPeriod,self.RefreshPeriod)
self.Bind (wx.EVT_COMBOBOX ,self.OnEnterRefreshPeriod,self.RefreshPeriod)
self.Bind (wx.EVT_CLOSE ,self.OnClose)
# Layout
layout = wx.GridBagSizer(1,1)
a = wx.ALIGN_CENTRE_VERTICAL
e = wx.EXPAND
label = wx.StaticText(panel,label="Refresh Period:")
layout.Add (label,(0,0),flag=a)
layout.Add (self.RefreshPeriod,(0,1),flag=a|e)
# Leave a 5-pixel wide border.
box = wx.BoxSizer(wx.VERTICAL)
box.Add (layout,flag=wx.ALL,border=5)
panel.SetSizer(box)
panel.Fit()
self.Fit()
self.Show()
self.refresh()
def OnEnterRefreshPeriod(self,event):
"""Called if IP address is changed"""
from time_string import seconds
from numpy import isnan
value = seconds(self.RefreshPeriod.Value)
if not isnan(value): self.Parent.refresh_period = value
self.refresh()
def OnRefresh(self,event=None):
"""Check whether the network connection is OK."""
self.refresh()
def refresh(self,event=None):
"""Update the controles and indicators with current values"""
if self.Shown:
from time_string import time_string
from numpy import nan
value = getattr(self.Parent,"refresh_period",nan)
self.RefreshPeriod.Value = time_string(value)
self.timer = wx.Timer(self)
self.Bind(wx.EVT_TIMER,self.refresh,self.timer)
self.timer.Start(1000,oneShot=True)
def OnClose(self,event):
self.Shown = False
##self.Destroy() # might crash under Windows
wx.CallLater(2000,self.Destroy)
def Title(object):
"""The name of a window component"""
if getattr(object,"Title","") != "": return object.Title
if getattr(object,"title","") != "": return object.title
if getattr(object,"Value","") != "": return str(object.Value)
if getattr(object,"Label","") != "": return object.Label
for child in getattr(object,"Children",[]):
t = Title(child)
if t != "": return t
return ""
def IsInVisibleWindow(object):
"""Is object inside a visible window?"""
# Find toplevel Frame object
def Parent(object): return getattr(object,"Parent",None)
def IsFrame(object): return hasattr(object,"Title")
##debug("IsInVisibleWindow: object=%r" % object)
while not IsFrame(object) and Parent(object) is not None:
object = Parent(object)
##debug("IsInVisibleWindow: object -> %r" % object)
IsInVisibleWindow = getattr(object,"Shown",False)
return IsInVisibleWindow
def getattr(object,attribute,default_value=None):
"""Get a propoerty of an object
attribute: e.g. 'value' or 'member.value'"""
if default_value is None: return eval("object."+attribute)
try: return eval("object."+attribute)
except: return default_value
def hasattr(object,attribute):
"""Does a property of an object exists?
attribute: e.g. 'value' or 'member.value'"""
try: eval("object."+attribute); return True
except: return False
def setattr(object,attribute,value):
"""Set a propoerty of an object
attribute: e.g. 'value' or 'member.value'"""
from numpy import nan,inf
command = "object.%s = %r" % (attribute,value)
try: exec(command)
except Exception,msg:
error("Panel: %s: %s\n%s" % (command,msg,format_exc()))
def to_SI_format(t,precision=3):
"""Convert number to string using "p" for 1e-12, "n" for 1 e-9, etc..."""
def format(precision,t):
s = "%.*g" % (precision,t)
# Add trailing zeros if needed
if not "e" in s:
if not "." in s and len(s) < precision:
s += "."+"0"*(precision-len(s))
if "." in s and len(s)-1 < precision:
s += "0"*(precision-(len(s)-1))
return s
try: t=float(t)
except: return ""
if t != t: return "" # not a number
if t == 0: return "0"
if abs(t) < 0.5e-12: return "0"
if abs(t) < 999e-12: return format(precision,t*1e+12)+" p"
if abs(t) < 999e-09: return format(precision,t*1e+09)+" n"
if abs(t) < 999e-06: return format(precision,t*1e+06)+" u"
if abs(t) < 999e-03: return format(precision,t*1e+03)+" m"
if abs(t) < 999e+00: return format(precision,t*1e+00)+" "
if abs(t) < 999e+03: return format(precision,t*1e-03)+" k"
if abs(t) < 999e+06: return format(precision,t*1e-06)+" M"
if abs(t) < 999e+09: return format(precision,t*1e-09)+" G"
return "%.*g" % (precision,t)
def from_SI_format(text):
"""Convert a text string as "1k" to the number 1000.
SI prefixes accepted are P, E, T, G, M, k, m, u, n, p, f, a."""
text = text.replace("P","*1e+18")
text = text.replace("E","*1e+15")
text = text.replace("T","*1e+12")
text = text.replace("G","*1e+09")
text = text.replace("M","*1e+06")
text = text.replace("k","*1e+03")
text = text.replace("m","*1e-03")
text = text.replace("u","*1e-06")
text = text.replace("n","*1e-09")
text = text.replace("p","*1e-12")
text = text.replace("f","*1e-15")
text = text.replace("a","*1e-18")
try: return float(eval(text))
except: return nan
def isnan(x):
"""Is x an invalid floating point value? ('Not a Number')"""
return x!= x
if __name__ == "__main__":
from pdb import pm # for debugging
import logging
logging.basicConfig(
level=logging.DEBUG,
format="%(asctime)s %(levelname)s %(module)s, line %(lineno)d: %(funcName)s: %(message)s",
)
from instrumentation import SAXS_WAXS_methods as configuration
class ConfigurationPanel(BasePanel):
name = "configuration"
title = "Configuration"
standard_view = [
"Title",
"Motor names",
"Motor labels",
"Formats",
"Tolerance",
"Rows",
"Go To",
]
def __init__(self,parent,configuration):
parameters = [
[[PropertyPanel,"Title",configuration,"title"],{}],
[[PropertyPanel,"Motor names",configuration,"motor_names"],{}],
[[PropertyPanel,"Motor labels",configuration,"motor_labels"],{}],
[[PropertyPanel,"Formats",configuration,"formats"],{}],
[[PropertyPanel,"Tolerance",configuration,"tolerance"],{}],
[[PropertyPanel,"Rows",configuration,"nrows"],{}],
[[PropertyPanel,"Go To",configuration,"serial"],{"type":"All motors at once/One motor at a time (left to right)"}],
]
from numpy import inf
BasePanel.__init__(self,
parent=parent,
name=self.name,
title=self.title,
parameters=parameters,
standard_view=self.standard_view,
subname=True,
label_width=90,
width=230,
refresh_period=1.0,
)
app = wx.App(redirect=False)
self = ConfigurationPanel(parent=None,configuration=configuration)
app.MainLoop()
<file_sep>motor_names = ['ChopX', 'ChopY', 'Ensemble_SAXS.cmcd']
motor_labels = ['X [mm]', 'Y [mm]', 'Phase']
nrows = 6
formats = ['%+6.3f', '%+6.3f', 'time']
title = 'Coppens Chopper Modes'
tolerance = [0.001, 0.001, 200e-09]
show_in_list = False
show_stop_button = True
row_height = 20
line0.ChopX = 30.58
line0.ChopY = 9.195
line0.Ensemble_SAXS.cmcd = 0.0
line0.description = 'CH-1'
line0.updated = '31 Oct 08:32'
line1.ChopX = 30.58
line1.ChopY = 9.195
line1.Ensemble_SAXS.cmcd = -1.8412543260952431e-06
line1.description = 'CH-56'
line1.updated = '31 Oct 08:32'
line2.ChopX = 28.58
line2.ChopY = 9.0
line2.Ensemble_SAXS.cmcd = nan
line2.description = 'C Bypass'
line2.updated = '23 Oct 09:37'
line3.ChopX = 30.58
line3.ChopY = 9.3625
line3.Ensemble_SAXS.cmcd = 0.0
line3.description = 'CS-5'
line3.updated = '23 Oct 10:40'
line4.ChopX = 30.58
line4.ChopY = 9.0
line4.Ensemble_SAXS.cmcd = 0.0
line4.description = 'CS-19'
line4.updated = '23 Oct 10:41'
line5.ChopX = 30.58
line5.ChopY = 9.165
line5.Ensemble_SAXS.cmcd = 0.0
line5.description = 'CS-13'
line5.updated = '26 Oct 02:04'
command_row = 1
command_rows = [0]<file_sep>"""Support module for "timing_modes" table
"""
class TimingParameters(object):
name = "timing_modes"
from persistent_property import persistent_property
mode_number = persistent_property("mode_number",0)
N = persistent_property("N",40)
period = persistent_property("period",264)
from numpy import inf
min_delay = persistent_property("min_delay",-inf)
max_delay = persistent_property("max_delay",inf)
transd = persistent_property("transd",17)
dt = persistent_property("dt",4)
t0 = persistent_property("t0",100)
z = persistent_property("z",1)
use = persistent_property("use",True)
timing_parameters = TimingParameters()
<file_sep>#!/usr/bin/env python
"""
Control panel for variable laser attenuator
<NAME>, APS, 8 Jun 2009 - 16 Nov 2014
"""
__version__ = "1.2" # trans -> trans2
import wx
from LaserAttenuatorPanel import LaserAttenuatorPanel
from id14 import trans2
wx.app = wx.App(redirect=False) # Needed to initialize WX library
panel = LaserAttenuatorPanel(trans2,title="Laser Attenuator [in X-ray Hutch]")
wx.app.MainLoop()
<file_sep>#!/usr/bin/env python
"""High-speed X-ray Chopper
Control panel to save and restore motor positions.
Author: <NAME>
Date created: 2018-09-11
Date last modified: 2018-09-11
"""
__version__ = "1.0"
from SavedPositionsPanel_2 import SavedPositionsPanel
if __name__ == '__main__':
from pdb import pm # for debugging
import logging # for debugging
from tempfile import gettempdir
logfile = gettempdir()+"/ChemMat_Chopper_Modes_Panel.log"
logging.basicConfig(level=logging.INFO,filename=logfile,
format="%(asctime)s %(levelname)s: %(message)s")
import autoreload
import wx
app = wx.App(redirect=False)
from instrumentation import * # -> globals()
panel = SavedPositionsPanel(name="ChemMat_chopper_modes",globals=globals())
app.MainLoop()
<file_sep>"""SAXS/WAXS data collection setup for Aerotech Ensemble motion controller.
"Fly-thru" and "Setting" mode are implemented using "piano player" mode
for the FPGA.
"Exotic mode" implements an optimized sample translation for multishot laser
pump X-ray probe data aquisition.
Author: <NAME>
Date created: 2015-05-27
Date last modified: 2019-05-29
"""
import numpy; numpy.seterr(invalid="ignore",divide="ignore") # Turn off IEEE-754 warnings
from logging import debug,info,warn,error
from traceback import format_exc
from time import time
__version__ = "4.22" # hsc_delay, cleanup
genenerator_version = "4.21"
class Sequence(object):
def __init__(self,delay=None,**kwargs):
from collections import OrderedDict
self.__parameters__ = OrderedDict()
if delay is not None: self.delay = delay
for name in kwargs: self.setattr(name,kwargs[name])
##self.set_defaults()
def set_defaults(self):
for name in self.properties:
if not name in self.__parameters__:
self.__parameters__[name] = Ensemble_SAXS.get_default(name)
def update(self,sequence):
"""Copy parameters from another Sequence object
sequence: another Sequence object"""
self.__parameters__.update(sequence.__parameters__)
def __getattr__(self,name):
"""A property"""
# Called when 'x.name' is evaluated.
# It is only invoked if the attribute wasn't found the usual ways.
if name.startswith("__") and name.endswith("__"):
raise AttributeError("Sequence object has no attribute %r" % name)
if name in self.__parameters__: value = self.__parameters__[name]
else: value = Ensemble_SAXS.get_default(name)
return value
def __setattr__(self,name,value):
"""Set a property"""
# Called when 'x.name = y' is evaluated.
if name.startswith("__") and name.endswith("__"):
object.__setattr__(self,name,value)
try:
object.__getattribute__(self,name)
object.__setattr__(self,name,value)
except AttributeError: self.setattr(name,value)
def setattr(self,name,value):
##self.__parameters__[name] = value
parameters = dict([(name,value)])
parameters = self.normalize(parameters)
self.__parameters__.update(parameters)
@staticmethod
def normalize(par):
"""translate parameters dictionary"""
from collections import OrderedDict
parameters = OrderedDict()
for name in par:
value = par[name]
if name == "delay":
from numpy import isnan
# <NAME>, 2018-10-04: nan means not save image
if isnan(value): parameters["acquire"] = 0
# <NAME>, 2018-10-01: integer value means nominal delay
# for logging purposes in multiples of 1 ms clock ticks.
elif value == int(value) and value >= 48:
parameters["nom_delay"] = value*Sequence.tick_period()
else: parameters["delay"] = value
elif name in ["S","SEQ","enable"]:
# <NAME>, 2018-10-01: "Sequence Configuration"
# 1010: xdet_on=1, laser_on=0, ms_on=0, pump_on=0 [dump_on not specified]
if len(value) >0: parameters["xdet_on"] = int(value[0])
if len(value) >1: parameters["laser_on"] = int(value[1])
if len(value) >2: parameters["ms_on"] = int(value[2])
if len(value) >3: parameters["pump_on"] = int(value[3])
if len(value) >4: parameters["dump_on"] = int(value[4])
# <NAME>, 2018-10-01...2018-10-05: "Player-Piano Modes"
elif name in ["PLP","PP","pp"]: parameters["mode"] = value
# <NAME>, 2018-09-28: circulate liquid sample
elif name in ["circulate"]: parameters["pump_on"] = value
# <NAME>, 2018-10-04...2018-10-05: short for of "acquire"
elif name in ["acq","image"]: parameters["acquire"] = value
elif name in ["laser","pump"]: parameters["laser_on"] = value
elif name in ["probe","xray","xray_on"]: parameters["ms_on"] = value
elif name in ["xdet"]: parameters["xdet_on"] = value
else: parameters[name] = value
return parameters
@staticmethod
def tick_period():
##from timing_system import timing_system
##T = timing_system.hsct
##T = 0.0010126898793523787
T = 0.0010182857142857144
return T
@property
def values(self):
"""Values of all parameters as tuple"""
return tuple(self.__parameters__.values())
@property
def packet_description(self):
"""Binary data and descriptive string as tuple"""
packet,description = Ensemble_SAXS.sequencer_packet(self)
return packet,description
@property
def register_counts(self):
"""Register objects and count arrays as tuple"""
registers,counts = Ensemble_SAXS.register_counts(self)
return registers,counts
@property
def description(self):
"""The parameters for generating a packet represented as text string."""
description = ""
description += "delay=%.3g," % self.delay
description += "nom_delay=%.3g," % self.nom_delay
description += "laser_on=%r," % self.laser_on
description += "ms_on=%r," % self.ms_on
description += "pump_on=%r," % self.pump_on
description += "xdet_on=%r," % self.xdet_on
description += "pass_number=%r," % self.pass_number
description += "image_number_inc=%r," % self.image_number_inc
description += "pass_number_inc=%r," % self.pass_number_inc
description += "acquiring=%r," % self.acquiring
description += "mode_number=%r," % self.mode_number
description += "N=%r," % self.N
description += "period=%r," % self.period
description += "transd=%r," % self.transd
description += "dt=%r," % self.dt
description += "t0=%r," % self.t0
description += "z=%r," % self.z
transc = Ensemble_SAXS.trigger_code_of(
self.mode_number,
self.ms_on,
self.following_sequence.pump_on,
self.following_sequence.delay,
self.z,
)
description += "transc=%r," % transc
description += "preceeding_sequence.delay=%.3g," % self.preceeding_sequence.delay
description += self.parameter_description
return description
descriptor = description
@property
def parameter_description(self):
if hasattr(self.sequences,"parameter_description"):
description = self.sequences.parameter_description
else:
if not hasattr(self,"__parameter_description__"):
self.__parameter_description__ = parameter_description()
return self.__parameter_description__
return description
@property
def id(self):
"""Binary data and descriptive string as tuple"""
from timing_sequence import hash
id = hash(self.description)
return id
@property
def packet_representation(self):
"""Sequence data as formatted text"""
from timing_sequence import packet_representation
return packet_representation(self.data)
@property
def is_cached(self):
"""Packet is generated"""
is_cached = len(self.cached_data) > 0
return is_cached
def get_data(self):
"""Binary sequence data"""
data = self.cached_data
if len(data) == 0:
data = self.generated_data
self.cached_data = data
return data
data = property(get_data)
packet = packet_data = data
def get_cached_data(self):
from timing_sequencer import timing_sequencer
data = timing_sequencer.cache_get(self.description)
return data
def set_cached_data(self,data):
from timing_sequencer import timing_sequencer
timing_sequencer.cache_set(self.description,data)
cached_data = property(get_cached_data,set_cached_data)
@property
def generated_data(self):
from timing_sequencer import sequencer_packet
registers,counts = self.register_counts
data = sequencer_packet(registers,counts,self.descriptor)
return data
def __repr__(self):
p = Sequence.ordered_parameters(self.__parameters__)
s = "Sequence("+", ".join(["%s=%r" % (key,p[key]) for key in p])+")"
return s
@staticmethod
def ordered_parameters(parameters):
from collections import OrderedDict
ordered_parameters = OrderedDict()
for name in Sequence.order:
if name in parameters: ordered_parameters[name] = parameters[name]
for name in parameters:
if not name in Sequence.order: ordered_parameters[name] = parameters[name]
return ordered_parameters
order = [
"delay",
"nom_delay",
"xdet_on",
"laser_on",
"ms_on",
"pump_on",
"image_number_inc",
"pass_number_inc",
"acquiring",
]
properties = [
"delay",
##"nom_delay",
"xdet_on",
"laser_on",
"ms_on",
"pump_on",
"image_number_inc",
"pass_number_inc",
"acquiring",
"pass_number",
"mode_number",
"N",
"period",
"transd",
"dt",
"t0",
"z",
]
@property
def nom_delay(self):
from numpy import isnan
if "nom_delay" in self.__parameters__ and not isnan(self.__parameters__["nom_delay"]):
return self.__parameters__["nom_delay"]
else: return self.delay
def get_sequences(self):
"""Which list of sequences is this sequence part of?"""
return getattr(self,"__sequences__",[self])
def set_sequences(self,value): self.__sequences__ = value
sequences = property(get_sequences,set_sequences)
def get_count(self):
"""At which place in the list of sequences it belongs to is this
sequence?"""
return getattr(self,"__count__",0)
def set_count(self,value): self.__count__ = value
count = property(get_count,set_count)
@property
def following_sequence(self):
return self.sequences[(self.count+1) % len(self.sequences)]
@property
def preceeding_sequence(self):
return self.sequences[(self.count-1) % len(self.sequences)]
s = seq = sequence = Sequence # shorthand notation
class Sequences(object):
def __init__(self,delay=None,sequences=None,**kwargs):
from collections import OrderedDict
self.__parameters__ = OrderedDict()
self.set_defaults()
acquiring = "acquiring" in kwargs and kwargs["acquiring"]
params = self.default_parameters(acquiring)
for name in params: self.setattr(name,params[name])
if delay is not None: self.setattr("delay",delay)
for name in kwargs: self.setattr(name,kwargs[name])
if sequences is not None: self.set_sequences(sequences)
self.update_parameter_description()
def set_defaults(self):
for name in Sequence.properties:
if not name in self.__parameters__:
self.__parameters__[name] = Ensemble_SAXS.get_default(name)
def set_sequences(self,sequences):
keys = self.common_keys(sequences)
from numpy import nan
for key in keys:
self.__parameters__[key] = [nan]*len(sequences)
for i,sequence in enumerate(sequences):
for key in keys:
if key in sequence.__parameters__:
self.__parameters__[key][i] = sequence.__parameters__[key]
@staticmethod
def common_keys(sequences):
keys = set()
for sequence in sequences: keys |= set(sequence.__parameters__.keys())
return keys
@staticmethod
def default_parameters(acquiring=False):
"""Dictionary"""
from expand_sequence import expand
if not acquiring: parameter_string = Ensemble_SAXS.sequence
else: parameter_string = Ensemble_SAXS.acquisition_sequence
parameter_string = expand(parameter_string)
parameters = {}
if parameter_string:
try: parameters = dict(eval(parameter_string))
except Exception,msg: warn("%s: %s" % (parameter_string,msg))
return parameters
def __getattr__(self,name):
"""A property"""
if name.startswith("__") and name.endswith("__"):
raise AttributeError("Sequences object has no attribute %r" % name)
# Called when 'x.name' is evaluated.
# It is only invoked if the attribute wasn't found the usual ways.
if name in self.__parameters__: value = self.__parameters__[name]
else: value = Ensemble_SAXS.get_default(name)
return value
def __setattr__(self,name,value):
"""Set a property"""
# Called when 'x.name = y' is evaluated.
if name.startswith("__") and name.endswith("__"):
object.__setattr__(self,name,value)
try:
object.__getattribute__(self,name)
object.__setattr__(self,name,value)
except AttributeError: self.setattr(name,value)
def setattr(self,name,value):
parameters = dict([(name,value)])
parameters = self.normalize(parameters)
self.__parameters__.update(parameters)
@staticmethod
def normalize(par):
"""translate parameters dictionary"""
from collections import OrderedDict
parameters = OrderedDict()
for name in par:
value = par[name]
if not isinstance(value,str) and hasattr(value,"__len__"):
for v in value:
p = Sequence.normalize(dict([(name,v)]))
for n in p: parameters[n] = []
for v in value:
p = Sequence.normalize(dict([(name,v)]))
for n in p: parameters[n] += [p[n]]
else:
p = Sequence.normalize(dict([(name,value)]))
for n in p: parameters[n] = p[n]
return parameters
def __repr__(self):
p = Sequence.ordered_parameters(self.__parameters__)
s = "Sequences("+", ".join(["%s=%r" % (key,p[key]) for key in p])+")"
return s
def __len__(self): return self.count
def __getitem__(self,item):
if type(item) == slice:
start = item.start if item.start is not None else 0
stop = item.stop if item.stop is not None else len(self)
step = item.step if item.step is not None else 1
value = [self.sequence(i) for i in range(start,stop,step)]
else: value = self.sequence(item)
return value
@property
def sequences(self):
"""Expand to list of Sequence objects"""
sequences = [self.sequence(count) for count in range(0,self.count)]
return sequences
def sequence(self,count):
"""Sequence object number *count*
Not taking into account order of collection"""
from collections import OrderedDict
parameters = OrderedDict()
for key in self.__parameters__:
value = self.__parameters__[key]
if not isinstance(value,str) and hasattr(value,"__len__"):
parameters[key] = value[count % len(value)]
else: parameters[key] = value
sequence = Sequence()
for key in parameters: setattr(sequence,key,parameters[key])
sequence.count = count
sequence.sequences = self
return sequence
@property
def count(self):
"""How many sequences are there?"""
N = 1
parameters = self.__parameters__
for key in parameters:
value = parameters[key]
if not isinstance(value,str) and hasattr(value,"__len__"):
N = max(N,len(value))
return N
def update_parameter_description(self):
if not hasattr(self,"__parameter_description__"):
self.__parameter_description__ = parameter_description()
@property
def parameter_description(self):
self.update_parameter_description()
return self.__parameter_description__
S = sequences = Sequences # shorthand notation
def parameter_description():
"""The parameters for generating a packet represented as text string."""
description = ""
# Calibration constants and parameters
from timing_system import timing_system
##description += "high_speed_chopper_phase.value=%.12f," % timing_system.high_speed_chopper_phase.value
##description += "high_speed_chopper_phase.offset=%.12f," % timing_system.high_speed_chopper_phase.offset
##description += "hsc.delay.offset=%.12f," % timing_system.hsc.delay.offset
description += "xd=%.12f," % timing_system.xd
# Channel configuration-based parameters
for i_channel in range(0,len(timing_system.channels)):
channel = timing_system.channels[i_channel]
if channel.PP_enabled:
if channel.special == "pso":
description += "psod3.offset=%.12f," % (timing_system.psod3.offset)
elif channel.special == "trans":
description += "%s.pulse_length=%.4g," % (channel.name,channel.pulse_length)
elif channel.special == "nsf":
description += "%s.offset=%.12f," % (channel.name,channel.offset)
else: description += Ensemble_SAXS.channel_description(i_channel)
description += "generator=%r," % "Ensemble_SAXS"
description += "generator_version=%r," % genenerator_version
import timing_sequence
description += "timing_sequence_version=%r," % timing_sequence.__version__
return description
class EnsembleSAXS(object):
"""SAXS/WAXS data collection with linear stage, controlled by Aerotech Ensemble"""
name = "Ensemble_SAXS"
from timing_sequence import timing_sequencer
def sequence_property(name):
def get(self):
return self.current_sequence_property(name,self.default_values[name])
def set(self,value):
self.set_command_value(name,value)
self.update_later = True
return property(get,set)
mode_number = sequence_property("mode_number")
# Packet length in 987-Hz cycles
period = sequence_property("period")
# Number of X-ray pulses
N = sequence_property("N")
# X-ray pulse repetition period, in 987-Hz cycles
dt = sequence_property("dt")
# Trigger rising edge to first X-ray pulse, in 987-Hz cycles
t0 = sequence_property("t0")
# Sample translation trigger delay
transd = sequence_property("transd")
# Laser focusing optics translation stage setting to compensate
# moving sample lateral offset as function of pump-probe delay,,
# when collecting in "Flythru" mode.
z = sequence_property("z")
default_values = {
"mode_number": 0,
"period": 264,
"N": 40,
"dt": 4,
"t0": 100,
"transd": 17,
"z": 1,
}
def command_value(self,name):
from timing_system import timing_system
value = timing_system.parameter(name,self.default_values[name])
##debug("%s=%r" % (name,value))
return value
def set_command_value(self,name,value):
debug("%s=%r" % (name,value))
from timing_system import timing_system
timing_system.set_parameter(name,value)
from thread_property_2 import thread_property
@thread_property
def update_later(self):
from time import sleep
sleep(0.1)
self.update()
def get_default(self,name):
"""Default value for the parameter given by name
name: "delay","laser_on","ms_on","pump_on"
"image_number_inc","pass_number_inc",
"xdet_on"
"""
name = self.standard_name(name)
if name in self.default_values: value = self.command_value(name)
else: value = self.timing_sequencer.get_default(name)
return value
def set_default(self,name,value):
"""Default value for the parameter given by name
name: "delay","laser_on","ms_on","pump_on",
"image_number_inc","pass_number_inc"
"""
name = self.standard_name(name)
if name in self.default_values: value = self.set_command_value(name,value)
else: self.timing_sequencer.set_default(name,value,update=False)
def standard_name(self,name):
"""'mode' -> 'translate_mode'"""
##if name == "mode": name = "translate_mode"
return name
from persistent_property import persistent_property
buffer_size = persistent_property("buffer_size",256*1024)
def get_delay(self):
"""Current Laser pump X-ray probe time delay"""
return self.current_sequence_property("delay")
def set_delay(self,delay):
self.set_default("delay",delay)
self.set_default_sequences()
delay = property(get_delay,set_delay)
def get_nom_delay(self):
"""Current Laser pump X-ray probe time delay"""
return self.current_sequence_property("nom_delay")
def set_nom_delay(self,delay): pass
nom_delay = property(get_nom_delay,set_nom_delay)
def get_mode(self):
"""Current mode name as string"""
mode = self.timing_modes.value
return mode
def set_mode(self,value):
self.timing_modes.value = value
mode = property(get_mode,set_mode)
@property
def modes(self):
"""Possible operation modes as list of strings"""
return self.timing_modes.values
@property
def timing_modes(self):
from configuration import configuration
return configuration("timing_modes",locals=locals(),globals=globals())
def get_sequence(self):
"""Sequence mode description (for idle mode)"""
return self.get_default("sequence")
def set_sequence(self,value):
self.set_default("sequence",value)
self.set_default_sequences()
sequence = property(get_sequence,set_sequence)
def get_acquisition_sequence(self):
"""Sequence mode description for acquisition mode"""
return self.get_default("acquisition_sequence")
def set_acquisition_sequence(self,value):
self.set_default("acquisition_sequence",value)
self.set_default_sequences()
acquisition_sequence = property(get_acquisition_sequence,set_acquisition_sequence)
def get_trigger_period_in_1kHz_cycles(self):
"""Sample translation trigger period in units of the 1-kHz (997 Hz) clock"""
return self.current_sequence_property("period",dtype=int)
trigger_period_in_1kHz_cycles = property(get_trigger_period_in_1kHz_cycles)
def get_trigger_enabled(self):
"""Is a trigger signal being sent by the FPGA to the Ensemble
Controller? True or False"""
return self.queue_length > 0 or self.timing_sequencer.enabled
trigger_enabled = property(get_trigger_enabled)
def get_laser_on(self):
"""Is the laser trigger enabled?"""
return self.current_sequence_property("laser_on",dtype=bool)
def set_laser_on(self,laser_on):
self.set_default("laser_on",laser_on)
self.set_default_sequences()
laser_on = property(get_laser_on,set_laser_on)
laseron = laser_on # for backward compatibility
def get_ms_on(self):
"""Is the X-ray ms shutter operated while the stage is moving?"""
return self.current_sequence_property("ms_on",dtype=bool)
def set_ms_on(self,ms_on):
self.set_default("ms_on",ms_on)
self.set_default_sequences()
ms_on = property(get_ms_on,set_ms_on)
xray_shutter_enabled = xray_on = mson = ms_on # for backward compatibility
def get_pump_on(self):
"""Is circulating pump operated while the stage is moving?"""
return self.current_sequence_property("pump_on",dtype=bool)
def set_pump_on(self,pump_on):
self.set_default("pump_on",pump_on)
self.set_default_sequences()
pump_on = property(get_pump_on,set_pump_on)
pumpA_enabled = pumpon = pump_on # for backward compatibility
def get_xdet_on(self):
"""Is the X-ray detector being triggered?"""
return self.current_sequence_property("xdet_on",dtype=bool)
def set_xdet_on(self,value):
from timing_system import timing_system
self.set_default("xdet_on",value)
self.set_default_sequences()
xdet_on = property(get_xdet_on,set_xdet_on)
def get_image_number_inc(self):
"""Is Pump A operated while the stage is moving?"""
return self.current_sequence_property("image_number_inc",dtype=bool)
def set_image_number_inc(self,value):
self.set_default("image_number_inc",value)
self.set_default_sequences()
image_number_inc = property(get_image_number_inc,set_image_number_inc)
def get_pass_number_inc(self):
"""Is Pump A operated while the stage is moving?"""
return self.current_sequence_property("pass_number_inc",dtype=bool)
def set_pass_number_inc(self,value):
self.set_default("pass_number_inc",value)
self.set_default_sequences()
pass_number_inc = property(get_pass_number_inc,set_pass_number_inc)
def get_trigger_code(self):
"""transation program code:
8-bit integer number transmitted to the Aerobasic program
running on the Ensemble controller by the FPGA timing system
as serial bit sequence following the trigger pulse."""
return self.current_sequence_property("transc",dtype=int)
def set_trigger_code(self,value): pass
trigger_code = property(get_trigger_code,set_trigger_code)
transc = trigger_code
@property
def generator(self):
"""Sequence generator Python module name"""
return self.current_sequence_property("generator","")
@property
def generator_version(self):
"""Sequence generator Python module version number"""
return self.current_sequence_property("generator_version","")
from numpy import nan
def current_sequence_property(self,name,default_value=nan,dtype=None):
"""
name: e.g. 'mode','delay','laseron','count'
dtype: data type
"""
descriptor = self.timing_sequencer.descriptor
if dtype is not None: default_value = dtype()
if len(descriptor) == 0: return default_value
return self.property_value(descriptor,name,default_value,dtype)
def property_value(self,property_string,name,default_value=nan,dtype=None):
"""Extract a value from a comma-separated list
property_string: comma separated list
e.g. 'mode=Stepping-48,delay=0.0316,laseron=True,count=6'
name: e.g. 'mode','delay','laseron','count'
default_value: e.g. ''
dtype: data type
"""
if dtype is None: dtype = type(default_value)
for record in property_string.split(","):
parts = record.split("=")
key = parts[0]
if key != name: continue
if len(parts) < 2: return default_value
value = parts[1]
try: return dtype(eval(value))
except: return default_value
return default_value
def get_configured(self):
"""Configure the FPGA for 'Player Piano' mode at 1 kHz."""
from timing_system import timing_system,timing_sequencer
##if not timing_system.inton.count == 1: return False
if not timing_system.IPIRE.count == 1: return False
if not timing_system.DEVICE_GIE.count == 1: return False
if not timing_system.IPIER.count == 1: return False
if not timing_sequencer.buffer_size == self.buffer_size: return False
return True
def set_configured(self,value):
"""Configure the FPGA for 'Player Piano' mode at 1 kHz."""
from timing_system import timing_system,timing_sequencer
if value:
##timing_system.inton.count = 1
timing_system.IPIRE.count = 1
timing_system.DEVICE_GIE.count = 1
timing_system.IPIER.count = 1
timing_sequencer.buffer_size = self.buffer_size
configured = property(get_configured,set_configured)
def sequencer_packet(self,sequence):
"""Binary data for one stroke of operation.
Return value: binary data + descriptive string
"""
if self.timing_sequencer.cache_enabled:
method = self.sequencer_packet_cached
else: method = self.sequencer_packet_generate
packet,description = method(sequence)
return packet,description
def sequencer_packet_cached(self,sequence):
"""Binary data for one stroke of operation.
Return value: binary data + descriptive string
"""
description = sequence.description
packet = self.timing_sequencer.cache_get(description)
if len(packet) == 0:
packet,description = self.sequencer_packet_generate(sequence)
self.timing_sequencer.cache_set(description,packet)
return packet,description
def sequencer_packet_generate(self,sequence):
"""Binary data for one stroke of operation.
Return value: binary data + descriptive string
"""
info("Generating packet...")
description = sequence.description
registers,counts = self.register_counts(sequence)
from timing_sequence import sequencer_packet
data = sequencer_packet(registers,counts,description)
return data,description
##from persistent_property import persistent_property
##xd = persistent_property("persistent_property",0.000985971429) # X-ray pulse timing
def register_counts(self,sequence):
"""list of registers and lists of counts
"""
# delay: laser to X-ray pump-probe delay in seconds
# laseron: trigger the laser?
# ms_on: operate the X-ray milliscond shutter?
# pump_on: operate the peristaltic pump?
# pass_number=1 for the first pass
# image_number_inc: increment the image count? True or False
# pass_number_inc: increment the pass count? True or False
delay = sequence.delay
nom_delay = sequence.nom_delay
laser_on = sequence.laser_on
ms_on = sequence.ms_on
pump_on = sequence.pump_on
xdet_on = sequence.xdet_on
pass_number = sequence.pass_number
image_number_inc = sequence.image_number_inc
pass_number_inc = sequence.pass_number_inc
acquiring = sequence.acquiring
mode_number = sequence.mode_number
period = sequence.period
N = sequence.N
dt = sequence.dt
t0 = sequence.t0
transd = sequence.transd
z = sequence.z
from timing_system import timing_system
from numpy import isnan,where,arange,rint,floor,ceil,array,cumsum,\
maximum,clip,concatenate,zeros
from sparse_array import sparse_array
Tbase = timing_system.hsct
n = period
# The high-speed chopper determines the X-ray pulse timing.
##xd = -timing_system.hsc.delay.offset
xd = self.xd
# If the chopper timing shift is more than 100 ns,
# assume the chopper selects a different bunch with a different timing.
# (e.g super bunch versus single bunch)
# However, if the time shift is more than 4 us, assume the tunnel
# 1-unch selection mode is used so the transmitted X-ray pulse
# arrives at nominally t=0.
##phase = timing_system.high_speed_chopper_phase.value
##if 100e-9 < abs(phase) < 4e-6: xd += phase
it_xray = t0 + arange(0,N*dt,dt)
t_xray = it_xray*Tbase+xd
t_laser = t_xray - delay
registers,counts=[],[]
if not isnan(pass_number):
pass_number_counts = sparse_array(n,pass_number)
registers += [timing_system.pass_number]; counts += [pass_number_counts]
elif not pass_number_inc:
pass_number_counts = sparse_array(n,0)
registers += [timing_system.pass_number]; counts += [pass_number_counts]
if image_number_inc:
image_number_inc_counts = sparse_array(n)
image_number_inc_counts[n-1] = 1
registers += [timing_system.image_number_inc]; counts += [image_number_inc_counts]
if pass_number_inc:
pass_inc_counts = sparse_array(n,0)
pass_inc_counts[0] = pass_number_inc
registers += [timing_system.pass_number_inc]; counts += [pass_inc_counts]
if ms_on:
pulses_counts = sparse_array(n,0)
pulses_inc_counts = sparse_array(n)
pulses_inc_counts[it_xray] = 1
registers += [timing_system.pulses_inc]; counts += [pulses_inc_counts]
registers += [timing_system.pulses]; counts += [pulses_counts]
# Indicate whether data acquisition is running.
acquiring_counts = sparse_array(n,acquiring)
registers += [timing_system.acquiring]; counts += [acquiring_counts]
# Channel configuration-based sequence generation
for i_channel in range(0,len(timing_system.channels)):
channel = timing_system.channels[i_channel]
if channel.PP_enabled:
if channel.special == "trans": # Sample translation trigger
# Transmit the mode number to the motion controller as bit pattern.
# 2 or 3 clock cycles start, 2 or 3 clock cycles per bit.
bit_length = int(rint(channel.pulse_length/Tbase))
transc = self.trigger_code_of(
mode_number,
ms_on,
sequence.following_sequence.pump_on,
sequence.following_sequence.delay,
z,
)
it_transst = range(0,bit_length)
for i in range(0,32):
if (transc>>i) & 1:
it_transst += range(bit_length*(i+1),bit_length*(i+2))
it_transst = array(it_transst)
it_transst += transd
it_transst %= period
trans_state_counts = sparse_array(n)
trans_state_counts[it_transst] = 1
registers += [channel.state]; counts += [trans_state_counts]
elif channel.special == "pso": # Picosecond oscillator reference clock
# Picosecond oscillator reference clock (course, 7.1 ns resolution)
pso_period = 5*timing_system.bct
pso_coarse_step = timing_system.psod3.stepsize
pst_dial_values = t_laser - timing_system.pst.offset
pst_dial = pst_dial_values[0] % Tbase
pso_dial = timing_system.psod3.dial_from_user(pst_dial) % pso_period
psod3_dial = floor(pso_dial/pso_coarse_step)*pso_coarse_step
psod3_count = timing_system.psod3.count_from_dial(psod3_dial)
psod3_counts = sparse_array(n,psod3_count)
# Picosecond oscillator reference clock (fine, 9 ps resolution)
psod2_dial = pso_dial % pso_coarse_step
clk_shift_count = timing_system.psod2.count_from_dial(psod2_dial)
psod2_counts = sparse_array(n,clk_shift_count)
registers += [timing_system.psod3]; counts += [psod3_counts]
registers += [timing_system.psod2]; counts += [psod2_counts]
elif channel.special == "nsf": # Nanosecond laser flashlamp trigger
nsf_nperiod = 48 # 20 Hz operation (10 Hz would be 96 counts)
T_nsf = nsf_nperiod * Tbase # flashlamp trigger period
N_nsf = n/nsf_nperiod # number of flashlamp triggers per image
t_nsf0 = (t_laser[0] + channel.offset_sign * channel.offset) % T_nsf # first trigger
t_nsf = t_nsf0 + arange(0,N_nsf) * T_nsf
# Abrupt timing jumps at the end of an image might cause the ns laser
# to trip. Make sure that no to trigger pulses arrive within less
# than 80% of the nominal period.
preceeding_t_laser = t_xray - sequence.preceeding_sequence.delay
preceeding_t_nsf0 = (preceeding_t_laser[0] - channel.offset_sign * channel.offset) % T_nsf
preceeding_t_nsf = preceeding_t_nsf0 + arange(0,N_nsf) * T_nsf
preceeding_t_nsf -= n*Tbase
if len(t_nsf) > 0 and t_nsf[0] - preceeding_t_nsf[-1] < 0.80 * T_nsf:
t_nsf = t_nsf[1:]
nsf_delay_dial = t_nsf[0] % Tbase if len(t_nsf)>0 else 0
nsf_count = channel.count_from_dial(nsf_delay_dial)
nsf_delay_counts = sparse_array(n,nsf_count)
it_nsf = floor(t_nsf/Tbase).astype(int)
nsf_enable_counts = sparse_array(n)
nsf_enable_counts[it_nsf] = 1
registers += [channel.delay]; counts += [nsf_delay_counts]
registers += [channel.enable]; counts += [nsf_enable_counts]
else:
try:
r,c = self.channel_register_counts(i_channel,sequence)
registers += r; counts += c
except Exception,msg: error("Ensemble_SAXS: Channel %r: %s\n%s" %
(i_channel,msg,format_exc()))
return registers,counts
def channel_register_counts(self,i_channel,sequence):
"""list of registers and lists of counts
i: channel number (0-based)
"""
# delay: laser to X-ray pump-probe delay in seconds
# laseron: trigger the laser?
# ms_on: operate the X-ray milliscond shutter?
# pump_on: operate the peristaltic pump?
# pass_number=1 for the first pass
# image_number_inc: increment the image count? True or False
# pass_number_inc: increment the pass count? True or False
# acquiring: is this packet used for data collection?
delay = sequence.delay
nom_delay = sequence.nom_delay
laser_on = sequence.laser_on
ms_on = sequence.ms_on
pump_on = sequence.pump_on
xdet_on = sequence.xdet_on
acquiring = sequence.acquiring
mode_number = sequence.mode_number
period = sequence.period
N = sequence.N
dt = sequence.dt
t0 = sequence.t0
transd = sequence.transd
z = sequence.z
from timing_system import timing_system
from numpy import isnan,where,arange,rint,floor,ceil,array,cumsum,\
maximum,clip,concatenate,zeros,array,diff,all
from sparse_array import sparse_array
channel = timing_system.channels[i_channel]
Tbase = timing_system.hsct
n = period
T = n*Tbase # packet period
# The high-speed chopper determines the X-ray pulse timing.
##xd = -timing_system.hsc.delay.offset
xd = self.xd
# If the chopper timing shift is more than 100 ns,
# assume the chopper selects a different bunch with a different timing.
# (e.g super bunch versus single bunch)
# However, if the time shift is more than 4 us, assume the tunnel
# 1-unch selection mode is used so the transmitted X-ray pulse
# arrives at nominally t=0.
##phase = timing_system.high_speed_chopper_phase.value
##if 100e-9 < abs(phase) < 4e-6: xd += phase
it_xray = t0 + arange(0,N*dt,dt)
t_xray = it_xray*Tbase+xd
t_laser = t_xray - delay
counts = []
registers = []
if channel.gated == "pump": on = laser_on
elif channel.gated == "probe": on = ms_on
elif channel.gated == "detector": on = xdet_on
else: on = True
if channel.timed == "pump": t_ref = t_laser
elif channel.timed == "probe": t_ref = t_xray
elif channel.timed == "period": t_ref = array([0.0])
else: t_ref = array([])
if on and len(t_ref) > 0:
if not isnan(channel.offset_HW): # precision-timed sub-ms pulses
t = t_ref + channel.offset_sign * channel.offset_HW
fine_delay = t[0] % Tbase
delay_count = channel.next_count(fine_delay/channel.stepsize)
delay_counts = sparse_array(n,delay_count)
it = floor(t/Tbase).astype(int)
enable_counts = sparse_array(n)
enable_counts[it] = 1
counts += [enable_counts,delay_counts]
registers += [channel.enable,channel.delay]
it_on = it # for trigger count
else: # ms-resolution multi-ms pulses
t0 = channel.offset
pulse_length = channel.pulse_length
timed = channel.timed
if isnan(pulse_length): pulse_length = 0
t = array([t_ref+t0,t_ref+t0+pulse_length]).T.flatten()
t = self.t_special(t,channel.special)
Noutside = sum((t<0)|(t>=T))
initial_value = 1 if Noutside % 2 == 1 else 0
t = t % T
it = clip(rint(t/Tbase),0,n-1).astype(int)
it_on,it_off = it.reshape((-1,2)).T
inc = sparse_array(n)
inc[it_on] += 1
inc[it_off] -= 1
state_counts = clip(cumsum(inc)+initial_value,0,1)
state_counts = sparse_array(state_counts)
counts += [state_counts]
registers += [channel.state]
if channel.counter_enabled:
# Increment the trigger count on the rising edge of the last
# trigger pulse within the measure.
it_last_trigger = it_on[-1:]
count_inc = sparse_array(n)
count_inc[it_last_trigger] = 1
registers += [channel.trig_count]
counts += [count_inc]
if acquiring:
registers += [channel.acq]
counts += [count_inc]
registers += [channel.acq_count]
counts += [count_inc]
return registers,counts
def t_special(self,t,special):
"""Process time delays for channels that have special functions
t: array of time delays in seconds for rising and falling edges,
alternating
special: e.g. "ms" for X-ray millisecond shutter
"""
from numpy import array
t_special = t
t_rise,t_fall = t[0::2],t[1::2]
if special == "ms":
if len(t) >= 2:
if len(t_rise) >= 2:
burst_period = (max(t_rise)-min(t_rise))/(len(t_rise)-1)
else: burst_period = 0
if 0 < burst_period < 0.024: # Open continuously for a burst
t_special = array([min(t_rise),max(t_rise)])
return t_special
def channel_description(self,i_channel):
"""The parameters for generating a packet represented as text string."""
from timing_system import timing_system
description = ""
channel = timing_system.channels[i_channel]
name = channel.mnemonic if channel.mnemonic else channel.name
description += name+".special=%r," % channel.special
description += name+".offset_PP=%r," % channel.offset_PP
description += name+".offset_sign=%r," % channel.offset_sign
description += name+".pulse_length_PP=%r," % channel.pulse_length_PP
description += name+".offset_HW=%r," % channel.offset_HW
description += name+".pulse_length_HW=%r," % channel.pulse_length_HW
description += name+".timed=%r," % channel.timed
description += name+".gated=%r," % channel.gated
description += name+".counter_enabled=%r," % channel.counter_enabled
return description
def trigger_code_of(self,mode_number,ms_on,pump_on,delay,z):
"""Byte code to be transmitted to the Ensemble motion controller
as bit pattern
ms_on: operate the X-ray milliscond shutter?
pump_on: operate the peristaltic pump?
"""
# mode: 4 bits: pump_on: 1 bit, delay 6 bits
delay_count = self.delay_count(delay) if z else 0
transc = (
(int(mode_number)<<0) |
(int(pump_on)<<4) |
(int(delay_count)<<5)
)
return transc
def delay_count(self,delay):
"""Count to indicate the linear translation of the laser beam on a
logarithmic scale
delay: delay in seconds, range 0-17.8 ms
Return value: integer, range 0-63"""
from numpy import log10,rint
delay_count = min(int(rint(8*log10(max(delay,10e-6)/10e-6))),63)
return delay_count
def acquisition_start(self,image_number=1):
"""To be called after 'acquire'
image_number: 1-based integer
"""
self.image_number = image_number-1
self.pass_number = 0
self.pulses = 0
self.queue_sequence_count = 0
self.queue_repeat_count = 0
self.queue_active = True
def acquisition_cancel(self):
"""End current data collection"""
self.queue_active = False
def set_default_sequences(self,sequences=None):
"""Set a sequece to be execute when the queue is empty.
"""
if sequences is None: sequences = Sequences()[:]
self.configured = True
self.timing_sequencer.set_default_sequences(sequences)
def get_queue(self): return self.timing_sequencer.queue
def set_queue(self,value):self.timing_sequencer.queue = value
queue = property(get_queue,set_queue)
def get_queue_length(self): return self.timing_sequencer.queue_length
def set_queue_length(self,value): self.timing_sequencer.queue_length = value
queue_length = property(get_queue_length,set_queue_length)
def get_queue_active(self): return self.timing_sequencer.queue_active
def set_queue_active(self,value): self.timing_sequencer.queue_active = value
queue_active = property(get_queue_active,set_queue_active)
def get_buffer_length(self): return self.timing_sequencer.buffer_length
def set_buffer_length(self,value): self.timing_sequencer.buffer_length = value
buffer_length = property(get_buffer_length,set_buffer_length)
def get_cache_enabled(self): return self.timing_sequencer.cache_enabled
def set_cache_enabled(self,value): self.timing_sequencer.cache_enabled = value
cache_enabled = property(get_cache_enabled,set_cache_enabled)
def cache_clear(self): return self.timing_sequencer.cache_clear()
def get_cache_size(self): return self.timing_sequencer.cache_size
def set_cache_size(self,value): self.timing_sequencer.cache_size = value
cache_size = property(get_cache_size,set_cache_size)
def get_acquiring(self):
from timing_system import timing_system
return timing_system.acquiring.count != 0
def set_acquiring(self,value):
if not value: self.update()
acquiring = property(get_acquiring,set_acquiring)
def get_running(self): return self.timing_sequencer.running
def set_running(self,value):
self.timing_sequencer.set_running(value,update=self.update)
running = property(get_running,set_running)
def update(self):
"""Execute sequence using the current default parameters"""
self.set_default_sequences()
self.timing_sequencer.enabled = True
def clear_queue(self):
"""Cancel current data acaquisstion"""
self.timing_sequencer.clear_queue()
def get_default_sequence_active(self):
return self.timing_sequencer.default_sequence_active
def set_default_sequence_active(self,value):
self.timing_sequencer.default_sequence_active = value
default_sequence_active = property(get_default_sequence_active,
set_default_sequence_active)
def get_image_number(self):
from timing_system import timing_system
return timing_system.image_number.count
def set_image_number(self,value):
from timing_system import timing_system
timing_system.image_number.count = value
image_number = property(get_image_number,set_image_number)
def get_pass_number(self):
from timing_system import timing_system
return timing_system.pass_number.count
def set_pass_number(self,value):
from timing_system import timing_system
timing_system.pass_number.count = value
pass_number = property(get_pass_number,set_pass_number)
def get_pulses(self):
from timing_system import timing_system
return timing_system.pulses.count
def set_pulses(self,value):
from timing_system import timing_system
timing_system.pulses.count = value
pulses = property(get_pulses,set_pulses)
def get_xd(self):
from timing_system import timing_system
return timing_system.xd
def set_xd(self,value):
from timing_system import timing_system
if timing_system.xd != value:
timing_system.xd = value
self.update()
xd = property(get_xd,set_xd)
def get_hsc_delay(self):
from timing_system import timing_system
return timing_system.hsc.delay.value
def set_hsc_delay(self,value):
from timing_system import timing_system
timing_system.hsc.delay.value = value
hsc_delay = property(get_hsc_delay,set_hsc_delay)
def __getattr__(self,name):
"""A property"""
# Called when 'x.name' is evaluated.
# It is only invoked if the attribute was not found the usual ways.
if name.startswith("__") and name.endswith("__"):
raise AttributeError("EnsembleSAXS object has no attribute %r" % name)
from timing_system import timing_system
alt_name = name.replace("_",".") # hsc_delay > hsc.delay
if hasattr(timing_system,name):
attr = getattr(timing_system,name)
if hasattr(attr,"value"): attr = attr.value
return attr
elif self.hasattr(timing_system,alt_name):
attr = eval("timing_system.%s" % alt_name)
if hasattr(attr,"value"): attr = attr.value
return attr
elif hasattr(self.timing_sequencer,name):
return getattr(self.timing_sequencer,name)
else: return object.__getattribute__(self,name)
@staticmethod
def hasattr(object,name):
"""name: e.g. 'hsc.delay'"""
try: eval("object.%s" % name); return True
except AttributeError: return False
def __setattr__(self,name,value):
"""Set a property"""
# Called when 'x.name = y' is evaluated.
from timing_system import timing_system
alt_name = name.replace("_",".") # hsc_delay > hsc.delay
if name.startswith("__") and name.endswith("__"):
object.__setattr__(self,name,value)
elif name in self.__class__.__dict__.keys():
object.__setattr__(self,name,value)
elif hasattr(timing_system,name):
attr = getattr(timing_system,name)
if hasattr(attr,"value"): attr.value = value
else: setattr(timing_system,name,value)
elif self.hasattr(timing_system,alt_name):
attr = eval("timing_system.%s" % alt_name)
if hasattr(attr,"value"): attr.value = value
else: exec("timing_system.%s = %r" % (alt_name,value))
elif hasattr(self.timing_sequencer,name):
setattr(self.timing_sequencer,name,value)
else: object.__setattr__(self,name,value)
def __repr__(self): return "Ensemble_SAXS"
Ensemble_SAXS = EnsembleSAXS()
def sorted_lists(lists):
from numpy import argsort
order = argsort(lists[0])
def reorder(list,order): return [list[i] for i in order]
sorted_lists = [reorder(list,order) for list in lists]
return sorted_lists
if __name__ == "__main__": # for testing
from pdb import pm # for debugging
import logging
logging.basicConfig(
level=logging.DEBUG,
format="%(asctime)s: %(levelname)s %(module)s.%(funcName)s: %(message)s",
)
import timing_system as t; t.DEBUG = True
from timing_system import timing_system
self = Ensemble_SAXS # for debugging
from time import time # for performace measuring
# parameters for Ensemble_SAXS.register_counts:
from numpy import nan
# parameters for "register_counts"
sequences = Sequences(acquiring=False)
sequence = sequences[0]
##sequence = Sequence(acquiring=False)
# parameters for "channel_register_counts"
##i_channel = 6-1 # ms
print('timing_system.prefix = %r' % timing_system.prefix)
print('timing_system.ip_address_and_port = %r' % timing_system.ip_address_and_port)
print('')
print('Ensemble_SAXS.cache_size = %r' % Ensemble_SAXS.cache_size)
print('Ensemble_SAXS.remote_cache_size = %r' % Ensemble_SAXS.remote_cache_size)
print('Ensemble_SAXS.running = True')
print('Ensemble_SAXS.update()')
print('')
print('Ensemble_SAXS.xd')
print('Ensemble_SAXS.hsc_delay')
<file_sep>"""<NAME>, Jan 29, 2016 - Jan 29, 2016"""
from pdb import pm
from logging import warn
try: from rayonix_detector_XPP import ccd
except: warn("rayonix_detector_XPP not available")
from timing_sequence import timing_sequencer
from timing_system import timing_system
from ImageViewer import show_images
__version__ = "1.0"
import logging
from tempfile import gettempdir
logging.basicConfig(level=logging.DEBUG,format="%(asctime)s: %(message)s",
filename=gettempdir()+"/lauecollect_debug.log")
nimages = 20
dir = "/reg/neh/operator/xppopr/experiments/xppj1216/Data/Test/Test2"
filenames = [dir+"/%03d.mccd" % i for i in range(0,nimages)]
image_numbers = range(1,nimages+1)
laser_on = [0,1]*(nimages/2)
ms_on = [0,1]*(nimages/2)
xatt_on = [1,0]*(nimages/2)
npulses = [11,1]*(nimages/2)
def test_FPGA():
timing_sequencer.restart()
timing_system.image_number.value = 0
timing_system.pass_number.value = 0
timing_system.pulses.value = 0
timing_sequencer.acquire(laser_on=laser_on,ms_on=ms_on,xatt_on=xatt_on,
npulses=npulses,image_numbers=image_numbers)
def test():
test_FPGA()
ccd.acquire_images_triggered(filenames)
show_images(filenames)
print("test_FPGA()")
print("test()")
<file_sep>title = 'Secondary KB Saved Positions'
serial = 1
motor_labels = ['V Pitch', 'V Height', 'V Curature', 'V Stripe', 'H Pitch', 'H Height', 'H Curvature', 'H Stripe']
formats = ['%+6.3f', '%+6.3f', '%+6.3f', '%+6.3f', '%+6.3f', '%+6.3f', '%+6.3f', '%+6.3f']
motor_names = ['KB_Vpitch', 'KB_Vheight', 'KB_Vcurvature', 'KB_Vstripe', 'KB_Hpitch', 'KB_Hheight', 'KB_Hcurvature', 'KB_Hstripe']
line0.Phi = -14.999999919609564
line0.updated = '04 Oct 10:04'
line0.KB_Vpitch = 3.8
line0.KB_Vheight = 0.0
line0.KB_curvature = nan
line0.KB_Hpitch = 3.8
line0.KB_Hheight = 8.000000000008001e-05
line0.KB_Hcurvature = 14.599979999999995
line0.KB_Vcurvature = 14.499979999999994
line0.description = 'Calibrated'
command_row = 0
line0.KB_Vstripe = 5.300000000000001
line0.KB_Hstripe = 2.5
line1.KB_Vpitch = 3.7792885599999972
line1.KB_Vheight = 9.000000000014552e-05
line1.KB_Vcurvature = 14.499979999999994
line1.KB_Vstripe = 5.300000000000001
line1.KB_Hpitch = 3.719160720000001
line1.KB_Hheight = 8.00000000005241e-05
line1.KB_Hcurvature = 14.599979999999995
line1.KB_Hstripe = 2.5
line1.updated = '04 Oct 13:34'
line1.description = 'Solution scattering 12 keV'
nrows = 3
line2.KB_Vpitch = 3.8022237999999997
line2.KB_Vheight = 0.20015999999999945
line2.KB_Vcurvature = 14.499979999999994
line2.KB_Vstripe = 5.300000000000001
line2.KB_Hpitch = 3.6565812399999995
line2.KB_Hheight = 0.0999800000000004
line2.KB_Hcurvature = 13.80002
line2.KB_Hstripe = 2.5
line2.updated = '11 Oct 16:30'
line2.description = 'Solution sc 8keV small beamstop'<file_sep>EPICS_enabled = True
description = 'High-speed chopper Y'
prefix = '14IDB:m2'
target = 30.808999999999997<file_sep>"""<NAME>, 23 Jul 2015 - 29 Sep 2015"""
__version__ = "3.0"
def set_vars(timepoint,laser_mode,nrepeat,waitt_delay):
"""
timepoint: delay in seconds
laser_modes: 0 = off, 1 = on
nrepeat: laser/xray pulses per image
waitt_delay: laser/xray repetition period
"""
dt = 1/hscf
waitt_delay = max(ceil(timepoint/dt)*dt,rint(waitt_delay/dt)*dt)
variables,value_lists = [],[]
variables += [timing_system.ps_lxd]; value_lists += [[timepoint]]
variables += [timing_system.waitt]; value_lists += [[waitt_delay]]
variables += [timing_system.npulses]; value_lists += [[nrepeat]]
variables += [timing_system.pst.on]; value_lists += [[laser_mode]]
variables += [timing_system.xosct.on]; value_lists += [[1]]
variables += [timing_system.losct.on]; value_lists += [[1]]
variables += [timing_system.ms.on]; value_lists += [[1]]
variables += [timing_system.xdet.on]; value_lists += [[1]]
set_sequence(variables,value_lists,repeat_counts=[10])
if __name__ == "__main__":
from pdb import pm # for debugging
import logging
logging.basicConfig(level=logging.DEBUG,format="%(asctime)s: %(message)s")
##import timing_system; timing_system.DEBUG = True
from timing_system import *
from numpy import *
print 'timing_system.ip_address = %r' % timing_system.ip_address
timepoint,laser_mode,nrepeat,waitt_delay = 0,1,5,0.2
print 'set_vars(0,1,5,0.2)'
print 'set_sequence(variables,value_lists,repeat_counts=[10])'
print 'packets,names = sequencer_packets(variables,value_lists)'
print 'timing_sequencer.set_sequence(variables,value_lists,1,name="collection")'
print 'timing_sequencer.add_sequence(variables,value_lists,1,name="collection")'
print 'timing_sequencer.enabled'
print 'timing_sequencer.running'
print 'timing_sequencer.queue'
print 'timing_sequencer.clear_queue()'
print 'timing_sequencer.abort()'
self = timing_sequencer
<file_sep>"""Nov 5, 2015"""
from temperature_controller import temperature_controller
from numpy import nan,array
print temperature_controller.setT.values
print len(temperature_controller.readT.values)
##setTs = temperature_controller.setT.values
##setT = setTs[-1] if len(setTs) > 0 else nan
##Ts = array(temperature_controller.readT.values)
##all(abs(Ts[-3:0]-setT)) < temperature_controller.setT.stabilization_RMS
<file_sep>#!/usr/bin/env python
"""Find the position of the direct X-ray beam in the X-ray detector,
attenuated by a transmissive beam stop.
Author: <NAME>, Aug 26 2014 - Feb 23 2016
<NAME>, Feb 29, 2016 = Mar 1, 2016
"""
from numimage import numimage
from xray_beam_stabilization import xray_beam_stabilization
from numpy import *
from scipy.ndimage.filters import gaussian_filter,gaussian_gradient_magnitude
__version__ = "1.0.1" # speedup 4 s -> 1 ms, caching mask
mask_filename = "//mx340hs/data/anfinrud_1602/Logfiles/beamstop-1.png"
offset = 10.0
# x-ray beam center
# estimated x and y pixel of x-ray beamcenter
xinit, yinit = 1985.249, 1964.92
window0 = 2*10+1 #7 #15 # full width, H and V are same
# beamstop center
xbsc, ybsc = 1986, 1964 #1983.,1968. #2*992.0, 2*981.0 # beamstop center
w,h = 3840, 3840 # 2x2 binning
pxl_size = 0.1772/2 # 2x2 binning [mm]
# roi window indices around beam center
x_i = round(xinit-window0/2)
x_f = round(x_i+window0)
y_i = round(yinit-window0/2)
y_f = round(y_i+window0)
def setup():
"""Calculate beamstop mask"""
global bc_roi,Beamstopid_roi,mask
mask_image = numimage(mask_filename)
mask = mask_image[x_i:x_f,y_i:y_f]
mask = mask_image[x_i+1.:x_f+1.,y_i:y_f]
# beamstop - maximum ring , circle or ellipse?
x_indices,y_indices = indices((w,h))
# beamstop assuming ellipse - beamstop roi
ellip_x, ellip_y = 2*4.0, 2*4.0 # pixels
# beamstopid - flat-area inside beamstop, assuming ellipse
ellip_xid, ellip_yid = ellip_x*0.75, ellip_y*0.75
distid_criteria = sqrt(ellip_yid**2*(x_indices-xbsc)**2+ellip_xid**2*(y_indices-ybsc)**2)
Beamstopid = distid_criteria<(ellip_xid*ellip_yid)
Beamstopid_roi = Beamstopid[x_i:x_f,y_i:y_f]
# beamcenter roi
# tweak beam center roi to avoid spurious scattering
beam_rx, beam_ry = 4.0, 4.0 # 5.0, 5.0 # pixels
# just a little shift by 0.5 pixel to avoid beam spillage
#Beamcenter_criteria =\
# sqrt(beam_ry**2*(x_indices-(xinit+0.5))**2+beam_rx**2*(y_indices-(yinit-1.0))**2)
Beamcenter_criteria =\
sqrt(beam_ry**2*(x_indices-(xinit))**2+beam_rx**2*(y_indices-(yinit))**2)
Beamcenter = Beamcenter_criteria < (beam_rx*beam_ry)
bc_roi = Beamcenter[x_i:x_f,y_i:y_f]
def beam_center(image):
"""x,y in mm from top left corner"""
if not "bc_roi" in globals(): setup()
pixelsize = image.pixelsize
Iroi_raw = image[x_i:x_f,y_i:y_f]
mask_sat = (Iroi_raw == 65535)
Iroi = image[x_i:x_f,y_i:y_f]-offset
BSmin = Iroi[Beamstopid_roi].min()
# generating "gaussian-filtered beamstop" set proper sigma
sigma_ = 0.6 #0.7 #0.6 # ~100/89./2.355 - 100um psf, 89um pixel by rayonix detector
sigma_2_scale = 9. #5.0 #10.
gfx_factor = 0.345 #0.1 #0.3
Ig_gf0 = gaussian_filter(Iroi*~mask+BSmin*mask,sigma=sigma_,order=0)
Ig_gfx = gaussian_filter(Iroi*~mask+BSmin*mask,sigma=sigma_2_scale*sigma_,order=0)
try: Ig_gf = Ig_gf0 + gfx_factor*(Ig_gfx-Ig_gfx[mask & (Ig_gfx>0)].min())*mask
except ValueError: Ig_gf = Ig_gf0
Ig_gf += (Iroi[mask].min()-Ig_gf[mask].min())*mask
I_xray = Iroi-Ig_gf
bc_roi_mod = bc_roi & ~mask_sat
xc = sum(sum(I_xray*bc_roi_mod,axis=1)*range(window0))/sum(I_xray*bc_roi_mod)
yc = sum(sum(I_xray*bc_roi_mod,axis=0)*range(window0))/sum(I_xray*bc_roi_mod)
Iroi_int = sum(I_xray*bc_roi) # saturation pixels ?
center_x = (xc+x_i)*pixelsize #[mm]
center_y = (yc+y_i)*pixelsize #[mm]
center_x,center_y = float(center_x),float(center_y)
return center_x,center_y
if __name__ == "__main__":
from pdb import pm
from time import time
print('image = xray_beam_stabilization.image')
print('beam_center(image)')
<file_sep>#!/usr/bin/env python
"""
Archive EPICS process variable via Channel Access
Author: <NAME>
Date created: 10/4/2017
Date last modified: 11/2/2017
"""
__version__ = "1.0.2" # wx 4.0
import wx,wx3_compatibility
from logging import debug,info,warn,error
from channel_archiver import channel_archiver
from EditableControls import TextCtrl
class ChannelArchiverPanel(wx.Frame):
name = "ChannelArchiver"
def __init__ (self,parent=None):
wx.Frame.__init__(self,parent=parent,title="Channel Archiver")
from Icon import SetIcon
SetIcon(self,"Archiver")
self.panel = wx.Panel(self)
border = wx.BoxSizer(wx.VERTICAL)
flag = wx.ALL|wx.EXPAND
box = wx.BoxSizer(wx.VERTICAL)
from wx import grid
self.Table = grid.Grid(self.panel)
nrows = max(len(self.PVs),1)
self.Table.CreateGrid(nrows,4)
self.Table.SetRowLabelSize(20) # 1,2,...
self.Table.SetColLabelSize(20)
self.Table.SetColLabelValue(0,"Log")
self.Table.SetColLabelValue(1,"Description")
self.Table.SetColLabelValue(2,"Process Variable")
self.Table.SetColLabelValue(3,"Value")
for i in range(0,min(nrows,len(self.PVs))):
if i<len(self.PVsuse) and self.PVsuse[i]: text = "Yes"
else: text = "No"
self.Table.SetCellValue(i,0,text)
if i<len(self.PVnames):
self.Table.SetCellValue(i,1,self.PVnames[i])
self.Table.SetCellValue(i,2,self.PVs[i])
self.Table.AutoSize()
self.Bind(wx.grid.EVT_GRID_CELL_CHANGE,self.OnEnterCell,self.Table)
self.Bind(wx.grid.EVT_GRID_SELECT_CELL,self.OnSelectCell,self.Table)
box.Add (self.Table,flag=flag,proportion=1)
buttons = wx.BoxSizer()
button = wx.Button(self.panel,label="+",style=wx.BU_EXACTFIT)
self.Bind(wx.EVT_BUTTON,self.add_row,button)
buttons.Add (button,flag=flag)
size = button.GetSize()
button = wx.Button(self.panel,label="-",size=size)
self.Bind(wx.EVT_BUTTON,self.delete_row,button)
buttons.Add (button,flag=flag)
box.Add (buttons,flag=flag)
# Leave a 10-pixel wide space around the panel.
border.Add (box,flag=flag,border=10,proportion=1)
flag = wx.ALL|wx.EXPAND
group = wx.BoxSizer(wx.HORIZONTAL)
label = wx.StaticText(self,label="Destination:")
group.Add (label,flag=flag)
style = wx.TE_PROCESS_ENTER
self.Directory = TextCtrl(self.panel,size=(250,-1),style=style)
self.Directory.Value = channel_archiver.directory
self.Bind(wx.EVT_TEXT_ENTER,self.OnDirectory,self.Directory)
group.Add (self.Directory,flag=flag,proportion=1)
button = wx.Button(self.panel,label="Browse...")
self.Bind(wx.EVT_BUTTON,self.OnBrowse,button)
group.Add (button,flag=flag)
# Leave a 10-pixel wide space around the panel.
flag = wx.ALL|wx.EXPAND
border.Add (group,flag=flag,border=10)
buttons = wx.BoxSizer()
button = wx.ToggleButton(self.panel,label="Active")
self.Bind(wx.EVT_TOGGLEBUTTON,self.OnActive,button)
buttons.Add (button,flag=flag)
buttons.AddSpacer((10,10))
button = wx.Button(self.panel,label="Test")
self.Bind(wx.EVT_BUTTON,self.test,button)
buttons.Add (button,flag=flag)
# Leave a 10-pixel wide space around the panel.
border.Add (buttons,flag=flag,border=10)
self.panel.Sizer = border
self.panel.Fit()
self.Fit()
self.Show()
self.Bind(wx.EVT_SIZE,self.OnResize)
def OnResize(self,event):
self.update_layout()
event.Skip() # call default handler
def update_layout(self):
"""Resize componenets"""
self.Table.AutoSize()
self.panel.Fit()
self.Fit()
def add_row(self,event):
"""Add one more row at the end of the table"""
self.Table.AppendRows(1)
self.Table.AutoSize()
self.update_layout()
def delete_row(self,event):
""""Remove the last row of the table"""
n = self.Table.GetNumberRows()
self.Table.DeleteRows(n-1,1)
self.Table.AutoSize()
self.update_layout()
def OnDirectory(self,event):
"""Set destination folder for archive"""
debug("channel_archiver.directory = %r" % str(self.Directory.Value))
channel_archiver.directory = str(self.Directory.Value)
def OnBrowse(self,event):
"""Set destination folder for archive"""
from os.path import exists,dirname
from normpath import normpath
pathname = channel_archiver.directory
while pathname and not exists(pathname): pathname = dirname(pathname)
dlg = wx.DirDialog(self, "Choose a directory:",style=wx.DD_DEFAULT_STYLE)
# ShowModal pops up a dialog box and returns control only after the user
# has selects OK or Cancel.
dlg.Path = pathname
if dlg.ShowModal() == wx.ID_OK:
self.Directory.Value = normpath(str(dlg.Path))
dlg.Destroy()
debug("channel_archiver.directory = %r" % str(self.Directory.Value))
channel_archiver.directory = str(self.Directory.Value)
def OnActive(self,event):
"""Start/stop archiving"""
##debug("channel_archiver.running = %r" % event.IsChecked())
channel_archiver.running = event.IsChecked()
def OnSelectCell(self,event):
"""Show Options"""
debug("Select")
def OnEnterCell(self,event):
"""Accept current values"""
PVsuse = []
PVnames = []
PVs = []
for i in range (0,self.Table.GetNumberRows()):
PVuse = (self.Table.GetCellValue(i,0).lower() == "yes")
PVname = str(self.Table.GetCellValue(i,1))
PV = str(self.Table.GetCellValue(i,2))
if PV:
PVsuse += [PVuse]
PVnames += [PVname]
PVs += [PV]
self.PVsuse = PVsuse
self.PVnames = PVnames
self.PVs = PVs
def test(self,event):
"""Check if PVs are working b yreading their current value"""
from CA import caget
for i in range (0,self.Table.GetNumberRows()):
enabled = self.Table.GetCellValue(i,0) == "Yes"
PV = str(self.Table.GetCellValue(i,2))
value = str(caget(PV)) if (PV and enabled) else ""
self.Table.SetCellValue(i,3,value)
self.update_layout()
def get_PVs(self):
self.update_known_PVs()
return self.known_PVs
def set_PVs(self,PVs):
self.known_PVs = PVs
##debug("known_PVs = %r" % self.known_PVs)
PVs = property(get_PVs,set_PVs)
def get_PVsuse(self):
active_PVs = channel_archiver.PVs
use = [PV in active_PVs for PV in self.known_PVs]
return use
def set_PVsuse(self,use_list):
PVs = [PV for (PV,use) in zip(self.known_PVs,use_list) if use]
channel_archiver.PVs = PVs
debug("channel_archiver.PVs = %r" % channel_archiver.PVs)
PVsuse = property(get_PVsuse,set_PVsuse)
def get_PVnames(self):
names = [self.names[PV] if PV in self.names else ""
for PV in self.PVs]
return names
def set_PVnames(self,names):
PV_names = self.names
for PV,name in zip(self.PVs,names):
PV_names[PV] = name
self.names = PV_names
##debug("names = %r" % self.names)
PVnames = property(get_PVnames,set_PVnames)
from persistent_property import persistent_property
names = persistent_property("names",{})
known_PVs = persistent_property("known_PVs",[])
def update_known_PVs(self):
known_PVs = self.known_PVs
for PV in channel_archiver.PVs:
if not PV in known_PVs: known_PVs += [PV]
self.known_PVs = known_PVs
if __name__ == "__main__": # for testing
from pdb import pm # for debugging
import logging # for debugging
from tempfile import gettempdir
logfile = gettempdir()+"/ChannelArchiverPanel.log"
logging.basicConfig(level=logging.DEBUG,
filename=logfile,
format="%(asctime)s %(levelname)s: %(message)s")
app = wx.App(redirect=False)
panel = ChannelArchiverPanel()
app.MainLoop()
<file_sep>#!/usr/bin/env python
"""<NAME>, Dec 13 2017 - Dec 13 2017"""
from CameraViewer import CameraViewer
import wx
__version__ = "1.8"
wx.app = wx.App(redirect=False) # Needed to initialize WX library
viewer = CameraViewer (
name="MicrofluidicsCamera",
title="Microfluidics Camera",
pixelsize=0.00465
)
wx.app.MainLoop()
<file_sep>history_length = 300
stabilization_RMS = 0.01
stabilization_time = 3.0
title = 'Temperature Configuration'
motor_names = ['collect.temperature', 'collect.temperature_wait', 'collect.temperature_idle']
motor_labels = ['list of temperatures', 'wait', 'Idle temp']
widths = [360, 35, 60]
line0.description = 'NIH:ramp-18_120_0.5_10_3'
line1.description = 'NIH:ramp-18_50_10_0.5_3'
line0.collect.temperature = 'ramp(low=-18,high=120,step=0.5,hold=10,repeat=3)'
line1.collect.temperature = 'ramp(low=-18,high=50,step=0.5,hold=10,repeat=3)'
line1.updated = '18 Oct 21:04'
row_height = 40
line0.updated = '18 Oct 21:04'
description_width = 110
nrows = 3
line2.description = 'NIH:GB3'
line2.updated = '18 Oct 21:07'
line2.collect.temperature = '-14,22,70,100'
names = ['list', 'wait', 'idle']
line0.collect.temperature_wait = '0'
line1.collect.temperature_wait = '0'
line2.collect.temperature_wait = '1'
line0.collect.temperature_idle = '22.0'
line1.collect.temperature_idle = '22.0'
line2.collect.temperature_idle = '22.0'
command_row = 0
formats = ['%s', '%g', '%g']
temp_points = [-16, -16, 120, 120, -16, -16, 120, 120, -16]
time_points = []
idle_temperature = 22.0
idle_temperature_oasis = 8.0
CustomView = ['Temp Points', 'Time Points', 'P default', 'I default', 'D default', 'Lightwave prefix,temperature', 'oasis slave (on/off)', 'Oasis threshold T', 'Oasis idle temperature (low limit) (C)', 'Oasis temperature limit high (C)', 'Oasis headstart time (s)', 'Oasis prefix']
view = 'Standard'<file_sep>"""
Variable Silicon X-ray attenuator of XPP hutch
10 retractable Silicon absorbers with thicknesses from 20 um to 10.24 mm
increasing in powers of two.
Driven by servo motors 20 = in, 0 mm = out.
<NAME>, 12 Dec 2010
"""
__version__ = "1.0.1"
from EPICS_motor import motor
from CA import PV
from Si_abs import Si_mu
class XrayAttenuator(object):
motors = [motor("XPP:SB2:MMS:%d" % i) for i in range(26,16,-1)]
for motor in motors: motor.readback_slop = 0.075
thicknesses = [0.020*2**i for i in range(0,len(motors))]
outpos = [0]*len(motors)
inpos = [20]*len(motors)
inpos[3] = 19 # Filter #4 is damaged at position 20 mm.
photon_energy_PV = PV("SIOC:SYS0:ML00:AO627") # in eV
"""Variable Si X-ray attenuator of XPP hutch"""
def get_transmission(self):
from numpy import exp
x = self.pathlength
E = self.photon_energy
return exp(-float(Si_mu(E))*x)
def set_transmission(self,T):
from numpy import log
E = self.photon_energy
x = -log(T)/float(Si_mu(E))
self.pathlength = x
transmission = property(get_transmission,set_transmission)
value = transmission
def get_photon_energy(self):
"Photon energy in eV"
return self.photon_energy_PV.value
photon_energy = property(get_photon_energy)
def get_pathlength(self):
"Thickness of silicon the X-ray beam passes through"
pathlength = 0
inserted = self.inserted
for i in range(0,len(self.motors)):
if inserted[i]: pathlength += self.thicknesses[i]
return pathlength
def set_pathlength(self,pathlength):
from numpy import rint
pathlength = min(pathlength,sum(self.thicknesses))
steps = int(rint(pathlength/min(self.thicknesses)))
insert = [(steps & 2**i != 0) for i in range(0,len(self.motors))]
self.inserted = insert
pathlength = property(get_pathlength,set_pathlength)
def get_inserted(self):
"True of False for each abosrber, list of 10"
positions = self.positions
return [abs(positions[i]-self.inpos[i]) < abs(positions[i]-self.outpos[i])
for i in range(0,len(self.motors))]
def set_inserted(self,insert):
"Inserted: list of booleans, one for each absorber"
positions = [self.inpos[i] if insert[i] else self.outpos[i]
for i in range(0,len(self.motors))]
self.positions = positions
inserted = property(get_inserted,set_inserted)
def get_positions(self):
"Position for each absorber, list of 10"
return [self.motors[i].value for i in range(0,len(self.motors))]
def set_positions(self,positions):
"Inserted: list of positions, one for each absorber"
for i in range(0,len(self.motors)): self.motors[i].value = positions[i]
positions = property(get_positions,set_positions)
def get_moving(self):
"""Is any of the absorbers moving?"""
return any(motor.moving for motor in self.motors)
def set_moving(self,moving):
"""If moving = False, stop all motors."""
for motor in self.motors: motor.moving = moving
moving = property(get_moving,set_moving)
def stop(self):
"""Stop all motors."""
for motor in self.motors: motor.stop()
xray_attenuator = XrayAttenuator()
if __name__ == "__main__": # for testing
from time import sleep
##xray_attenuator.transmission = 0.337
print "moving",xray_attenuator.moving
print "inserted",xray_attenuator.inserted
print "pathlength",xray_attenuator.pathlength
print "photon energy",xray_attenuator.photon_energy
print "transmission",xray_attenuator.transmission
sleep(1)
print "moving",xray_attenuator.moving
<file_sep>#!/usr/bin/env python
"""
Author: <NAME>
Date created: 2019-03-20
Date last modified: 2019-03-26
"""
__version__ = "1.0" # cleanup
from logging import debug,info,warn,error
from traceback import format_exc
import wx
from dataset_check import dataset # passed on in "globals()"
class Dataset_Check_Panel(wx.Frame):
"""Control panel for Lecroy Oscilloscope"""
title = "Dataset Check"
name = "Dataset_Check_Panel"
icon = "Tool"
def __init__(self,parent=None):
wx.Frame.__init__(self,parent=parent)
self.update()
self.Show()
# Refresh
self.timer = wx.Timer(self)
self.Bind (wx.EVT_TIMER,self.OnTimer,self.timer)
self.timer.Start(5000,oneShot=True)
def update(self):
self.Title = self.title
from Icon import SetIcon
SetIcon(self,self.icon)
panel = self.ControlPanel
if hasattr(self,"panel"): self.panel.Destroy()
self.panel = panel
self.Fit()
def OnTimer(self,event):
"""Perform periodic updates"""
update_globals()
try: self.update_controls()
except Exception,msg: error("%s\n%s" % (msg,format_exc()))
self.timer.Start(5000,oneShot=True)
def update_controls(self):
if self.code_outdated:
self.update_code()
self.update()
@property
def code_outdated(self):
if not hasattr(self,"timestamp"): self.timestamp = self.module_timestamp
outdated = self.module_timestamp != self.timestamp
return outdated
@property
def module_timestamp(self):
from inspect import getfile
from os.path import getmtime,basename
filename = getfile(self.__class__).replace(".pyc",".py")
##debug("module: %s" % basename(filename))
timestamp = getmtime(filename)
return timestamp
def update_code(self):
from inspect import getfile
from os.path import getmtime,basename
filename = getfile(self.__class__).replace(".pyc",".py")
##debug("module: %s" % basename(filename))
module_name = basename(filename).replace(".pyc",".py").replace(".py","")
module = __import__(module_name)
reload(module)
self.timestamp = self.module_timestamp
debug("Reloaded module %r" % module.__name__)
debug("Updating class of %r instance" % self.__class__.__name__)
self.__class__ = getattr(module,self.__class__.__name__)
@property
def ControlPanel(self):
from Controls import Control
panel = wx.Panel(self)
frame = wx.BoxSizer()
panel.Sizer = frame
layout = wx.BoxSizer(wx.VERTICAL)
frame.Add(layout,flag=wx.EXPAND|wx.ALL,border=10,proportion=1)
control = Control(panel,type=wx.StaticText,
globals=globals(),
locals=locals(),
name=self.name+".report",
size=(420,160),
)
layout.Add(control,flag=wx.ALIGN_CENTRE|wx.ALL)
panel.Fit()
return panel
def update_globals():
global dataset
try:
import dataset_check
reload(dataset_check)
from dataset_check import dataset
globals()["dataset"] = dataset
except Exception,msg: error("%s\n%s" % (msg,format_exc()))
if __name__ == '__main__':
from pdb import pm
from redirect import redirect
redirect("Check_Dataset_Panel")
import autoreload
# Needed to initialize WX library
wx.app = wx.App(redirect=False)
panel = Dataset_Check_Panel()
wx.app.MainLoop()
<file_sep>description_width = 105
formats = ['%d', '%d', '%d', '%d', '%d', '%d', '%d']
motor_labels = ['mode #', 'period', 'N', 'DT', 't0', 'td', 'z']
motor_names = ['Ensemble_SAXS.mode_number', 'Ensemble_SAXS.period', 'Ensemble_SAXS.N', 'Ensemble_SAXS.dt', 'Ensemble_SAXS.t0', 'Ensemble_SAXS.transd', 'Ensemble_SAXS.z']
names = ['mode_number', 'period', 'N', 'dt', 't0', 'transd', 'z']
nrows = 12
row_height = 21
serial = 0
show_in_list = True
title = 'PP Modes'
widths = [65, 60, 60, 55, 50, 50, 40]
line0.description = 'Flythru-4'
line0.Ensemble_SAXS.mode_number = 0.0
line0.Ensemble_SAXS.N = 40.0
line0.t.burst_delay = 0.0648
line0.t.burst_waitt = 0.00405
line0.timing_sequencer.waitt = 0.267
line0.t.npulses = 40.0
line0.t.transc = 40.0
line0.t.waitt = 0.267
line0.updated = '2019-03-13 18:53:27'
line1.description = 'Flythru-12'
line1.Ensemble_SAXS.mode_number = 1.0
line1.t.burst_delay = 0.292
line1.t.burst_waitt = 0.048600000000000004
line1.timing_sequencer.waitt = 2.236
line1.t.npulses = 40.0
line1.t.transc = 44.0
line1.t.waitt = 2.236
line1.updated = '2019-03-13 18:53:33'
line2.description = 'Flythru-24'
line2.Ensemble_SAXS.mode_number = 2.0
line2.Ensemble_SAXS.N = 40.0
line2.t.burst_delay = 0.0
line2.t.burst_waitt = 0.024300000000000002
line2.t.npulses = 1.0
line2.t.transc = 0.0
line2.t.waitt = 0.024300000000000002
line2.updated = '2019-03-13 18:53:38'
line3.description = 'Flythru-48'
line3.Ensemble_SAXS.mode_number = 3.0
line3.t.burst_delay = 0.0
line3.t.burst_waitt = 0.109
line3.t.npulses = 1.0
line3.t.transc = 0.0
line3.t.waitt = 0.10940000000000001
line3.updated = '2019-03-13 18:53:41'
line4.description = 'Flythru-96'
line4.Ensemble_SAXS.mode_number = 4.0
line4.t.burst_delay = 0.292
line4.t.burst_waitt = 0.048600000000000004
line4.t.npulses = 40.0
line4.t.transc = 44.0
line4.t.waitt = 2.236
line4.updated = '2019-03-13 18:53:45'
line5.description = 'Stepping-24'
line5.Ensemble_SAXS.mode_number = 5.0
line5.updated = '2019-03-13 18:53:48'
line6.description = 'Stepping-48'
line6.Ensemble_SAXS.mode_number = 6.0
line6.updated = '2019-03-13 18:53:53'
line7.description = 'Stepping-96'
line7.Ensemble_SAXS.mode_number = 7.0
line7.updated = '2019-03-13 18:53:57'
line8.description = 'Laue-5Hz'
line8.Ensemble_SAXS.mode_number = 8.0
line8.updated = '2019-01-30 18:54:16'
line9.description = 'Laue-10Hz'
line9.Ensemble_SAXS.mode_number = 9.0
line9.updated = '2019-01-30 18:54:21'
line10.Ensemble_SAXS.mode_number = 10.0
line10.updated = '2019-01-30 18:54:41'
line11.description = 'Laue-41Hz'
line11.Ensemble_SAXS.mode_number = 11.0
line11.updated = '2019-03-19 11:41:21'
line10.description = 'Laue-20Hz'
line1.Ensemble_SAXS.N = 40.0
line3.Ensemble_SAXS.N = 40.0
line4.Ensemble_SAXS.N = 40.0
line5.Ensemble_SAXS.N = 40.0
line6.Ensemble_SAXS.N = 40.0
line7.Ensemble_SAXS.N = 40.0
line8.Ensemble_SAXS.N = 1.0
line9.Ensemble_SAXS.N = 1.0
line10.Ensemble_SAXS.N = 1.0
line11.Ensemble_SAXS.N = 10.0
line0.Ensemble_SAXS.period = 276.0
line6.Ensemble_SAXS.period = 2016.0
line1.Ensemble_SAXS.period = 636.0
line2.Ensemble_SAXS.period = 1176.0
line3.Ensemble_SAXS.period = 2256.0
line4.Ensemble_SAXS.period = 4416.0
line5.Ensemble_SAXS.period = 1056.0
line7.Ensemble_SAXS.period = 3936.0
line8.Ensemble_SAXS.period = 192.0
line9.Ensemble_SAXS.period = 96.0
line10.Ensemble_SAXS.period = 48.0
line11.Ensemble_SAXS.period = 240.0
line0.Ensemble_SAXS.min_delay = -9.999999999999999e-05
line1.Ensemble_SAXS.min_delay = -0.0001
line2.Ensemble_SAXS.min_delay = -0.001
line3.Ensemble_SAXS.min_delay = -0.001
line4.Ensemble_SAXS.min_delay = -9.999999999999999e-05
line5.Ensemble_SAXS.min_delay = -9.999999999999999e-05
line6.Ensemble_SAXS.min_delay = -9.999999999999999e-05
line7.Ensemble_SAXS.min_delay = -9.999999999999999e-05
line8.Ensemble_SAXS.min_delay = -9.999999999999999e-05
line9.Ensemble_SAXS.min_delay = -9.999999999999999e-05
line10.Ensemble_SAXS.min_delay = -9.999999999999999e-05
line11.Ensemble_SAXS.min_delay = -9.999999999999999e-05
line0.Ensemble_SAXS.max_delay = 0.0178
line0.Ensemble_SAXS.transd = -43.0
line0.Ensemble_SAXS.dt = 4
line0.Ensemble_SAXS.t0 = 108.0
line0.Ensemble_SAXS.z = 1
line0.Ensemble_SAXS.use = True
line1.Ensemble_SAXS.dt = 12.0
line2.Ensemble_SAXS.dt = 24.0
line3.Ensemble_SAXS.dt = 48.0
line4.Ensemble_SAXS.dt = 96.0
line5.Ensemble_SAXS.dt = 24.0
line6.Ensemble_SAXS.dt = 48.0
line7.Ensemble_SAXS.dt = 96.0
line8.Ensemble_SAXS.dt = 192.0
line9.Ensemble_SAXS.dt = 96.0
line10.Ensemble_SAXS.dt = 48.0
line11.Ensemble_SAXS.dt = 24.0
line1.Ensemble_SAXS.transd = -43.0
line2.Ensemble_SAXS.transd = -43.0
line3.Ensemble_SAXS.transd = -43.0
line4.Ensemble_SAXS.transd = -43.0
line5.Ensemble_SAXS.transd = -43.0
line6.Ensemble_SAXS.transd = -43.0
line7.Ensemble_SAXS.transd = -43.0
line8.Ensemble_SAXS.transd = 0.0
line9.Ensemble_SAXS.transd = 0.0
line10.Ensemble_SAXS.transd = 0.0
line11.Ensemble_SAXS.transd = 0.0
line1.Ensemble_SAXS.z = 1.0
line2.Ensemble_SAXS.z = 1.0
line1.Ensemble_SAXS.t0 = 156.0
line2.Ensemble_SAXS.t0 = 228.0
line3.Ensemble_SAXS.t0 = 372.0
line4.Ensemble_SAXS.t0 = 660.0
line5.Ensemble_SAXS.t0 = 108.0
line6.Ensemble_SAXS.t0 = 132.0
line7.Ensemble_SAXS.t0 = 180.0
line8.Ensemble_SAXS.t0 = 180.0
line9.Ensemble_SAXS.t0 = 84.0
line10.Ensemble_SAXS.t0 = 36.0
line11.Ensemble_SAXS.t0 = 16.0
line3.Ensemble_SAXS.z = 1.0
line4.Ensemble_SAXS.z = 1.0
line5.Ensemble_SAXS.z = 0.0
line6.Ensemble_SAXS.z = 0.0
line7.Ensemble_SAXS.z = 0.0
line8.Ensemble_SAXS.z = 0.0
line9.Ensemble_SAXS.z = 0.0
line10.Ensemble_SAXS.z = 0.0
line11.Ensemble_SAXS.z = 0.0
line1.Ensemble_SAXS.use = 1.0
line2.Ensemble_SAXS.use = 1.0
line3.Ensemble_SAXS.use = 1.0
line4.Ensemble_SAXS.use = 1.0
line5.Ensemble_SAXS.use = 1.0
line6.Ensemble_SAXS.use = 1.0
line7.Ensemble_SAXS.use = 1.0
line8.Ensemble_SAXS.use = 1.0
line9.Ensemble_SAXS.use = 1.0
line10.Ensemble_SAXS.use = 1.0
line11.Ensemble_SAXS.use = 1.0
line1.Ensemble_SAXS.max_delay = 0.0563
line2.Ensemble_SAXS.max_delay = 0.1
line3.Ensemble_SAXS.max_delay = 0.238
line4.Ensemble_SAXS.max_delay = 0.422
line5.Ensemble_SAXS.max_delay = 0.01
line6.Ensemble_SAXS.max_delay = 0.032
line7.Ensemble_SAXS.max_delay = 0.075
line8.Ensemble_SAXS.max_delay = 0.2
line9.Ensemble_SAXS.max_delay = 0.1
line10.Ensemble_SAXS.max_delay = 0.012
line11.Ensemble_SAXS.max_delay = 0.024
command_rows = [0]<file_sep>#!/usr/bin/env python
"""Grapical User Interface for X-ray beam stabilization
<NAME>, Nov 23, 2015 - Mar 6, 2017
"""
from pdb import pm # for debugging
from logging import debug,warn,info,error
##import logging; logging.basicConfig(level=logging.DEBUG)
from xray_beam_stabilization import Xray_Beam_Stabilization
from Panel import BasePanel,PropertyPanel,ButtonPanel,TogglePanel,TweakPanel
from BeamProfile_window import BeamProfile
from TimeChart import TimeChart
from persistent_property import persistent_property
import wx
__version__ = "1.2" # TimeChart new API
class Panel(BasePanel,Xray_Beam_Stabilization):
standard_view = [
"Image",
"Image filename",
"Nominal X [mm]",
"Nominal Y [mm]",
"Beam X [mm]",
"Beam Y [mm]",
"Calibration X [mrad/mm]",
"Calibration Y [V/mm]",
"Control X [mrad]",
"Control Y [V]",
"Control X corr. [mrad]",
"Control Y corr. [V]",
"Correct X",
"Correct Y",
]
saturation_level = persistent_property("saturation_level",10000.0) # counts
def __init__(self,parent=None):
Xray_Beam_Stabilization.__init__(self)
parameters = [
[[BeamProfile, "Image", self ],{}],
[[TimeChart, "History X", self.log,"date time","x"],{"axis_label":"X [mm]","name":self.name+".TimeChart"}],
[[TimeChart, "History Y", self.log,"date time","y"],{"axis_label":"Y [mm]","name":self.name+".TimeChart"}],
[[TimeChart, "History Control X", self.log,"date time","x_control"],{"axis_label":"Control X [mrad]","name":self.name+".TimeChart"}],
[[TimeChart, "History Control Y", self.log,"date time","y_control"],{"axis_label":"Control Y [V]" ,"name":self.name+".TimeChart"}],
[[PropertyPanel,"History Length", self,"history_length" ],{}],
[[PropertyPanel,"History filter", self,"history_filter" ],{"choices":["","1pulses","5pulses"]}],
[[PropertyPanel,"Logfile", self.log,"filename" ],{}],
[[PropertyPanel,"Image filename", self,"image_basename" ],{"read_only":True}],
[[PropertyPanel,"Image timestamp", self,"image_timestamp" ],{"type":"date","read_only":True}],
[[PropertyPanel,"Analysis filter", self,"analysis_filter" ],{"choices":["","1pulses","5pulses"]}],
[[PropertyPanel,"Image usable", self,"image_OK" ],{"type":"Unusable/OK","read_only":True}],
[[PropertyPanel,"Overloaded pixels", self,"image_overloaded" ],{"read_only":True}],
[[PropertyPanel,"Signal-to-noise ratio", self,"SNR" ],{"digits":1,"read_only":True}],
[[TogglePanel, "Auto update", self,"auto_update" ],{"type":"Off/On"}],
[[TweakPanel, "Average count", self,"average_samples" ],{"digits":0}],
[[TweakPanel, "ROI center X [mm]", self,"x_ROI_center" ],{"digits":3}],
[[TweakPanel, "ROI center Y [mm]", self,"y_ROI_center" ],{"digits":3}],
[[TweakPanel, "ROI width [mm]", self,"ROI_width" ],{"digits":3}],
[[TweakPanel, "Saturation level", self,"saturation_level" ],{"digits":0}],
[[TweakPanel, "Nominal X [mm]", self,"x_nominal" ],{"digits":3}],
[[TweakPanel, "Nominal Y [mm]", self,"y_nominal" ],{"digits":3}],
[[PropertyPanel,"Beam X [mm]", self,"x_beam" ],{"digits":3,"read_only":True}],
[[PropertyPanel,"Beam Y [mm]", self,"y_beam" ],{"digits":3,"read_only":True}],
[[PropertyPanel,"Beam X avg. [mm]", self,"x_average" ],{"digits":3,"read_only":True}],
[[PropertyPanel,"Beam Y avg. [mm]", self,"y_average" ],{"digits":3,"read_only":True}],
[[TweakPanel, "Calibration X [mrad/mm]",self,"x_gain" ],{"digits":4}],
[[TweakPanel, "Calibration Y [V/mm]", self,"y_gain" ],{"digits":4}],
[[PropertyPanel,"Control X PV", self,"x_PV" ],{}],
[[PropertyPanel,"Control Y PV", self,"y_PV" ],{}],
[[PropertyPanel,"Control X read PV", self,"x_read_PV" ],{}],
[[PropertyPanel,"Control Y read PV", self,"y_read_PV" ],{}],
[[TweakPanel, "Control X [mrad]", self,"x_control" ],{"digits":4}],
[[TweakPanel, "Control Y [V]", self,"y_control" ],{"digits":4}],
[[TweakPanel, "Control X avg. [mrad]", self,"x_control_average" ],{"digits":4}],
[[TweakPanel, "Control Y avg. [V]", self,"y_control_average" ],{"digits":4}],
[[PropertyPanel,"Control X corr. [mrad]", self,"x_control_corrected"],{"digits":4,"read_only":True}],
[[PropertyPanel,"Control Y corr. [V]", self,"y_control_corrected"],{"digits":4,"read_only":True}],
[[TogglePanel, "Stabilization X", self,"x_enabled" ],{"type":"Off/On"}],
[[TogglePanel, "Stabilization Y", self,"y_enabled" ],{"type":"Off/On"}],
[[ButtonPanel, "Correct X", self,"apply_x_correction" ],{"label":"Correct X"}],
[[ButtonPanel, "Correct Y", self,"apply_y_correction" ],{"label":"Correct Y"}],
[[ButtonPanel, "Correct Position", self,"apply_correction" ],{"label":"Correct"}],
]
BasePanel.__init__(self,
parent=parent,
name=self.name,
title="X-Ray Beam Stabilization",
parameters=parameters,
standard_view=self.standard_view,
refresh=True,
live=True,
)
if __name__ == '__main__':
import logging; logging.basicConfig(level=logging.DEBUG)
# Needed to initialize WX library
if not "app" in globals(): app = wx.App(redirect=False)
panel = Panel()
app.MainLoop()
<file_sep>time_window = 7200.0
center_time = 1559430892.0016363
show_latest = True<file_sep>#!/usr/bin/env python
"""Alio diffractometer
Control panel to save and motor positions.
Author: <NAME>
Date created: 2009-10-18
Date last modified: 2019-01-27
"""
__version__ = "1.3.1" # logging
from pdb import pm # for debugging
from redirect import redirect
redirect("AlioDiffractometerSavedPositionsPanel")
import wx
app = wx.App(redirect=False)
from instrumentation import * # -> globals()
from SavedPositionsPanel_2 import SavedPositionsPanel
panel = SavedPositionsPanel(name="alio_diffractometer_saved",globals=globals())
app.MainLoop()
<file_sep>#!/usr/bin/env python
"""Controls for control panels
Author: <NAME>,
Date created: 2017-06-20
Date last modified: 2019-05-28
"""
__version__ = "1.5" # unit,type
from logging import debug,info,warn,error
import wx, wx3_compatibility
class Control(wx.Panel):
"""Control panel for SAXS-WAXS Experiments"""
from persistent_property import persistent_property
value = persistent_property("value","")
format = persistent_property("format","%s")
unit = persistent_property("unit","")
type = persistent_property("type","")
scale = persistent_property("scale",0.0)
properties = persistent_property("properties",{})
action = persistent_property("action",{})
defaults = persistent_property("defaults",{})
refresh_period = persistent_property("refresh_period",1.0)
def __init__(self,parent,type=wx.ToggleButton,name="Control",
locals=None,globals=None,*args,**kwargs):
self.name = name
self.locals = locals
self.globals = globals
wx.Panel.__init__(self,parent)
# Controls
self.control = type(self,*args,**kwargs)
# Needed for wx.Button on MacOS, because Position defaults to 5,3:
self.control.Position = (0,0)
self.control.Enabled = False
# Layout
self.Fit()
# Initialization
self.initial = {}
# Callbacks
self.Bind(wx.EVT_TOGGLEBUTTON,self.OnAction,self.control)
self.Bind(wx.EVT_BUTTON,self.OnAction,self.control)
self.Bind(wx.EVT_TEXT_ENTER,self.OnAction,self.control)
self.Bind(wx.EVT_COMBOBOX,self.OnAction,self.control)
self.Bind(wx.EVT_CHOICE,self.OnAction,self.control)
self.Bind(wx.EVT_CHECKBOX,self.OnAction,self.control)
# Refresh
from numpy import nan
self.values = {}
self.old_values = {}
self.refreshing = False
self.executing = False
from wx.lib.newevent import NewEvent
self.EVT_THREAD = NewEvent()[1]
self.Bind(self.EVT_THREAD,self.OnUpdate)
from threading import Thread
self.thread = Thread(target=self.keep_updated,name=self.name)
self.thread.start()
# Initialization
self.refresh_status()
def OnAction(self,event):
"""Start a home run, if the button is toggled on.
Cancel a home run, if is is toggled off."""
value = self.my_value
info("User requested %s = %r" % (self.name,value))
if self.value: self.execute("%s = %r" % (self.value,value))
for choice in self.action:
if choice == value:
self.execute(self.action[choice])
break
self.refresh()
def get_my_value(self):
value = getattr(self.control,"Value",True)
if self.unit:
try: value = value.replace(self.unit,"")
except: warn("%s: Failed remove unit %r from %r" % (self.name,self.unit,value))
if self.type:
try: value = eval(self.type)(value)
except: warn("%s: Failed to convert %r to %s" % (self.name,value,self.type))
if self.scale:
##debug("Scaling %s / %r" % (value,self.scale))
try: value = eval(value,self.globals,self.locals)/self.scale
except: warn("%s: Failed to scale %s / %r" % (self.name,value,self.scale))
return value
my_value = property(get_my_value)
def execute(self,command):
if not self.executing:
from threading import Thread
self.execute_thread = Thread(target=self.execute_background,
args=(command,),name=self.name+".execute")
self.executing = True
self.execute_thread.start()
def execute_background(self,command):
info("%s: executing %r" % (self.name,command))
try: exec(command,self.locals,self.globals)
except Exception,msg:
if command: warn("%s: %s: %s" % (self.name,command,msg))
event = wx.PyCommandEvent(self.EVT_THREAD.typeId,self.Id)
# call OnUpdate in GUI thread
wx.PostEvent(self.EventHandler,event)
self.executing = False
def keep_updated(self):
"""Periodically refresh the displayed settings."""
from time import time,sleep
while True:
try:
t0 = time()
while time() < t0+self.refresh_period: sleep(0.1)
if self.Shown:
self.update_data()
if self.data_changed:
##debug("keep_updated: data_changed")
event = wx.PyCommandEvent(self.EVT_THREAD.typeId,self.Id)
# call OnUpdate in GUI thread
wx.PostEvent(self.EventHandler,event)
except wx.PyDeadObjectError: break
def refresh(self):
"""Force update"""
from threading import Thread
if not self.refreshing and self.Shown:
self.refresh_thread = Thread(target=self.refresh_background,
name=self.name+".refresh")
self.refreshing = True
self.refresh_thread.start()
def refresh_background(self):
"""Force update"""
self.update_data()
if self.data_changed:
event = wx.PyCommandEvent(self.EVT_THREAD.typeId,self.Id)
wx.PostEvent(self.EventHandler,event) # call OnUpdate in GUI thread
self.refreshing = False
def update_data(self):
"""Retreive status information"""
from copy import deepcopy
from numpy import nan
self.old_values = deepcopy(self.values)
for prop in self.properties:
#StartRasterScan.properties = {
# "Value": [
# (False, "control.scanning == False"),
# (True, "control.scanning == True"),
# ],
#}
if type(self.properties[prop]) == list:
if not prop in self.values: self.values[prop] = {}
for (choice,expr) in self.properties[prop]:
try: value = eval(expr,self.globals,self.locals)
except Exception,msg:
if expr: warn("%s.%s.%s: %s: %s" % (self.name,prop,choice,expr,msg))
value = nan
self.values[prop][choice] = value
#Image.properties = {"Image": "control.camera.RGB_array"}
elif type(self.properties[prop]) == str:
expr = self.properties[prop]
try: value = eval(expr,self.globals,self.locals)
except Exception,msg:
if expr: warn("%s.%s: %s: %s" % (self.name,prop,expr,msg))
value = nan
self.values[prop] = value
if self.value:
try: value = eval(self.value,self.globals,self.locals)
except Exception,msg:
warn("%s: %s: %s" % (self.name,self.value,msg))
value = nan
self.values["value"] = value
@property
def data_changed(self):
"""Did the last 'update_data' change the data to be plotted?"""
changed = (self.values != self.old_values)
return changed
@property
def data_changed(self):
"""Did the last 'update_data' change the data to be plotted?"""
##changed = (self.values != self.old_values)
if sorted(self.values.keys()) != sorted(self.old_values.keys()):
##debug("%r != %r" % (self.values.keys(),self.old_values.keys()))
changed = True
else:
changed = False
for a in self.values:
item_changed = not nan_equal(self.values[a],self.old_values[a])
##debug("%r: changed: %r" % (a,item_changed))
changed = changed or item_changed
##debug("data changed: %r" % changed)
return changed
def OnUpdate(self,event=None):
"""Periodically refresh the displayed settings."""
self.refresh_status()
def refresh_status(self,event=None):
"""Update the controls with current values"""
##debug("refresh_status")
refresh_needed = True
# One-time initialization
for prop in self.properties.keys():
if hasattr(self.control,prop):
if not prop in self.initial:
self.initial[prop] = getattr(self.control,prop)
else: warn("%r has no property %r" % (self.name,prop))
for prop in self.properties.keys():
if hasattr(self.control,prop):
value = self.initial[prop]
if prop in self.defaults: value = self.defaults[prop]
if prop in self.values and prop in self.properties:
#StartRasterScan.properties = {
# "Value": [
# (False, "control.scanning == False"),
# (True, "control.scanning == True"),
# ],
#}
if type(self.properties[prop]) == list:
for choice,expr in self.properties[prop]:
if choice in self.values[prop] \
and not isnan(self.values[prop][choice]) \
and self.values[prop][choice]:
value = choice
break
#Image.properties = {"Image": "control.camera.RGB_array"}
elif type(self.properties[prop]) == str:
value = self.values[prop]
if prop == "ToolTip": value = wx.ToolTip(value)
##debug("%s.%s=%r" % (type_name(self.control),prop,value))
if getattr(self.control,prop,None) != value:
try:
setattr(self.control,prop,value)
refresh_needed = True
except Exception,msg:
error("%s.%s = %r: %s" % (type_name(self.control),prop,value,msg))
else: warn("%r has no property %r" % (self.name,prop))
if self.value:
prop = "Value"
if hasattr(self.control,prop):
value = ""
if prop in self.initial: value = self.initial[prop]
if prop in self.defaults: value = self.defaults[prop]
if "value" in self.values: value = self.values["value"]
if prop == "ToolTip": value = wx.ToolTip(value)
value = self.control_value(value)
##debug("%s.%s=%r" % (type_name(self.control),prop,value))
if getattr(self.control,prop,None) != value:
try:
setattr(self.control,prop,value)
refresh_needed = True
except Exception,msg:
error("%s.%s=%r: %s" % (type_name(self.control),prop,value,msg))
else: warn("%r has no property %r" % (self.name,prop))
if self.executing:
self.control.Label = self.control.Label.strip(".")+"..."
if refresh_needed: self.control.Refresh()
def control_value(self,value):
"""Convert the value into the form that can be represented by the
control"""
if self.control_data_type == str and not isinstance(value,str):
if isinstance(value,float) and isnan(value): value = ""
else:
if self.scale:
try: value = value*self.scale
except Exception,msg: error("%r*%r: %s" % (value,self.scale,msg))
try: value = self.format % value
except Exception,msg: error("%r % %r: %s" % (self.format,value,msg))
try: value = str(value)
except Exception,msg:
error("str(%r): %s" % (value,msg))
value=""
if self.control_data_type == bool and not isinstance(value,bool):
try: value = bool(value)
except Exception,msg:
error("bool(%r): %s" % (value,msg))
value=False
if self.unit: value += " "+self.unit
return value
@property
def control_data_type(self):
"""Python data type (str,int,bool) that can be represented by the
control"""
type = str
if isinstance(self.control,wx.ToggleButton): type = bool
if isinstance(self.control,wx.CheckBox): type = bool
return type
def type_name(object):
type_name = repr(type(object))
# E.g. <class 'wx._controls.ToggleButton'>
type_name = type_name.strip("<>")
# E.g. class 'wx._controls.ToggleButton'
type_name = type_name.replace("class ","")
# E.g. 'wx._controls.ToggleButton'
type_name = type_name.strip("'")
# E.g. wx._controls.ToggleButton
type_name = type_name.replace("_controls.","")
# E.g. wx.ToggleButton
return type_name
def test_eval(expr,globals=None,locals=None):
return eval(expr,globals,locals)
def test_exec(expr,globals=None,locals=None):
exec(expr,globals,locals)
def nan_equal(a,b):
"""Are to array equal? a and b may contain NaNs"""
import numpy
try: numpy.testing.assert_equal(a,b)
except AssertionError: return False
return True
def isnan(x):
"""Is x 'Not a Number'? fail-safe version"""
from numpy import isnan
try: return isnan(x)
except: return True
if __name__ == '__main__':
from pdb import pm
import logging; from tempfile import gettempdir
logfile = gettempdir()+"/SAXS_WAXS_Control_Panel.log"
logging.basicConfig(level=logging.INFO,
format="%(asctime)s %(levelname)s %(module)s.%(funcName)s, line %(lineno)d: %(message)s",
##filename=logfile,
)
# Needed to initialize WX library
if not hasattr(wx,"app"): wx.app = wx.App(redirect=False)
from SAXS_WAXS_Control_Panel import SAXS_WAXS_Control_Panel
panel = SAXS_WAXS_Control_Panel()
wx.app.MainLoop()
<file_sep>"""
One-dimensional scans
<NAME>, APS, Mar 12, 2008 - Jul 23, 2015
<NAME>, APS, Feb 28, 2018 - March 1, 2018
Run simuation:
from sim_scan import *
data=rscan(sim_taby,-0.2,0.2,20,sim_flux)
COM(data)
app=wx.App(False)
Plot(data)
Run electronic test:
tmode.value = 1
trigger="pulses.value=1;sleep(0.1)"
data=rscan (sim_taby,-0.2,0.2,10,xray_pulse,trigger=trigger)
Center the laser beam:
data=rscan (LaserZ,-1,1,50,laser_pulse,plot=True)
data=rscan (LaserX,-0.4,0.4,40,laser_pulse,plot=True)
Tweak the optical table with single X-ray pulses:
tmode.value = 1
trigger="pulses.value=1;sleep(0.1)"
data=rscan (TableY,-0.05,0.05,10,xray_pulse,trigger=trigger,plot=True)
COM(data)
Measure the X-ray beam profile:
data=rscan (sx,-0.25,0.25,50,xray_pulse,plot=True)
data=read_xy("J:\\anfinrud_0803\\Scans\\2008.03.14 X-ray Y proj 2.txt")
FWHM(data),COM(data),CFWHM(data)
Feb 28 2018 <NAME>
version 1.6 - Added analysis of the slit scan.
slit_scan_analysis_1d(data)
This code takes "data", takes derivative and fits it with 2 gaussians.
The initial parameters for the fit are taken:
amplitudes: max/min values
positions: max/min argument
width: 200 um <- I ahve tested with 56 um as well. It always finds nice fit.
version 1.7 - March 1 2018 Valentyn
added compensation for the pulse fluctions
in the X-Ray hutch Lecroy ps laser ch4 area
(search for Valentyn March 1 2018)
Later commented it out since it wasn't doing much(this line added on July 4 2018)
"""
from Plot import Plot
from numpy import sqrt,isnan
from time import time
from sleep import sleep
from logging import debug,info,warn,error
__version__ = "1.7" # plotting in background thread
def rscan(motors,begins,ends,nsteps,counters=[],averaging_time=0,logfile=None,
trigger=None,plot=False,verbose=True,data=None):
"""
Performs a relative scan around the current position.
This moves 'motor' from the current position - 'begin' to
the current position + 'end' in 'nsteps' steps, while
reading 'counters' each time the motor stops.
The number of scan points acquired is nsteps+1.
The motor returns to the initial position after the scan is complete.
If 'averaging_time' (in seconds) is given the motor stops for the given
time at each scan point, while the counter result is averaged.
'counters' can be either a single counter or list of counters (in square
backets).
'trigger' is a python command to be executed before each scan point.
If 'plot' is True the scan data is dsiplayed a curve in a graphocs window
during the scan.
If 'verbose' is True scan data is printed in the terminal window during
the scan.
If 'data' is given, this list is used to store the scan result, rather than
creating a new one.
"""
if not isinstance(motors,list): motors = [motors]
nm = len(motors)
if not isinstance(begins,list): begins = [begins]
while len(begins) < nm: begins.append(begins[-1])
for i in range(0,nm): begins[i] = float(begins[i])
if not isinstance(ends,list): ends = [ends]
while len(ends) < nm: ends.append(ends[-1])
for i in range(0,nm): ends[i] = float(ends[i])
nsteps = int(round(nsteps))
if not isinstance(counters,list): counters = [counters]
nc = len(counters)
steps = range(0,nm)
for i in range(0,nm): steps[i] = (ends[i]-begins[i])/nsteps
if logfile != None: logfile = file(logfile,"w")
if data == None:
data = []
return_data = True
else:
while len(data) > 0: data.pop()
return_data = False
cancelled = False
# Record initial motor positions.
starting_positions = range(0,nm)
for i in range(0,nm): starting_positions[i] = motors[i].value
# Write scan header.
line = "#"
for i in range(0,nm):
if hasattr(motors[i],"name"): line += motors[i].name
else: line += "pos"
if hasattr(motors[i],"unit") and motors[i].unit != "": line += "/"+motors[i].unit
line += "\t"
for i in range(0,nc):
if hasattr(counters[i],"name"): line += counters[i].name
else: line += "\tcount"
if hasattr(counters[i],"unit") and counters[i].unit != "":
line += "/"+counters[i].unit
line += "\t"
line.strip("\t")
if verbose: print line
if logfile != None: logfile.write(line+"\n"); logfile.flush()
# Open plot window.
if plot: StartMyMainLoop(); plot_data.append([[0,0],[1,1]])
positions = range(0,nm); counts = range(0,nc)
try:
for j in range (0,nsteps+1):
try:
# Move motors
for i in range(0,nm):
motors[i].value = starting_positions[i] + begins[i]+steps[i]*j
# Wait for motors to stop
while 1:
moving = False
for i in range(0,nm):
if hasattr(motors[i],"moving"): moving = moving or motors[i].moving
if not moving: break
sleep(0.01)
for i in range(0,nm): positions[i] = motors[i].value
# Acquire scan point
if averaging_time == 0:
if trigger: exec(trigger)
for i in range(0,nc): counts[i] = counters[i].value#/laser_scope.measurement(1).value
# line above March 1, 2018 Valentyn added /laser_scope.measurement(1).value
else:
for i in range(0,nc):
if hasattr(counters[i],"count_time"): counters[i].count_time = averaging_time; #laser_scope.measurement(1).count_time = averaging_time;
for i in range(0,nc):
if hasattr(counters[i],"start"): counters[i].start(); #laser_scope.measurement(1).start() # line above March 1, 2018 Valentyn added
if trigger: exec(trigger)
sleep(averaging_time)
for i in range(0,nc):
if hasattr(counters[i],"stop"): counters[i].stop(); #laser_scope.measurement(1).stop() # line above March 1, 2018 Valentyn added
for i in range(0,nc):
if hasattr(counters[i],"average"): counts[i] = counters[i].average#/laser_scope.measurement(1).average
# line above March 1, 2018 Valentyn added /laser_scope.measurement(1).average
else: counts[i] = counters[i].value
# Write scan record
line = ""
for i in range(0,nm): line += str(positions[i])+"\t"
for i in range(0,nc): line += str(counts[i])+"\t"
line.strip("\t")
if verbose: print line
if logfile != None: logfile.write(line+"\n"); logfile.flush()
# Skip 'Not a Number' values (problems with plotting)
skip = False
for val in positions+counts:
if isnan(val): skip = True
if not skip: data.append(positions+counts)
# Update plot window
if plot: plot_data[-1] = data+[]
except KeyboardInterrupt: cancelled = True; break
# Return motors to the starting positions
for i in range(0,nm): motors[i].value = starting_positions[i]
# Wait for motors to stop
while not cancelled:
try:
moving = False
for i in range(0,nm):
if hasattr(motors[i],"moving"): moving = moving or motors[i].moving
if not moving: break
sleep(0.01)
except KeyboardInterrupt: break
# Restart the counter after than scan is done (useful for oscilloscope-based counters)
for i in range(0,nc):
if hasattr(counters[i],"start"): counters[i].start(); laser_scope.measurement(1).start()
if return_data: return data
except KeyboardInterrupt:
info("Returning motors to the starting positions.")
for i in range(0,nm): motors[i].value = starting_positions[i]
finally:
info("Returning motors to the starting positions.")
for i in range(0,nm): motors[i].value = starting_positions[i]
def peakinfo(data):
"Generate a report about peak wdith and position"
return "FWHM %.3f mm at %.3f mm, COM %.3f mm, peak %.2g at %.3f mm" %\
(FWHM(data),CFWHM(data),COM(data),peak(data),peakpos(data))
def peak(data):
"""Returns the maximum y of a curve given as list of [x,y] values"""
return max(yvals(data))
def pkpk(data):
"""Returns peak to peak difference of the y values of a curve given as
list of [x,y] values"""
return max(yvals(data))-min(yvals(data))
def peakpos(data):
"""Returns the x value of the maximum curve given as list of [x,y] values"""
x = xvals(data); y = yvals(data); n = len(data)
if n < 1: return NaN
x_at_ymax = x[0]; ymax = y[0]
for i in range (0,n):
if data[i][1] > ymax: x_at_ymax = x[i]; ymax = y[i]
return x_at_ymax
def COM(data):
"""Calculates the center of mass of the positive peak of a curve
given as list of [x,y] values"""
data = subtract_baseline(data)
x = xvals(data); y = yvals(data); n = len(data)
# Subtract baseline
y0 = min(y)
for i in range (0,n): y[i] -= y0
sumxy = 0
for i in range (0,n): sumxy += x[i]*y[i]
return sumxy/sum(y)
def RMSD(data):
"""Calculates root mean square deviation width of the positive peak of
a curve given as list of [x,y] values"""
data = subtract_baseline(data)
x0 = COM(data)
x = xvals(data); y = yvals(data); n = len(data)
sumx2 = 0
for i in range (0,n): sumx2 += y[i]*(x[i]-x0)**2
return sqrt(sumx2/sum(y))
def FWHM(data):
"""Calculates full-width at half-maximum of a positive peak of a curve
given as list of [x,y] values"""
x = xvals(data); y = yvals(data); n = len(data)
HM = (min(y)+max(y))/2
for i in range (0,n):
if y[i]>HM: break
x1 = interpolate_x((x[i-1],y[i-1]),(x[i],y[i]),HM)
r = range(0,n); r.reverse()
for i in r:
if y[i]>HM: break
x2 = interpolate_x((x[i+1],y[i+1]),(x[i],y[i]),HM)
return abs(x2-x1)
def CFWHM(data):
"""Calculates the center of the full width half of the positive peak of
a curve given as list of [x,y] values"""
x = xvals(data); y = yvals(data); n = len(data)
HM = (min(y)+max(y))/2
for i in range (0,n):
if y[i]>HM: break
x1 = interpolate_x((x[i-1],y[i-1]),(x[i],y[i]),HM)
r = range(0,n); r.reverse()
for i in r:
if y[i]>HM: break
x2 = interpolate_x((x[i+1],y[i+1]),(x[i],y[i]),HM)
return (x2+x1)/2.
def remove_NaN(data):
"""Filters out 'Not a Number' values from a list of [x,y] values"""
x = xvals(data); y = yvals(data); n = len(data)
data2 = []
for i in range (0,n):
if not isnan(x[i]) and not isnan(y[i]): data2.append([x[i],y[i]])
return data2
def subtract_baseline(data):
"""Returns baseline-ccorrects a curve given as list of [x,y] values"""
x = xvals(data); y = yvals(data); n = len(data)
y0 = min(y)
for i in range (0,n): y[i] -= y0
return zip(x,y)
def interpolate_x((x1,y1),(x2,y2),y):
"Linear interpolation between two points"
# In case result is undefined, midpoint is as good as any value.
if y1==y2: return (x1+x2)/2.
x = x1+(x2-x1)*(y-y1)/float(y2-y1)
#print "interpolate_x [%g,%g,%g][%g,%g,%g]" % (x1,x,x2,y1,y,y2)
return x
def xvals(xy_data):
"xy_data = list of (x,y)-tuples. Returns list of x values only."
xvals = []
for i in range (0,len(xy_data)): xvals.append(xy_data[i][0])
return xvals
def yvals(xy_data):
"xy_data = list of (x,y)-tuples. Returns list of y values only."
yvals = []
for i in range (0,len(xy_data)): yvals.append(xy_data[i][1])
return yvals
def print_xy(xy_data):
"Displays (x,y) tuples as two columns"
for i in range(0,len(xy_data)): print "%g\t%g" % (xy_data[i][0],xy_data[i][1])
def save_xy(xy_data,filename, directory = ""):
"Write (x,y) tuples as two-column tab separated ASCII file."
output = file(filename,"w")
for i in range(0,len(xy_data)):
output.write("%g\t%g\n" % (xy_data[i][0],xy_data[i][1]))
def read_xy(filename):
"""Reads two two-column ASCII file and returns as list of floating point
[x,y] pairs"""
data = []
infile = file(filename)
line = infile.readline()
while line != '':
try:
cols = line.split()
x = float(cols[0]); y = float(cols[1])
data.append([x,y])
except ValueError: pass
line = infile.readline()
return data
def timescan(counters=[],waiting_time=1,averaging_time=0,total_time=1e1000,
logfile=None):
"""Monitor a counter or list of counters at a regular time interval.
If "waiting_time" is not specified that interval is 1 second.
"counters" can be either a single counter or list of counters (in square backets).
If "total_time" is given, the scan is ended after the specified number of seconds.
Otherwise, it is ended on keyboard interrupt (Control-C).
"""
if not isinstance(counters,list): counters = [counters]
nc = len(counters)
if logfile != None: logfile = file(logfile,"w")
# Write scan header
line = "#date\ttime/s\t"
for i in range(0,nc):
if hasattr(counters[i],"name"): line += counters[i].name
else: line += "\tcount"
if hasattr(counters[i],"unit") and counters[i].unit != "":
line += "/"+counters[i].unit
line += "\t"
line.strip("\t")
#print line # commented on Feb 28 2018, Valentyn
if logfile != None: logfile.write(line+"\n"); logfile.flush()
counts = range(0,nc)
n = 0
start = time()
while time() < start + total_time:
try:
t = time()
# Acquire scan point
if averaging_time == 0:
for i in range(0,nc): counts[i] = counters[i].value
else:
for i in range(0,nc):
if hasattr(counters[i],"count_time"): counters[i].count_time = averaging_time
for i in range(0,nc):
if hasattr(counters[i],"start"): counters[i].start()
sleep(averaging_time)
for i in range(0,nc):
if hasattr(counters[i],"stop"): counters[i].stop()
for i in range(0,nc):
if hasattr(counters[i],"average"): counts[i] = counters[i].average
else: counts[i] = counters[i].value
# Write scan record
line = datestring(t)+"\t"+str(t-start)+"\t"
for i in range(0,nc): line += str(counts[i])+"\t"
line.strip("\t")
print line
if logfile != None: logfile.write(line+"\n"); logfile.flush()
n = n+1
dt = n*waiting_time - (time()-start)
while dt>0:
sleep (min(dt,0.1))
dt = n*waiting_time - (time()-start)
except KeyboardInterrupt: break
def datestring(seconds):
from datetime import datetime
date = str(datetime.fromtimestamp(seconds))
return date[:-3] # omit microsconds
def StartMyMainLoop():
import wx
import threading
if not hasattr(wx,"MainLoopThread") or not wx.MainLoopThread.isAlive():
wx.MainLoopThread = threading.Thread(target=MyMainLoop,name="MyMainLoop")
if not wx.MainLoopThread.isAlive():
wx.MainLoopThread = threading.Thread(target=MyMainLoop,name="MyMainLoop")
wx.MainLoopThread.start()
def MyMainLoop():
import wx
from time import sleep
if not hasattr(wx,"app"): wx.app = wx.App(False)
evtloop = wx.GUIEventLoop()
wx.EventLoop.SetActive(evtloop)
while True:
while evtloop.Pending(): evtloop.Dispatch()
evtloop.ProcessIdle()
update_plots()
sleep(0.1)
def gauss(x,a1,x01,fwhm1,a2,x02,fwhm2):
from numpy import exp
return a1 * exp(-(x-x01)**2 / (2*(fwhm1/2.355)**2)) + a2 * exp(-(x-x02)**2 / (2*(fwhm2/2.355)**2))
def slit_scan_analysis_1d(xy_data, plot = False, img_filename = ''):
from numpy import asarray, gradient
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
from numpy import exp, argmin, argmax
arr = asarray(xy_data) #create numpy array
x = arr[:,0]
y = arr[:,1]
grad_y = gradient(y)
popt, pcov = curve_fit(gauss,x,grad_y, p0 = [max(grad_y), x[argmax(grad_y)] , 0.2, min(grad_y), x[argmin(grad_y)] , 0.2])
print('FWHM_1 = ' + str(round(1000*popt[2],1)) + ' um' + ' and FWHM_2= ' + str(round(popt[5]*1000,1)) + ' um' + ' and average of ' + str(round(1000*(0.5*popt[2]+0.5*popt[5]),1)) + ' um' )
print('center1 = ' + str(round(popt[1],3)) + ' mm' + ' and center2 = ' + str(round(popt[4],3)) + ' mm' + ' and center at ' + str(round(0.5*popt[4]+0.5*popt[1],3)) + ' mm')
#return x, gauss(x,*popt), x, grad_y
plt.plot(x,grad_y,'o')
plt.plot(x,gauss(x,*popt), linewidth = 4)
plt.title('FWHM_1 = ' + str(round(1000*popt[2],1))+ ' um' + ' and FWHM_2 = ' + str(round(popt[5]*1000,1)) + ' um'+ '\n and center at' + str(round(0.5*popt[4]+0.5*popt[1],3)) + ' mm')
if plot:
plt.show()
try:
plt.savefig(img_filename)
except:
print("couldn't save img to a file")
def scan_and_analyse(axis = 'GonZ', filename = '/Laser Z scan-3'):
"""
filename is a local filename in the folder dir.
"""
if axis == 'GonZ':
data = rscan(GonZ,-0.5,+0.5,200,xray_pulse,1.0, plot=True)
elif axis == 'GonY':
data = rscan(GonY,-2,+2,160,xray_pulse,1.0, plot=True)
elif axis == 'GonX':
data = rscan(GonX,-2,+2,40,xray_pulse,1.0, plot=True)
logfile = dir + filename
try:
save_xy(data,logfile+'.txt')
except:
print("couldn't save to a file")
try:
slit_scan_analysis_1d(data, plot = True, img_filename = logfile + '.png')
except:
print("couldn't plot and analyse")
return data
plots = []
plot_data = []
def update_plots():
import wx
while len(plots) < len(plot_data): plots.append(Plot())
for plot,data in zip(plots,plot_data):
try:
if plot.data != data: plot.data = data; plot.update()
except wx.PyDeadObjectError: pass
if __name__ == "__main__": # This is for testing, remove when done
import logging
logging.basicConfig(level=logging.INFO,format="%(levelname)s: %(message)s")
from instrumentation import * # Beamline
import os
dir = '/net/mx340hs/data/anfinrud_1807/Scans/2018.07.04 ns laser beam profile'
logfile = dir+"/Laser Z scan-1.txt"
if not os.path.exists(dir):
print("directory didn't exist, creating (%r)" % dir)
os.mkdir(dir)
else:
print('directory %r exists' % dir)
print('logfile = %r' %logfile)
print('data = rscan(GonZ,-0.4,+0.4,160,xray_pulse,1.0,plot=True)')
print('data = rscan(GonY,-2,+2,160,xray_pulse,1.0,plot=True)')
print('data = rscan(GonX,-2,+2,40,xray_pulse,1.0,plot=True)')
print('save_xy(data,%r)' % logfile)
print('"FWHM %.3f @ %.3f" % (FWHM(data),CFWHM(data))')
print('slit_scan_analysis_1d(data, plot = True) #run analysis and plot the result')
print('data = scan_and_analyse(axis = "GonZ", filename = "/Laser Z scan-3")')
<file_sep>Ensemble.ip_address = 'nih-instrumentation.aps.anl.gov:2000'
MicroscopeCamera.ImageWindow.Center = (680, 512)
MicroscopeCamera.Mirror = True
MicroscopeCamera.NominalPixelSize = 0.000526
MicroscopeCamera.Orientation = 0
MicroscopeCamera.camera.IP_addr = 'id14b-prosilica1.cars.aps.anl.gov'
MicroscopeCamera.x_scale = 1.0
MicroscopeCamera.y_scale = 1.0
MicroscopeCamera.z_scale = 1.0
WideFieldCamera.ImageWindow.Center = (680, 512)
WideFieldCamera.Mirror = False
WideFieldCamera.NominalPixelSize = 0.00465
WideFieldCamera.Orientation = 0
WideFieldCamera.camera.IP_addr = 'id14b-prosilica2.cars.aps.anl.gov'
WideFieldCamera.x_scale = 1.0
WideFieldCamera.y_scale = 1.0
WideFieldCamera.z_scale = 1.0
laser_scope.ip_address = 'id14l-scope.cars.aps.anl.gov:2000'
rayonix_detector.ip_address = 'mx340hs.cars.aps.anl.gov:2222'
sample.phi_motor_name = 'Phi'
sample.phi_scale = 1.0
sample.rotation_center = (0.0, 0.0)
sample.x_motor_name = 'GonX'
sample.x_scale = 1.0
sample.xy_rotating = True
sample.y_motor_name = 'GonY'
sample.y_scale = 1.0
sample.z_motor_name = 'GonZ'
sample.z_scale = 1.0
timing_system.ip_address = 'id14timing2.cars.aps.anl.gov:2000'
xray_scope.ip_address = 'id14b-xscope.cars.aps.anl.gov:2000'<file_sep>filename = '//mx340hs/data/anfinrud_1903/Archive/NIH.pressure_barometric.txt'<file_sep>#!/bin/env python
"""
More or Less generic python code for image analysis.
functions:
property: is_new_image returns True\False if there is new image
method: get_image return 4,X,Y image where 0 - R, 1 - G, 2 - B, 3 - K - colors
<NAME>
created: Feb 29 2018
last updated: July 2, 2018
Microscope Camera chip orientations:
NIH: vertical; APS: horizontal;
Vertical:
DxWxH = 3,1024,1360
*----
| |
| |
| |
| |
|---|
* is (0,0) pixel
Horizontal:
DxWxH = 3,1360,1024
|---------------|
| |
| |
*---------------|
* is (0,0) pixel
"""
__version__ = '0.1'
import matplotlib.pyplot as plt
from logging import info,warn,debug, error
from numpy import mean, transpose, std,array,hypot , abs, zeros, savetxt,loadtxt,save,load ,uint8, uint16, reshape, asarray
from numpy.ma import masked_array
from time import sleep, time
from PIL import Image
from threading import Thread, Condition
from persistent_property import persistent_property
from datetime import datetime
from scipy import ndimage, misc
import os
from thread import start_new_thread
from CAServer import casput,casdel
from CA import caget
import traceback
import os
class Image_analyzer(object):
cameraName = persistent_property('camera name', '')
fieldOfAnalysis = persistent_property('field of analysis', '')
cameraSettingGain = persistent_property('camera Setting Gain', 6)
cameraSettingExposureTime = persistent_property('camera Setting exposure time', 0.072)
background_image_filename = persistent_property('background image filename', 'background_default')
mask_image_filename = persistent_property('mask image filename', 'mask_default')
frozen_threshold = persistent_property('freezing threshhold', 0.08)
def __init__(self, name = 'freeze_detector'):
self.name = name
#camera.exposure_time = self.cameraSettingExposureTime
#camera.gain = self.cameraSettingGain
## self.frozen_threshold = 0.1
## self.frozen_threshold_temperature = -15.0
##
## #orientation of the camera
## #self.orientation = 'vertical' #
## self.orientation = 'horizontal' #
##
##
## self.difference_array = zeros((1,1))
## self.background_array = zeros((1,1))
## self.mask_array = zeros((1,1))
## self.background_image_flag = False
#self.analyse_dict = {}
def init(self, camera_name = 'MicroscopeCamera'):
self.camera_name = camera_name #Microfluidics camera #MicroscopeCamera
self.imageCounter = camera.frame_count
#camera.exposure_time = self.cameraSettingExposureTime
#camera.gain = self.cameraSettingGain
# self.logFolder = os.getcwd() + '/optical_image_analyzer/' + self.name + '/'
# if os.path.exists(os.path.dirname(self.logFolder)):
# pass
# else:
# os.makedirs(os.path.dirname(self.logFolder))
# if os.path.exists(os.path.dirname(self.logFolder+ 'Archive/') ):
# pass
# else:
# os.makedirs(os.path.dirname(self.logFolder+ 'Archive/'))
# self.background_image_filename = 'background_default_rgb.tiff'
# try:
# #self.background_image = Image.open(self.logFolder + self.background_image_filename)
# self.background_array = load(self.logFolder + 'background_default_rgb.npy')
# self.background_image_flag = True
# info('got bckg image from the drive')
# except:
# warn('couldn"t load bckg image')
# self.background_image_flag = False
#
# self.logfile = self.logFolder +'sample_frozen_image_rgb.log'
# my_file = os.path.isfile(self.logfile )
# if my_file:
# pass
# else:
# f = open(self.logfile,'w')
# timeRecord = time()
# f.write('####This experiment started at: %r and other information %r \r\n' %(timeRecord,'Other Garbage'))
# f.write('time,imageCounter, temperature, mean, mean_R,mean_G,mean_B,stdev,stdev_R,stdev_B,stdev_G\r\n')
# f.close()
def get_is_new_image(self):
"""
"""
try:
temp = camera.acquiring
if temp != True and temp != False:
print("Camera status: %r" %(temp))
camera.acquiring = False
sleep(0.1)
except:
print('error at this line: if camera.acquiring != True and camera.acquiring != False: camera.acquiring = Flase')
if not camera.acquiring: camera.acquiring = True
idx = 0
frame_count = camera.frame_count
if self.imageCounter - frame_count > 100:
self.imageCounter = 0
if self.imageCounter < frame_count:
flag = True
else:
flag = False
info('Image counter: %r' % self.imageCounter)
return flag
is_new_image = property(get_is_new_image)
def get_image(self, timeout = 5, image = None):
"""
return an array with RGBK colors and convers it to int 16 instead of int 8, for the K array
"""
from time import time
from numpy import insert
flag_fail = False
if image == None:
t = time()
while t + timeout > time():
if self.is_new_image:
tmp = camera.RGB_array.astype('int16')
img = zeros(shape = (tmp.shape[0]+1,tmp.shape[1],tmp.shape[2]), dtype = 'int16')
img[0,:,:] = tmp[0,:,:]
img[1,:,:] = tmp[1,:,:]
img[2,:,:] = tmp[2,:,:]
img[3,:,:] = tmp[0,:,:]+tmp[1,:,:]+tmp[2,:,:]
self.imageCounter = camera.frame_count
flag_fail = False
break
else:
img = None
flag_fail = True
sleep(0.250)
if flag_fail:
info('get_image has timed-out: restarting the camera.acquiring')
camera.acquiring = False
sleep(2)
camera.acquiring = True
sleep(0.25)
else:
img = img.astype('int16')
img[3,:,:] = img[0,:,:] + img[1,:,:] + img[2,:,:]
return img
def frame_count(self):
try:
count = camera.frame_count
except:
error(traceback.format_exc())
count = -1
return count
def create_mask(self,arr, anchors = [(0,0),(1,1)]):
"""
defines region of interest between anchor points defined by anchors. Yields rectangular shape
"""
from numpy import ma, zeros, ones
shape = arr.shape
mask = ones(shape, dtype = 'int16')
try:
for i in range(anchors[0][0],anchors[1][0]):
for j in range(anchors[0][1],anchors[1][1]):
mask[:,i,j] = 0
except:
error(traceback.format_exc())
mask = None
return mask
def mask_array(self,array,mask):
from numpy import ma
arr_res = ma.masked_array(array, mask)
return arr_res
def masked_section(self,array, anchors = [(0,0),(1,1)]):
x1 = anchors[0][0]
y1 = anchors[0][1]
x2 = anchors[1][0]
y2 = anchors[1][1]
return array[:,x1:x2,y1:y2]
def save_array_as_image(self,arr, filename):
image = Image.new('RGB',(1360,1024))
image.frombytes(arr.T.tostring())
image.save(filename)
def rgb2gray(self,rgb):
r, g, b = rgb[:,:,0], rgb[:,:,1], rgb[:,:,2]
gray = 0.2989 * r + 0.5870 * g + 0.1140 * b
return gray
def get_background_array(self):
arr = self.get_image()
self.background_array = arr
return True
def set_background_array(self, filename = 'blank'):
self.background_image_flag = False
start_new_thread(self.get_background_array,())
def plot_slices_difference(self):
for i in range(7):
plt.plot(image_analyser.difference_array[0,:,i])
plt.show()
def plot_difference(self):
plt.subplot(121)
plt.imshow(self.difference_image)
plt.colorbar()
plt.subplot(122)
plt.imshow(abs(self.difference_image))
plt.colorbar()
plt.show()
def plot_background(self):
plt.subplot(121)
plt.imshow(self.background_image)
plt.colorbar()
plt.subplot(122)
plt.imshow(self.mask_image)
plt.colorbar()
plt.show()
def plot(self,image):
plt.imshow(image)
plt.colorbar()
plt.show()
def save_images(self):
from PIL import Image
import logging; from tempfile import gettempdir
#/var/folders/y4/cw92kt415kz7wtk13fkjhh2r0000gn/T/samplr_frozen_opt.log'
import os
file_path = gettempdir() + "/Images/Optical_images_march4/log.log" # gettempdir + "/Optical_images/log.log"
directory = os.path.dirname(file_path)
try:
os.stat(directory)
except:
os.mkdir(directory)
for i in range(360):
sleep(10)
while self.is_new_image() != True:
sleep(0.05)
if self.is_new_image():
img = Image.fromarray(camera.RGB_array.transpose((-1,0,1)).transpose((-1,0,1)))
temp = str(caget("NIH:TEMP.RBV"))
img.save(directory +'/_T_'+temp + '_t_' +str(time())+'.tiff')
print('saving',directory +'_T_'+temp + '_t_' +str(time())+'.tiff')
def scan_saved_images(self):
pass
def load_image_from_file(self, filename = ""):
if len(filename)>0:
img = Image.open(filename)
arr = asarray(img, dtype="int16" ).transpose((-1,0,1))
return arr
else:
return None
def test_load_current_1_image(self):
self.test_current_1 = Image.open(self.logFolder + 'current_rgb.tiff')
def test_save_current_s_image(self):
self.test_current_s.save(self.logFolder + 'current_test_saved.tiff')
def test_load_current_s_image(self):
self.test_current_s = Image.open(self.logFolder + 'current_test_saved.tiff')
def test_load_current_2_image(self):
self.test_current_2 = Image.open(self.logFolder + 'current_test_2.tiff')
from GigE_camera_client import Camera
#camera = Camera("LabMicroscope")
camera = Camera("MicroscopeCamera")
image_analyzer = Image_analyzer()
if __name__ == "__main__":
import logging; from tempfile import gettempdir
#/<KEY>frozen_opt.log'
logfile = gettempdir()+"/optical_image_analyser.log"
##print(logfile)
logging.basicConfig( level=logging.DEBUG,
format="%(asctime)s %(levelname)s: %(message)s",
filename=logfile,
)
self = image_analyzer
print('Time Start: %r' % str(datetime.now()))
print('arr = image_analyzer.get_image()')
print("image_analyzer.plot()")
print("image_analyzer.plot_difference()")
print('file_path = gettempdir() + "/Images/Optical_images/')
debug('?')
<file_sep>#!/usr/bin/env python
# <NAME>, Mar 2, 2016-Mar 2, 2016
from inspect import getfile
from os.path import dirname
dir=dirname(getfile(lambda x:None))
if dir == "": dir = "."
execfile(dir+"/EnsembleSAXS_PP_Panel.py")
<file_sep>import CA ; CA.DEBUG = "silent"
from EPICS_serial_CA_test import Serial
port = Serial("14IDB:serial3") # loop back connector
fail_count = 0
for length in range(1,38):
string = "x"*length+"\n"
reply = port.query(string,terminator="\n")
##print "%r" % string
##print "%r" % reply
if reply != string:
print "Length %d: expected %d, got %d bytes" % \
(length,len(string),len(reply))
fail_count += 1
if fail_count > 0: print "%d failures" % fail_count
<file_sep># Import socket module
import socket
port = 2060
def connection(N = 1):
# Create a socket object
s = socket.socket()
# Define the port on which you want to connect
# connect to the server on local computer
s.connect(('128.231.5.299', port))#172.16.31.10
# receive data from the server
data = '1'*N
s.send(data)
length = len(data)
while len(data)<length:
data += s.recv(length-len(data))
# close the connection
s.close()
return data
def run():
from thread import start_new_thread
start_new_thread(run_once,())
def run_once():
sock = socket.socket()
sock.bind(('',port))
sock.listen(5)
while True:
client, adrr = sock.accept()
t1 = clock()
#print('Got connection from ' , adrr)
#x = raw_input('type response:')
x = '1'*(200000 -20)
client.send('Connection Received %r' % x)
t2 = clock()
print(t2-t1)
#client.close()
print('data = connection()')
<file_sep>#!/usr/bin/env python
"""Control panel for SAXS/WAXS Experiments.
Author: <NAME>, <NAME>
Date created: 2017-06-12
Date last modified: 2019-05-29
"""
__version__ = "1.10.1" # Friedrich: cleanup
from logging import debug,info,warn,error
import wx
from SAXS_WAXS_control import SAXS_WAXS_control,control # passed on in "globals()"
class SAXS_WAXS_Control_Panel(wx.Frame):
"""Control panel for SAXS/WAXS Experiments"""
name = "SAXS_WAXS_Control_Panel"
def __init__(self):
wx.Frame.__init__(self,parent=None,title="SAXS-WAXS Control")
# Icon
from Icon import SetIcon
SetIcon(self,"SAXS-WAXS Control")
self.panel = self.ControlPanel
self.Fit()
self.Show()
# Refresh
self.timer = wx.Timer(self)
self.Bind (wx.EVT_TIMER,self.OnTimer,self.timer)
self.timer.Start(5000,oneShot=True)
def OnTimer(self,event):
"""Perform periodic updates"""
try: self.update_controls()
except Exception,msg:
error("%s" % msg)
import traceback
traceback.print_exc()
self.timer.Start(5000,oneShot=True)
def update_controls(self):
if self.code_outdated:
self.update_code()
panel = self.ControlPanel
self.panel.Destroy()
self.panel = panel
self.Fit()
@property
def code_outdated(self):
outdated = False
try:
from inspect import getfile
from os.path import getmtime,basename
filename = getfile(self.__class__)
##debug("module: %s" % filename)
if self.timestamp == 0: self.timestamp = getmtime(filename)
outdated = getmtime(filename) != self.timestamp
except Exception,msg: pass ##debug("code_outdated: %s" % msg)
return outdated
def update_code(self):
from inspect import getfile
from os.path import getmtime,basename
filename = getfile(self.__class__)
##debug("module: %s" % filename)
self.timestamp = getmtime(filename)
module_name = basename(filename).replace(".pyc",".py").replace(".py","")
module = __import__(module_name)
reload(module)
debug("Reloaded module %r" % module.__name__)
debug("Updating class of %r instance" % self.__class__.__name__)
self.__class__ = getattr(module,self.__class__.__name__)
timestamp = 0
@property
def ControlPanel(self):
panel = wx.Panel(self)
from EditableControls import ComboBox,TextCtrl
from Controls import Control
##from wx.lib.buttons import GenButton as Button, GenToggleButton as ToggleButton
from wx import Button,ToggleButton
style = wx.ALIGN_CENTRE_HORIZONTAL
self.Environment = Control(panel,type=ComboBox,
name="SAXS_WAXS_Control_Panel.Environment",globals=globals(),
size=(80,-1),choices=["0 (NIH)","1 (APS)","2 (LCLS)"])
self.XRayDetector = Control(panel,type=wx.StaticText,
name="SAXS_WAXS_Control_Panel.XRayDetector",globals=globals(),
size=(170,-1),label="X-Ray Detector",style=style)
self.XRayDetectorInserted = Control(panel,type=ToggleButton,
name="SAXS_WAXS_Control_Panel.XRayDetectorInserted",globals=globals(),
size=(130,-1),label="Insert/Retract")
self.Home = Control(panel,type=ToggleButton,
name="SAXS_WAXS_Control_Panel.Home",globals=globals(),
size=(100,-1),label="Home")
self.Home.ToolTip = wx.ToolTip("Calibrate motor positions")
self.ProgramRunning = Control(panel,type=ToggleButton,
name="SAXS_WAXS_Control_Panel.ProgramRunning",globals=globals(),
size=(100,-1),label="Running")
self.GotoSaved = Control(panel,type=Button,
name="SAXS_WAXS_Control_Panel.GotoSaved",globals=globals(),
label="Go To Saved Position",
size=(180,-1))
self.Save = Control(panel,type=Button,
name="SAXS_WAXS_Control_Panel.Save",globals=globals(),
label="Save Current X,Y Positions",size=(180,-1))
self.Inserted = Control(panel,type=ToggleButton,
name="SAXS_WAXS_Control_Panel.Inserted",globals=globals(),
size=(160,-1),label="Insert/Retract")
choices = ["-16.0 C","22.0 C","40.0 C","80.0 C","120.0 C"]
self.Temperature_Setpoint = Control(panel,type=ComboBox,
name="SAXS_WAXS_Control_Panel.Temperature_Setpoint",globals=globals(),
size=(80,-1),choices=choices)
self.Temperature = Control(panel,type=wx.TextCtrl,
name="SAXS_WAXS_Control_Panel.Temperature",globals=globals(),
size=(90,-1),style=wx.TE_READONLY)
self.XRayShutter = Control(panel,type=ToggleButton,
name="SAXS_WAXS_Control_Panel.XRayShutter",globals=globals(),
size=(60,-1),label="Disabled")
self.XRayShutterAutoOpen = Control(panel,type=wx.CheckBox,
name="SAXS_WAXS_Control_Panel.XRayShutterAutoOpen",globals=globals(),
size=(-1,-1),label="auto")
self.LaserShutter = Control(panel,type=ToggleButton,
name="SAXS_WAXS_Control_Panel.LaserShutter",globals=globals(),
size=(60,-1),label="Disabled")
self.LaserShutterAutoOpen = Control(panel,type=wx.CheckBox,
name="SAXS_WAXS_Control_Panel.LaserShutterAutoOpen",globals=globals(),
size=(-1,-1),label="auto")
self.Mode = Control(panel,type=wx.ComboBox,
name="SAXS_WAXS_Control_Panel.Mode",globals=globals(),
size=(100,-1),choices=SAXS_WAXS_control.modes)
self.PumpEnabled = Control(panel,type=wx.CheckBox,
name="SAXS_WAXS_Control_Panel.PumpEnabled",globals=globals(),
size=(80,-1))
self.PumpStep = Control(panel,type=ComboBox,
name="SAXS_WAXS_Control_Panel.PumpStep",globals=globals(),
size=(80,-1),choices=SAXS_WAXS_control.pump_step_choices)
self.PumpPosition = Control(panel,type=TextCtrl,
name="SAXS_WAXS_Control_Panel.PumpPosition",globals=globals(),
size=(70,-1))
self.PumpHomed = Control(panel,type=ToggleButton,
name="SAXS_WAXS_Control_Panel.PumpHomed",globals=globals(),
size=(140,-1),label="Homed")
choices = ["500","600","700","800","1000"]
self.LoadSampleStep = Control(panel,type=ComboBox,
name="SAXS_WAXS_Control_Panel.LoadSampleStep",globals=globals(),
size=(70,-1),choices=choices)
self.LoadSample = Control(panel,type=ToggleButton,
name="SAXS_WAXS_Control_Panel.LoadSample",globals=globals(),
label="Load Sample",size=(140,-1))
choices = ["-500","-600","-700","-800","-1000"]
self.ExtractSampleStep = Control(panel,type=ComboBox,
name="SAXS_WAXS_Control_Panel.ExtractSampleStep",globals=globals(),
size=(70,-1),choices=choices)
self.ExtractSample = Control(panel,type=ToggleButton,
name="SAXS_WAXS_Control_Panel.ExtractSample",globals=globals(),
label="Extract Sample",size=(140,-1))
choices = ["500","600","700","800","1000"]
self.CirculateSampleStep = Control(panel,type=ComboBox,
name="SAXS_WAXS_Control_Panel.CirculateSampleStep",globals=globals(),
size=(70,-1),choices=choices)
self.CirculateSample = Control(panel,type=ToggleButton,
name="SAXS_WAXS_Control_Panel.CirculateSample",globals=globals(),
label="Circulate Sample",size=(140,-1))
self.PumpSpeed = Control(panel,type=TextCtrl,
name="SAXS_WAXS_Control_Panel.PumpSpeed",globals=globals(),
size=(70,-1))
# Layout
flag = wx.ALIGN_CENTRE_HORIZONTAL|wx.ALL
border = 2
layout = wx.BoxSizer(wx.HORIZONTAL)
left_panel = wx.BoxSizer(wx.VERTICAL)
group = wx.BoxSizer(wx.HORIZONTAL)
text = wx.StaticText(panel,label="Environment:")
group.Add (text,flag=flag,border=border)
group.Add (self.Environment,flag=flag,border=border)
left_panel.Add (group,flag=flag,border=border)
group = wx.BoxSizer(wx.VERTICAL)
group.Add (self.XRayDetector,flag=flag,border=border)
group.Add (self.XRayDetectorInserted,flag=flag,border=border)
left_panel.Add (group,flag=flag,border=border)
group = wx.BoxSizer(wx.VERTICAL)
text = wx.StaticText(panel,label="Ensemble Operation")
group.Add (text,flag=flag,border=border)
group.Add (self.Home,flag=flag,border=border)
group.Add (self.ProgramRunning,flag=flag,border=border)
left_panel.Add (group,flag=flag,border=border)
group = wx.BoxSizer(wx.VERTICAL)
text = wx.StaticText(panel,label="Capillary Position")
group.Add (text,flag=flag,border=border)
group.Add (self.GotoSaved,flag=flag,border=border)
group.Add (self.Save,flag=flag,border=border)
group.Add (self.Inserted,flag=flag,border=border)
left_panel.Add (group,flag=flag,border=border)
group = wx.BoxSizer(wx.VERTICAL)
text = wx.StaticText(panel,label="Sample Temperature")
group.Add (text,flag=flag,border=border)
subgroup = wx.BoxSizer(wx.HORIZONTAL)
subgroup.Add (self.Temperature_Setpoint,flag=flag,border=border)
subgroup.Add (self.Temperature,flag=flag,border=border)
group.Add (subgroup,flag=flag,border=border)
left_panel.Add (group,flag=flag,border=border)
layout.Add (left_panel,flag=flag,border=border)
right_panel = wx.BoxSizer(wx.VERTICAL)
group = wx.GridBagSizer(4,2)
l = wx.ALIGN_LEFT; r = wx.ALIGN_RIGHT; cv = wx.ALIGN_CENTER_VERTICAL
a = wx.ALL; e = wx.EXPAND
row = 0
text = wx.StaticText(panel,label="X-Ray Beam Shutter:")
group.Add (text,(row,0),flag=r|cv)
subgroup = wx.BoxSizer(wx.HORIZONTAL)
subgroup.Add (self.XRayShutter,flag=cv)
subgroup.Add (self.XRayShutterAutoOpen,flag=cv)
group.Add (subgroup,(row,1),flag=l|cv)
row += 1
text = wx.StaticText(panel,label="Laser Beam Shutter:")
group.Add (text,(row,0),flag=r|cv)
subgroup = wx.BoxSizer(wx.HORIZONTAL)
subgroup.Add (self.LaserShutter,flag=cv)
subgroup.Add (self.LaserShutterAutoOpen,flag=cv)
group.Add (subgroup,(row,1),flag=l|cv)
row += 1
text = wx.StaticText(panel,label="Mode:")
group.Add (text,(row,0),flag=r|cv)
group.Add (self.Mode,(row,1),flag=l|cv)
row += 1
text = wx.StaticText(panel,label="Pump:")
group.Add (text,(row,0),flag=r|cv)
group.Add (self.PumpEnabled,(row,1),flag=l|cv)
row += 1
text = wx.StaticText(panel,label="Pump Steps/Stroke:")
group.Add (text,(row,0),flag=r|cv)
group.Add (self.PumpStep,(row,1),flag=l|cv)
right_panel.Add (group,flag=flag,border=border)
text = wx.StaticText(panel,label="Peristaltic Pump Operation [motor steps]")
right_panel.Add (text,flag=flag,border=border)
group = wx.GridBagSizer(1,1)
group.Add (self.PumpPosition,(0,0),flag=r|cv|a,border=border)
group.Add (self.PumpHomed,(0,1),flag=l|cv|a,border=border)
group.Add (self.LoadSampleStep,(1,0),flag=r|cv|a,border=border)
group.Add (self.LoadSample,(1,1),flag=l|cv|a,border=border)
group.Add (self.ExtractSampleStep,(2,0),flag=r|cv|a,border=border)
group.Add (self.ExtractSample,(2,1),flag=l|cv|a,border=border)
group.Add (self.CirculateSampleStep,(3,0),flag=r|cv|a,border=border)
group.Add (self.CirculateSample,(3,1),flag=l|cv|a,border=border)
group.Add (self.PumpSpeed,(4,0),flag=r|cv|a,border=border)
text = wx.StaticText(panel,label="Pump Speed [steps/s]",size=(140,-1))
group.Add (text,(4,1),flag=l|cv|a,border=border)
right_panel.Add (group,flag=flag,border=border)
layout.Add (right_panel,flag=flag,border=border)
group = wx.GridBagSizer(1,1)
panel.SetSizer(layout)
panel.Fit()
return panel
if __name__ == '__main__':
from pdb import pm
import logging; from tempfile import gettempdir
logfile = gettempdir()+"/SAXS_WAXS_Control_Panel.log"
logging.basicConfig(level=logging.DEBUG,
format="%(asctime)s %(levelname)s: %(message)s",
filename=logfile,
)
import autoreload
# Needed to initialize WX library
if not hasattr(wx,"app"): wx.app = wx.App(redirect=False)
panel = SAXS_WAXS_Control_Panel()
wx.app.MainLoop()
<file_sep>#!/usr/bin/env python
"""
Setup panel for diffractomter.
<NAME>, 28 Feb 2013 - 12 Jun 2015
"""
from diffractometer import diffractometer
import wx
from EditableControls import TextCtrl,ComboBox
__version__ = "1.0.2"
class DiffractometerSetup (wx.Dialog):
"""Configures Diffractometer"""
def __init__ (self,parent=None):
wx.Dialog.__init__(self,parent,-1,"Diffractometer Setup")
# Controls
style = wx.TE_PROCESS_ENTER
self.Configuration = ComboBox (self,size=(175,-1),style=style,
choices=["BioCARS Diffractometer","NIH Diffractometer","LCLS Diffractometer"])
self.Apply = wx.Button(self,label="Apply",size=(75,-1))
self.Save = wx.Button(self,label="Save",size=(75,-1))
self.X = ComboBox (self,size=(160,-1),style=style,
choices=["GonX","SampleX"])
self.Y = ComboBox (self,size=(160,-1),style=style,
choices=["GonY","SampleY"])
self.Z = ComboBox (self,size=(160,-1),style=style,
choices=["GonZ","SampleZ"])
self.Phi = ComboBox (self,size=(160,-1),style=style,
choices=["Phi","SamplePhi"])
self.XYType = ComboBox (self,size=(160,-1),style=style,
choices=["rotating","stationary"])
self.RotationCenterX = TextCtrl (self,size=(160,-1),style=style)
self.RotationCenterY = TextCtrl (self,size=(160,-1),style=style)
self.XScale = TextCtrl (self,size=(160,-1),style=style)
self.YScale = TextCtrl (self,size=(160,-1),style=style)
self.ZScale = TextCtrl (self,size=(160,-1),style=style)
self.PhiScale = TextCtrl (self,size=(160,-1),style=style)
self.Bind (wx.EVT_TEXT_ENTER,self.OnEnter)
self.Bind (wx.EVT_COMBOBOX,self.OnEnter)
self.Configuration.Bind (wx.EVT_COMBOBOX,self.OnSelectConfiguration)
self.Save.Bind (wx.EVT_BUTTON,self.OnSave)
self.Apply.Bind (wx.EVT_BUTTON,self.OnApply)
# Layout
layout = wx.BoxSizer()
vbox = wx.BoxSizer(wx.VERTICAL)
config = wx.BoxSizer(wx.HORIZONTAL)
flag = wx.ALIGN_CENTER
config.Add (self.Configuration,flag=flag)
config.Add (self.Apply,flag=flag)
config.Add (self.Save,flag=flag)
vbox.Add (config,flag=wx.EXPAND|wx.ALL)
grid = wx.FlexGridSizer(cols=2,hgap=5,vgap=5)
flag = wx.ALIGN_CENTER_VERTICAL
label = "X Translation:"
grid.Add (wx.StaticText(self,label=label),flag=flag)
grid.Add (self.X,flag=flag)
label = "Y Translation:"
grid.Add (wx.StaticText(self,label=label),flag=flag)
grid.Add (self.Y,flag=flag)
label = "Z Translation:"
grid.Add (wx.StaticText(self,label=label),flag=flag)
grid.Add (self.Z,flag=flag)
label = "Phi Rotation:"
grid.Add (wx.StaticText(self,label=label),flag=flag)
grid.Add (self.Phi,flag=flag)
label = "XY Translation Type:"
grid.Add (wx.StaticText(self,label=label),flag=flag)
grid.Add (self.XYType,flag=flag)
label = "Rotation Center X:"
grid.Add (wx.StaticText(self,label=label),flag=flag)
grid.Add (self.RotationCenterX,flag=flag)
label = "Rotation Center Y:"
grid.Add (wx.StaticText(self,label=label),flag=flag)
grid.Add (self.RotationCenterY,flag=flag)
label = "X Scale Factor:"
grid.Add (wx.StaticText(self,label=label),flag=flag)
grid.Add (self.XScale,flag=flag)
label = "Y Scale Factor:"
grid.Add (wx.StaticText(self,label=label),flag=flag)
grid.Add (self.YScale,flag=flag)
label = "Z Scale Factor:"
grid.Add (wx.StaticText(self,label=label),flag=flag)
grid.Add (self.ZScale,flag=flag)
label = "Phi Scale Factor:"
grid.Add (wx.StaticText(self,label=label),flag=flag)
grid.Add (self.PhiScale,flag=flag)
# Leave a 10-pixel wide space around the panel.
vbox.Add (grid,flag=wx.EXPAND|wx.ALL)
layout.Add (vbox,flag=wx.EXPAND|wx.ALL,border=10)
self.SetSizer(layout)
self.Fit()
self.Show()
self.update()
def update(self,Event=0):
self.X.Value = diffractometer.x_motor_name
self.Y.Value = diffractometer.y_motor_name
self.Z.Value = diffractometer.z_motor_name
self.Phi.Value = diffractometer.phi_motor_name
self.XYType.Value = \
"rotating" if diffractometer.xy_rotating else "stationary"
self.RotationCenterX.Value = "%.4f mm" % \
diffractometer.rotation_center_x
self.RotationCenterY.Value = "%.4f mm" % \
diffractometer.rotation_center_y
self.XScale.Value = str(diffractometer.x_scale)
self.YScale.Value = str(diffractometer.y_scale)
self.ZScale.Value = str(diffractometer.z_scale)
self.PhiScale.Value = str(diffractometer.phi_scale)
self.Configuration.Value = self.current_configuration
# Reschedule "update".
self.update_timer = wx.Timer(self)
self.Bind (wx.EVT_TIMER,self.update,self.update_timer)
self.update_timer.Start(2000,oneShot=True)
def get_current_configuration(self):
from DB import dbget
return dbget("diffractometer.current_configuration")
def set_current_configuration(self,value):
from DB import dbput
dbput("diffractometer.current_configuration",value)
current_configuration = property(get_current_configuration,
set_current_configuration)
def OnEnter(self,event):
diffractometer.x_motor_name = str(self.X.Value)
diffractometer.y_motor_name = str(self.Y.Value)
diffractometer.z_motor_name = str(self.Z.Value)
diffractometer.phi_motor_name = str(self.Phi.Value)
diffractometer.xy_rotating = True if self.XYType.Value == "rotating" else False
value = self.RotationCenterX.Value.replace("mm","")
try: diffractometer.rotation_center_x = float(eval(value))
except: pass
value = self.RotationCenterY.Value.replace("mm","")
try: diffractometer.rotation_center_y = float(eval(value))
except: pass
try: diffractometer.x_scale = float(eval(self.XScale.Value))
except: pass
try: diffractometer.y_scale = float(eval(self.YScale.Value))
except: pass
try: diffractometer.z_scale = float(eval(self.ZScale.Value))
except: pass
try: diffractometer.phi_scale = float(eval(self.PhiScale.Value))
except: pass
self.update()
def OnSelectConfiguration(self,event):
self.current_configuration = str(self.Configuration.Value)
##print "current configuration: % r" % self.current_configuration
def OnEnterConfiguration(self,event):
self.current_configuration = str(self.Configuration.Value)
##print "current configuration: % r" % self.current_configuration
def OnSave(self,event):
##print "save_configuration %r" % self.current_configuration
save_configuration(self.current_configuration)
def OnApply(self,event):
##print "load_configuration %r" % self.current_configuration
load_configuration(self.current_configuration)
self.update()
configuration_parameters = [
"x_motor_name","y_motor_name","z_motor_name","phi_motor_name",
"x_scale","y_scale","z_scale","phi_scale",
"xy_rotating","rotation_center_x","rotation_center_y"]
def save_configuration(name):
"""name: 'NIH Diffractometer' or 'BioCARS Diffractometer'"""
from DB import dbput
for par in configuration_parameters:
dbput("diffractometer/"+name+"."+par,repr(getattr(diffractometer,par)))
def load_configuration(name):
"""name: 'NIH Diffractometer' or 'BioCARS Diffractometer'"""
from DB import dbget
for par in configuration_parameters:
par_name = "diffractometer/"+name+"."+par
str_value = dbget(par_name)
try: value = eval(str_value)
except Exception,message:
print("%s: %s: %s" % (par_name,str_value,message))
continue
setattr(diffractometer,par,value)
if __name__ == '__main__': # for testing
from pdb import pm
app = wx.App(redirect=False)
win = DiffractometerSetup()
app.MainLoop()
<file_sep>prefix = '14IDB:m150'
description = 'Alio Z'
target = 0.22700000000000004
EPICS_enabled = True<file_sep>Size = (720, 711)
Position = (812, 120)
ScaleFactor = 0.5
ZoomLevel = 1.0
Orientation = 0
Mirror = 0
NominalPixelSize = 0.0046500000000000005
filename = '/data/xu_1602/powder_time_resolve/after_320uj_160uj_80uj_70uj_laser_exposure.jpg'
ImageWindow.Center = (680, 507)
ImageWindow.ViewportCenter = (3.1620000000000004, 2.3808000000000002)
ImageWindow.crosshair_color = (255, 0, 0)
ImageWindow.boxsize = (0.3, 1.5)
ImageWindow.box_color = (255, 255, 0)
ImageWindow.show_box = True
ImageWindow.Scale = [[-0.037200000000000004, 0.78585], [0.009300000000000001, -0.023250000000000003]]
ImageWindow.show_scale = True
ImageWindow.scale_color = (255, 0, 0)
ImageWindow.crosshair_size = (0.05, 0.05)
ImageWindow.show_crosshair = True
ImageWindow.show_profile = False
ImageWindow.show_FWHM = False
ImageWindow.show_center = False
ImageWindow.calculate_section = False
ImageWindow.profile_color = (255, 0, 255, 255)
ImageWindow.FWHM_color = (255, 255, 0)
ImageWindow.center_color = (255, 255, 0)
ImageWindow.ROI = [[-0.6138, 0.8788500000000001], [0.58125, -0.6091500000000001]]
ImageWindow.ROI_color = (255, 255, 0, 255)
ImageWindow.show_saturated_pixels = False
ImageWindow.mask_bad_pixels = False
ImageWindow.saturation_threshold = 233
ImageWindow.saturated_color = (255, 0, 0, 255)
ImageWindow.linearity_correction = False
ImageWindow.bad_pixel_threshold = 233
ImageWindow.bad_pixel_color = (30, 30, 30, 255)
ImageWindow.show_grid = False
ImageWindow.grid_type = u'x'
ImageWindow.grid_color = (113, 113, 113)
ImageWindow.grid_x_spacing = 0.055
ImageWindow.grid_x_offset = 0.006324999999999914
ImageWindow.grid_y_spacing = 1.0
ImageWindow.grid_y_offset = 0.0
camera.use_multicast = True
camera.IP_addr = 'id14b-prosilica2.cars.aps.anl.gov'
show_alignment_controls = True
show_edge_controls = False
stepsize = 0.5
camera_angle = 60.0
x_scale = -1
y_scale = 1
z_scale = -1.0
phi_stepsize = 10.0
auto_rotate = False
<file_sep>#!/usr/bin/python
"""
<NAME>, NIH, 6 Sep 2007
"""
def update(module):
"""This allows you to reload a module previously loaded with
"from ... import *". This is useful if you have edited the module source
file using an external editor and want to try out the new version without
leaving the Python interpreter."""
exec "import "+module
exec "reload("+module+")"
exec "from "+module+" import *"
<file_sep>P_default = 0.749
I_default = 0.176
idle_temperature_oasis = 8.0
temperature_oasis_limit_high = 45.0
T_threshold = 83.0
oasis_slave = 1
oasis_headstart_time = 15.0<file_sep>"""Delay line linearity characterization
<NAME>, Jul 22, 2015 - May 1, 2015
Setup:
Ramsay-100B RF Generator, 351.93398 MHz +10 dBm -> FPGA RF IN
FPGA 1: X-scope trig -> CH1, DC50, 500 mV/div
FPGA 13: ps L oscill -> DC block -> 90-MHz low-pass -> CH2, DC50, 500 mV/div
Timebase 5 ns/div
Measurement P1 CH2, time@level, Absolute, 0, Slope Pos, Gate Start 4.5 div,
Stop 5.5 div
Waitting time: 97.8 ms
"""
__version__ = "3.5.1"
from instrumentation import timing_system,timing_sequencer,round_next
from timing_sequence import Sequence
from instrumentation import actual_delay,lecroy_scope,agilent_scope
from LokToClock import LokToClock
from timing_sequence import lxd,Sequence
from scan import rscan,timescan as tscan
from motor_wrapper import motor_wrapper
from sleep import sleep
from numpy import arange
locked = motor_wrapper(LokToClock,"locked")
psod1_count = motor_wrapper(timing_system.psod1,"count")
psod2_count = motor_wrapper(timing_system.psod2,"count")
scope = lecroy_scope()
delay = scope.measurement(2)
dt = timing_system.psod2.stepsize
tmax = round_next(5*timing_system.bct,dt)
nsteps = tmax/dt
def scan():
lxd.value = 0
data = rscan([lxd,delay.gate.start,delay.gate.stop],[0,0,0],
[tmax,-tmax,-tmax],nsteps,[psod1_count,psod2_count,delay],
averaging_time=1.0,logfile="logfiles/scan.log")
def scan_fast():
timing_sequencer.running = False
lxd_fast.value = 0
data = rscan([lxd_fast,delay.gate.start,delay.gate.stop],[0,0,0],
[tmax,-tmax,-tmax],nsteps,[psod1_count,psod2_count,delay],
averaging_time=1.0,logfile="logfiles/scan.log")
def scan_delayline():
tmax = timing_system.psod2.max_dial
nsteps = tmax/dt
timing_sequencer.running = False
timing_system.xosct.enable.count = 1
timing_system.psod2.dial = 0
data = rscan([timing_system.psod2,delay.gate.start,delay.gate.stop],
[0,0,0],[tmax,tmax,tmax],nsteps,[psod2_count,delay],
averaging_time=10.0,logfile="logfiles/scan_delayline.log")
def timescan():
data = tscan(delay,averaging_time=10.0,logfile="logfiles/timescan.log")
class Lxd(object):
from numpy import nan
__value__ = nan
def get_value(self):
return self.__value__
def set_value(self,value):
self.__value__ = value
timing_system.cache = 1
psod1,psod2 = Sequence(ps_lxd=value).register_counts[1][13:15]
timing_system.psod1.count = psod1[0]
timing_system.psod2.count = psod2[0]
value = property(get_value,set_value)
lxd_fast = Lxd()
if __name__ == "__main__":
print('timing_system.ip_address = %r' % timing_system.ip_address)
print('delay.scope.ip_address = %r' % delay.scope.ip_address)
print('timing_system.reset_dcm()')
print('scan_fast()')
print('scan()')
<file_sep>MicroscopeCamera.ImageWindow.Center = (679.0, 512.0)
MicroscopeCamera.Mirror = False
MicroscopeCamera.NominalPixelSize = 0.000517
MicroscopeCamera.Orientation = -90
MicroscopeCamera.camera.IP_addr = '172.21.46.202'
MicroscopeCamera.x_scale = -1.0
MicroscopeCamera.y_scale = 1.0
MicroscopeCamera.z_scale = -1.0
WideFieldCamera.ImageWindow.Center = (738.0, 486.0)
WideFieldCamera.Mirror = False
WideFieldCamera.NominalPixelSize = 0.002445
WideFieldCamera.Orientation = -90
WideFieldCamera.camera.IP_addr = '172.21.46.70'
WideFieldCamera.x_scale = -1.0
WideFieldCamera.y_scale = 1.0
WideFieldCamera.z_scale = -1.0
laser_scope.ip_address = 'femto10.niddk.nih.gov:2000'
rayonix_detector.ip_address = '172.21.46.133:2222'
sample.phi_motor_name = 'SamplePhi'
sample.rotation_center = (-0.7938775, -0.31677586081529113)
sample.x_motor_name = 'SampleX'
sample.xy_rotating = False
sample.y_motor_name = 'SampleY'
sample.z_motor_name = 'SampleZ'
timing_system.ip_address = '172.21.46.207:2000'
xray_scope.ip_address = 'pico21.niddk.nih.gov:2000'<file_sep>title = 'Microfluidics Camera'<file_sep>"""
<NAME>, Aug 20, 2015 - Aug 20, 2015
"""
__version__ = "3.0"
from instrumentation import timing_system
from sleep import sleep
def test_output_state():
for name in timing_system.output_names:
timing_system.register(name+"_enable").count = 0
timing_system.register(name+"_state").count = 1
sleep(0.5)
timing_system.register(name+"_state").count = 0
def test_output_enable():
for name in timing_system.output_names:
timing_system.register(name+"_state").count = 0
timing_system.register(name+"_enable").count = 1
sleep(0.5)
timing_system.register(name+"_enable").count = 0
def enable_all():
for name in timing_system.output_names:
timing_system.register(name+"_enable").count = 1
timing_system.register(name+"_state").count = 0
def disable_all():
for name in timing_system.output_names:
timing_system.register(name+"_enable").count = 0
timing_system.register(name+"_state").count = 0
if __name__ == "__main__":
print('timing_system.ip_address = %r' % timing_system.ip_address)
print('enable_all()')
print('disable_all()')
print('test_output_state()')
print('test_output_enable()')
<file_sep>title = 'Power Configuration'
motor_names = ['collect.power_configuration']
names = ['list']
motor_labels = ['transmission']
widths = [420]
line0.collect.power_configuration = 'power(T0=1.0, N_per_decade=4, N_power=6, reverse=False)'
line1.collect.power_configuration = 'power(T0=0.33, N_per_decade=4, N_power=10, reverse=1)'
line0.description = 'NIH:1.0_4_6_0'
line1.description = 'NIH:0.5_4_10_1'
nrows = 2
line0.updated = '18 Oct 20:50'
line1.updated = '18 Oct 20:50'
description_width = 120
command_row = 2
line2.description = 'None'
line2.updated = 'Nov 3 30:30'
command_rows = []
line2.collect.power_configuration = ' '<file_sep>"""EPICS Channel Access Process Variable as class property
Author: <NAME>
Date created: 2019-05-18
Date last modified: 2019-05-21
"""
__version__ = "1.1" #
from numpy import nan
def PV_property(name,default_value=nan):
"""EPICS Channel Access Process Variable as class property"""
def prefix(self):
prefix = ""
if hasattr(self,"prefix"): prefix = self.prefix
if hasattr(self,"__prefix__"): prefix = self.__prefix__
if prefix and not prefix.endswith("."): prefix += "."
return prefix
def get(self):
from CA import caget
value = caget(prefix(self)+name.upper())
if value is None: value = default_value
if type(value) != type(default_value):
if type(default_value) == list: value = [value]
else:
try: value = type(default_value)(value)
except: value = default_value
return value
def set(self,value):
from CA import caput
value = caput(prefix(self)+name.upper(),value)
return property(get,set)
<file_sep>"""
Data base save and recall motor positions
<NAME>, 29 Nov 2013 - 29 Nov 2019
"""
__version__ = "1.0"
from DB import dbput,dbget
from numpy import nan,asarray
class SavedPositions(object):
"""Data base save and recall motor positions"""
def __init__(self,parent=None,
name = "goniometer_saved",
motors = [],
motor_names = [],
nrows = 8):
"""name: basename of settings file"""
self.name = name
self.motors = motors
self.motor_names = motor_names
self.nrows = nrows
def description(self,row):
"""row: zero-based index"""
return dbget("%s.line%d.description" % (self.name,row))
def position(self,row):
"""Saved motor positions.
row: zero-based index or description string"""
if not isinstance(row,basestring): return self.position_of_row(row)
else: return self.position_of_description(row)
def position_of_row(self,row):
position = []
for j in range(0,len(self.motors)):
position += [tofloat(
dbget("%s.line%d.%s" % (self.name,row,self.motor_names[j])))]
return asarray(position)
def position_of_description(self,description):
for row in range(0,self.nrows):
if self.description(row) == description:
return self.position_of_row(row)
return [nan]*len(self.motor_names)
def tofloat(s):
"""Convert string to float and return 'not a number' in case of """
from numpy import nan
try: return float(s)
except Exception: return nan
if __name__ == '__main__': # for testing
from pdb import pm # for debugging
from id14 import SampleX,SampleY,SampleZ,SamplePhi
saved_positions = SavedPositions(
name="goniometer_saved",
motors=[SampleX,SampleY,SampleZ,SamplePhi],
motor_names=["SampleX","SampleY","SampleZ","SamplePhi"],
nrows=13)
self = saved_positions # for debugging
print 'saved_positions.position("Chip 0,0,0,0")'
<file_sep>#!/usr/bin/env python
"""
Configuration panel for the BioCARS FPGA timing system.
Saving and restoring settings
Author: <NAME>
Date created: 2019-03-26
Date last modified: 2019-06-01
"""
__version__ = "1.1" # redirect
from logging import debug,info,warn,error
from traceback import format_exc
import wx
from instrumentation import timing_system # -> globals()
from Control_Panel import Control_Panel
class Timing_Configuration_Panel(Control_Panel):
name = "Timing_Configuration_Panel"
title = "Timing Configuration"
@property
def ControlPanel(self):
from Controls import Control
panel = wx.Panel(self)
frame = wx.BoxSizer()
panel.Sizer = frame
layout = wx.BoxSizer(wx.VERTICAL)
frame.Add(layout,flag=wx.EXPAND|wx.ALL,border=10,proportion=1)
width = 160
control = Control(panel,type=wx.ComboBox,
globals=globals(),
locals=locals(),
name=self.name+".EPICS_Record",
size=(width,-1),
)
layout.Add(control,flag=wx.ALIGN_CENTRE|wx.ALL)
control = Control(panel,type=wx.TextCtrl,
globals=globals(),
locals=locals(),
name=self.name+".IP_Address",
size=(width,-1),
)
layout.Add(control,flag=wx.ALIGN_CENTRE|wx.ALL)
control = Control(panel,type=wx.ComboBox,
globals=globals(),
locals=locals(),
name=self.name+".Configuration",
size=(width,-1),
)
layout.Add(control,flag=wx.ALIGN_CENTRE|wx.ALL)
control = Control(panel,type=wx.Button,
globals=globals(),
locals=locals(),
name=self.name+".Load",
size=(width,-1),
)
layout.Add(control,flag=wx.ALIGN_CENTRE|wx.ALL)
control = Control(panel,type=wx.Button,
globals=globals(),
locals=locals(),
name=self.name+".Save",
size=(width,-1),
)
layout.Add(control,flag=wx.ALIGN_CENTRE|wx.ALL)
panel.Fit()
return panel
if __name__ == '__main__':
from pdb import pm
import autoreload
from redirect import redirect
redirect("Timing_Configuration_Panel")
# Needed to initialize WX library
import wx
app = wx.App(redirect=False)
panel = Timing_Configuration_Panel()
app.MainLoop()
<file_sep>"""Spectra Physics 3930 Lok-to-Clock frequency stabilizer for the Tsunami laser
This is to make the device remote controllable accross the network using
EPICS.
<NAME>, 3 Jun 2013 - 27 Apr 2016
"""
__version__ = "1.1.1" # EPICS_CA_ADDR_LIST
from CA import Record
from os import environ
environ["EPICS_CA_ADDR_LIST"] = "id14l-spitfire2.cars.aps.anl.gov"
LokToClock = Record("14IDL:LokToClock")
if __name__ == "__main__":
from CA import caget
print 'caget("14IDL:LokToClock.locked")'
print "LokToClock.locked"
print "LokToClock.locked = 1"
<file_sep>#!/usr/bin/env python
"""<NAME>, 13 Dec 2012 - 16 Mar 2018"""
from CameraViewer import CameraViewer
import wx
__version__ = "1.8" # no hard-coded paramneters
wx.app = wx.App(redirect=False) # Needed to initialize WX library
viewer = CameraViewer(name="Microscope")
wx.app.MainLoop()
<file_sep># <NAME>, Feb 24 2015
#!/usr/bin/python
ver = 1.0
import wx
from time import sleep
from syringe_pump import SyringePump
from CA import Record
#p = SyringePump("syringe_pump")
p = Record("NIH:syringe_pump")
CurrentVolume = p.V
#print CurrentVolume
class JogPump(wx.Frame):
def __init__(self, parent, id, title):
wx.Frame.__init__(self, parent, id, title, size=(320,180))
panel = wx.Panel(self, -1)
wx.Button(panel, -1, "Pump Init", (10,120))
wx.StaticText(panel, -1, "Jog Speed [uL/s] : ", (20,15), style=wx.ALIGN_CENTER_VERTICAL)
wx.StaticText(panel, -1, "Jog Volume [uL] : ", (20,50), style=wx.ALIGN_CENTER_VERTICAL)
wx.StaticText(panel, -1, "Current Volume [uL] : ", (20,85), style=wx.ALIGN_CENTER_VERTICAL)
wx.StaticText(panel, -1, "Jog with < or > arrow key", (120,125), style=wx.ALIGN_CENTER_VERTICAL)
self.JogValue = "2.0"
self.JogSpeed = "2.0"
JogSpeedList = ["1.0","2.0","5.0","10.0","50.0"]
JogValueList = ["1.0","2.0","5.0","10.0","50.0"]
self.CurrentVolume = p.V #
self.CB1 = wx.ComboBox(panel, 1, self.JogSpeed, (200,10),(100, 30),JogSpeedList)
self.CB2 = wx.ComboBox(panel, 2, self.JogValue, (200,45),(100, 30), JogValueList)
self.CB3 = wx.ComboBox(panel, 3, str(self.CurrentVolume) , (200,80),(100, 30))
panel.Bind(wx.EVT_BUTTON, self.OnInit)
panel.Bind(wx.EVT_COMBOBOX, self.OnJogSpeed, self.CB1)
panel.Bind(wx.EVT_COMBOBOX, self.OnJogValue, self.CB2)
panel.Bind(wx.EVT_KEY_DOWN, self.OnKeyDown)
panel.SetFocus()
self.Centre()
self.Show(True)
def OnInit(self, event):
""" pump initialization """
MB = wx.MessageBox('Are you sure?', 'Pump Initialization', wx.YES | wx.NO | wx.ICON_INFORMATION)
if MB == wx.YES:
p.set_speed(200.0)
p.init()
p.set_speed(float(self.JogSpeed))
self.CurrentVolume = 0.0
self.CB3.SetValue(str(self.CurrentVolume))
def OnJogSpeed(self, event):
p.set_speed(float(self.CB1.GetValue()))
sleep(0.25)
self.JogSpeed = str(p.get_speed())
#print p.get_speed()
def OnJogValue(self, event):
self.JogValue = float(self.CB2.GetValue())
def OnKeyDown(self, event):
keycode = event.GetKeyCode()
JogVal = float(self.JogValue)
if keycode == wx.WXK_RIGHT:
p.V += JogVal
if keycode == wx.WXK_LEFT:
p.V -= JogVal
time_wait = JogVal/float(self.JogSpeed)
#print JogVal
sleep(max(.25,time_wait)) # RS232 lag time + Jog time
self.CurrentVolume = p.V
self.CB3.SetValue(str(self.CurrentVolume))
if __name__ == "__main__":
app = wx.App()
JogPump(None, -1, 'JogPump.py')
app.MainLoop()
<file_sep>#!/usr/bin/env python
"""Laue Data Collection
Author: <NAME>
Date created: 2007-08-22
Date last modified: 2018-09-13
"""
from pdb import pm # for debugging
# Beamline instrumentation
from instrumentation import *
from CA import caget,caput
# General Python library functions
from numpy import nan,isnan,inf,isinf,array,sqrt,floor,ceil,log10,sin,cos,pi,\
radians,clip,allclose,where,rint
##import numpy; numpy.seterr(all="ignore") # Turn off warning "All-NaN axis encountered"
from time import sleep,strftime,time,localtime
from os import getcwd,remove,makedirs,listdir,chmod
from os.path import exists,dirname,basename,join,splitext,normpath,getmtime
from tempfile import gettempdir
from textfile import read,save
from sound import play_sound
from sample_alignment import sample
from sample_translation_raster import grid
from peak_integration import peak_integration_mask
from ImageViewer import show_images
from string_table import string_table
from logging import info,error,warn # for debugging
from exists import exist_files
from time_string import time_string,seconds
from thread import start_new_thread,allocate_lock
from numimage import numimage
from checklist import beam_ok
__version__ = "28.0" # Methods-based data collection: SAXS_WAXS_methods
DiffX = diffractometer.X
DiffY = diffractometer.Y
DiffZ = diffractometer.Z
##Phi = diffractometer.Phi
Spindle = Phi # motor for sample rotation
class param: "Container for data collection parameters"
# Set reasonable defaults
param.amin = -90.0
param.amax = 90.0
param.astep = 4.0
param.amode = "Single pass"
param.alist = range(-30,30,4)
param.ref_timepoint = nan # off
param.file_basename = "test"
param.extension = "mccd"
param.description = ""
param.logfile_filename = "test.log"
param.path = getcwd()
class options: "Container for data collection options"
# List of variable names, starting with the fastest variable to the slowest
# variable
options.collection_order = [["laser_on","delay"],["translation"],["angle"]]
options.variable_include_in_filename = ["delay","angle","laser_on","repeat",
"repeat2","level","translation","temperature"]
options.variable_choices = {"level":[1.],"temperature":[20]}
options.variable_wait = {"level":False,"temperature":True,"repeat":False,"repeat2":False}
options.variable_return = {"level":False,"temperature":True,"repeat":False,"repeat2":False}
options.variable_return_value = {"temperature":22}
options.npulses = 1
options.npulses_off = 1
options.npasses = 1
options.npasses2 = 1
options.min_waitts = [0.304]
options.min_waitt_off = 0.097
options.max_waitt_off = 0.097
options.estimate_collection_time = False
options.wait_for_beam = False # suspend data collection during storage ring down time
options.wait_for_topup = False # suspend data collection during injection
options.open_laser_safety_shutter = False # automatically open the laser shutter
options.save_raw_image = False
options.periodically_read_ccd = False
options.use_illuminator = False # insert/retract backlight
options.ccd_bin_factor = 4 # determines image size for data collection
options.ccd_hardware_trigger = False
options.ccd_readout_mode = "frame transfer"
options.xray_detector_enabled = True
options.xray_on = [True] # Acquire image with X-rays?
options.finish_series_variable = "delay"
class temp: "Container for temperature scan parameters"
temp.hardware_triggered = True # Ramp on backpanel TTL trigger
temp.step = 0.050 # Triggered increment in deg C
temp.settling_time = 0.0 # Extra wait time when changing temperature
class align: "Container for alignment scan parameters"
align.enabled = False # Perform aligmnent scans?
align.step = 0.025 # alignment scan step size in mm (negative sign implied)
align.start = 0 # alignment scan starting point in mm
align.end = -0.400 # alignment scan starting point in mm
align.beamsize = 0.030 # vertical X-ray beam size
align.center_time = 0 # Time center point was defined
align.center_sample = "" # sample name at the time the sample was centered
align.profile = [] # data of last alignment scan
align.threshold = 4.0 # Peak search threshold signal to noise ratio
align.boxsize = 15 # Spot intgration box size in pixels
align.npoints = 5 # number of points to calculate slope
align.optimize = False # use shoter scan range once the crystal shape is known
align.min_scanpoints = 7 # used when optimizing the scan range
align.last_scans_use = 8 # number of scans to use to determine the scan range
align.scan_offset = 0.060 # Start of scan range outside the crystal visual edge
align.attenuate_xray = False # Attenuate X-ray beam
align.npulses = 10 # number of pulses for each alignemnt image
align.waitt = 0.024 # X-ray pulse spacing for alignment images
align.align_at_collection_phis = False # Do aligment scan at every angle?
align.align_at_collection_zs = False # Do aligment scan at every DiffZ if translating?
align.intepolation_dphi = 30 # Interpolate if support angles within +/-30 deg
align.intepolation_dz = 0.2 # Interpolate if support GonZs within +/-0.2 mm
align.ccd_bin_factor = 8 # determines image size for alignment scans
class translate: "Container for sample translation parameters"
translate.mode = "off" # Operation mode for sample translation
translate.hardware_triggered = False # Slave motion controller to timing system?
translate.interleave_factor = 1 # translate in multiple passes
translate.single = True # single shot per spot per pass
translate.after_image_interleave_factor = 1 # translate in multiple passes
translate.after_images = 1 # after how many images to translate
translate.return_after_series = 1 # after how many series to return to the starting point
translate.after_image_nspots = 1 # used if "after image" translation enabled
translate.during_image_nspots = 1 # used if "after image" translation enabled
translate.move_when_idle = False # Keep moving the linear stage when idle?
translate.move_time = 0.020 # time to move the sample stage in a triggered move
translate.modes = [] # for linear stage, 'Fly-thru', 'Stepping-12'
class pump: "Container for Syringe pump. parameters"
pump.enabled = False
pump.hardware_triggered = True
pump.step = 90
pump.frequency = 1 # very how many image?
pump.on = [True] # for every image
class chopper: "Container for chopper parameters"
chopper.x = [34.491,34,491,34.491,31.016,37.210,37.210,37.210]
chopper.y = [30.825,30.755,30.455,30.060,30.345,30.425,30.140]
chopper.phase = [0,0,0,0,0,0,0,0]
chopper.pulses = [1,3,1,1,1,1,1,1]
chopper.time = [1e-12,308e-9,1.54e-6,1e-12,1e-12,1e-12,1e-12,1e-12]
chopper.min_dt = [-20e-6,100e-9,150e-6,-20e-6,0,0,0,0]
chopper.gate_start = [+115e-9,-35e-9,-625e-9,+115e-9,0,0,0,0]
chopper.gate_stop = [+490e-9,+640e-9,+1200e-9,+490e-9,0,0,0,0]
chopper.use = [False,False,False,True,False,False,False,False]
chopper.wait = True # suspend data collection while chopper mode is changing?
chopper.modes = [] # if not using te time dealy to select the mode
class diagnostics: "Container for alignment scan parameters"
diagnostics.enabled = False
diagnostics.delay = False
diagnostics.xray = False
diagnostics.laser = False
diagnostics.min_window = 2e-6
diagnostics.timing_offset = 0
diagnostics.xray_reference = -122e-12
diagnostics.xray_offset_level = 0
diagnostics.xray_gate_start = -625e-9
diagnostics.xray_gate_stop = +1200e-9
diagnostics.xray_record_waveform = False
diagnostics.xray_sampling_rate = 1e9
diagnostics.xray_time_range = 5e-6
diagnostics.xray_time_offset = 0
diagnostics.laser_reference = 2.5e-9
diagnostics.laser_offset = 0
diagnostics.laser_record_waveform = False
diagnostics.laser_sampling_rate = 1e9
diagnostics.laser_time_range = 2e-6
diagnostics.laser_time_offset = 0
diagnostics.PVs = ["S:SRcurrentAI.VAL","BNCHI:BunchCurrentAI.VAL","14IDB:oxTemp",
"14Keithley1:DMM1Ch1_raw.VAL","14Keithley1:DMM1Ch3_raw.VAL","14Keithley1:DMM1Ch4_raw.VAL"]
diagnostics.PVnames = ["ring-current[mA]","bunch-current[mA]","CryoJet[K]",
"cooling-water-temp[C]","room-temp[C]","table-temp[C]"]
diagnostics.PVuse = [True,True,True,False,False,True]
class xraycheck: "Container for X-ray beam optimization parameters"
xraycheck.enabled = False # Auto-tweak during data collection?
xraycheck.run_variable = "delay"# Run check when this colection variable repeats
xraycheck.interval = 3600 # time in seconds before repeating
xraycheck.at_start_of_time_series = True
xraycheck.retract_sample = -1.5 # [mm] to spare sample from expore to X-ray beam
xraycheck.sample_motor = "DiffZ" # use "DiffZ" motor to retract the sample
xraycheck.last = 0 # last time alignment scan finished
xraycheck.min_intensity = 0.1 # do not run optimization if x-ray intensity if less than 20% of refernce
xraycheck.type = "beam position"# which type of optimization? "beam position" or "I0"
xraycheck.comment = "" # summary of last check
class lasercheck: "Container for laser beam profiler"
lasercheck.enabled = False # Auto-tweak during data collection?
lasercheck.check_only = False # Measure position only, not applying correction
lasercheck.interval = 3600 # time in seconds before repeating
lasercheck.at_start_of_time_series = True
lasercheck.retract_sample = True # Move sample out of laser beam during check?
lasercheck.park_motors = ["DetZ","Phi","DiffX","DiffY"]
lasercheck.park_positions = [678.47,-35,10.35,1.725]
lasercheck.sample_position = []
lasercheck.last = 0 # Last time alignment scan finished
lasercheck.attenuator = 180.0 # VNFilterangle in deg
lasercheck.reprate = 40 # Laser trigger frequency
lasercheck.naverage = 4 # How many times to measure the beam position
lasercheck.signal_to_noise = 15. # Take no corrective action below this value.
lasercheck.comment = "" # summary of last laser beam check
lasercheck.zprofile = [] # last recorded beam profile in X-ray beam direction
lasercheck.xprofile = [] # last recorded beam profile orthogonal to X-ray direction
lasercheck.last_image = "" # pathname of last saved beam profile image
lasercheck_image = None # last redorded beam profile image in PIL format
class timingcheck: "Container for timinig calibration parameters"
timingcheck.enabled = False # Auto-tweak during data collection?
timingcheck.interval = 3600 # time in seconds before repeating
timingcheck.at_start_of_time_series = True
timingcheck.retract_sample = -1.0 # move sample by 1.0 mm
timingcheck.attenuator_angle = 300# VNFilter seeting in deg
timingcheck.sample_motor = "DiffY" # use "DiffZ" motor to retract the sample
timingcheck.last = 0 # last time alignment scan finished
timingcheck.min_intensity = 0.1 # do not run optimization if x-ray intensity if less than 20% of refernce
timingcheck.comment = "" # summary of last check
class sample_photo: "Container for sample image"
sample_photo.enabled = False # Auto-tweak during data collection?
sample_photo.phis = [0] # List of orientations at which to take photos/
sample_photo.frequency_orientations = 1 # How often to save the image
class checklist: "Container for check list parameters"
checklist.U23 = 10.741 # operating gap of undulator
checklist.U27 = 15.848 # operating gap of undulator
checklist.wbshg = 1.000 # nom. white-beam slits horizontal gap
checklist.wbsvg = 1.000 # nom. white-beam slits vertical gap
checklist.shg = 0.200 # nom. horizontal gap of sample JJ slits
checklist.svg = 0.120 # nom. vertical gap of sample JJ slits
# Initialize status variables
class task: "Container for status variables"
task.image_number = 1
task.last_image = None # for 'Finish Time Series' option
task.cancelled = False
task.finish_series = False
task.action = ""
task.last_pulse = 0 # timestamp of the last X-ray pulse
task.next_pulse = 0 # time to wait until before sending the next laser pulse
task.run_background_threads = False
task.comment = "" # progress info
task.autorecovery_needed = False # something left in a messy state
task.last_image_xdet_count = nan # acquisition finished after this count
def save_settings():
"""Update the default parameter file"""
global settings_file_timestamp
filename = settings_file()
save_settings_to_file(filename)
settings_file_timestamp = getmtime(filename)
def reload_settings():
"""Reload default parameters parameters if changed."""
global settings_file_timestamp
filename = settings_file()
if exists(filename) and getmtime(filename) != settings_file_timestamp:
load_settings(filename)
settings_file_timestamp = getmtime(filename)
settings_file_timestamp = 0
def save_settings_to_file(filename):
"""Write a parameter file"""
if not exists(dirname(filename)): makedirs(dirname(filename))
f = file(filename,"w")
for obj in param,options,temp,align,translate,chopper,pump,diagnostics,\
xraycheck,lasercheck,timingcheck,sample_photo,checklist:
for name in dir(obj):
if name.startswith("__"): continue
line = "%s.%s = %r\n" % (obj.__name__,name,getattr(obj,name))
line = line.replace("-1.#IND","nan") # Needed for Windows Python
line = line.replace("1.#INF","inf") # Needed for Windows Python
f.write(line)
def load_settings(filename=None):
"""Reload last saved parameters."""
if filename == None: filename = settings_file()
if not exists(filename): return
for line in file(filename).readlines():
try: exec(line)
except: warn("ignoring line %r in settings" % line)
global Spindle
try: Spindle = eval(param.amotor)
except:
warn("Resetting spindle motor from %r to Phi" % param.amotor)
param.amotor = "Phi"; Spindle = Phi
def save_dataset_settings():
"""Generate or update a settings file in the current data collection
directory."""
filename = param.path+"/"+param.file_basename+".par"
save_settings_to_file(filename)
def settings_file():
"""Where to save to the default settings"""
filename = settingsdir()+"/lauecollect_settings.py"
return filename
def settingsdir():
"""In which directory to save to the settings file"""
return module_dir()+"/settings"
def single_image():
"""This is for quick test shots.
Acquire a single image in the current orientation without saving it."""
action = task.action; task.action = "Single Image"
set_chopper(0)
task.image_number = 0 # for status display
start_images([0])
acquire_image(0)
finish_images([0])
task.action = action
def collect_dataset():
"""Acquire all the images of a dataset, resuming a collection
where interrupted"""
from checklist import checklist as my_checklist
if not exists (param.path): makedirs (param.path)
if not exists (param.path): return
start_dataset()
image_numbers = collection_pass(1)
while len(image_numbers)>0 and not task.cancelled:
while not beam_ok() and len(image_numbers)>0 and not task.cancelled:
task.image_number = image_numbers[0] # for GUI update
info("Waiting because %s..." % my_checklist.test_failed)
sleep(1)
image_numbers = collection_pass(1)
if task.cancelled: break
acquire_images(image_numbers)
image_numbers = collection_pass(task.image_number+1)
finish_dataset()
if not task.cancelled: play_sound("ding")
def start_dataset():
"""Called once at the beginning of a dataset"""
diagnostics_start_dataset()
collection_variables_start_dataset()
def finish_dataset():
"""Called once at the end of a dataset"""
diagnostics_finish_dataset()
collection_variables_finish_dataset()
def acquire_images(image_numbers):
"""Collect a series of images in hardware triggred mode.
The actions between the images can be performed in quickly enough
so the collection does not need to be suspended.
image_numbers: 1-based integers
e.g. image_numbers = collection_pass(1)"""
if len(image_numbers) > 0:
align_sample_if_needed_for_phi(angle(image_numbers[0]))
if xray_beam_check_before(image_numbers[0]):
run_xray_beam_check(apply_correction=True)
task.image_number = image_numbers[0] # for progress report
set_collection_variables(image_numbers[0],wait=True)
start_images(image_numbers)
for image_number in image_numbers:
if task.cancelled: break
if not image_number <= nimages_to_collect(): break
set_collection_variables(image_number,wait=False)
acquire_image(image_number)
if task.cancelled or not beam_ok(): break
finish_images(image_numbers)
def start_images(image_numbers):
"""This is run at the beginning of 'collect_dataset' or 'single_image'.
image_numbers: list of 1-based integers
e.g. image_numbers = collection_pass(1)"""
prepare_images(image_numbers)
acquisition_start(image_numbers)
def prepare_images(image_numbers):
"""Perform all the setup, without starting the acquisition.
image_numbers: list of 1-based integers
e.g. image_numbers = collection_pass(1)"""
from threading import Thread
threads = []
threads += [Thread(target=logfile_start_images,args=(image_numbers,))]
threads += [Thread(target=diagnostics_start_images,args=(image_numbers,))]
threads += [Thread(target=temperature_controller_start_images,args=(image_numbers,))]
threads += [Thread(target=motion_controller_start_images,args=(image_numbers,))]
threads += [Thread(target=timing_system_start_images,args=(image_numbers,))]
threads += [Thread(target=xray_detector_start_images,args=(image_numbers,))]
for thread in threads: thread.start()
for thread in threads: thread.join()
def prepare_images_serial(image_numbers):
"""Perform all the setup, without starting the acquisition.
image_numbers: list of 1-based integers
e.g. image_numbers = collection_pass(1)"""
logfile_start_images(image_numbers)
diagnostics_start_images(image_numbers)
temperature_controller_start_images(image_numbers)
motion_controller_start_images(image_numbers)
timing_system_start_images(image_numbers)
xray_detector_start_images(image_numbers)
def motion_controller_start_images(image_numbers):
"""Configure motion controller
image_numbers: list of 1-based integers
e.g. image_numbers = collection_pass(1)"""
if "after image" in translate.mode:
XYZ = array([translation_after_image_xyz(i) for i in image_numbers])
triggered_motion.xyz = XYZ
triggered_motion.waitt = timing_system.waitt.next(wait_time(image_numbers[0]))
triggered_motion.armed = True
def timing_system_start_images(image_numbers):
"""Set up the trigger pulse generation for a series of images
image_numbers: list of 1-based integers
e.g. image_numbers = collection_pass(1)"""
debug("Lauecollect: timing system setup...")
timing_sequencer.queue_active = False # hold off exection till all is set up
timing_system.image_number.count = 0
timing_system.pass_number.count = 0
timing_system.pulses.count = 0
debug("Lauecollect: Compiling parameters for timing system...")
my_delays = [delay(i) for i in image_numbers]
my_laser_on = [laser_on(i) for i in image_numbers]
my_ms_on = [1]*len(image_numbers)
my_image_numbers=list(image_numbers)
debug("Lauecollect: Compiling parameters for timing system done.")
Ensemble_SAXS.acquire(
delays=my_delays,
laser_on=my_laser_on,
ms_on=my_ms_on,
image_numbers=my_image_numbers,
)
def xray_detector_start_images(image_numbers):
"""Configure X-ray area detector
image_numbers: list of 1-based integers
e.g. image_numbers = collection_pass(1)"""
if options.xray_detector_enabled:
filenames = [filename(i) for i in image_numbers]
show_images(filenames)
ccd.bin_factor = options.ccd_bin_factor
ccd.acquire_images(image_numbers,filenames)
def acquisition_start(image_numbers):
"""Start imitng system after all subsystem are initialized"""
if len(image_numbers) > 0:
if not "linear stage" in translate.mode:
filenames = [filename(i) for i in image_numbers]
xdet_on = timing_sequencer.xdet_on
progress("X-ray detector continuously triggered: %r" % xdet_on)
# If the X-ray detector is not continuously triggered...
if not xdet_on: xdet_count = timing_system.xdet_count.count+2 # discard first dummy image
timing_sequencer.acquisition_start()
progress("Timing system: Waiting for acquisition to start...")
while not timing_system_acquiring() and not task.cancelled: sleep(0.01)
progress("Timing system: Acquisition started.")
if xdet_on: xdet_count = timing_system.xdet_count.count+1
from rayonix_detector_continuous_1 import ccd
progress("First image %r, xdet_count=%r" % (basename(filenames[0]),xdet_count))
ccd.acquire_images_triggered(filenames,start=xdet_count)
task.last_image_xdet_count = xdet_count+len(image_numbers)-1
else:
progress("Timing system: Starting acquisition...")
Ensemble_SAXS.acquisition_start(image_numbers[0])
while not timing_sequencer.queue_active and not task.cancelled:
sleep(0.05)
task.last_image_xdet_count = nan
def timing_system_acquiring():
"""Has the timing system started acquiring data?"""
return timing_system.image_number.count > 0 \
or timing_system.pass_number.count > 0
def finish_images(image_numbers):
"""This is run at the end of 'collect_dataset' or 'single_image'
image_numbers: list of 1-based integers
e.g. image_numbers = collection_pass(1)"""
timing_system_finish_images(image_numbers)
diagnostics_finish_images(image_numbers)
xray_detector_finish_images(image_numbers)
temperature_controller_finish_images(image_numbers)
logfile_finish_images(image_numbers)
save_dataset_settings()
def timing_system_finish_images(image_numbers):
"""Stop trigger pulse generation"""
if "linear stage" in translate.mode:
Ensemble_SAXS.acquisition_cancel()
else: timing_sequencer.acquisition_cancel()
def xray_detector_finish_images(image_numbers):
if options.xray_detector_enabled:
if task.cancelled or not beam_ok(): ccd.cancel_acquisition()
def acquire_image(image_number):
"""Follow the data collection for one image"""
debug("acquire image %r..." % image_number)
task.image_number = image_number # for reporting progress
start_image(image_number)
wait_for_image(image_number)
finish_image(image_number)
debug("acquire image %r done" % image_number)
def start_image(image_number):
"""This is run before each image"""
temperature_controller_start_image(image_number)
diagnostics_start_image(image_number)
def finish_image(image_number):
"""This is run after each image"""
diagnostics_finish_image(image_number)
def wait_for_image(image_number):
"""Follow the data collection for one image"""
while not completed_image(image_number) and not task.cancelled and beam_ok():
sleep(0.002)
def exec_delayed(time,command):
"""Execute a command on background after a certain delay
time: seconds
command: string, executable Python code"""
from thread import start_new_thread
start_new_thread(exec_delayed_background,(time,command))
def exec_delayed_background(time,command):
"""Execute a command after a certain delay
time: seconds
command: string, executable Python code"""
sleep(time)
exec(command)
def completed_image(image_number):
return timing_system_completed_image(image_number)
def timing_system_completed_image(image_number):
##debug("completed image %d? current image number %r" %
## (image_number,timing_system.image_number.count))
if timing_system.image_number.count > image_number: completed = True
elif not timing_sequencer.queue_active: completed = True
else: completed = False
##debug("completed image %d? %r" % (image_number,completed))
return completed
def wait_for_beam():
"""In case the storage ring is down suspend the data collection.s"""
while not beam_ok() and not task.cancelled: sleep(1)
# Temperature controller
def temperature(image_number):
"""Which temperature to set while acquiring this image?"""
return collection_variable_value("temperature",image_number)
def dT(image_number):
"""How much does temperature change while acquiring this image?
iamge_number: 1-based index"""
i = image_number
if i <= nimages()-1: dT = temperature(i+1)-temperature(i)
elif i >= 2: dT = temperature(i)-temperature(i-1)
else: dT = 0
return dT
def dTs(image_numbers): return [dT(i) for i in image_numbers]
def temp_inc(image_number):
"""How many temperature increments while acquiring this image?"""
i = image_number
dT = temperature(i+1)-temperature(i)
temp_inc = int(rint(abs(dT)/temp.step))
return temp_inc
def temp_incs(image_numbers):
"""How many temperature increments while acquiring these images?"""
if temp.hardware_triggered:
from numpy import concatenate
T = array([temperature(i) for i in image_numbers])
dT = T[1:]-T[0:-1]
dT = concatenate((dT,dT[-1:] if len(dT)>0 else [0]))
##assert all(dT == dTs(image_numbers))
temp_inc = dT/temp.step
# Make sure rounding error does not accumulate
for i in range(0,len(temp_inc)-1):
d = rint(temp_inc[i])-temp_inc[i]
temp_inc[i] -= d
temp_inc[i+1] += d
temp_inc = abs(rint(temp_inc).astype(int))
temp_inc = list(temp_inc)
else: temp_inc = [nan]*len(image_numbers)
return temp_inc
def temp_step(image_number):
"""How much to increment the temperature at each trigger?"""
i = image_number
T = temperature
N = nimages()
# Find the nexdt image where the temperature is changing.
while i < N-1 and T(i+1) == T(i): i += 1
if i > N-1 and i > 1: i -= 1
dT = T(i+1)-T(i)
step = (1 if dT >= 0 else -1)*temp.step
return step
def temp_steps(image_numbers): return [temp_step(i) for i in image_numbers]
def temperature_controller_start_images(image_numbers):
"""Configure temperature controller
image_numbers: list of 1-based integers
e.g. image_numbers = collection_pass(1)"""
if collection_variable_enabled('temperature') \
and variable_hardware_triggered('temperature') \
and len(image_numbers) > 0:
image_number = image_numbers[0]
T = temperature(image_number)
Tstep = temp_step(image_number)
Tstop = 120 if temp_step(image_number) > 0 else -30
temperature_controller.command_value = T
temperature_controller.trigger_start = T
temperature_controller.trigger_stepsize = Tstep
temperature_controller.trigger_stop = Tstop
temperature_controller.trigger_enabled = True
def temperature_controller_start_image(image_number):
"""Configure temperature controller
image_number: 1-based integer"""
if collection_variable_enabled('temperature') \
and variable_hardware_triggered('temperature'):
if dT(image_number) == 0:
T = temperature(image_number)
Tstep = temp_step(image_number)
Tstop = 120 if temp_step(image_number) > 0 else -30
if temperature_controller.command_value != T:
temperature_controller.command_value = T
if temperature_controller.trigger_start != T:
temperature_controller.trigger_start = T
if temperature_controller.trigger_stepsize != Tstep:
temperature_controller.trigger_stepsize = Tstep
if temperature_controller.trigger_stop != Tstop:
temperature_controller.trigger_stop = Tstop
def temperature_controller_finish_images(image_numbers):
"""Configure temperature controller
image_numbers: list of 1-based integers
e.g. image_numbers = collection_pass(1)"""
if collection_variable_enabled('temperature') \
and variable_hardware_triggered('temperature'):
temperature_controller.trigger_enabled = False
# Sample Translation
def prepare_sample_translation(passno=0,wait=True):
"""This is to bring the sample in the right starting position for continuous
translation.
The passno parameter refers to the pass number, because the each pass can have a different
travel range (alternating direction, or incomplete pass at the end)"""
# Go to the start of translation range.
if "continuous" in translate.mode:
(DiffX.speed,DiffY.speed,DiffZ.speed) = sample_translation_speed()
(DiffX.value,DiffY.value,DiffZ.value) = sample_translation_start(passno)
if wait: # Wait until the sample to stops moving
while (DiffX.moving or DiffY.moving or DiffZ.moving) and not task.cancelled:
sleep (0.025)
def initiate_sample_translation(passno=0):
"""Starts translating the sample
The passno parameter refers to the pass number, because the each pass can have a different
travel range (alternating direction, or incomplete pass at the end)
passno is 0-based"""
if "continuous" in translate.mode:
(DiffX.speed,DiffY.speed,DiffZ.speed) = sample_translation_speed()
(DiffX.value,DiffY.value,DiffZ.value) = sample_translation_end(passno)
def bursts_per_image(image_number):
"""How many groups of X-ray pulses are used to acquire one image?"""
# Methods-based data collection
bursts = toint(SAXS_WAXS_methods.passes_per_image.value)
return bursts
def burst_length(image_number):
"""How many X-ray pulses are group together in a burst?"""
# Methods-based data collection
mode = SAXS_WAXS_methods.Ensemble_mode.value
burst_length = Ensemble_SAXS.burst_length_of_mode(mode)
return burst_length
def npasses(image_number):
"""If sample translation is enabled, several passes may be needed to
acquire a n image.
Depending of the speed of translation and the number of pulses, the
sample translation needs to be broken up into a number of separate
strokes.
image_number: 1-based index"""
# Methods-based data collection
return toint(SAXS_WAXS_methods.passes_per_image.value)
def npulses_of_pass(image_number,passno):
"""Return the number of X-ray pulses in nth passno
image_number: 1-based index
passno: 0-based index"""
# Methods-based data collection
mode = SAXS_WAXS_methods.Ensemble_mode.value
burst_length = Ensemble_SAXS.burst_length_of_mode(mode)
return burst_length
def sample_translation_starting_point():
"""The starting position for DiffX,DiffY,DiffZ.
Return value: (x,y,z)"""
z = min(sample.zs)
if align.enabled: x,y = 0,align_offset(Phi.value,z)
else: x,y = nan,nan # nan = Do not move. Keep current position.
return (x,y,z)
def sample_translation_ending_point():
"""The starting position for DiffX,DiffY,DiffZ.
Return value: (x,y,z)"""
z = max(sample.zs)
if align.enabled: x,y = 0,align_offset(Phi.value,z)
else: x,y = nan,nan # nan = Do not move. Keep current position.
return (x,y,z)
def sample_translation_start(passno):
"""The starting position for DiffX,DiffY,DiffZ for the nth passno.
passno is 0-based.
Return value: (x,y,z)"""
if passno % 2 == 0: return sample_translation_starting_point()
else: return sample_translation_ending_point()
def sample_translation_end(passno):
"""return the ending position for DiffX,DiffY,DiffZ for the nth passno
passno is 0-based"""
x,y,z = zip(sample_translation_starting_point(),sample_translation_ending_point())
dt = abs(z[1] - z[0])/DiffZ.speed
pps = int(dt/timing_system.waitt.value) # pulses_per_stroke
fraction = float(npulses_of_pass(task.image_number,passno))/pps
fraction = min(max(0.0,fraction),1.0)
i = passno % 2 ; j = 1-i
x = x[i]*(1-fraction) + x[j]*fraction
y = y[i]*(1-fraction) + y[j]*fraction
z = z[i]*(1-fraction) + z[j]*fraction
return (x,y,z)
def sample_translation_speed():
"""This is to continuously translate the sample during the acqusition of
an image.
Returns the required translation speeds for DiffX,DiffY,DiffZ in mm/s"""
if "continuous" in translate.mode: return (DiffX.speed,DiffY.speed,DiffZ.speed)
x,y,z = zip(sample_translation_starting_point(),sample_translation_ending_point())
dx = abs(x[1] - x[0])
dy = abs(y[1] - y[0])
dz = abs(z[1] - z[0])
vx = DiffX.speed
vy = DiffY.speed
vz = DiffZ.speed
dt = dz/DiffZ.speed
if dt>0 and dx>0: vx = dx/dt
if dt>0 and dy>0: vy = dy/dt
return (vx,vy,vz)
def normal_speed():
"""Returns the standard translation speeds for DiffX,DiffY,DiffZ in mm/s"""
# Set speed to always go at a slow rate. RH
return (0.2,0.2,DiffZ.speed)
#return (0.00313991, 0.00128627,DiffZ.speed)
def sample_translation_summary():
"""short description for log file"""
s = ""
if "during image" in translate.mode:
dz = max(sample.zs)-min(sample.zs)
s += "during image step: %.3f mm, " % sample.z_step
s += "%s spots, " % translation_during_image_unique_nspots()
if translate.interleave_factor > 1:
s += "in %d interleaved passes, " % translate.interleave_factor
if translate.single: s += "single shot per pass, "
s += "Z speed %.3f mm/s, " % DiffZ.speed
if "after image" in translate.mode:
s += "after image step: %.5f mm, " % translation_after_image_zstep()
s += "every %d images, " % translate.after_images
s += "return every %d series, " % translate.return_after_series
if translate.after_image_interleave_factor > 1:
s += "in %d interleaved passes, " % \
translate.after_image_interleave_factor
if "continous" in translate.mode:
dz = max(sample.zs)-min(sample.zs)
s += "continous: DZ=%.3f mm, " % dz
s += ", Z speed %.3f mm/s" % DiffZ.speed
if "linear stage" in translate.mode:
s += "linear stage"
s = s.rstrip(", ")
if s == "": s = "off"
return s
def logfile_start_images(image_numbers):
logfile_update() # Generate header if needed
# In case the image is recollected, make sure to leave no duplicate
# entries in the logfile.
logfile_delete_image_numbers(image_numbers)
current_image_number_start_updating()
logfile_start_updating(image_numbers)
def logfile_finish_images(image_numbers):
logfile_finish_updating()
##exec_delayed(1,'logfile_finish_updating()')
logfile_keep_updating = False
def logfile_start_updating(image_numbers):
"""Begin collecting per-image statistics for diagnostics PVs."""
global logfile_keep_updating
logfile_keep_updating = True
from thread import start_new_thread
start_new_thread(logfile_update_task,(image_numbers,))
def logfile_finish_updating():
"""End collecting per-image statistics for diagnostics PVs."""
global logfile_keep_updating
logfile_keep_updating = False
def logfile_update_task(image_numbers):
"""Keep updating the logfile as new images are acquired"""
debug("lauecollect: logging started")
from time import time
if logfile_keep_updating: last_active = time()
ending = False
while logfile_keep_updating or time()-last_active < 2.0:
Nfinished = 0
for i in image_numbers:
if not image_logged(i) and image_finished(i):
image_info[i]["logged"] = time()
logfile_update(i)
if all([image_logged(i) for i in image_numbers]):
debug("lauecollect: logging completed")
break
if logfile_keep_updating and not ending: last_active = time()
elif not ending: ending = True; debug("lauecollect: logging ending")
debug("lauecollect: logging stopped")
def initialize_logfile():
"""Create a log file with an inforational header and column labels"""
if not exists(logfile()):
debug("logfile header...")
if not exists(dirname(logfile())): makedirs(dirname(logfile()))
log = file(logfile(),"a")
for line in logfile_info().split("\n"): log.write("# "+line+"\n")
# Generate column headers.
if "phi" in Spindle.name.lower(): angle = "angle"
else: angle = Spindle.name.replace(" ","")
header = "#date time\tfile\tdelay"+\
"\twaiting-time[s]\tbunches-per-pulse\tnom.pulses"+\
"\tnom.delay[s]\tact.delay[s]\tsdev(act.delay)[s]\tnum(act.delay)"+\
"\tx-ray[Vs]\tsdev(x-ray[Vs])\tnum(x-ray)"+\
"\txray-gate-start[s]\txray-gate-stop[s]\tx-ray-offset[V]"+\
"\tlaser\tsdev(laser)\tnum(laser)"
for name in collection_variables():
header += "\t"+name
unit = variable_unit(name)
if unit: header += "["+unit+"]"
for i in range(0,diagnostics_PVs()):
header += "\t"+diagnostics_PV_comment(i)
header += "\tsdev("+diagnostics_PV_comment(i)+")"
header += "\tnum("+diagnostics_PV_comment(i)+")"
header += "\t"+"comment"
log.write(header+"\n")
debug("logfile header done")
logfile_lock = allocate_lock()
def logfile_update(image_number=None):
"""Add image information to the end of the data collection log file"""
with logfile_lock:
if not exists(logfile()): initialize_logfile()
if image_number is not None:
timestamp = image_timestamp(image_number)
image_filename = basename(filename(image_number))
import datetime
date_time = datetime.datetime.fromtimestamp(timestamp).strftime("%d-%b-%y %H:%M:%S.%f")[:-3]
if laser_on(image_number): delay_string = time_string(timepoint(image_number))
else: delay_string = "-"
waitting_time = tostr(wait_time(image_number))
bunches_per_pulse = tostr(chopper_pulses())
nom_pulses = tostr(npulses(image_number))
if laser_on(image_number): nom_delay = tostr(delay(image_number))
else: nom_delay = "nan"
if diagnostics.enabled and diagnostics.delay:
act_delay = tostr(timing_diagnostics_delay(image_number))
sdev_delay = tostr(timing_diagnostics_sdev_delay(image_number))
num_delay = tostr(timing_diagnostics_num_delay(image_number))
else: act_delay = sdev_delay = "nan"; num_delay = "0"
if diagnostics.enabled and diagnostics.xray:
xray = tostr(xray_pulse.average)
sdev_xray = tostr(xray_pulse.stdev)
num_xray = tostr(xray_pulse.count)
xray_gate_start = tostr(diagnostics.xray_gate_start)
xray_gate_stop = tostr(diagnostics.xray_gate_stop)
xray_offset = tostr(diagnostics.xray_offset_level)
else:
xray = sdev_xray = "nan"; num_xray = "0"
xray_gate_start = xray_gate_stop = xray_offset = "nan"
if diagnostics.enabled and diagnostics.laser:
ref = diagnostics.laser_reference
offset = diagnostics.laser_offset
laser = tostr((laser_pulse.average - offset) / (ref - offset))
sdev_laser = tostr(laser_pulse.stdev / (ref - offset))
num_laser = tostr(laser_pulse.count)
else: laser = sdev_laser = "nan"; num_laser = "0"
record = date_time+"\t"+image_filename+"\t"+delay_string+\
"\t"+waitting_time+"\t"+bunches_per_pulse+"\t"+nom_pulses+\
"\t"+nom_delay+\
"\t"+act_delay+"\t"+sdev_delay+"\t"+num_delay+\
"\t"+xray+"\t"+sdev_xray+"\t"+num_xray+\
"\t"+xray_gate_start+"\t"+xray_gate_stop+"\t"+xray_offset+\
"\t"+laser+"\t"+sdev_laser+"\t"+num_laser
for name in collection_variables():
record += "\t"+tostr(collection_variable_value(name,image_number))
for i in range(0,diagnostics_PVs()):
record += "\t"+tostr(diagnostics_PV_image_avg(i,image_number))
record += "\t"+tostr(diagnostics_PV_image_sdev(i,image_number))
record += "\t"+tostr(diagnostics_PV_image_count(i,image_number))
global logfile_comment
record += "\t"+logfile_comment
logfile_comment = ""
with logfile_lock:
# In case the image is recollected, make sure to leave no duplicate
# entries in the logfile.
##logfile_delete_filename(image_filename) # time consuming
file(logfile(),"a").write(record+"\n")
def log_comment(comment):
"""This will be logged as comment to the next image when the image is saved."""
global logfile_comment
if logfile_comment: logfile_comment += "; "
logfile_comment += comment
logfile_comment = ""
def logfile_has_entries(image_filenames):
"""Is there an entry for this image in the log file?
image_filenames: filenames of images (with or without directory)
"""
from os.path import basename
entries = logfile_entries()
return array([basename(f) in entries for f in image_filenames])
def logfile_has_entry(image_filename):
"""Is there an entry for this image in the log file?
image_filename: filename of image (with or without directory)
"""
return logfile_has_entries([image_filename])[0]
def logfile_entries():
"""Is there an entry for this image in the log file?
image_filename: basename of image filename (without directory)
"""
try: log = file(logfile())
except: return []
lines = log.read().split("\n")
# 'split' makes the last line an empty line.
if lines and lines[-1] == "": lines.pop(-1)
filenames = []
for line in lines:
if line.startswith("#"): continue # Ignore comment lines.
fields = line.split("\t")
if len(fields)>1: filenames += [fields[1]]
return filenames
def logfile_delete_image_numbers(image_numbers):
"""Make sure that there are no duplicate entries in the
data collection logfile, in the case an image is recollected.
image_filename: basename of image filename (without directory)
"""
image_filenames = [basename(filename(i)) for i in image_numbers]
logfile_delete_filenames(image_filenames)
def logfile_delete_filenames(image_filenames):
"""Make sure that there are no duplicate entries in the
data collection logfile, in the case an image is recollected.
image_filename: basename of image filename (without directory)
"""
try: log = file(logfile())
except: return
lines = log.read().split("\n")
# 'split' makes the last line an empty line.
if lines and lines[-1] == "": lines.pop(-1)
output_lines = list(lines)
# Remove matching lines.
for line in lines:
if line.startswith("#"): continue # Ignore comment lines.
fields = line.split("\t")
if len(fields)>1 and fields[1] in image_filenames:
output_lines.remove(line)
# Update the log file if needed.
if output_lines != lines:
log = file(logfile(),"w")
for line in output_lines: log.write(line+"\n")
def logfile_delete_filename(image_filename):
"""Make sure that there are not duplicate entries in the
data collection logfile, in the case an image is recollected.
image_filename: basename of image filename (without directory)
"""
logfile_delete_filenames([image_filename])
current_logfile = string_table()
def logfile_set_values(column_names,image_numbers,values_list):
"""Modify multiple columns
column_names: list of strings
image_numberes: list of 1-based integers
values_list: list of lists of strings"""
current_logfile.reread(logfile())
if current_logfile.comments == "": current_logfile.comments = logfile_info()
current_logfile.set_values(column_names,array(image_numbers)-1,values_list)
current_logfile.save()
def logfile_info():
"""Comment lines for headre of logfile as
Multiline string"""
comments = ""
comments += ("Data collection log file generated by Lauecollect "+
__version__+"\n")
comments += ("Description: "+param.description+"\n")
try:
comments += ("source: U23 at %.2f mm, U27 at %.2f mm\n" %
(U23.value,U27.value))
except: pass
w = Slit1H.value
h = Slit1V.value
comments += ("white beam slits (at 28 m): %.3f mmh x %.3f mmv\n" % (w,h))
m1 = mir1Th.value
m2 = mir2Th.value
comments += ("mirrors incidence angles: %.3f mrad, %.3f mrad\n" %(m1,m2))
comments += ("high-speed chopper phase: %s\n" % time_string(timing_system.hsc.delay.value))
comments += ("sample slits: %.3f mmh x %.3f mmv" %
(shg.value,svg.value))
if sho.value != 0: comments += (", offset %+.3f mmh" % sho.value)
if svo.value != 0: comments += (", offset %+.3f mmv" % svo.value)
comments += ("\n")
comments += ("detector distance: %.1f mm\n" % DetZ.value)
comments += ("pulses per image (on,off): %d,%d\n" % (options.npulses,options.npulses_off))
s = "%.3f" % options.min_waitts[0]
for t in options.min_waitts[1:]: s += ",%.3f" % t
s += "/%.3f" % options.min_waitt_off
comments += ("min. time between pulses (on/off): %s\n" % s)
comments += ("max. time between pulses (off): %.3f s\n" %
options.max_waitt_off)
if align.enabled:
comments += ("auto align: probe depth %.3f mm\n" % align.beamsize)
else: comments += ("auto align: off\n")
comments += ("sample translation: "+sample_translation_summary()+"\n")
comments += ("syringe pump: "+pump_summary()+"\n")
if collection_variable_enabled("chopper_mode"):
comments += ("chopper: variable")
for i in range (0,len(chopper.y)):
comments += (", Y=%g mm: %g pulses, %s, min delay %s" %
(chopper.y[i],chopper.pulses[i],time_string(chopper.time[i]),
time_string(chopper.min_dt[i])))
comments += ("\n")
else: comments += ("chopper: fixed, Y=%g mm\n" % ChopY.value)
comments += ("diagnostics: %s\n" % diagnostics_summary())
comments += ("process variables: %s\n" % diagnostics_PV_summary())
comments += ("beam check: %s\n" % xray_beam_check_summary())
return comments
def tostr(x):
"""Converts a number to a string.
This is needed to handle "not a number" and infinity properly.
Under Windows, 'str()','repr()' and '%' format 'nan' as '-1.#IND' and 'inf'
as '1.#INF', which is inconsistent with Linux ('inf' and 'nan').
"""
if isinstance(x,basestring): return x
try:
if isnan(x): return "nan"
if isinf(x) and x>0: return "inf"
if isinf(x) and x<0: return "-inf"
return "%g" % x
except: return str(x)
def str_to_float_list(s):
"""Convert comma-separated text to Python list of floating point numbers."""
from numpy import arange
try: l = eval(s)
except: l = 0
if not hasattr(l,"__len__"): l = [l]
if type(l) != list: l = list(l)
for i in range(0,len(l)):
try: l[i] = float(l[i])
except: l[i] = 0.0
return l
def filename(image_number):
"""Absolute pathname of the nth image of the current dataset.
Image numbers start with 1."""
# For speedup, cache the filename for 10 s.
global filename_cache
if not "filename_cache" in globals(): filename_cache = {}
if image_number in filename_cache:
f,timestamp = filename_cache[image_number]
if time()-timestamp < 10: return f
f = __filename__(image_number)
filename_cache[image_number] = (f,time())
return f
def __filename__(image_number):
"""Absolute pathname of the nth image of the current dataset.
Image numbers start with 1."""
##if image_number > nimages(): return ""
if image_number == 0: return single_image_filename()
filename = param.path+"/xray_images/"+param.file_basename
for name in collection_variables()[::-1]:
if variable_include_in_filename(name):
value = collection_variable_value(name,image_number)
text = variable_formatted_value(name,value)
if text: filename += "_"+text
count = collection_variable_repeat_count(name,image_number)
if count>1: filename += "-"+str(count)
ext = param.extension.strip(".")
filename += "."+ext
return filename
def image_filenames(image_numbers):
"""List of image file names with directory
image_numbers: list or array of 1-based indices
"""
return [filename(i) for i in image_numbers]
def all_image_filenames():
"""List of all image file names of the current data set with directory
"""
return image_filenames(range(1,nimages()+1))
def waveform_filenames(image_numbers,name="xray"):
"""Where to store the X-ray diagnostics oscilloscope data
image_numbers: list of 1-based indices"""
filenames = []
img_filenames = image_filenames(image_numbers)
# Assuming bursts_per_image is the same for all images...
Nfiles = bursts_per_image(image_numbers[0]) if len(image_numbers) > 0 else 0
if Nfiles <= 1:
for f in img_filenames:
filename = f.replace("."+param.extension,"_"+name+".trc")
filename = filename.replace("/xray_images/","/"+name+"_traces/")
filenames.append(filename)
else:
for f in img_filenames:
for j in range(0,Nfiles):
filename = f.replace("."+param.extension,"_%02d_" % (j+1) + name+".trc")
filename = filename.replace("/xray_images/","/"+name+"_traces/")
filenames.append(filename)
return filenames
def basenames(nmax=1000):
"""List the filenames of the dataset"""
nmax = min(nmax,nimages())
return "\n".join("%4d %s"%(i,basename(filename(i))) for i in range(1,nmax+1))
def extension():
"""Ending of filename, including dot(.)"""
return "."+param.extension.strip(".")
def single_image_filename():
"""Used by "single image"
Return value: absolute pathname"""
ext = param.extension.strip(".")
i = 0
filename = "%s/xray_images/%s_%03d.%s" % \
(param.path,param.file_basename,i+1,ext)
while exists(filename):
i += 1
filename = "%s/xray_images/%s_%03d.%s" % \
(param.path,param.file_basename,i+1,ext)
return filename
def logfile():
return param.path+"/"+param.logfile_filename
def first_image_number():
"""The number of the first image that has not been collected already.
If all image are collected, return Nimages+1.
return value: 1-based index"""
filenames = all_image_filenames()
exist = exist_files(filenames) & logfile_has_entries(filenames)
if not all(exist): first_image_number = where(~exist)[0][0]+1
else: first_image_number = nimages()+1
return first_image_number
# Because of NFS attribute caching 'exists' sometimes reports files created
# by the MAR CCD server non-existing. Lising the directory contents re-
# freshes the NFS cache.
def exists2(filename):
"""Tell whether, on the local fie system, there exists a file or directory
with a given name."""
import os.path
if os.path.exists(filename): return True
try: listdir(dirname(filename)) # trigger update of NFS attribute cache
except: pass
return os.path.exists(filename)
# Replacement for Python's built-in "mkdirs" from the os.path module
def makedirs(path):
"""Replacement for Python's built-in "mkdirs" from the os module
This version of makedirs makes sure that all directories created are
world-writable. This is necessary because the MAR CC Dserver writes
from a different computer with a different user id (marccd=500) than
then user caccount on the beamline control computer (useridb=615).
"""
from os import makedirs
if not exists(path): makedirs(path)
try: chmod (path,0777)
except OSError: pass
# Data collection strategy
def variables():
"""Data collection parameter names.
List of strings."""
return ["delay","angle","laser_on","repeat","repeat2","level","translation",
"translation_mode","chopper_mode","temperature","xray_on"]
def collection_variable_order():
"""List of variable names, starting with the fastest variable to the slowest
variable"""
return options.collection_order
def collection_variable_set_order(order):
# Perform sanity check
for i in range(0,len(order)):
for name in order[i]:
if name not in variables(): order[i].remove(name)
while [] in order: order.remove([])
old_order = options.collection_order
options.collection_order = order
# Keep filename in sync
old_names = flatten(old_order)
new_names = flatten(order)
added = [name for name in new_names if not name in old_names]
removed = [name for name in old_names if not name in new_names]
for name in removed:
if name in options.variable_include_in_filename:
options.variable_include_in_filename.remove(name)
for name in added:
if name not in options.variable_include_in_filename:
options.variable_include_in_filename.append(name)
def collection_variables():
"""Which variabled change during the data collection?
Return value: list of strings
Order: Fast, medium, slow"""
variable_names = flatten(collection_variable_order())
##variable_names = [name for name in variable_names if variable_nchoices(name) > 1]
return variable_names
def collection_variable_enabled(name):
"""Is this variable used during data collection?"""
return name in collection_variables()
def collection_variable_set_enabled(name,value):
"""Turn off on on the usage of this variable used during data collection.
value: False or True"""
if value: collection_variable_enable(name)
else: collection_variable_disable(name)
def collection_variable_enable(name):
"""Use this variable during data collection.
By default, this will be the slowest changing variable."""
if name in variables():
if not collection_variable_enabled(name):
order = collection_variable_order()+[[name]]
collection_variable_set_order(order)
def collection_variable_disable(name):
"""Do not use this variable during data collection."""
groups = collection_variable_order()
for i in range(0,len(groups)):
if name in groups[i]: groups[i].remove(name)
while [] in groups: groups.remove([])
collection_variable_set_order(groups)
def flatten(l):
"""Make a simple list out of list of lists"""
try: return [item for sublist in l for item in sublist]
except: return l
def variable_nchoices(name):
"""Number of choices for a data collection parameter
name: data collection parameter:
"delay","angle","laser_on","repeat","level","translation"
"""
if name == "angle": nchoices = nangles()
elif name == "delay": nchoices = len(variable_choices(name))
elif name == "laser_on": nchoices = len(variable_choices(name))
elif name == "repeat": nchoices = options.npasses
elif name == "repeat2": nchoices = options.npasses2
elif name == "level": nchoices = len(variable_choices(name))
elif name == "translation": nchoices = translation_after_image_nspots()
elif name == "translation_mode": nchoices = ntimepoints()
elif name == "chopper_mode":
nchoices = ntimepoints() if len(chopper.modes) == 0 else len(chopper.modes)
elif name == "temperature": nchoices = len(variable_choices(name))
elif name == "xray_on": nchoices = len(options.xray_on)
else: len(variable_choices(name))
nchoices = max(nchoices,1)
return nchoices
def variable_choice(name,i):
"""ith of the possible n values for a data collection parameter
name: data collection parameter:
"delay","angle","laser_on","repeat","level","translation"
i: 0-based integer
Return value: real number
"""
if name == "angle": choice = angle_of_orientation(i)
elif name == "delay": choice = variable_choices(name)[i]
elif name == "laser_on": choice = variable_choices(name)[i]
elif name == "repeat": choice = i
elif name == "repeat2": choice = i
elif name == "level": choice = variable_choices(name)[i]
elif name == "translation":
nspots = translation_after_image_nspots()
m = translate.after_image_interleave_factor
i = interleaved_order(i,m,nspots)
z = min(sample.zs) + i*translation_after_image_zstep()
choice = z
elif name == "translation_mode":
# Avoid mode changes for reference images.
while i<ntimepoints()-1 and timepoints()[i] == param.ref_timepoint: i+=1
choice = Ensemble_SAXS.mode_of_delay(timepoints()[i])
elif name == "chopper_mode":
if len(chopper.modes) == 0:
choice = chopper_mode_of_timepoint_number(i)
else:
if not i < len(chopper.modes): i = len(chopper.modes)-1
return chopper.modes[i]
elif name == "temperature": choice = variable_choices(name)[i]
elif name == "xray_on":
choice = options.xray_on[i] if i<len(options.xray_on) else True
else: choice = variable_choices(name)[i]
return choice
def variable_choices(name):
"""All possible values for a data collection parameter
name: data collection parameter:
"delay","angle","laser_on","repeat","level","translation"
Return value: list of real number"""
if name == "angle": choices = angle_choices()
elif name == "delay":
choices = options.variable_choices[name] if name in options.variable_choices else []
elif name == "laser_on":
choices = options.variable_choices[name] if name in options.variable_choices else []
elif name == "repeat": choices = range(0,options.npasses)
elif name == "repeat2": choices = range(0,options.npasses2)
elif name == "level":
choices = options.variable_choices[name] if name in options.variable_choices else []
elif name == "temperature":
choices = options.variable_choices[name] if name in options.variable_choices else []
elif name == "translation_mode":
choices = [Ensemble_SAXS.mode_of_delay(t) for t in timepoints()]
elif name == "chopper_mode":
if len(chopper.modes) == 0:
choices = [chopper_mode_of_timepoint_number(i) \
for i in range(0,ntimepoints())]
else: choices = chopper.modes
elif name == "xray_on": choices = options.xray_on
else:
choices = options.variable_choices[name] if name in options.variable_choices else []
if len(choices) == 0: choices = [variable_value(name)]
return choices
def variable_set_choices(name,values):
"""Set all possible values for a data collection parameter
values: list of values"""
options.variable_choices[name] = values
def variable_choice_repeat_count(name):
"""If there are duplicate values in the choices,
a unique integer count for each"""
# For speedup, cache the filename for 10 s.
global cache
if not "cache" in globals(): cache = {}
if ("variable_choice_repeat_count",name) in cache:
x,timestamp = cache["variable_choice_repeat_count",name]
if time()-timestamp < 10: return x
x = __variable_choice_repeat_count__(name)
cache["variable_choice_repeat_count",name] = (x,time())
return x
def __variable_choice_repeat_count__(name):
"""If there are duplicate values in the choices,
a unique integer count for each"""
values = variable_choices(name)
return [values[0:i+1].count(values[i]) for i in range(0,len(values))]
def variable_value(name):
"""Data collection parameter as currently read
name: data collection parameter:
"delay","angle","laser_on","repeat","level","translation"
"""
if name == "angle": return Spindle.command_value
if name == "delay":
if "linear stage" in translate.mode: return Ensemble_SAXS.delay
else: return timing_sequencer.delay
if name == "laser_on":
if "linear stage" in translate.mode: return Ensemble_SAXS.laser_on
else: return timing_sequencer.laser_on
if name == "repeat": return 1
if name == "repeat2": return 1
if name == "level": return trans.value
if name == "translation": return diffractometer.zc
if name == "translation_mode": return Ensemble_SAXS.mode
if name == "chopper_mode": return chopper_mode_current()
if name == "temperature":
try: return temperature_controller.value
except AttributeError: return nan
if name == "xray_on":
if "linear stage" in translate.mode: return Ensemble_SAXS.ms_on
else: return timing_sequencer.ms_on
return nan
def variable_set_value(name,value):
"""Change the data collection parameter (in hardware)
name: data collection parameter:
"delay","angle","laser_on","repeat","level","translation"
value: real number"""
if name == "angle": Spindle.command_value = value
if name == "delay":
if "linear stage" in translate.mode: Ensemble_SAXS.delay = value
else: timing_sequencer.delay = value
if name == "laser_on":
if "linear stage" in translate.mode: Ensemble_SAXS.laser_on = value
else: timing_sequencer.laser_on = value
if name == "repeat": pass
if name == "repeat2": pass
if name == "level": trans.value = value
if name == "translation": diffractometer.z = value
if name == "translation_mode":
if value != Ensemble_SAXS.mode: Ensemble_SAXS.mode = value
if name == "chopper_mode":
if value != chopper_mode_current(): set_chopper_mode(value,wait=False)
if name == "temperature":
# Only update set point if needed.
if value != temperature_controller.command_value:
progress("temperature: set point %.3fC -> %.3fC"
% (temperature_controller.command_value,value))
temperature_controller.command_value = value
global temperature_controller_last_update
temperature_controller_last_update = time()
if name == "xray_on":
if "linear stage" in translate.mode: Ensemble_SAXS.ms_on = value
else: timing_sequencer.ms_on = value
temperature_controller_last_update = 0
temperature_controller_last_instable = 0
def variable_changing(name):
"""Is a motors currenly moving?
name: data collection parameter:
"delay","angle","laser_on","repeat","level","translation"
value: real number
"""
if name == "angle": return diffractometer.Phi.moving
if name == "delay": return False
if name == "laser_on": return False
if name == "repeat": return False
if name == "repeat2": return False
if name == "level": return trans.moving
if name == "translation": return diffractometer.Z.moving
if name == "translation_mode": return False
if name == "chopper_mode": return chopper.wait and chopper_moving()
if name == "temperature":
# Work-around for slow "stable" PV update issue.
if time() - temperature_controller_last_update < 2.0: return True
instable = temperature_controller.moving
global temperature_controller_last_instable
if instable: temperature_controller_last_instable = time()
settling = time()-temperature_controller_last_instable < temp.settling_time
return settling
if name == "xray_on": return False
return False
def variable_wait(name):
"""Suspend data collection when changing this variable?"""
##if variable_hardware_triggered(name): return False
wait = options.variable_wait[name] if name in options.variable_wait else True
return wait
def variable_set_wait(name,value):
"""Suspend data collection when changing this variable?
value: True of False"""
options.variable_wait[name] = bool(value)
def variable_hardware_triggered(name):
"""Can this variable be changed in hardware-triggred mode?"""
if name == "angle": return False
if name == "delay": return True
if name == "laser_on": return True
if name == "repeat": return True
if name == "repeat2": return True
if name == "level": return False
if name == "translation": return translate.hardware_triggered
if name == "translation_mode": return True
if name == "chopper_mode": return not chopper.wait
if name == "temperature": return temp.hardware_triggered
if name == "xray_on": return True
return False
def variable_formatted_value(name,value):
"""Data collection variable as formatted string"""
if name == "angle": return "%.3f%s" % (value,Spindle.unit)
if name == "delay": return time_string(value)
if name == "laser_on": return "on" if value else "off"
if name == "repeat": return "%d" % (value+1)
if name == "repeat2": return "%d" % (value+1)
if name == "translation": return "%.3fmm" % value
if name == "translation_mode": return value
if name == "chopper_mode": return "%gpulses" % chopper_pulses_of_mode(value)
if name == "level": return "%.4f" % value
if name == "temperature": return ("%.3f" % value).rstrip("0").rstrip(".")+"C"
if name == "xray_on": return "xray" if value else "bkg"
return str(value)
def variable_unit(name):
"""Unit symbol for a collection variable"""
if name == "angle": return "deg"
if name == "delay": return "s"
if name == "laser_on": return ""
if name == "repeat": return ""
if name == "repeat2": return ""
if name == "translation": return "mm"
if name == "level": return ""
if name == "temperature": return "C"
if name == "xray_on": return ""
return ""
def variable_include_in_filename(name):
return name in options.variable_include_in_filename;
def set_collection_variables(image_number,wait=False):
"""Set all collection variables
image_number: 1-based index
wait=True: only return after motor move has completed"""
names = collection_variables()
names = [name for name in names
if not (variable_hardware_triggered(name) and not variable_wait(name))]
if not wait: names = [name for name in names if not variable_wait(name)]
for name in names:
variable_set_value(name,collection_variable_value(name,image_number))
if wait:
names = [name for name in names if variable_wait(name)]
variables_wait(names)
def set_collection_variable(name,image_number,wait=False):
"""name: one of 'collection_variables()'
image_number: 1-based index
wait=True: only return after motor move has completed"""
variable_set_value(name,collection_variable_value(name,image_number))
if wait:
while variable_changing(name) and not task.cancelled:
value = variable_value(name)
progress(name+": "+variable_formatted_value(name,value))
sleep(0.1)
def variables_wait(names=None):
"""Wait for all motors to complete moving"""
if names is None: names = collection_variables()
changing = [variable_changing(name) for name in names]
while any(changing) and not task.cancelled:
t = []
for i in range(0,len(names)):
if changing[i]:
value = variable_value(names[i])
t += [names[i]+": "+variable_formatted_value(names[i],value)]
t = ",".join(t)
progress(t)
sleep(0.1)
changing = [variable_changing(name) for name in names]
def collection_variables_changing():
"""Is any motor currently moving"""
for name in collection_variables():
if variable_changing(name): return True
return False
collection_starting_values = {}
def collection_variables_start_dataset():
"""Set all collection variables"""
global collection_starting_values
names = [n for n in collection_variables() if variable_return(n)]
collection_starting_values = dict([(n,variable_value(n)) for n in names])
##motors = [variable_motor(n) for n in names]
##generate_autorecovery_restore_point("Data Collection",motor)
image_number = first_image_number()
for name in names: set_collection_variable(name,image_number,wait=False)
variables_wait(names)
def variable_return(name):
"""Restore this motor to its oroingal position afte data collection
finishes?"""
if name in options.variable_return: value = options.variable_return[name]
else: value = False
return value
def variable_set_return(name,value):
"""Restore this motor to its oroingal position afte data collection
finishes?
value: True or False"""
options.variable_return[name] = value
def collection_variables_finish_dataset():
"""Set all collection variables"""
names = [name for name in collection_variables() if variable_return(name)]
for name in names:
value = collection_variable_return_value(name)
if not isnan(value): variable_set_value(name,value)
##variables_wait(names)
def collection_variable_return_value(name):
if name in options.variable_return_value:
value = options.variable_return_value[name]
elif name in collection_starting_values:
value = collection_starting_values[name]
else: value = variable_value(name)
return value
def collection_variable_set_return_value(name,value):
if not isnan(value): options.variable_return_value[name] = value
else: del options.variable_return_value[name]
def collection_variable_return_to_starting_value(name):
return name not in options.variable_return_value
def collection_variable_set_return_to_starting_value(name,value):
if value:
if name in options.variable_return_value:
del options.variable_return_value[name]
else: options.variable_return_value[name] = variable_value(name)
def nimages():
"""Total number of image in the data set"""
counts = variable_counts()
max_counts = [max(x) for x in counts]
from numpy import product
ntotal = product(max_counts)
return ntotal
def nimages_to_collect():
"""At which number of images to end data collection if "Finish Time Series"
is requested"""
if not task.finish_series: return nimages()
period = collection_variable_period(options.finish_series_variable)
n = int(round_up(task.image_number,period))
return n
def variable_values(image_number):
"""image_number: 1-based integer
Return value: nested list of real numbers"""
indices = variable_indices(image_number)
values = []
for name_list,index_list in zip(collection_variable_order(),indices):
values += [[]]
for name,index in zip(name_list,index_list):
values[-1] += [variable_choice(name,index)]
return values
def collection_variable_value(name,image_number):
"""What is the value of a data collection parameter for a given image.
image_number: 1-based integer
name: data collection parameter:
"delay","angle","laser_on","repeat","level","translation"
Return value: real numbers"""
i = collection_variable_index(name,image_number)
return variable_choice(name,i)
def collection_variable_repeat_count(name,image_number):
"""What is the value of a data collection parameter for a given image.
image_number: 1-based integer
name: data collection parameter:
"delay","angle","laser_on","repeat","level","translation"
Return value: real numbers"""
if name == "repeat": return 1
i = collection_variable_index(name,image_number)
counts = variable_choice_repeat_count(name)
count = counts[i] if i < len(counts) else 1
return count
def collection_variable_values(name):
"""List of the values for a data collection parameter for
the entrire dataset
name: data collection parameter"""
return [collection_variable_value(name,i) for i in range(1,nimages()+1)]
def variable_constant_range(name,starting_image_number):
"""Number of images that will be collected without changing the
parameter given be 'name', starting from the image given by
'starting_image_number'
name: data collection parameter
starting_image_number: 1-based integer"""
value = collection_variable_value(name,starting_image_number)
for i in range(starting_image_number,nimages()+1):
if collection_variable_value(name,i) != value: return i-starting_image_number
return nimages()+1 - starting_image_number
def collection_passes(starting_image_number=1,npasses=inf):
"""Break up the datea dataset into passes that can be collected using
hardware trigger
starting_image_number: 1-based index
return value: list of lists of image numbers"""
# Not hardware-triggerd collection parameters.
wait_vars = [var for var in collection_variables()
if variable_wait(var)]
passes = []
i = starting_image_number
while i <= nimages_to_collect() and len(passes) < npasses:
# Group the images into block that can be collected in one pass using
# hardware trigger.
if len(wait_vars) > 0:
n = min([variable_constant_range(var,i) for var in wait_vars])
else: n = nimages()-(i-1)
# Create a break to perform an X-Ray beam check.
n = min(n,xray_beam_check_after(i)-(i-1))
image_numbers = array(range(i,i+n))
##filenames = [filename(j) for j in image_numbers]
filenames = image_filenames(image_numbers)
progress("looking for existing images files...")
exist = exist_files(filenames) & logfile_has_entries(filenames)
progress("looking for existing images files done.")
image_numbers = image_numbers[~exist]
if len(image_numbers) > 0: passes += [image_numbers]
i += n
if n == 0: break
return passes
def collection_pass(starting_image_number):
"""The series of images that can be collected using hardware trigger,
starting_image_number: 1-based index"""
passes = collection_passes(starting_image_number,npasses=1)
if len(passes) == 0: return []
return passes[0]
def variable_counts():
"""The number of values for each variable.
Return value: nested list if integers"""
counts = []
for name_list in collection_variable_order():
counts += [[]]
for name in name_list: counts[-1] += [variable_nchoices(name)]
return counts
def variable_indices(image_number):
"""image_number: 1-based integer
Return value: nested list of integers"""
image_number -= 1# convert to 0-baed integer
counts = []
for name_list in collection_variable_order():
counts += [[]]
for name in name_list: counts[-1] += [variable_nchoices(name)]
max_counts = [max(x) for x in counts]
max_indices = []
for n in max_counts:
max_indices += [image_number % n]
image_number /= n
indices = []
for max_index,count_list in zip(max_indices,counts):
indices += [[]]
for count in count_list: indices[-1] += [max_index % count]
return indices
def collection_variable_period(name):
"""Every how many images t ohte values of this variable repeat?
name: data collection parameter, e.g. "delay" """
n = 1
for name_list in collection_variable_order():
n *= max([variable_nchoices(n) for n in name_list])
if name in name_list: break
return n
def collection_variable_index(name,image_number):
"""For a given image, the value of the data collection is the nth
of the choices for the values of this parameter.
image_number: 1-based integer
name: data collection parameter:
"delay","angle","laser_on","repeat","level","translation"
Return value: 0-based integer"""
indices = variable_indices(image_number)
values = []
for name_list,index_list in zip(collection_variable_order(),indices):
values += [[]]
for n,i in zip(name_list,index_list):
if name == n: return i
return 0
def linear_ranges(values):
"""Break of list of values into lists where the value changes linearly"""
ranges = []
def close(x,y): return abs(y-x) < 1e-6
for i in range(0,len(values)):
is_linear_before = i >= 2 and \
close(values[i]-values[i-1],values[i-1]-values[i-2])
is_linear_after = 1 <= i <= len(values)-2 and \
close(values[i]-values[i-1],values[i+1]-values[i])
if is_linear_before or \
(len(ranges) > 0 and len(ranges[-1]) == 1 and is_linear_after):
ranges[-1] += [values[i]]
else: ranges += [[values[i]]]
return ranges
def list_to_string(values):
"""Format a list of values, using shortcuts.
[20,21,22,23,24,25] -> '20 to 25 in steps of 1'"""
ranges = linear_ranges(values)
parts = []
for r in ranges:
if len(r) == 1: part = "%g" % r[0]
else:
begin,end,step = r[0],r[-1],r[1]-r[0]
if step != 0: part = "%g,%g..%g" % (begin,begin+step,end)
else: part = "%g(x%d)" % (r[0],len(r))
parts += [part]
text = ",".join(parts)
return text
def string_to_list(text):
"""Convert a string to a list of numbers, interpresting shortcuts
'20 to 25 in steps of 1' -> [20,21,22,23,24,25]"""
from parse import parse
from numpy import arange,sign
text = text.replace("\n","")
parts = text.split(",")
values = []
for part in parts:
part = part.replace(" ","")
if ".." in part and "step" in part:
if parse("{:g}..{:g}step{:g}",part):
begin,end,step = parse("{:g}..{:g}step{:g}",part)
dir = sign(end-begin)
step = dir*abs(step)
if step != 0: values += list(arange(begin,end+step/2,step))
else: values += [begin]
if ".." in part:
if parse("{:g}..{:g}",part):
begin,end = parse("{:g}..{:g}",part)
if len(values) > 0: step = begin-values[-1]
else: step = 1
dir = sign(end-begin)
step = dir*abs(step)
if step != 0: values += list(arange(begin,end+step/2,step))
else: values += [begin]
elif "(x" in part:
if parse("{:g}(x{:d})",part):
value,n = parse("{:g}(x{:d})",part)
values += [value]*n
else:
try: values += [float(eval(part))]
except Exception,msg: warn("%r: %r" % (part,msg))
return values
def nimages_per_timeseries():
"""Number of images before the timepoints repeat"""
return nimages_per_timepoint()*ntimepoints()
def nimages_per_orientation():
"""Number of images before the sample is rotated"""
# TO DO
if nangles() == 1: return nimages()
return nimages_per_orientation_()
def nimages_per_orientation_():
"""Number of images before the sample is rotated"""
# TO DO
return nimages_per_timeseries()*nlevels_used()
def nimages_per_pass():
"""Number of images per if the number of passes (repeats) is set to 1"""
return nimages_per_orientation_()*nangles()
def passno(image_number):
"""To which pass belongs the image number?
image_number: 1-based index
Return value: 1-based index"""
n = nimages_per_pass()
return (image_number-1)/n + 1
def angle(image_number):
"""Goniometer spindle setting; image_number is 1-based"""
return collection_variable_value("angle",image_number)
def orientation_number(image_number):
"""Sequence number for spindle angles, same as series number.
image_number: 1-based index
Return value: 1-based index"""
return collection_variable_index("angle",image_number)+1
def nangles():
"""Number of spindle orientation in the entire data set"""
if param.amode == "User-defined list": return max(len(param.alist),1)
if param.amax == param.amin: return 1
if param.astep == 0: return 1
na = abs(param.amax-param.amin)/param.astep
return int(round(na))+1
def angle_choices():
"""All goniometer angles to use during the data collection"""
return [angle_of_orientation(i) for i in range(0,nangles())]
def angle_of_orientation(j):
"""Goniometer spindle setting; orientation_number j is 0-based"""
# If no rotation range is 0, do not rotate at all.
n = nangles()
da = abs(param.astep)*sign(param.amax-param.amin)
if param.amode == "Single pass":
if param.amin == param.amax: return Spindle.value
return param.amin + j*da
elif param.amode == "Two interlaced passes":
if param.amin == param.amax: return Spindle.value
j = j*2
if j>n: j=n-(j-n)
return param.amin + j*da
elif param.amode == "Filling gaps":
if param.amin == param.amax: return Spindle.value
# Use gap-filling scheme based on the 'golden ratio'.
# At any given time duiring the data collection the ratio between the
# largest and smallest gap is 1:0.6180.
phi = (sqrt(5)-1)/2
return param.amin + (j*phi % 1)*(param.amax-param.amin)
elif param.amode == "User-defined list":
if len(param.alist) == 0: return Spindle.value
return param.alist[j % len(param.alist)]
else: return Spindle.value
def timepoints():
"""List of time points"""
if not laser_enabled(): return [nan]
return variable_choices("delay")
def ntimepoints():
"""Number of time points"""
if not laser_enabled(): return 1
return variable_nchoices("delay")
def next_delay(t):
"""Next possible pump-probe delay to the given value"""
if "linear stage" in translate.mode: t = Ensemble_SAXS.next_delay(t)
return t
def next_delays(t):
"""Next possible pump-probe delay to the given value
t: list of time delays in seconds"""
tn = [next_delay(ti) for ti in t]
T = tn[0:1]
for i in range(1,len(t)):
if t[i] == t[i-1] or tn[i] != tn[i-1]: T += [tn[i]]
return T
def nimages_per_timepoint():
"""Number of images acquired for each timpoint
on = 1, off/on = 2, off/on/off = 3"""
return variable_nchoices("laser_on")
def laser_on_nchoices():
"""How many laser modes (on/off) to use?"""
return len(variable_choices("laser_on"))
def laser_on_choices():
"""List of booleans"""
return variable_choices("laser_on")
def laser_mode_on(image_number):
"""Is the laser to be fired for this image?
When using laser mode 'off/on', or 'off/on/off'
image_number: 1-based index
return value: true or false"""
return collection_variable_value("laser_on",image_number)
def laser_on(image_number):
"""Is the laser to be fired for this image?
image_number: is 1-based integer
Return value: True or False"""
if not laser_mode_on(image_number): return False
if isnan(timepoint(image_number)): return False
if collection_variable_value("level",image_number) == 0: return False
return True
def laser_enabled():
"""Use the laser during data acqisition?
True or False"""
if len(variable_choices("laser_on")) == 0: use = False
elif len(variable_choices("laser_on")) == 1 and variable_choices("laser_on")[0] == False: use = False
else: use = True
return use
def timepoint(image_number):
"""Laser to X-ray pump-probe delay.
image_number: is 1-based integer
Returns time in seconds, None for laser off image"""
return collection_variable_value("delay",image_number)
def delay(image_number):
"""Laser to X-ray pump-proble delay for a given image number.
Image number start with 1. delay = 0 for a laser off image."""
# If the image does not require the laser firing, set time timing
# for the followong image
i = image_number
i0 = i
while timepoint(i) is None and i<i0+4 and i<nimages(): i += 1
t = timepoint(i)
if t is None: t= nan
return t
def timepoint_number(image_number):
"""Which pump-probe delay to use for this image number?
image_number: 1-based index
Return value: 0-based index"""
return collection_variable_index("delay",image_number)
def orientation_image_number(image_number=0):
"""How many images into a time series is this image number?
image_number: 1-based index
Return value: 0-based index"""
# TO DO
return (image_number-1) % nimages_per_orientation_()
def nlevels_used():
"""In case a variable attenuator is used, number of laser energy levels"""
if not collection_variable_enabled("level"): return 1
return variable_nchoices("level")
def wait_time(image_number):
"""Waiting time between pulses for a given image number"""
t = timepoint(image_number)
# If the image is an "off" image and the waiting time for the off images
# is specified to be different from the on images, always use this
# value.
if isnan(t) and options.min_waitt_off != options.min_waitts[0]:
return options.min_waitt_off
# For "off" images, it is possible to specify a maximum waiting time.
if isnan(t): maxwt = options.max_waitt_off
else: maxwt = inf
# If the image is an "off" image, use the waitting time for the next
# timepoint. If the are two off images following each other
# the first is for the preceeding time point, the second for the
# following time point.
if isnan(t): t = timepoint(image_number+1)
if isnan(t): t = timepoint(image_number-1)
wt = wait_time_for_delay(t)
wt = min(wt,maxwt)
return wt
def wait_time_for_delay(t):
"""Waiting time between pulses as function of pump-probe delay
t: pump-probe delay in seconds"""
if isnan(t): return options.min_waitt_off
# Leave an 15-ms margin after the probe pulse for sample translation.
##dt = translate.move_time if "linear stage" in translate.mode else 0
dt = 0
wt = round_up(t+dt,timing_system.waitt.stepsize)
# Find the smallest specified waitting time that is large than the current.
options.min_waitts.sort()
for t in options.min_waitts:
if t >= wt: wt = t ; break
return wt
def timepoint_repeat_number(image_number):
"""How many times has the time point of the image been repeated in the
current time series?
image_number: 1-based index"""
t = collection_variable_value("delay",image_number)
it = collection_variable_index("delay",image_number)
ts = variable_choices("delay")[0:it]
return ts.count(t)
def timepoint_repeat_per_series(image_number):
"""Tell how many times does a timepoint occur per time series
image_number: 1-based index"""
t = collection_variable_value("delay",image_number)
ts = variable_choices("delay")
return ts.count(t)
def npulses(image_number,passno=0):
"""How many X-ray bursts to send to the sample as function of image
number. image_number is 1-based, passno is 0-based.
"""
# When using sample translation the exposure may be boken up
# into several passes.
if passno != None: npulses = npulses_of_pass(image_number,passno)
else:
# Methods-based data collection
mode = SAXS_WAXS_methods.Ensemble_mode.value
burst_length = Ensemble_SAXS.burst_length_of_mode(mode)
passes = SAXS_WAXS_methods.passes_per_image.value
npulses = burst_length*passes
return npulses
def ms_shutter_opening_time(image_number,passno=None):
"""Tell the ms shutter opening time is seconds"""
wt = wait_time(image_number)
# If running slower than 82 Hz, operate the shutter in pulsed mode.
# (minimum opening time).
if wt > timing_system.hlct: return 0
# If operating at 82 Hz, the opening time is determined by the number
# of pulses per image or per pass.
np = npulses(image_number,passno)
t = np*wt
return t
def ms_shutter_mode(image_number):
""" "pulsed" or "timed".
At maximum reption rate the shutter no longer isolates single pulses
but gates the X-ray exposure time."""
wt = wait_time(image_number)
# If running slower than 82 Hz, operate the shutter in pulsed mode.
# (minimum opening time).
if wt > timing_system.hlct: return "pulsed"
else: return "timed"
def set_chopper(image_number=None):
""" This sets the chopper operating offset aproprialy for the bunch mode
of the given image number."""
if not collection_variable_enabled("chopper_mode"): return
if image_number == None: image_number = task.image_number
set_chopper_mode(collection_variable_value("chopper_mode",image_number))
def set_chopper_mode(chopper_mode,wait=True):
"""chopper_mode: 0-base index, row of table of chopper settings"""
x = chopper.x[int(chopper_mode)]
y = chopper.y[int(chopper_mode)]
phase = chopper.phase[int(chopper_mode)]
if wait: set_chopper_parameters(x,y,phase)
else: set_chopper_parameters_nowait(x,y,phase)
def set_chopper_parameters(x,y,phase):
"""phase: in units of seconds"""
old_y = ChopY.value
old_phase = timing_system.hsc.delay.value
phase_change_time = time()
ChopX.value = x
ChopY.value = y
timing_system.hsc.delay.value = phase
while (ChopX.moving or ChopY.moving) and not task.cancelled: sleep(0.1)
# When moving the chopper vertically, it can excite an oscillation in
# the magnetic bearing. Wait for 5 s for the oscillation to subside.
settling_time = 5.0
if abs(ChopY.value - y) > 0.001:
t = time()
while time()-t < settling_time and not task.cancelled: sleep(0.1)
# When changing the high-speed chopper phase, there is a slew rate and
# a settling time.
slew_rate = 100e-9 # 100 ns per second
settling_time = 10.0
waiting_time = abs(timing_system.hsc.delay.value-old_phase)/slew_rate + settling_time
if abs(timing_system.hsc.delay.value - old_phase) > 1e-9:
while time()-phase_change_time < waiting_time and not task.cancelled:
sleep(0.1)
if task.cancelled: ChopX.stop(); ChopY.stop()
chopper_old_y,chopper_old_phase = nan,nan
chopper_change_time = 0
def set_chopper_parameters_nowait(x,y,phase):
"""phase: in units of seconds"""
global chopper_old_y,chopper_old_phase,chopper_change_time
chopper_old_y,chopper_old_phase = ChopY.value,timing_system.hsc.delay.value
chopper_change_time = time()
ChopX.value = x
ChopY.value = y
timing_system.hsc.delay.value = phase
def chopper_moving():
"""Hase th echoppre not yet settled?"""
while (ChopX.moving or ChopY.moving): return True
# When moving the chopper vertically, it can excite an oscillation in
# the magnetic bearing. Wait for 5 s for the oscillation to subside.
settling_time = 5.0
if abs(chopper_old_y - ChopY.value) > 0.001:
if time()-chopper_change_time < settling_time: return True
# When changing the high-speed chopper phase, there is a slew rate and
# a settling time.
slew_rate = 100e-9 # 100 ns per second
settling_time = 10.0
waiting_time = abs(timing_system.hsc.delay.value-chopper_old_phase)/slew_rate + settling_time
if abs(timing_system.hsc.delay.value - chopper_old_phase) > 1e-9:
if time()-chopper_change_time < waiting_time: return True
return False
def set_chopper_y(chopy):
"""This sets the chopper operating offset."""
if abs(ChopY.value - chopy) < 0.001: return
ChopY.value = chopy
while ChopY.moving and not task.cancelled: sleep(0.1)
# After the chopper reached the final position, wiat for 5 s for the
# magnetic bearing to settle.
t = time()
while time()-t < 5.0 and not task.cancelled: sleep(0.1)
if task.cancelled: ChopY.stop()
def chopper_mode(image_number):
"""0-based index to look up chopper.x, chopper.y, chopper.phase
image_number: 1-based integer"""
return collection_variable_value("chopper_mode",image_number)
def chopper_pulses(image_number=None):
"""How many single pulses the chopper transmits per opening,
or in hybrid mode, how many single bunches the tranmitted intensity
corresponds to, for a given image number.
If the image number is omitted, return the current value.
image_number: 1-based integer"""
if image_number == None: return chopper_pulses_current()
if not collection_variable_enabled("chopper_mode"): return chopper_pulses_current()
mode_number = collection_variable_value("chopper_mode",image_number)
n = chopper.pulses[int(mode_number)] if not isnan(mode_number) else nan
return n
def chopper_pulses_of_mode(i):
"""How many single pulses the chopper transmits per opening,
or in hybrid mode, how many single bunches the tranmitted intensity
corresponds to, based on the current settings of the chopper.
i: 0-based integer"""
if isnan(i) or i<0 or i>=len(chopper.pulses): return nan
return chopper.pulses[int(i)]
def chopper_pulses_current():
"""How many single pulses the chopper transmits per opening,
or in hybrid mode, how many single bunches the tranmitted intensity
corresponds to, based on the current settings of the chopper."""
i = chopper_mode_current()
if isnan(i) or i<0 or i>=len(chopper.pulses): return nan
return chopper.pulses[int(i)]
def chopper_mode_of_timepoint_number(i):
"""0-based index to look up chopper.x, chopper.y, chopper.phase
for the given laser to X-ray time delay in seconds.
The criteria for selection the operation mode are the following:
1. The opening with the highest possible transmission should be used
2. The chopper opening time should not exceed 1/2.5 of the pump probe time
delay.
i: 0-based timepoint index (range: 0 to ntimepoints()-1)
"""
# Avoid mode changes for reference images.
while i<ntimepoints()-1 and timepoints()[i] == param.ref_timepoint: i+=1
mode = chopper_mode_of_timepoint(timepoints()[i])
return mode
def chopper_mode_of_timepoint(t):
"""0-based index to look up chopper.x, chopper.y, chopper.phase
for the given laser to X-ray time delay in seconds.
The criteria for selection the operation mode are the following:
1. The opening with the highest possible transmission should be used
2. The chopper opening time should not exceed 1/2.5 of the pump probe time
delay.
"""
from numpy import array,where,nanmax,nanargmax
if isnan(t) or isnan(t): return chopper_mode_max()
usable = (array(chopper.min_dt) <= t) & (array(chopper.use) == 1)
npulses = nanmax(array(chopper.pulses)[usable])
i = where((array(chopper.pulses) == npulses) & (array(chopper.use) == 1))[0]
i = i[0]
return i
def chopper_mode_current():
"""0-based index to look up chopper.x, chopper.y, chopper.phase.
Based on current x and y position.
Return nan if too far from any known position.
"""
from numpy import nanmin,nanargmin,array,sqrt,nan
n = min(len(chopper.x),len(chopper.y))
dx = array(chopper.x[0:n])-ChopX.value
dy = array(chopper.y[0:n])-ChopY.value
dt = array(chopper.phase[0:n])-timing_system.hsc.delay.value
rmsd = sqrt(((dx/0.1)**2+(dy/0.1)**2+(dt/10e-9)**2)/3)
if not nanmin(rmsd) <= 1: return nan
return nanargmin(rmsd)
def chopper_mode_max():
"0-based index. In which chopper mode do you get the maximum intensity?"
from numpy import array,nanargmax
return nanargmax(array(chopper.pulses)*array(chopper.use))
def time_remaining():
"Estimates the time in seconds to complete the current dataset"
t = 0.0
for i in range (task.image_number,nimages()): t += acquisition_time(i)
return t
def time_info():
"Informational message about collection time"
t = time_remaining()
if t: return time_string(t)
else: return ""
def acquisition_time(image_number):
i = image_number
readout_time = 2.5 # X-ray detector readout time
overhead = 2.0 # writing log file etc.
t = alignment_time(i) + integration_time(i)
# CCD readout can be concurrent with everything except integration.
t += max(rotation_time(i)+overhead,readout_time)
return t
def rotation_time(image_number):
i = image_number
da = abs(angle(i) - angle(i-1))
rotation_speed = 30.0 # deg/s
return da/rotation_speed
def alignment_time(image_number):
"Estimated time spend on sample alignment scans"
i = image_number
da = abs(angle(i) - angle(i-1))
if align.enabled and da > 0:
scan_points = round(abs((align.end-align.start)/align.step))+1
# bin factor chgange: 2 x 1.9 s
# 1.9 s readout time, 0.7 s for moving, 5 s processing time
# Epirically found 2.6 s per scan point + 16 s overhead
return scan_points * (1.9 + 0.7) + 16.0
else: return 0
def integration_time(image_number):
"Estimated time spend accumulating data in the X-ray detector"
i = image_number
t = timepoint(i)
if isnan(t): t = 0
wt = wait_time(i)
integration_time = (0.5+npulses(i)-1)*wt+t
# time lost due to top-ups: 50 top-ups per hour, 5 s pre top-up
# + 1 s safty margin + 1 waiting time lost per top up
usable_fraction = 1 - 50*(5.0+1.0+wt) / 3600
integration_time *= 1/usable_fraction
return integration_time
def sign(x):
"1 for a positive number, -1 for a negative number, 0 for zero"
if x>0: return 1
if x<0: return -1
return 0
def update_bkg_image():
"""Update the backgound image if needed, for instance after the server has
been restarted or after the bin factor has been changed.
"""
if options.xray_detector_enabled:
if ccd.bkg_valid(): return
##sleep(2.5) # needed for the clearing of the CCD chip
ccd.read_bkg()
def xray_safety_shutters():
"""Tell the status of 'Remote Shutter' (in beamline frontend).
Return 'open' or 'closed'"""
state = caget("PA:14ID:STA_A_FES_OPEN_PL.VAL")
if state == 1: return "open"
elif state == 0: return "closed"
else: return "state "+str(state)
def open_xray_safety_shutters():
"""Try to remote frontend shutter and waits until the shutter opens
(If the X-ray hutches are not locked or the storage ring is down this may take
forever.)"""
t = time()
xray_safety_shutters_open.value = True
while not xray_safety_shutters_open.value == True and not task.cancelled:
sleep(0.2)
if time()-t > 30 and not options.wait_for_beam: break
def close_xray_safety_shutters():
"""Remote Frontend shutter"""
xray_safety_shutters_open.value = False
while not xray_safety_shutters_open.value == False and not task.cancelled:
sleep(0.2)
def open_laser_safety_shutter():
laser_safety_shutter_open.value = True
t = time()
while not laser_safety_shutter_open.value == True and not task.cancelled:
sleep(0.2)
if time()-t > 4 and not options.open_laser_safety_shutter and \
True in variable_choices("laser_on"): break
def wait_for(condition,timeout=nan):
"""Halt execution until the condition passed as string evaluates to
True.
timeout: in unit of seconds. If specified unconditionally return after
the number of seconds has passed."""
start = time()
while not eval(condition) and not task.cancelled:
if time() - start > timeout: break
sleep(0.05)
def timing_diagnostics_start_dataset():
global timing_diagnostics_delays
timing_diagnostics_delays = {}
timing_diagnostics_delays = {}
def timing_diagnostics_start_images(image_numbers=None):
"""Measure the Laser to X-ray delay using the timing oscilloscope
and save the results to a log file."""
global timing_diagnostics_keep_monitoring
timing_diagnostics_keep_monitoring = True
from thread import start_new_thread
start_new_thread(timing_diagnostics_monitor,())
timing_diagnostics_keep_monitoring = False
def timing_diagnostics_finish_images(image_numbers=None):
"""Turn off the timing oscilloscope time scale updates and logging of
time delays."""
global timing_diagnostics_keep_monitoring
timing_diagnostics_keep_monitoring = False
def timing_diagnostics_monitor():
"""Measure the Laser to X-ray delay using the timing oscilloscope
and save the results to a log file."""
global timing_diagnostics_last_delay, timing_diagnostics_last_image_number
while timing_diagnostics_keep_monitoring:
if diagnostics.enabled and diagnostics.delay:
adjust_timing_scope_range()
image_number1 = timing_system.image_number.count
delay = actual_delay.value - diagnostics.timing_offset
image_number = timing_system.image_number.count
if not image_number in diagnostics_image_times:
diagnostics_image_times[image_number] = [time()]
else: diagnostics_image_times[image_number] += [time()]
if not isnan(delay) and image_number == image_number1 and \
delay != timing_diagnostics_last_delay:
if not image_number in timing_diagnostics_delays:
timing_diagnostics_delays[image_number] = [delay]
else: timing_diagnostics_delays[image_number] += [delay]
if image_number != timing_diagnostics_last_image_number and \
not isnan(timing_diagnostics_last_image_number):
timing_diagnostics_log(timing_diagnostics_last_image_number)
timing_diagnostics_last_delay = delay
timing_diagnostics_last_image_number = image_number
timing_diagnostics_last_delay = nan
timing_diagnostics_last_image_number = nan
diagnostics_image_times = {}
def diagnostics_image_start_time(image_number):
if not image_number in diagnostics_image_times: t = time()
else: t = min(diagnostics_image_times[image_number])
return t
def diagnostics_image_end_time(image_number):
if not image_number in diagnostics_image_times: t = time()
else: t = max(diagnostics_image_times[image_number])
return t
def timing_diagnostics_delay(image_number):
from numpy import average
if not image_number in timing_diagnostics_delays: delay = nan
else: delay = average(timing_diagnostics_delays[image_number])
return delay
def timing_diagnostics_sdev_delay(image_number):
from numpy import std
if not image_number in timing_diagnostics_delays: sdev_delay = nan
else: sdev_delay = std(timing_diagnostics_delays[image_number])
return sdev_delay
def timing_diagnostics_num_delay(image_number):
from numpy import std
if not image_number in timing_diagnostics_delays: num_delay = 0
else: num_delay = len(timing_diagnostics_delays[image_number])
return num_delay
def timing_diagnostics_log(image_number):
"""Write timing diagnostics infomration into a separate log file"""
logfile = timing_diagnostics_logfile()
if not exists(logfile):
if not exists(dirname(logfile)): makedirs(dirname(logfile))
header = "#date time\tfilename\tact.delay[s]\tsdev(act.delay)[s]\tnum(act.delay)\n"
file(logfile,"w").write(header)
line = "%s\t%s\t%s\t%s\t%s\n" % (
timestamp(diagnostics_image_end_time(image_number)),
basename(filename(image_number)),
timing_diagnostics_delay(image_number),
timing_diagnostics_sdev_delay(image_number),
timing_diagnostics_num_delay(image_number),
)
file(logfile,"a").write(line)
def timing_diagnostics_logfile():
"""Write timing diagnostics information into a separate log file"""
base,ext = splitext(logfile())
filename = base+"_timing.txt"
return filename
def timing_scope_range(t):
"""Time scale of the oscilloscope such that both laser
and X-ray pulses are within the recorded time window.
The X-ray pulse is at the trigger point T=0 in the middle of the
window the laser pulse preceeds is by the nominal time delay
specified by t.
t: laser to X-tay time sedleay in seconds"""
return max(abs(t)*2*1.25,diagnostics.min_window)
def adjust_timing_scope_range(image_number=None):
"""Adjust the time scale of the oscilloscope such that both laser
and X-ray pulses are within the recorded time window.
The X-ray pulse is at the trigger point T=0 in the middle of the
window the laser pulse preceeds is by the nominal time delay."""
if image_number is None: image_number = timing_system.image_number.count
nom_delay = collection_variable_value("delay",image_number)
actual_delay.time_range = timing_scope_range(nom_delay)
def image_info_reset():
global current_image_number_keep_updating
current_image_number_keep_updating = False
global image_info_acquiring
image_info_acquiring = False
global image_info_image_number
image_info_image_number = 0
global image_info
image_info = {}
image_info_reset()
def current_image_number_start_updating():
"""Begin collecting per-image statistics for diagnostics PVs."""
global image_info_acquiring
image_info_acquiring = False
global current_image_number_keep_updating
current_image_number_keep_updating = True
from thread import start_new_thread
start_new_thread(current_image_number_update_task,())
def current_image_number_finish_updating():
"""End collecting per-image statistics for diagnostics PVs."""
global current_image_number_keep_updating
current_image_number_keep_updating = False
def current_image_number_update_task():
"""Keep the variable 'image_info_image_number' up to date"""
while current_image_number_keep_updating:
current_image_number_update()
sleep(0.02)
def current_image_number_update():
"""Update the variable 'image_info_image_number' once"""
image_number = timing_system.image_number.count
global image_info_image_number
last_image_number = image_info_image_number
if image_number != last_image_number:
if not last_image_number in image_info: image_info[last_image_number] = {}
image_info[last_image_number]["finished"] = time()
if not image_number in image_info: image_info[image_number] = {}
image_info[image_number]["started"] = time()
image_info_image_number = image_number
acquiring = timing_sequencer.queue_active
global image_info_acquiring
last_acquiring = image_info_acquiring
if acquiring != last_acquiring:
if acquiring:
if not image_number in image_info: image_info[image_number] = {}
image_info[image_number]["started"] = time()
if not acquiring:
if not image_number in image_info: image_info[image_number] = {}
image_info[image_number]["finished"] = time()
image_info_acquiring = acquiring
def current_image_number():
return image_info_image_number
def image_timestamp(image_number):
if image_number in image_info and "started" in image_info[image_number]:
t = image_info[image_number]["started"]
else: t = 0
return t
def image_finished(image_number):
# Make sure image_info get s updated.
if not current_image_number_keep_updating: current_image_number_update()
i = image_number
if i in image_info and\
"started" in image_info[i] and "finished" in image_info[i] and\
image_info[i]["finished"] > image_info[i]["started"]:
finished = True
else: finished = False
return finished
def image_logged(image_number):
i = image_number
logged = i in image_info and "logged" in image_info[i]
return logged
def diagnostics_start_dataset():
"""To be called beffore the start of data collection"""
image_info_reset()
diagnostics_reset()
timing_diagnostics_start_dataset()
def diagnostics_finish_dataset():
"""To be called after the end of data collection"""
if diagnostics.enabled and diagnostics.xray_record_waveform:
exec_delayed(2,"xray_trace.waveform_autosave = False")
if diagnostics.enabled and diagnostics.laser_record_waveform:
exec_delayed(2,"laser_trace.waveform_autosave = False")
def diagnostics_start_images(image_numbers):
"""To be called before starting the dataset"""
if diagnostics.enabled:
if diagnostics.delay:
xray_pulse.enabled = diagnostics.xray
if diagnostics.delay:
laser_pulse.enabled = diagnostics.laser
if diagnostics.xray_record_waveform:
progress("uploading x-ray waveform file list...")
filenames = waveform_filenames(image_numbers,"xray")
# Split up waveforms into multiple files if there are mutiple bursts.
n = burst_length(image_numbers[0])
xray_trace.acquire_sequence(n)
xray_trace.sequence_timeout_enabled = False
xray_trace.noise_filter = "None"
xray_trace.sampling_rate = diagnostics.xray_sampling_rate
xray_trace.time_range = diagnostics.xray_time_range
xray_trace.trigger_delay = diagnostics.xray_time_offset
xray_trace.acquire_waveforms(filenames)
xray_trace.scope.trigger_mode = "Normal" # Needed?
progress("uploading x-ray waveform file list done.")
progress("")
# Turn off measurments slowing down the scope, if not needed.
if not diagnostics.xray: xray_trace.scope.measurement_enabled = False
if diagnostics.laser_record_waveform and laser_enabled():
progress("uploading laser waveform file list...")
filenames = waveform_filenames(image_numbers,"laser")
# Split up waveforms into multiple files if there are mutiple bursts.
n = burst_length(image_numbers[0])
laser_trace.acquire_sequence(n)
laser_trace.sequence_timeout_enabled = False
laser_trace.noise_filter = "None"
laser_trace.sampling_rate = diagnostics.laser_sampling_rate
laser_trace.time_range = diagnostics.laser_time_range
laser_trace.trigger_delay = diagnostics.laser_time_offset
laser_trace.acquire_waveforms(filenames)
laser_trace.scope.trigger_mode = "Normal" # Needed?
progress("uploading laser waveform file list done.")
progress("")
# Turn off measurments slowing down the scope, if not needed.
if not diagnostics.laser: laser_trace.scope.measurement_enabled = False
if diagnostics.delay:
timing_diagnostics_start_images(image_numbers)
diagnostics_start_montitoring()
def diagnostics_finish_images(image_numbers):
if diagnostics.enabled and diagnostics.delay:
timing_diagnostics_finish_images(image_numbers)
diagnostics_finish_montitoring()
current_image_number_finish_updating()
def diagnostics_start_image(image_number):
"""To called before an image is acquired.
image_number: 1-based index"""
if diagnostics.enabled:
if diagnostics.xray:
n = npulses(task.image_number)
if not diagnostics.xray_record_waveform or n==1: xray_pulse.start()
if diagnostics.laser: laser_pulse.start()
def diagnostics_finish_image(image_number):
"""Called after an image was acquired.
image_filename: used as a basename for additional diagnositcs files to be
writtten
image_number: 1-based index"""
if not diagnostics.enabled: return
diagnostics_keep_monitoring = False
def diagnostics_start_montitoring():
"""Begin collecting per-image statistics for diagnostics PVs."""
global diagnostics_keep_monitoring
diagnostics_keep_monitoring = True
from thread import start_new_thread
for i in range(0,diagnostics_PVs()):
start_new_thread(diagnostics_monitor_PV,(diagnostics_PV_name(i),))
def diagnostics_finish_montitoring():
"""End collecting per-image statistics for diagnostics PVs."""
global diagnostics_keep_monitoring
diagnostics_keep_monitoring = False
def diagnostics_reset():
global diagnostics_data
diagnostics_data = {}
diagnostics_reset()
def diagnostics_monitor_PV(name):
"""Collect per image statistics for diagnostics PVs."""
while diagnostics_keep_monitoring:
if diagnostics.enabled:
if not name in diagnostics_data: diagnostics_data[name] = {}
i = current_image_number()
if not i in diagnostics_data[name]: diagnostics_data[name][i] = \
{"sum":0.0,"sum2":0.0,"count":0,"last":0.0}
s = diagnostics_data[name][i]
val = diagnostics_value(name)
if current_image_number() == i:
if not isnan(val) and val != s["last"]:
s["sum"] += val
s["sum2"] += val**2
s["count"] += 1
s["last"] = val
sleep(0.02)
def diagnostics_PV_image_avg(i_PV,image_number,):
"""Average value of a process variable that is monitored during an
image acquisition
i_PV: 0-based index
image_number: 1-based index
"""
i = image_number
name = diagnostics_PV_name(i_PV)
if name in diagnostics_data:
if i in diagnostics_data[name]:
s = diagnostics_data[name][i]
sum,n = s["sum"],s["count"]
if n > 0: value = sum/n
else: value = nan
else: value = nan
else: value = nan
return value
def diagnostics_PV_image_sdev(i_PV,image_number):
"""Standard deviation of the individual sampled value
that is monitored during an image acquisition
i_PV: 0-based index
image_number: 1-based index
"""
i = image_number
name = diagnostics_PV_name(i_PV)
if name in diagnostics_data:
if i in diagnostics_data[name]:
s = diagnostics_data[name][i]
sum,sum2,n = s["sum"],s["sum2"],s["count"]
if n > 0: value = sqrt(sum2/n - (sum/n)**2)
else: value = nan
else: value = nan
else: value = nan
return value
def diagnostics_PV_image_count(i_PV,image_number):
"""How many times has a process variable been measured during
an image acquisition?
i_PV: 0-based index
image_number: 1-based index
"""
i = image_number
name = diagnostics_PV_name(i_PV)
if name in diagnostics_data:
if i in diagnostics_data[name]:
s = diagnostics_data[name][i]
value = s["count"]
else: value = 0
else: value = 0
return value
def diagnostics_value(name):
"""The value of a process variable, if name is a process variable.
Otherwise, name is assumed to be the name of a Python object and
its 'value' property is used."""
try: x = eval(name)
except: return tofloat(caget(name))
return tofloat(getattr(x,"value",x))
def diagnostics_xray_offset():
"""Integral area over width of gate in units of Vs"""
gate_width = diagnostics.xray_gate_stop - diagnostics.xray_gate_start
return diagnostics.xray_offset_level*gate_width
def diagnostics_set_xray_offset(offset):
"offset: integral area over width of gate"
gate_width = diagnostics.xray_gate_stop - diagnostics.xray_gate_start
diagnostics.xray_offset_level = offset/gate_width
def diagnostics_PVs():
"""Number of active diagnostics PVs"""
n = 0
for i in range(0,min(len(diagnostics.PVs),len(diagnostics.PVuse))):
if diagnostics.PVuse[i]: n += 1
return n
def diagnostics_PV_name(i):
"""Name of ith active process variable"""
n = -1
for j in range(0,min(len(diagnostics.PVuse),len(diagnostics.PVs))):
if diagnostics.PVuse[j]: n += 1
if n == i: return diagnostics.PVs[j]
return ""
def diagnostics_PV_comment(i):
"""Descriptive comment for ith active process variable"""
n = -1
for j in range(0,min(len(diagnostics.PVuse),len(diagnostics.PVnames))):
if diagnostics.PVuse[j]: n += 1
if n == i: return diagnostics.PVnames[j]
return "PV"
def diagnostics_PV_summary():
"Listing of process variable definitions in text form (for log file header)."
s = ""
for i in range(0,diagnostics_PVs()):
s += diagnostics_PV_comment(i)+": "
s += diagnostics_PV_name(i)+"; "
s = s.rstrip("; ")
return s
def diagnostics_summary():
"Short listing of calibration constants in text form (for log file header)."
s = ""
if diagnostics.delay:
s += "delay: offset %g s; " % diagnostics.timing_offset
if diagnostics.xray:
ref = diagnostics.xray_reference
offset = diagnostics_xray_offset()
s += "x-ray: reference %g, offset %g; " % (ref,offset)
if diagnostics.laser:
ref = diagnostics.laser_reference
offset = diagnostics.laser_offset
s += "laser: reference %g, offset %g; " % (ref,offset)
s = s.rstrip("; ")
return s
def tofloat(x):
"""Like builtin 'float', but do not raise an exception, return 'nan'
instead."""
try: return float(x)
except: return nan
# Sample Alignment:
def collectinion_zs():
"""At which z positions to collect data"""
n = translation_after_image_nspots()
zs = []
for i in range(0,n):
zs += [min(sample.zs) + i*translation_after_image_zstep()]
return zs
def zs(image_number):
"Number of DiffZ position for an given image"
return translation_during_image_unique_zs(image_number)
def alignment_all_support_points():
""""Phi values and Z values for all alignment scan done so far as numpy
array"""
PHI,Z = array(align_table())[0:2]
return array([PHI,Z])
def sample_aligned_at(phi,z):
"""Whas an alignment scan performed at (phi,z)?"""
PHI,Z = alignment_all_support_points()
for (phis,zs) in zip(PHI,Z):
if abs(phi-phis)<1e-3 and abs(z-zs)<1e-3: return True
return False
## image_number=90; phi = angle(image_number); z = zs(image_number)[0]
def within_interpolation_range(phi,z):
"""Is the position (phi,z) close enough to an already measured support points
such that interpolation can be used?"""
PHI,Z = alignment_closest_support_points(phi,z)
dphi,dz = alignment_interpolation_dphi(),alignment_interpolation_dz()
eps = 1e-3
def amax(a): return max(a) if len(a)>0 else nan
def amin(a): return min(a) if len(a)>0 else nan
phi1,phi2 = amax(PHI[PHI<=phi+eps]),amin(PHI[phi-eps<=PHI])
phi_within_range = phi2-phi1 <= dphi+eps
Zs = Z[(PHI==phi1) | (PHI==phi2)]
# z need to be in between the zs
z_within_range = amin(Zs) <= z+eps and z-eps <= amax(Zs)
within_range = phi_within_range and z_within_range
return within_range
def alignment_closest_support_points(phi,z):
"""Phi values and z values of the four closest (phi,z) pairs
for which alignemnt scans have been performed.
If (phi,z) is inside the support point network, four points are returned.
If outside, less than four.
Return value: two numpy arrays: PHI,Z"""
from numpy import concatenate,argmin,nan,isnan,array,any
phi = phi % 360
PHI,Z = alignment_all_support_points()
PHI = concatenate((PHI-360,PHI,PHI+360))
PHI1,PHI2 = PHI[PHI<=phi],PHI[PHI>=phi]
PHI1,PHI2 = PHI[PHI<=phi],PHI[PHI>=phi]
phi1 = PHI1[argmin(abs(PHI1-phi))] if len(PHI1)>0 else nan
phi2 = PHI2[argmin(abs(PHI2-phi))] if len(PHI2)>0 else nan
phi1 = phi1 % 360
phi2 = phi2 % 360
if phi1 == phi2: phi2 = nan
Z1,Z2 = Z[Z<=z],Z[Z>=z]
z1 = Z1[argmin(abs(Z1-z))] if len(Z1)>0 else nan
z2 = Z2[argmin(abs(Z2-z))] if len(Z2)>0 else nan
if z1 == z2: z2 = nan
points = array([[phi1,z1],[phi1,z2],[phi2,z1],[phi2,z2]])
points = points[~any(isnan(points),axis=1)]
PHI,Z = points.T
# Check if the points are support points.
PHIs,Zs = alignment_all_support_points()
OK = array([any((phi==PHIs) & (z == Zs)) for (phi,z) in zip(PHI,Z)],bool)
PHI,Z = PHI[OK],Z[OK]
return PHI,Z
def alignment_interpolation_dphi():
"""How close have measured support points to on both sides to to calculate
the crsyal edge rather than measure it."""
if align.align_at_collection_phis: return align.intepolation_dphi
else: return inf
def alignment_interpolation_dz():
"""How close have measured support points to on both sides to to calculate
the crsyal edge rather than measure it."""
if align.align_at_collection_zs: return align.intepolation_dz
else: return inf
def alignment_support_points(phi,z):
"""The closest values of Phi and DiffZ for which an aligment was
already done.
returns (phi1,phi2,z1,z2)
If no support point is avaiable any of phi1,phi2,z1,z2 can by nan."""
from numpy import array,argmin,nan
PHI,Z = array(align_table())[0:2]
PHI1,PHI2 = PHI[PHI<=phi],PHI[PHI>=phi]
phi1 = PHI1[argmin(abs(PHI1-phi))] if len(PHI1)>0 else nan
phi2 = PHI2[argmin(abs(PHI2-phi))] if len(PHI2)>0 else nan
Z1,Z2 = Z[Z<=z],Z[Z>=z]
z1 = Z1[argmin(abs(Z1-z))] if len(Z1)>0 else nan
z2 = Z2[argmin(abs(Z2-z))] if len(Z2)>0 else nan
return phi1,phi2,z1,z1
def alignment_closest_phi_z(phi=None,z=None):
"""The closest values of Phi and DiffZ for which an aligment was
already done."""
if phi == None: phi = Phi.command_value
if z == None: z = diffractometer.zc
table = align_table()
PHI = table[0]
Z = table[1]
n = len(table[0])
if n == 0: return nan,nan
dphi = inf
for i in range(0,n): dphi=min(dphi,abs(phi-PHI[i]))
j = 0; dz = inf
for i in range(0,n):
if abs(phi-PHI[i]) <= dphi:
if abs(z-Z[i]) < dz: dz = abs(z-Z[i]); j = i
return PHI[j],Z[j]
def alignment_center(gonz=None):
"""Return the (gonx,gony) reference for aligning the crystal top edge
to the X-ray beam.
With automatic sample translation the alignment center is dynamically
changing as the sample is translated in goniometer z direction. The
(gonx,gony) center as function of DiffZ is calculated by linear inter-
polation between the tranlation endpoints."""
x,y,z = sample.center
return x,y
def set_sample_center(x=None,y=None,z=None):
"Define the center of the sample"
if x == None: x = DiffX.command_value
if y == None: y = DiffY.command_value
if z == None: z = DiffZ.command_value
center = x,y,z
if sample_center() != center: align.center_time = time()
sample.center = center
align.center_sample = param.file_basename
save_settings()
def sample_center():
"""DiffX,DiffY,DiffZ motor positions at the time 'Define Center'
button was pressed."""
return sample.center
def alignment_needed_for(image_number):
"""Run at least one alignment scan for the given image number?"""
phi = angle(image_number)
for z in zs(image_number):
if within_interpolation_range(phi,z): continue
PHI,Z = sample.closest_support_points(phi,z)
if align.align_at_collection_zs:
if len(zs(image_number)) <= 1: Z = [z]
if align.align_at_collection_phis:
PHI = [phi]*len(Z)
for (phi_s,z_s) in zip(PHI,Z):
if not sample_aligned_at(phi_s,z_s): return True
return False
def align_sample_if_needed_for(image_number):
"""Run the neccessary alignment scans for the given image number
restore: Return X,Y,Z,Phi to their original values?"""
phi = angle(image_number)
align_sample_if_needed_for_phi(phi)
def align_sample_if_needed_for_phi(phi):
"""Run the neccessary alignemt scans for the given orientation
restore: Return X,Y,Z,Phi to their original values?"""
if not align.enabled: return
PHIs,Zs = scans_at_phi_z_needed_for_phi(phi)
align_sample_at(PHIs)
def scans_at_phi_z_needed_for_phi(phi):
"""At which values of phi and z alignment scans need to be done
to collect at phi?
Return value: list of phi values,list of z vales as tuple"""
if align.align_at_collection_phis and not align.align_at_collection_zs:
Zs = [z for z in sample.spot_zs if not within_interpolation_range(phi,z)]
PHIs = [phi]*len(Zs)
else:
PHIs,Zs = [],[]
for z in sample.spot_zs:
if not within_interpolation_range(phi,z):
PHI,Z = sample.closest_support_points(phi,z)
if align.align_at_collection_zs:
if len(collectinion_zs()) <= 1: Z = [z]
if align.align_at_collection_phis:
from numpy import unique
Z = unique(Z)
PHI = [phi]*len(Z)
PHIs += PHI
Zs += list(Z)
return PHIs,Zs
def alignment_scan_dir(phi=None,z=None):
"""Scratch directory where to store the images acquired during an alignment
scan."""
if phi == None: phi = diffractometer.phic
if z == None: z = diffractometer.zc
return param.path+"/alignment/scan_phi=%.3f_z=%.3f" % (phi,z)
def align_sample_at(PHIs):
"""Acquire a series of image with different vertical offsets
in order to to find the edge of the crystal
PHIs: list of phi angles
Zs: list of z support points in z direction"""
# Group alignment scans by phi.
from numpy import unique
for phi in unique(PHIs):
diffractometer.phi = phi
while diffractometer.moving and not task.cancelled: sleep (0.01)
align_sample()
def align_sample():
"""Acquire a series of alignment scans at different horizontal
positions given by Zs, in order to to find the edge of the crystal at the
current phi orienation.
Zs: lists of horizontal positions at which to perform alignment scans"""
action = task.action; task.action = "Align Sample"
PHIs = [diffractometer.phic]
Zs = sample.spot_zs
progress("Performing alignment scans at phi=%r,z=%r"%(list(PHIs),list(Zs)))
alignment_scan_start()
image_numbers = alignment_pass(1)
while len(image_numbers) > 0 and not task.cancelled:
alignment_scan_start_images(image_numbers)
alignment_scan_wait(image_numbers)
image_numbers = alignment_pass(image_numbers[-1]+1)
alignment_scan_finish(image_numbers)
task.action = action
def alignment_pass(starting_image_number=1):
"""starting_image_number: 1-based
return value: lsit of 1-based image numbers"""
# Break up the dataset into passes limited by the number of positions
# the motion controller can store.
X,Y,Z,PHI,OFFSET,filenames = alignment_scan_parameters()
i = starting_image_number-1
nmax = triggered_motion.max_steps(3)
Nimages = min(len(filenames)-i,nmax)
image_numbers = range(i+1,i+Nimages+1)
return image_numbers
def alignment_scan_start():
# Generate a logfiles to be used later by "diffraction_profile".
X,Y,Z,PHI,OFFSET,filenames = alignment_scan_parameters()
from os.path import relpath
data = {}
for i in range(0,len(filenames)):
x,y,z,phi,offset,filename = X[i],Y[i],Z[i],PHI[i],OFFSET[i],filenames[i]
logfilename = param.path+"/alignment/scan_phi=%.3f_z=%.3f.log" % (phi,z)
if "reference" in filename: continue
if not logfilename in data: data[logfilename]= []
f = relpath(filename,param.path+"/alignment")
data[logfilename] += [(phi,offset,f)]
for logfilename in data:
tab = data[logfilename]
s = "#phi\toffset\tfilename\n"
for record in tab: s += "%g\t%g\t%s\n" % record
if not exists(dirname(logfilename)): makedirs(dirname(logfilename))
file(logfilename,"wb").write(s)
# Make sure that the image files do not exists already.
for filename in filenames:
if exists(filename): remove(filename)
def alignment_scan_start_images(image_numbers):
"""Configure hardware
image_numbers: list of 1-based integers,
e.g. image_numbers = alignment_pass(1)"""
alignment_scan_motion_controller_start_images(image_numbers)
alignment_scan_xray_detector_start_images(image_numbers)
alignment_scan_timing_system_start_images(image_numbers)
def alignment_scan_motion_controller_start_images(image_numbers):
"""Configure motion controller
image_numbers: list of 1-based integers
e.g. image_numbers = alignment_pass(1)"""
X,Y,Z,PHI,OFFSET,filenames = alignment_scan_parameters()
XYZ = array([X,Y,Z]).T
triggered_motion.xyz = XYZ
triggered_motion.waitt = timing_system.waitt.next(align.waitt)
triggered_motion.armed = True
def alignment_scan_timing_system_start_images(image_numbers):
"""Configure timing system
image_numbers: list of 1-based integers
e.g. image_numbers = alignment_pass(1)"""
nimages = len(image_numbers)
# The detector trigger pulse at the beginning of the first image is to
# dump zingers that may have accumuated on the CCD. This image is discarded.
# An extra detector trigger is required after the last image,
waitt = [align.waitt]*nimages+[align.waitt]
burst_waitt = [0.012]*nimages+[0.012]
burst_delay = [0]*nimages+[0]
npulses = [align.npulses]*nimages+[align.npulses]
laser_on = [0]*nimages+[0]
ms_on = [1]*nimages+[0]
xatt_on = [align.attenuate_xray]*nimages+[align.attenuate_xray]
trans_on = [1]*nimages+[0]
xdet_on = [1]*nimages+[1]
xosct_on = [1]*nimages+[0]
image_numbers = image_numbers+[image_numbers[-1]+1]
##timing_sequencer.inton_sync = 0
timing_system.image_number.count = 0
timing_system.pulses.count = 0
##timing_sequencer.running = False
timing_sequencer.acquire(
waitt=waitt,
burst_waitt=burst_waitt,
burst_delay=burst_delay,
npulses=npulses,
laser_on=laser_on,
ms_on=ms_on,
xatt_on=xatt_on,
trans_on=trans_on,
xdet_on=xdet_on,
xosct_on=xosct_on,
image_numbers=image_numbers,
)
def alignment_scan_xray_detector_start_images(image_numbers):
"""Configure X-ray area detector
image_numbers: list of 1-based integers
e.g. image_numbers = alignment_pass(1)"""
if options.xray_detector_enabled:
X,Y,Z,PHI,OFFSET,filenames = alignment_scan_parameters()
filenames = [filenames[i-1] for i in image_numbers]
# The first image needs to be discarded, because there is one more
# detector trigger pulse than there are images.
filenames = ["/tmp/jumk.rx"]+[filenames]
ccd.bin_factor = align.ccd_bin_factor # Speeds up the acquisition time
ccd.acquire_images(image_numbers,filenames)
show_images(filenames)
def alignment_scan_wait(image_numbers):
"""Wait for scan to complete
image_numbers: list of 1-based integers, e.g. image_numbers = alignment_pass(1)"""
while alignment_scan_running(image_numbers) and not task.cancelled:
sleep(0.01)
def alignment_scan_running(image_numbers):
"""Is scan complete?
image_numbers: list of 1-based integers, e.g. image_numbers = alignment_pass(1)"""
if alignment_scan_timing_system_running(image_numbers): return True
elif alignment_scan_xray_detector_running(image_numbers): return True
else: return False
def alignment_scan_timing_system_running(image_numbers):
"""Is scan complete?
image_numbers: list of 1-based integers, e.g. image_numbers = alignment_pass(1)"""
i = timing_system.image_number.count
p = timing_system.pulses.count
progress("acquiring image %3d, %d pulses" % (i,p))
running = (i < image_numbers[-1]) if len(image_numbers)>0 else False
return running
def alignment_scan_xray_detector_running(image_numbers):
"""Is scan complete?
image_numbers: list of 1-based integers, e.g. image_numbers = alignment_pass(1)"""
if options.xray_detector_enabled:
state = ccd.state()
progress("X-ray detector: %s" % state)
running = (state == "acquiring series")
else: running = False
return running
def alignment_scan_finish(image_numbers):
"""image_numbers: list of 1-based integers, e.g. image_numbers = alignment_pass(1)"""
alignment_scan_timing_system_finish(image_numbers)
if options.xray_detector_enabled: alignment_scan_xray_detector_finish(image_numbers)
def alignment_scan_timing_system_finish(image_numbers):
"""image_numbers: list of 1-based integers, e.g. image_numbers = alignment_pass(1)"""
# Make sure shutters are closed
timing_sequencer.psg_state = 0
timing_sequencer.ms_state = 0
timing_sequencer.s3_state = 0
def alignment_scan_xray_detector_finish(image_numbers):
"""image_numbers: list of 1-based integers, e.g. image_numbers = alignment_pass(1)"""
PHIs = [diffractometer.phic]
Zs = sample.spot_zs
update_diffraction_profiles(PHIs,Zs)
for phi in PHIs:
for z in Zs: process_alignment_scan(phi,z)
def alignment_scan_parameters(PHIs=None,Zs=None):
"""Return value: X,Y,Z,PHI,OFFSET,filename
(X,Y,Z for SampleX,SampleY,SampleZ)"""
if PHIs is None: PHIs = [diffractometer.phic]
X,Y,Z,PHI,OFFSET,filenames = [],[],[],[],[],[]
for phi in PHIs:
for s in sample.samples:
cx1,cy1,cz1 = diffractometer.xyz_of_sample(s["start"],phi)
cx2,cy2,cz2 = diffractometer.xyz_of_sample(s["end"],phi)
# Start with a reference image through the center of the crystal that
# is valid for all scans done at the same orientation
cx,cy,cz = (cx1+cx2)/2,(cy1+cy2)/2,(cz1+cz2)/2
X += [cx]; Y += [cy]; Z += [cz]; PHI += [phi]; OFFSET += [0]
filenames += [param.path+"/alignment/reference_phi=%.3f.mccd" % phi]
if align.align_at_collection_zs: align_zs = collectinion_zs()
else: align_zs = [cz1,cz2] if Zs is None else Zs
for z in align_zs:
cx = interpolate([[cz1,cx1],[cz2,cx2]],z)
cy = interpolate([[cz1,cy1],[cz2,cy2]],z)
npoints = int(ceil(sample.sample_r/align.step))+1
# Start outside the crystal, scan till the center is reached.
offsets = [-align.step*i for i in range(0,npoints)][::-1]
X += [cx]*npoints
Y += [cy+offset for offset in offsets]
Z += [z]*npoints
PHI += [phi]*npoints
OFFSET += offsets
scan_dir = param.path+"/alignment/scan_phi=%.3f_z=%.3f" % (phi,z)
filenames += [scan_dir+"/offset=%.3f.mccd" % y for y in offsets]
return X,Y,Z,PHI,OFFSET,filenames
def alignment_status():
"Short status report about progress of current alignement scan"
status = ""
if task.action == "Align Sample": status += "Aligning: "
else: status += "Current settings: "
status += "%s=%g %s, " % (Spindle.name,Spindle.value,Spindle.unit)
status += "Z=%.3f mm, " % DiffZ.value
status += "offset %.3f mm, " % diffractometer.y
if task.action == "Align Sample":
ccd_state = ccd.state()
if ccd_state != "idle" and ccd_state != "": status += ccd_state+", "
if timing_system.pulses.count > 0: status += "%d pulses, " % timing_system.pulses.count
if options.wait_for_topup and time_to_next_refill.value < 1.0:
t = time_to_next_refill.value
if t > 0: status += "%g s until next top-up, " % t
if t == 0: status += "top-up in progress, "
if task.comment: status += task.comment+", "
status = status.strip(", ")
return status
def alignment_summary():
"Short report about last alignment scan"
s = ""
if any(isnan(sample_center())): s += "Sample not yet centered."
else:
x,y,z = sample_center()
s += "Sample '%s' centered at " % align.center_sample
s += "X=%.3f, Y=%.3f, Z=%.3f" % (x,y,z)
if align.center_time:
if time()- align.center_time < 24*60*60: format = "at %H:%M"
else: format = "on %d %b %y %H:%M"
s += " "+strftime(format,localtime(align.center_time))+"."
s += "\n"
if not align.enabled:
s += "No alignment scans. No vertical adjustment."
return s
if alignment_needed_for(task.image_number):
phi = angle(task.image_number)
align_phi,align_z = alignment_closest_phi_z(phi)
offset = align_offset(align_phi,align_z)
s += "Alignment needed at Phi=%g %s. " % (phi,Phi.unit)
if not isnan(offset):
s += ("Last measured offset %.3f mm " % offset)
s += ("at Phi=%g, Z=%.3f mm." % (align_phi,align_z))
else:
s += "No previous information available."
else:
align_phi,align_z = alignment_closest_phi_z()
offset = align_offset(align_phi,align_z)
s += ("Using offset %.3f mm, recorded at %s=%.3f deg, Z=%.3f" %
(offset,Spindle.name,align_phi,align_z))
return s
def set_offset(offset):
"""Translates the sample vertically relative to the position it was
centered."""
while diffractometer.moving and not task.cancelled: sleep(0.05)
diffractometer.xy = 0,offset
while diffractometer.moving and not task.cancelled: sleep(0.05)
diffractometer.stop()
def align_offset(phi=None,z=None):
"""Tell the position of DiffX and DiffY where the sample is aligned as
function of Phi and DiffZ, based on ealier diffraction scans.
Interpolate as function of phi and z."""
from numpy import array,argsort
if phi == None: phi = diffractometer.phic
if z == None: z = diffractometer.zc
# Load lookup table of already measured offsets.
PHI,Z,X,Y,OFFSET = array(align_table())[0:5]
# Interpolate
offset = interpolate_2D(PHI,Z,OFFSET,phi,z)
return offset
def interpolate_2D(PHI,Z,OFFSET,phi,z):
"""Perform two-dimensional interpolation of data define on a rectangular
grid.
PHI,Z: arrays, define grid of support points.
OFFSET: array, defines value at support points.
phi,z: where to interpolate
Return value: OFFSET at (phi,z)"""
from numpy import concatenate,mean,nan,unique,sort
if len(OFFSET) == 0: return nan
# Take into account that angles are periodic.
phi %= 360
PHI %= 360
PHI = concatenate((PHI-360,PHI,PHI+360))
Z = concatenate((Z,Z,Z))
OFFSET = concatenate((OFFSET,OFFSET,OFFSET))
# Find the next smaller and larger phi.
# If interpolation is not possible, extrapolate.
phis = unique(PHI)
if phi < min(phis): phi1,phi2 = phis[0:2][0],phis[0:2][-1]
elif phi > max(phis): phi1,phi2 = phis[-2:][0],phis[-2:][-1]
else: phi1,phi2 = max(phis[phis<=phi]),min(phis[phis>=phi])
# Find the next smaller and larger z for both phis.
# If interpolation is not possible, extrapolate.
zs1 = unique(Z[PHI==phi1])
zs2 = unique(Z[PHI==phi2])
if z < min(zs1): z11,z12 = zs1[0:2][0],zs1[0:2][-1]
elif z > max(zs1): z11,z12 = zs1[-2:][0],zs1[-2:][-1]
else: z11,z12 = max(zs1[zs1<=z]),min(zs1[zs1>=z])
if z < min(zs2): z21,z22 = zs2[0:2][0],zs2[0:2][-1]
elif z > max(zs2): z21,z22 = zs2[-2:][0],zs2[-2:][-1]
else: z21,z22 = max(zs2[zs2<=z]),min(zs2[zs2>=z])
# Look up the offset at the four support points.
offset11 = mean(OFFSET[(PHI==phi1) & (Z==z11)])
offset12 = mean(OFFSET[(PHI==phi1) & (Z==z12)])
offset21 = mean(OFFSET[(PHI==phi2) & (Z==z21)])
offset22 = mean(OFFSET[(PHI==phi2) & (Z==z22)])
# Interpolate in z.
if z12 == z11: offset1 = offset11
else: offset1 = offset11*(z12-z)/(z12-z11) + offset12*(z-z11)/(z12-z11)
if z22 == z21: offset2 = offset21
else: offset2 = offset21*(z22-z)/(z22-z21) + offset22*(z-z21)/(z22-z21)
# Interpolate in phi.
if phi1 == phi2: offset = offset1
else: offset = offset1*(phi2-phi)/(phi2-phi1) + offset2*(phi-phi1)/(phi2-phi1)
return offset
def update_diffraction_profiles(PHIs=None,Zs=None):
"""Calculate the figure of merit for each image and save it to a file.
This procedure is intented to be run a a sparate thread while the scan image are
still being collected"""
from numpy import sum
if PHIs is None: PHIs = [diffractometer.phic]
if Zs is None: Zs = sample.spot_zs
phi = PHIs[0]
ref_filename = param.path+"/alignment/reference_phi=%.3f.mccd" % phi
PHI,Z,OFFSET,filenames = [],[],[],[]
for z in Zs:
scan_logfile = alignment_scan_dir(phi,z)+".log"
if exists(scan_logfile):
offset_list,filename_list = read(scan_logfile,labels="offset,filename")
PHI += [phi]*len(filename_list)
Z += [z]*len(filename_list)
OFFSET += offset_list
filenames += [param.path+"/alignment/"+f for f in filename_list]
FOM = [nan]*len(filenames)
processed = [False]*len(filenames)
Nprocessed = 0
result_files = []
for i in range(0,len(filenames)):
result_file = param.path+"/alignment/profile_phi=%.3f_z=%.3f.txt" % (PHI[i],Z[i])
if not result_file in result_files: result_files += [result_file]
image_size = ccd.filesize(align.ccd_bin_factor)
if not (exists_file(ref_filename) and getsize(ref_filename) == image_size):
progress("waiting for %r..." % basename(ref_filename))
while not (exists_file(ref_filename) and getsize(ref_filename) == image_size) \
and not task.cancelled: sleep(0.1)
progress("%s: peak integration mask..." % basename(ref_filename))
integration_mask = peak_integration_mask(numimage(ref_filename))
progress("%s: peak integration mask done" % basename(ref_filename))
while sum(processed)<len(filenames) and not task.cancelled:
for i in range(0,len(filenames)):
if task.cancelled: break
if exists_file(filenames[i]) and getsize(filenames[i]) == image_size \
and not processed[i]:
progress("processing %3d/%d %r" % (i+2,len(filenames)+1,basename(filenames[i],1)))
FOM[i] = sum(integration_mask*numimage(filenames[i]))
processed[i] = True
if sum(processed) > Nprocessed and not task.cancelled:
progress("saving results")
results = {}
for i in range(0,len(FOM)):
if not processed[i]: continue
result_file = param.path+"/alignment/profile_phi=%.3f_z=%.3f.txt" % (PHI[i],Z[i])
if not result_file in results: results[result_file] = "#offset\tFOM\n"
results[result_file] += "%.3f\t%.0f\n" % (OFFSET[i],FOM[i])
for result_file in results: file(result_file,"wb").write(results[result_file])
Nprocessed = sum(processed)
if sum(processed) < len(filenames):
progress("%r/%r images found" % (sum(processed),len(filenames)))
# Give up on the missing image files if no change for 60 s.
processed_time = max([getmtime(f) for f in result_files if exists_file(f)])
last_image_time = max([getmtime(f) for f in filenames if exists_file(f)])
if time() - last_image_time > 15: break
else: sleep(1)
if sum(processed) < len(filenames):
missing_files = ", ".join([basename(filenames[i],1)
for i in range(0,len(filenames)) if not processed[i]])
if len(missing_files)>60: msg = missing_files[0:60]+"..."
warn("missing: "+missing_files)
def basename(pathname,level=0):
"""Ending part of a pathanme.
level: how mane directories levels to include"""
from os.path import basename,dirname
s = basename(pathname)
for i in range(0,level):
pathname = dirname(pathname)
s = basename(pathname)+"/"+s
return s
def getsize(filename):
"""The length of a file in bytes or 0 if te file does not exists"""
from os.path import getsize
try: return getsize(filename)
except OSError: return 0
def exists_file(pathname):
"""Like "exists" but deals with a problem related NFS attribute caching, which makes
"exits" sometimes erronously report a file as nonexsitent, that was newly created
from a remote machine"""
from os.path import basename,dirname; from os import listdir
filename = basename(pathname)
dir = dirname(pathname)
if dir == "": dir = "."
try: filenames = listdir(dir)
except OSError: return False
return filename in filenames
def process_alignment_scan(phi=None,z=None):
"""Analyze series of diffraction images recorded at different sample offsets"""
if phi == None: phi = diffractometer.phic
if z == None: z = diffractometer.zc
progress("processing alignment scan for phi=%.3f,z=%.3f" % (phi,z))
align.profile = diffraction_profile(phi,z)
if len(align.profile) == 0: return
edge = find_edge(align.profile)
offset = edge + align.beamsize
# Save the lookup table.
PHI,Z,X,Y,OFFSET = align_table()
# Eliminate dupliate entries
if len(PHI) > 0:
PHI,Z,X,Y,OFFSET = zip(*[row for row in zip(PHI,Z,X,Y,OFFSET)
if not allclose(row[0:2],(phi,z))])
PHI,Z,X,Y,OFFSET = list(PHI),list(Z),list(X),list(Y),list(OFFSET)
PHI += [phi]; Z += [z]; X += [0]; Y += [0]; OFFSET += [offset]
set_align_table((PHI,Z,X,Y,OFFSET))
try: merge_alignment_scans()
except: warn("'merge_alignment_scans' failed")
progress("processed alignment scan for phi=%.3f,z=%.3f" % (phi,z))
def align_table():
"""Lookup table for past alignemnt scans.
Columns: Phi,DiffZ,DiffX,DiffY,offset"""
filename = param.path+"/alignment/phi,z,x,y,offset.txt"
try: table = read(filename)
except: table = [[],[],[],[],[]]
if len(table) != 5: table = [[],[],[],[],[]]
return table
def set_align_table(table):
"""Update lookup table for past alignemnt scans,
Columns: Phi,DiffZ,DiffX,DiffY,offset"""
filename = param.path+"/alignment/phi,z,x,y,offset.txt"
save(table,filename,labels="phi,z,x,y,offset")
def align_time():
"""Last ime an alignemt scan was done successfully"""
from os import stat
filename = param.path+"/alignment/phi,z,x,y,offset.txt"
try: return stat(filename)[8]
except OSError: return 0
def merge_alignment_scans():
"""Generate a file containing all the alignment scans"""
scan_dir = param.path+"/alignment"
PHI,Z = read(scan_dir+"/phi,z,x,y,offset.txt",labels="phi,z")
N = len(PHI)
if N == 0: return
z = [[]]*N
I = [[]]*N
n = [nan]*N
for i in range(0,N):
z[i],I[i] = read(scan_dir+"/profile_phi=%.3f_z=%.3f.txt" % (PHI[i],Z[i]))
# Extra reference intensities
Iref = [[]]*N
for i in range(0,N): Iref[i] = I[i][0]
# Skip first data point (reference)
for i in range(0,N): z[i],I[i] = z[i][1:],I[i][1:]
# Round offset to 1 um precision.
dz = 0.001
for i in range(0,N): z[i] = list(rint(array(z[i])/dz)*dz)
# Sort all scans
from numpy import argsort
for i in range(0,N):
order = argsort(z[i])
z[i] = list(array(z[i])[order])
I[i] = list(array(I[i])[order])
# Make all scans have the same range be prepending an appending NaNs.
zmin = inf
for i in range(0,N): zmin = min(zmin,min(z[i]))
for i in range(0,N):
n = int(round((z[i][0]-zmin)/align.step))
z[i] = [nan]*n + z[i]
I[i] = [nan]*n + I[i]
length = 0
for i in range(0,N): length = max(length,len(z[i]))
for i in range(0,N):
z[i] = z[i] + [nan]*(length-len(z[i]))
I[i] = I[i] + [nan]*(length-len(I[i]))
from numpy import average,where
z = array(z)
za = [average(z[:,i][where(~isnan(z[:,i]))]) for i in range(length)]
filename = scan_dir+"/profiles.txt"
header = "Iref"
for i in range(0,N): header += "\t%g" % Iref[i]
save([za]+I,filename,labels=["Phi"]+PHI,header=header)
merge_derivatives()
def merge_derivatives():
"Generate a file containing the derivatives of all the alignment scans"
scan_dir = param.path+"/alignment"
PHI,Z = read(scan_dir+"/phi,z,x,y,offset.txt",labels="phi,z")
N = len(PHI)
if N == 0: return
z = [[]]*N
I = [[]]*N
n = [nan]*N
for i in range(0,N):
z[i],I[i] = read(scan_dir+"/profile_phi=%.3f_z=%.3f.txt" % (PHI[i],Z[i]))
# Calculcate derivatives.
for i in range(0,N):
derivative_xy = derivative(zip(z[i],I[i]),npoints=align.npoints)
z[i],I[i] = xvals(derivative_xy),yvals(derivative_xy)
# Skip first data point (reference)
for i in range(0,N): z[i],I[i] = z[i][1:],I[i][1:]
# Round offset to 1 um precision.
dz = 0.001
for i in range(0,N): z[i] = list(rint(array(z[i])/dz)*dz)
# Sort all scans
from numpy import argsort
for i in range(0,N):
order = argsort(z[i])
z[i] = list(array(z[i])[order])
I[i] = list(array(I[i])[order])
# Make all scans have the same range be prepending an appending NaNs.
zmin = inf
for i in range(0,N): zmin = min(zmin,min(z[i]))
for i in range(0,N):
n = int(round((z[i][0]-zmin)/align.step))
z[i] = [nan]*n + z[i]
I[i] = [nan]*n + I[i]
length = 0
for i in range(0,N): length = max(length,len(z[i]))
for i in range(0,N):
z[i] = z[i] + [nan]*(length-len(z[i]))
I[i] = I[i] + [nan]*(length-len(I[i]))
from numpy import average,where
z = array(z)
za = [average(z[:,i][where(~isnan(z[:,i]))]) for i in range(length)]
filename = scan_dir+"/derivatives.txt"
save([za]+I,filename,labels=["z"]+PHI)
# Needed by update_diffraction_profile
integration_mask = [] # used for peak integration
integration_mask_filename = "" # file from which integration_mask was generated
def update_diffraction_profile(phi=None,z=None):
"""Reduce a set of images into a one-dimensional diffraction strength profile.
The result is saved in a file named 'alignment/profile_phi=N.NNN_z=N.NNN.txt'"""
from numpy import sum
if phi == None: phi = diffractometer.phic
if z == None: z = diffractometer.zc
profile_file = param.path+"/alignment/profile_phi=%.3f_z=%.3f.txt" % (phi,z)
scan_logfile = alignment_scan_dir(phi,z)+".log"
if not exists_file(scan_logfile):
warn("%s not updated: %s not found" % \
(basename(profile_file),basename(scan_logfile)))
return
try: offset = array(read(scan_logfile,labels="offset"))
except:
warn("%s not updated: %s corrupted" % \
(basename(profile_file),basename(scan_logfile)))
return
image_files = array(read(scan_logfile,labels="filename"))
if len(image_files) == 0:
warn("%s not updated: %s contains no image files" % \
(basename(profile_file),basename(scan_logfile)))
return
image_files = [param.path+"/alignment/"+image_files[i]
for i in range(0,len(offset))]
# Use image recorded through the center of the crystal as reference image
# for all scans at the same orientation.
ref_image_file = param.path+"/alignment/reference_phi=%.3f.mccd" % phi
if not exists_file(ref_image_file):
warn("%s not updated: reference image %s not found" % \
(basename(profile_file),ref_image_file))
return
# Reuse data from existing diffraction profile.
filenames = [ref_image_file]+image_files
last_modified = max([getmtime(f) for f in filenames if exists_file(f)])
if exists(profile_file) and getmtime(profile_file) > last_modified:
info("%r is up to date" % basename(profile_file))
return
global integration_mask,integration_mask_filename
if ref_image_file != integration_mask_filename:
# Use the reference image for the spot positions.
Iref = numimage(ref_image_file)
progress("Peak integration mask")
integration_mask = peak_integration_mask(Iref)
integration_mask_filename = ref_image_file
progress("Figure of merit")
FOM = array([nan]*len(offset))
for i in range(0,len(offset)):
image_file = image_files[i]
if not exists(image_file):
FOM[i] = nan
else:
I = numimage(image_file)
FOM[i] = sum(integration_mask*I)
# Eliminate bad data points.
bad = isnan(FOM)
offset,FOM = offset[~bad],FOM[~bad]
# Save the profile.
progress("Saving")
save([offset,FOM],profile_file,labels="offset,FOM")
def diffraction_profile(phi=None,z=None):
"""One-dimensional diffraction strength profile.
Returns list of (x,y)-tuples."""
if phi == None: phi = diffractometer.phic
if z == None: z = diffractometer.zc
update_diffraction_profile(phi,z)
profile_file = \
param.path+"/alignment/profile_phi=%.3f_z=%.3f.txt" % (phi,z)
offset,FOM = array([]),array([])
if exists(profile_file):
try: offset,FOM = array(read(profile_file))
except: warn("ignoring corrupted file '%s'" % basename(profile_file))
# Skip first data point (reference image)
offset,FOM = offset[1:],FOM[1:]
# Generate list of x,y pairs.
from numpy import argsort
order = argsort(offset)
return zip(offset[order],FOM[order])
def diffraction_Iref(phi=None,z=None):
"""Reference intensity of diffraction strength profile."""
if phi == None: phi = diffractometer.phic
if z == None: z = diffractometer.zc
update_diffraction_profile(phi,z)
profile_file = \
param.path+"/alignment/profile_phi=%.3f_z=%.3f.txt" % (phi,z)
offset,FOM = array([]),array([])
if exists(profile_file):
try: offset,FOM = array(read(profile_file))
except: warn("ignoring corrupted file '%s'" % basename(profile_file))
# The reference intensity is the first scan point in the file.
if len(FOM) == 0: return nan
return FOM[0]
def alignment_scan_has_edge(phi=None,z=None):
"""Determines wether a diffraction scan contains sufficient information to determine
the edge of the crystal reliably."""
if phi == None: phi = diffractometer.phic
if z == None: z = diffractometer.zc
profile = diffraction_profile(phi,z)
Iref = diffraction_Iref()
return has_edge(profile,Iref)
def has_edge(profile,Iref):
"""Determine wether a diffraction scan contains sufficient information to determine
the edge of the crystal reliably.
profile: list of (x,y)-tuples
Iref: reference_intensity"""
if len(profile) < 2: return False
slope_profile = derivative(profile,npoints=align.npoints)
if len(slope_profile) < 2: return False
I = yvals(profile)
slope = yvals(slope_profile)
return slope[-1] < slope[-2] and I[-2] > 0.1*Iref
def test_edge_finder():
"""test the 'has_edge' function
Prints table to stdout"""
zs = sample.spot_zs
phis = range(0,360,30)
for phi in phis:
for z in zs:
print("%g %.3f %r" % (phi,z,alignment_scan_has_edge(phi,z)))
def find_edge(profile):
"""Find the point of maximum slope, with the slope averaged over
align.npoints, and extrapolate down to the baseline.
profile = list of (x,y)-tuples"""
if len(profile) == 0: return nan
slope = derivative(profile,npoints=align.npoints)
##x = x_at_ymax(slope)
x = x_at_first_max_of_derivative(profile)
dydx = yval(slope,x)
y = yval(profile,x)
y0 = min(yvals(profile))
if dydx == 0: return nan
x0 = x - (y-y0)/dydx
# Sanity check: The edge must be inside the scan range.
xmin,xmax = min(xvals(profile)),max(xvals(profile))
x0 = clip(x0,xmin,xmax)
return x0
def x_at_first_max_of_derivative(profile):
"""The first maximum of the derivative of "profile" where the intensity is
higher that 5% of the maximum intensity.
profile: list of (offset,I) pairs"""
slope_xy = derivative(profile,npoints=align.npoints)
x,I = xvals(profile),yvals(profile)
slope_x,slope = xvals(slope_xy),yvals(slope_xy)
# "profile" and "slope_xy" have different x scale
i = 0
while i<len(x) and len(slope_x)>0 and x[i]<slope_x[0]: i+= 1
x,I = x[i:],I[i:]
Iref = max(array(I)) if len(I)>0 else nan
for i in range(3,min(len(I),len(slope))):
if slope[i] < slope[i-1] and I[i-1] > 0.05*Iref: break
x_at_max = x[i] if i<len(x) else nan
return x_at_max
def estimate_scan_range(phi=None):
"""This is to speed to the edge finder by using prior information from
previous edge scans, to minimize the scan range.
Return (start,end) in units of mm.
"""
if phi == None: phi = diffractometer.phic
scan_dir = join(param.path,"alignment")
phis = xvals(read_xy(join(scan_dir,"phi,offset.txt")))
if len(phis) < align.last_scans_use:
return align.start,align.end
phis = phis[-align.last_scans_use:]
phis.sort()
phi_offset = []
for angle in phis:
profile = read_xy(join(scan_dir,"profile_%g.txt" % angle))
offset = x_at_max_slope(profile)
phi_offset += [(angle,offset)]
# Extend the phi range beyond [0,360].
if len(phi_offset) > 0:
first = (phi_offset[-1][0]-360,phi_offset[-1][1])
last = (phi_offset[0][0]+360,phi_offset[0][1])
phi_offset = [first] + phi_offset + [last]
offset = interpolate(phi_offset,phi)
start = offset + 0.5*(align.min_scanpoints-1) * align.step
# Do not go outside the full range.
if start > align.start: start = align.start
# Round start to the next multiple of step.
start = align.start + round((start-align.start)/align.step)*align.step
end = start - (align.min_scanpoints-1) * align.step
return start,end
def x_at_max_slope(xy_data):
"""Find the point of maximum slope, with the slope averaged over
align.npoints."""
if len(xy_data) == 0: return nan
slope = derivative(xy_data,npoints=align.npoints)
return x_at_ymax(slope)
def interpolate(xy_data,xval):
"Linear interpolation"
x = xvals(xy_data); y = yvals(xy_data); n = len(xy_data)
if n == 0: return nan
if n == 1: return y[0]
for i in range (1,n):
if x[i]>xval: break
if x[i-1]==x[i]: return (y[i-1]+y[i])/2.
yval = y[i-1]+(y[i]-y[i-1])*(xval-x[i-1])/(x[i]-x[i-1])
return yval
def x_at_ymax(xy_data):
if len(xy_data) < 1: return nan
x_at_ymax = xy_data[0][0]; ymax = xy_data[0][1]
for i in range (0,len(xy_data)):
if xy_data[i][1] > ymax: x_at_ymax = xy_data[i][0]; ymax = xy_data[i][1]
return x_at_ymax
def invert(xy_data):
"takes the negative of y of yx_data"
xy_inverted = []
for i in range (0,len(xy_data)): xy_inverted.append((xy_data[i][0],-xy_data[i][1]))
return xy_inverted
def yval (xy_data,x0):
"""xy_data = list of (x,y)-tuples.
Pairs (x,y[x]) are taken as support points for a function which is evaluated at 'x'. Linear
Interpolation is used.
"""
N = len(xy_data); x = xvals(xy_data); y = yvals(xy_data)
if N<1: return nan
if N==1: return y[0]
i=0
if x[0] <= x[N-1]:
while i+1<N-1 and x0>x[i+1]: i=i+1
else:
while i+1<N-1 and x0<=x[i+1]: i=i+1
l = (x0-x[i])/(x[i+1]-x[i])
return (1-l)*y[i]+l*y[i+1]
def xvals(xy_data):
"xy_data = list of (x,y)-tuples. Teturns list of x values only."
xvals = []
for i in range (0,len(xy_data)): xvals.append(xy_data[i][0])
return xvals
def yvals(xy_data):
"xy_data = list of (x,y)-tuples. Returns list of y values only."
yvals = []
for i in range (0,len(xy_data)): yvals.append(xy_data[i][1])
return yvals
def derivative(xy_data,npoints):
"""calculates the slope of xy data averaged of a number of points given by npoints
xy_data = list of (x,y)-tuples
"""
derivative=[]
for j in range (0,len(xy_data)-npoints):
sumx=0; sumy=0
for i in range(j,j+npoints): sumx+=xy_data[i][0]; sumy+=xy_data[i][1]
xmean = sumx/npoints; ymean = sumy/npoints
sumxy=0; sumx2=0
for i in range(j,j+npoints):
sumxy+=(xy_data[i][0]-xmean)*(xy_data[i][1]-ymean)
sumx2+=pow(xy_data[i][0]-xmean,2)
if sumx2 != 0: dydx = sumxy/sumx2
else: dydx = 0
derivative.append((xmean,dydx))
return derivative
# (Warning: The following code might crash occasionally, because there is no bounds
# checking on the index "i" of the array "slope". F .Schotte, Oct 26, 2014)
# Zero out derivative beyond its first maximum.
I = yvals(xy_data)
Iref = array(I).max()
slope = yvals(derivative)
for i in range(3,len(I)):
if slope[i] < slope[i-1] and I[i-1] > 0.05*Iref:
break
test = []
for j in range(0,len(I)-npoints):
if j <= i:
test.append(derivative[j])
else: test.append((derivative[j][0],0))
return test
def print_xy(xy_data):
"""(x,y) tuples as two columns.
Prints table to stdout."""
for i in range(0,len(xy_data)):
print("%g\t%g" % (xy_data[i][0],xy_data[i][1]))
def save_xy(xy_data,filename):
"""Write (x,y) tuples as two-column tab separated ASCII file."""
if not exists (dirname(filename)): makedirs (dirname(filename))
output = file(filename,"w")
for i in range(0,len(xy_data)):
output.write("%g\t%g\n" % (xy_data[i][0],xy_data[i][1]))
def read_xy(filename):
"""Reads two two-column ASCII file and returns as list of floating point
[x,y] pairs"""
try: infile = file(filename)
except: return []
data = []
line = infile.readline()
while line != '':
try:
cols = line.split()
x = float(cols[0]); y = float(cols[1])
data.append([x,y])
except ValueError: pass
line = infile.readline()
return data
# Sample Translation
def translation_hardware_triggered():
"""Translate the sample during data collection"""
return translate.mode != "off" and translate.hardware_triggered
def translate_sample():
"""Position the sample for the beginning of an image acquisition"""
if translate.mode in ("off","linear stage"): return
x,y,z = translation_after_image_xyz(task.image_number)
DiffX.value,DiffY.value,DiffZ.value = x,y,z
while (DiffX.moving or DiffY.moving or DiffZ.moving) and not task.cancelled:
sleep (0.05)
def translation_after_image_xyz(image_number):
"""for "after image" translation mode. Return value: (x,y,z)"""
if "grid scan" in translate.mode:
x,y,z = grid_position(image_number)
else:
z = translation_after_image_z(image_number)
x,y = translation_xy(z,angle(image_number))
return (x,y,z)
def grid_position(image_number):
"""For photocrystallography chip"""
i = image_number
i = i-1 # convert from 1-based to 0-based index
i = int(floor(i/translate.after_images))
x,y,z = grid.point(i) # SampleX,SampleY,SampleZ
dx,dy,dz = diffractometer_xyz((x,y,z))
return dx,dy,dz
def diffractometer_xyz((x,y,z)):
"""Transform from hardwre to diffractometer coordinates
(x,y,z): hardware coordinates (SampleX,SampleY,SampleZ)
return value: (x,y,z) tuple"""
dx,dy = diffractometer.diffractometer_xy(x,y,SamplePhi.value)
dz = diffractometer.diffractometer_z(z)
return dx,dy,dz
def translation_after_image_z(image_number):
"""Starting point defined by "after image" translation
image_number: 1-based index"""
if not ("after image" in translate.mode or
"during image" in translate.mode or
"continuous" in translate.mode):
z = nan # Do not move. Keep current position.
elif not "after image" in translate.mode: z = min(sample.zs)
else:
i = image_number
i = i-1 # convert from 1-based to 0-based index
# Return to starting position after how many series?
nrepeat = translate.return_after_series * nimages_per_orientation()
i = i % nrepeat
# After how many images to translate?
i = int(floor(i/translate.after_images))
nspots = translation_after_image_nspots()
i = i % nspots
m = translate.after_image_interleave_factor
i = interleaved_order(i,m,nspots)
z = min(sample.zs) + i*translation_after_image_zstep()
return z
def translation_after_image_plot():
n = nimages_per_timeseries()
N = range(1,n+1)
Z = [translation_after_image_z(i+1) for i in range(0,n)]
from Plot import Plot
Plot(zip(N,Z),title="Sample Translation",xaxis="image #",yaxis="DiffZ[mm]")
def translation_after_image_nspots():
"""Number of unique spots for 'after image' sampel translation
defined by marked range in microscope camera"""
n = translate.after_image_nspots
n = max(int(n),1)
return n
def set_translation_after_image_nspots(n):
"""Number of unique spots for 'after image' sampel translation
defined by marked range in microscope camera"""
n = max(int(n),1)
translate.after_image_nspots = n
def translation_after_image_zstep():
"""How much to translation the sampel after each image?"""
if len(sample.zs) == 0: return nan
full_range = max(sample.zs) - min(sample.zs)
if translate.after_image_nspots > 1:
zstep = full_range/(translate.after_image_nspots-1)
else: zstep = 0
return zstep
def set_translation_after_image_zstep(zstep):
"""How much to translation the sampel after each image?"""
full_range = max(sample.zs) - min(sample.zs)
if zstep > 0:
translate.after_image_nspots = int(rint(full_range/zstep))+1
else: translate.after_image_nspots = 1
def translation_xy(z,phi):
"""Matching DiffX,DiffY positionion for a given DiffZ position"""
if not ("after image" in translate.mode or
"during image" in translate.mode or
"continuous" in translate.mode):
x,y = nan,nan # nan = Do not move. Keep current position.
else:
s = sample.samples[0]
cx1,cy1,cz1 = diffractometer.xyz_of_sample(s["start"],phi)
cx2,cy2,cz2 = diffractometer.xyz_of_sample(s["end"],phi)
x = interpolate([[cz1,cx1],[cz2,cx2]],z)
y = interpolate([[cz1,cy1],[cz2,cy2]],z)
if align.enabled:
offset = align_offset(phi,z)
if not isnan(offset): y += offset
return (x,y)
def translation_during_image_stroke():
"""Sample translation during te aquisition of an image in mm"""
if "during image" in translate.mode:
n = translation_during_image_unique_nspots()
return max(n-1,0) * sample.z_step
elif "continuous" in translate.mode: return 0 # Update this!
else: return 0
def translation_during_image_unique_zs(image_number):
"""for 'during image' translation"""
z0 = translation_after_image_z(image_number)
if "during image" in translate.mode:
dz = sample.z_step
n = translation_during_image_unique_nspots()
return [z0 + dz*i for i in range(0,n)]
else: return [z0]
def translation_during_image_unique_nspots():
"""How many spots are visited in 'during image' translation
couinting each position only once."""
if not "during image" in translate.mode: return 1
if not "after image" in translate.mode: return len(sample.zs)
return translate.during_image_nspots
def translation_during_image_set_unique_nspots(n):
"""How many spots are visited in 'during image' translation
couinting each position only once."""
translate.during_image_nspots = n
def translation_during_image_nspots(image_number):
"""How many spots are visited when collecting an image
in "during image" translation mode?"""
if translate.single: return npulses(image_number)
nunique = translation_during_image_unique_nspots()
n = int(ceil(float(npulses(image_number))/nunique))
return int(ceil(float(npulses(image_number))/n))
def translation_during_image_pulses_per_spot(image_number,spot_number):
"""How many X-ray pulses send to each spot
when using "during image" translation mode?"""
if translate.single: n = 1
else:
nunique = translation_during_image_unique_nspots()
n = int(ceil(float(npulses(image_number))/nunique))
return max(0,min(npulses(image_number) - n * spot_number,n))
def translation_during_image_xyz(image_number,spot_number):
"""Where does the sample need to be translated as function of pulse number
when using "during image" translation mode?
image_number: 1-based index
spot_number: 0-based index
Return value: DiffX,DiffY,DiffZ position in mm.
"""
z = translation_during_image_z(image_number,spot_number)
x,y = translation_xy(z,angle(image_number))
return x,y,z
def translation_during_image_z(image_number,spot_number):
"""Tell where the sample needs to translated as function of pulse number
when using "during image" translation mode.
Return DiffZ position in mm
image_number: 1-based index
spot_number: 0-based index"""
if not "during image" in translate.mode: return diffractometer.zc
i = spot_number
zs = translation_during_image_unique_zs(image_number)
i = i % len(zs)
m = translate.interleave_factor
i = interleaved_order(i,m,len(zs))
return zs[i]
def translation_during_image_zs(image_number):
"""Tell where the sample needs to translated as function of pulse number
when using "during image" translation mode.
Return DiffX,DiffY,DiffZ position in mm
image_number: 1-based index"""
n = translation_during_image_nspots(image_number)
return [translation_during_image_z(image_number,i) for i in range(0,n)]
def interleaved_order(i,m,n):
"""Permute the order 0...n, to m passes.
i: 0-based index
m: interleave factor
n: total number"""
return interleaved_sequence(m,n)[i]
def interleaved_sequence(m,n):
"""Permute the order 0...n into m passes.
m: interleave factor
n: total number"""
from numpy import arange
l = int(ceil(n/float(m)))
order = arange(0,l*m).reshape(l,m).T.flatten()
order = order[order<n]
return order
def pump_setup():
"""Prepare for hardwre trigged pumping"""
axis_number = 4 ##PumpA.axis_number
if pump.enabled and pump.hardware_triggered:
transon.value = 1 # Tell timing system to generate trigger pulses
triggered_motion.PumpA.enabled = 1
triggered_motion.PumpA.trigger_divisor = options.npulses*pump.frequency
triggered_motion.PumpA.relative_move = 1
triggered_motion.PumpA.positions = [pump.step]
triggered_motion.enabled = True
##triggered_motion.step_count = 1
else:
try: triggered_motion.axis_enabled[axis_number] = 0
except: pass
def pump_sample_if_needed():
"""Execute a syringe pump command, if needed for the NEXT image."""
if not pump.enabled or pump.hardware_triggered: return
if not pump_needed_after_image(task.image_number): return
progress("Pumping...")
PumpA.command_value += pump.step
while PumpA.moving and not task.cancelled: sleep(0.1)
progress("Pumping... done")
def pump_needed_after_image(image_number):
"""Tell whether the syringe pump should be operated before the given
image_number."""
if not pump.enabled: return False
# pump.frequency defines every how many image the pumping needs to be
# performed.
R = round(image_number % pump.frequency)
return (R == 0)
def pump_summary():
"""This is what is written into the log file"""
if not pump.enabled: return "disabled"
return "step %g" % pump.step
def xray_beam_check_after(starting_image_number):
"""After which image number perform the next beam check?
image_number: 1-based index"""
if xraycheck.enabled:
period = collection_variable_period(xraycheck.run_variable)
n = int(round_up(starting_image_number,period))
else: n = inf
return n
def xray_beam_check_before(image_number):
"""Perform an beam chech before this image?
image_number: 1-based index"""
if xraycheck.enabled:
period = collection_variable_period(xraycheck.run_variable)
check = (image_number % period == 1) and image_number > 1
else: check = False
return check
def xray_beam_check_summary():
"""Summary for log file."""
if not xraycheck.enabled: return "disabled"
s = 'run after series of "%s"' % xraycheck.run_variable
return s
def run_xray_beam_check(apply_correction=False):
"""Correct X-ray beam position drift"""
if task.cancelled: return
action = task.action; task.action = "X-Ray Beam Check"
generate_autorecovery_restore_point("Beamcheck",
("MirrorV","MirrorH","shg","svg"))
if xraycheck.type == "beam position":
from xray_beam_position_check import xray_beam_position_check
xray_beam_position_check.acquire_image()
if apply_correction: xray_beam_position_check.apply_correction()
else: # "I0"
from xray_beam_check import xray_beam_check
xray_beam_check.perform_x_scan()
if apply_correction: xray_beam_check.apply_x_correction()
xray_beam_check.perform_y_scan()
if apply_correction: xray_beam_check.apply_y_correction()
xraycheck.comment = ""
save_settings()
clear_autorecovery_restore_point()
task.action = action
def laser_beamcheck_needed():
"""Tell whether beam position drift should be corrected
before the current image"""
if not lasercheck.enabled: return False
if not laser_enabled(): return False # Not needed when not using the laser.
# Only optimize the beamline before the beginning of a time series.
if lasercheck.at_start_of_time_series:
if orientation_image_number(task.image_number) != 0: return False
if time() - lasercheck.last > lasercheck.interval: return True
else: return False
def laser_beamcheck(apply_correction=True):
"""Correct laser beam position drift.
This reads an image if thw laser beam profile from CCD camera
measures te centered position and applies corrective action by moving the
LaserX and LaserZ motors.
"""
from beam_profiler import acquire_image,xy_projections,FWHM,CFWHM,SNR,ROI
from PIL import Image
global lasercheck_image
if task.cancelled: return
action = task.action; task.action = "Laser Beam Check"
if options.open_laser_safety_shutter:
lasercheck.comment = "Opening laser shutter..."
open_laser_safety_shutter()
# Record the current settings to restore them after the optimization is
# completed.
old_laserx = LaserX.value
old_laserz = LaserZ.value
old_tmode = tmode.value
old_waitt = timing_system.waitt.value
old_lxd = timing_system.lxd.value
old_laseron = laseron.value
old_mson = mson.value
old_VNFilter = VNFilter.command_value
old_illuminator_on = illuminator_on.value
generate_autorecovery_restore_point("Laser Beamcheck",["LaserX","LaserZ",
"tmode","waitt","lxd","laseron","mson","VNFilter"]+
lasercheck.park_motors)
# Make sure the sample illuminator is not obscuring the beam profile camera.
if options.use_illuminator:
illuminator_on.value = False
lasercheck.comment = "Retracting illuminator..."
wait_for("not illuminator_on.moving",timeout=1)
if lasercheck.retract_sample:
# In order to spare the sample, move it out of the X-ray beam and turn off
# the laser firing.
laser_beamcheck_remember_sample_pos()
lasercheck.comment = "Retracting sample..."
laser_beamcheck_goto_park_pos()
# In order to get a well-defined beam profile the laser needs to be triggered
# at sufficient repetition rate.
lasercheck.comment = "Attenuating..."
VNFilter.value = lasercheck.attenuator
while VNFilter.moving and not task.cancelled: sleep (0.1)
timing_system.lxd.value = 0 # to make sure it is compatible with rep rate
timing_system.waitt.value = 1.0/lasercheck.reprate
# When chainging the repetiton rate, the new rate does not take effect
# immediately. The change is delayed by up to one cycle of the previous
# waiting time. (<NAME>, 21 Jun 2010)
sleep(old_waitt)
mson.value = 0 # turn off X-ray beam by disable ms shutter opening
tmode.value = 0 # continuous mode
laseron.value = 1 # fire laser
lasercheck.comment = "Acquiring image..."
image = acquire_image() # Get a beam profile image from the CCD camera.
lasercheck.comment = "Acquiring image...done"
lasercheck.zprofile,lasercheck.xprofile = xy_projections(image)
lasercheck_image = ROI(image)
lasercheck.last = time()
sum_x = 0.0; sum_z = 0.0; sum_SN = 0.0; n = 0
# Make sure that the profile is meaured with sufficient signal-to-noise
# ratio before attempting to run the optimization.
signal_to_noise = min(SNR(lasercheck.zprofile),SNR(lasercheck.xprofile))
if signal_to_noise > lasercheck.signal_to_noise:
sum_z += CFWHM(lasercheck.zprofile)
sum_x += CFWHM(lasercheck.xprofile)
sum_SN += signal_to_noise
n += 1
if signal_to_noise > lasercheck.signal_to_noise:
# Average the center positions
N = lasercheck.naverage
while n < N:
if task.cancelled: break
lasercheck.comment = "Averaging %d/%d images..." % (n+1,N)
image = acquire_image()
lasercheck.zprofile,lasercheck.xprofile = xy_projections(image)
signal_to_noise = min(SNR(lasercheck.zprofile),SNR(lasercheck.xprofile))
if signal_to_noise > lasercheck.signal_to_noise:
sum_z += CFWHM(lasercheck.zprofile)
sum_x += CFWHM(lasercheck.xprofile)
sum_SN += signal_to_noise
n += 1
lasercheck_image = ROI(image)
lasercheck.last = time()
z = sum_z/n
x = sum_x/n
signal_to_noise = sum_SN/n
new_laserz = LaserZ.value - z
new_laserx = LaserX.value - x
lasercheck.comment = "Average error %.3f, %.3f mm, " % (z,x)
lasercheck.comment += "signal/noise: %.3g. " % (signal_to_noise)
if apply_correction:
LaserZ.value = new_laserz
LaserX.value = new_laserx
lasercheck.comment += "Change: "
lasercheck.comment += \
"LaserZ from %.3f to %.3f, " % (old_laserz,new_laserz)
lasercheck.comment += \
"LaserX from %.3f to %.3f mm " % (old_laserx,new_laserx)
while (LaserZ.moving or LaserZ.moving) and not task.cancelled:
sleep (0.1)
else:
lasercheck.comment = "Insufficient signal/noise (%g<%g)" % \
(signal_to_noise,lasercheck.signal_to_noise)
lasercheck.last_image = param.path+"/beam profile.png"
if not exists(dirname(lasercheck.last_image)):
makedirs(dirname(lasercheck.last_image))
lasercheck_image.save(lasercheck.last_image)
logfile = param.path+"/laser_beamcheck.log"
timestamp = strftime("%d %b %y %H:%M",localtime(lasercheck.last))
file(logfile,"a").write(timestamp+" "+lasercheck.comment+"\n")
log_comment("Laser Beam check: "+lasercheck.comment)
save_settings()
# Restore the settings to their value before the optimization.
lasercheck.comment += " - Restoring settings"
tmode.value = old_tmode
timing_system.waitt.value = old_waitt
timing_system.lxd.value = old_lxd
laseron.value = old_laseron
mson.value = old_mson
VNFilter.value = old_VNFilter
if options.use_illuminator:
illuminator_on.value = old_illuminator_on
if lasercheck.retract_sample: laser_beamcheck_goto_sample_pos()
while VNFilter.moving and not task.cancelled: sleep (0.1)
lasercheck.comment = lasercheck.comment.replace(" - Restoring settings","")
if not task.cancelled: clear_autorecovery_restore_point()
else: trigger_autorecovery()
task.action = action
def laser_beamcheck_remember_park_pos():
"""Make the current position the one to go in
'laser_beamcheck_goto_park_pos'."""
lasercheck.park_positions = []
for motor_name in lasercheck.park_motors:
motor = eval(motor_name)
lasercheck.park_positions += [motor.command_value]
def laser_beamcheck_remember_sample_pos():
"""Make the current position the one to go in
'laser_beamcheck_goto_sample_pos'."""
lasercheck.sample_position = []
for motor_name in lasercheck.park_motors:
motor = eval(motor_name)
lasercheck.sample_position += [motor.command_value]
def laser_beamcheck_goto_park_pos():
"""Move the sample out of the laser beam.
Needed before running a laser beam check."""
for i in range(0,len(lasercheck.park_motors)):
motor = eval(lasercheck.park_motors[i])
if i >= len(lasercheck.park_positions): break
motor.value = lasercheck.park_positions[i]
while motor.moving and not task.cancelled: sleep (0.1)
if task.cancelled: motor.stop(); break
def laser_beamcheck_goto_sample_pos():
"""Return the sample to the position for data collection.
Needed before running a laser beam check."""
# The motors need to be moved in reverse order, compared to retracting
# the sample.
for i in range(len(lasercheck.park_motors)-1,-1,-1):
motor = eval(lasercheck.park_motors[i])
if i >= len(lasercheck.sample_position): break
motor.value = lasercheck.sample_position[i]
while motor.moving and not task.cancelled: sleep (0.1)
if task.cancelled: motor.stop(); break
def laser_beamcheck_park_summary():
"""Summarize the motors to move, before running a laser beam check."""
s = ""
N = min(len(lasercheck.park_motors),len(lasercheck.park_positions))
for i in range(0,N):
s += "%s: %g, " % (lasercheck.park_motors[i],lasercheck.park_positions[i])
return s.rstrip(", ")
def timing_check_needed():
"""Tell whether beam position drift should be correected
before the current image"""
if not timingcheck.enabled: return False
if not laser_enabled(): return False
# Run only before the beginning of a time series.
if timingcheck.at_start_of_time_series:
if orientation_image_number(task.image_number) != 0: return False
if time() - timingcheck.last > timingcheck.interval: return True
else: return False
def timing_check_summary():
"""Summary for log file."""
if not timingcheck.enabled: return "disabled"
s = "repeat every "+time_string(timingcheck.interval)
if timingcheck.at_start_of_time_series:
s += ", only at start of time series"
if timingcheck.retract_sample:
s += ", retracting sample by %g mm " % timingcheck.retract_sample
s += "using motor %s" % timingcheck.sample_motor
return s
def run_timing_check(apply_correction=True):
"""This check and correct laser-to-X-ray timing drift"""
# This calls an EPICS state notation code program called "BeamCheck"
# written by <NAME>, running on the server "everest".
# This program used the Pulsed X-ray signal of the I0 PIN diode,
# recorded by the Wavesurfer oscilloscope.
if task.cancelled: return
action = task.action; task.action = "Timing Check"
motors = "tmode","waitt","lxd","laseron","ChopX","ChopY","hscd","VNFilter"
if timingcheck.sample_motor: motors += [timingcheck.sample_motor]
generate_autorecovery_restore_point("Timing Check",motors)
if options.wait_for_beam:
timingcheck.comment = "Opening X-ray Shutter..."
wait_for_beam()
if options.open_laser_safety_shutter:
timingcheck.comment = "Opening Laser Shutter..."
open_laser_safety_shutter()
# Record the current settings to restore them after the optimization is
# completed.
old_xoscton = xoscton.value
old_xray_shutter_enabled = Ensemble_SAXS.xray_shutter_enabled
old_tmode = tmode.value
old_waitt = timing_system.waitt.value
old_lxd = timing_system.lxd.value
old_laseron = laseron.value
old_chopx = ChopX.command_value
old_chopy = ChopY.command_value
old_chopper_phase = timing_system.hsc.delay.value
if timingcheck.sample_motor:
sample_motor = eval(timingcheck.sample_motor)
old_sample_pos = sample_motor.command_value
old_VNFilter = VNFilter.command_value
# In order to spare the sample, move it out of the X-ray beam and
# attenuate the laser beam to minimum power.
if timingcheck.sample_motor and timingcheck.retract_sample:
timingcheck.comment = "Retracting sample..."
sample_motor.value += timingcheck.retract_sample
while sample_motor.moving and not task.cancelled: sleep (0.1)
timingcheck.comment = "Attenuating laser beam at sample..."
VNFilter.value = timingcheck.attenuator_angle
while VNFilter.moving and not task.cancelled: sleep (0.1)
# If the chopper height is variable, use the maximum number of bunches per
# pulse for the optimization (for example use 11 bunches rather than 1.)
if collection_variable_enabled("chopper_mode"): set_chopper_mode(chopper_mode_of_timepoint(0))
xoscton.value = 1
Ensemble_SAXS.xray_shutter_enabled = True
laseron.value = 1
##timing_system.waitt.value = 0.024
timing_system.lxd.value = 0
##tmode.value = 0
# Make sure that there is an X-ray signal before attempting to run
# the optimization.
# The X-ray intensity should be at least 20% of the value recorded as
# reference.
# Average for 1 s (10 samples at 10 Hz)
xray_pulse.start()
start = time()
while time()-start < 1 and not task.cancelled: sleep (0.1)
offset = diagnostics_xray_offset()
xray1 = (xray_pulse.average-offset) / (diagnostics.xray_reference-offset)
if not task.cancelled:
if xray1 > timingcheck.min_intensity:
# Adjust the time scale of the oscilloscope such that both laser
# and X-ray pulses are within the recorded time window.
# The X-ray pulse is at the trigger point T=0 in the middle of the
# window the laser pulse preceeds is by the nominal time delay
# specified by timing_system.lxd.value.
actual_delay.time_range = diagnostics.min_window
# Measure for 10 seconds.
actual_delay.start()
start = time()
while time()-start < 10 and not task.cancelled:
sleep (0.1)
t = actual_delay.average
sdev = actual_delay.stdev
N = actual_delay.count
err = sdev/sqrt(N-1)
timingcheck.comment = \
"Timing error %s, sdev %s, %s samples, sampling error %s" % \
(time_string(t),time_string(sdev),N,time_string(err))
# Sanity check.
max_sdev = 70e-12
OK = (not task.cancelled and not isnan(t) and sdev < max_sdev)
if isnan(t): timingcheck.comment = "Measurement failed"
if sdev > 70e-12:
timingcheck.comment = "Jitter of measurement too high (%s < %s)" % \
(time_string(sdev),time_string(max_sdev))
# Apply correction
if OK and apply_correction and abs(t) > 10e-12 and abs(t) > 2*err:
offset0 = timing_system.lxd.offset
timing_system.lxd.define_value(t)
# Resolution oftiming_system.lxd. is 10 ps. Define the closes possible value to 0
# as 0.
timing_system.timing_system.lxd.value = 0
timing_system.lxd.define_value(0)
correction = timing_system.lxd.offset - offset0
timingcheck.comment += " - Correction: %s" % time_string(correction)
else:
timingcheck.comment = "X-ray intensity too low (%.3g < %g)" % \
(xray1,timingcheck.min_intensity)
if task.cancelled: timingcheck.comment = "Cancelled"
# Restore the settings to their value before the optimization.
comment = timingcheck.comment
timingcheck.comment += " - Restoring settings..."
xoscton.value = old_xoscton
Ensemble_SAXS.xray_shutter_enabled = old_xray_shutter_enabled
tmode.value = old_tmode
timing_system.waitt.value = old_waitt
timing_system.lxd.value = old_lxd
laseron.value = old_laseron
if timingcheck.sample_motor: sample_motor.value = old_sample_pos
VNFilter.value = old_VNFilter
ChopX.value = old_chopx
ChopY.value = old_chopy
timing_system.hsc.delay.value = old_chopper_phase
if timingcheck.sample_motor:
while sample_motor.moving and not task.cancelled: sleep (0.1)
while VNFilter.moving and not task.cancelled: sleep (0.1)
if collection_variable_enabled("chopper_mode"):
set_chopper_parameters(old_chopx,old_chopy,old_chopper_phase)
timingcheck.comment = comment
# Record the last time the optimization was done.
timingcheck.last = time()
save_settings()
log_comment("Timing check: "+timingcheck.comment)
clear_autorecovery_restore_point()
task.action = action
def sample_photo_needed(image_number=None):
"""Acquire a sample photo?"""
if image_number is None: image_number = task.image_number
if not sample_photo.enabled: return False
# Acquire a sample photo at the beginning of every series.
at_start_of_series = orientation_number(image_number) != orientation_number(image_number-1)
return at_start_of_series
def sample_photo_acquire(test=False):
"""Take a snapshot of the sample"""
if task.cancelled: return
action = task.action; task.action = "Sample Photo"
generate_autorecovery_restore_point("Sample Photo",("laser_safety_shutter_open",
"illuminator_on","DiffX","DiffY","DiffZ","Phi"))
# Remember settings:
laser_shutter_was_open = laser_safety_shutter_open.value
illuminator_was_inserted = illuminator_on.value
phi = Phi.value
x,y,z = DiffX.value,DiffY.value,DiffZ.value
# When the laser shutter is open, a liquid crystal shutter protects
# the camera.
if options.open_laser_safety_shutter: laser_safety_shutter_open.value = False
# Illuminate the sample.
if options.use_illuminator: illuminator_on.value = True
# View the sample at phi = 0.
if len(sample_photo.phis) > 0: Phi.value = sample_photo.phis[0]
# Return the sample to the click-center position.
if align.enabled: DiffX.value,DiffY.value,DiffZ.value = sample.center
while (illuminator_on.moving or Phi.moving or
DiffX.moving or DiffY.moving or DiffZ.moving) and not task.cancelled:
sleep(0.2)
from WideFieldCamera_image import acquire_image
# If the liquid crystal shutter was closed, discard the first few images,
# because the auto-exposure feature of the camera needs time to
# Adjust to the new higher light level.
##if laser_shutter_was_open or not illuminator_was_inserted:
## for i in range(0,3): sample_photo_set_current_image(acquire_image())
for phi in sample_photo.phis:
Phi.value = phi
while Phi.moving and not task.cancelled: sleep(0.1)
if task.cancelled: break
image = acquire_image()
if not test: save_image(image,sample_photo_filename())
sample_photo_set_current_image(image)
# Restore settings.
Phi.value = phi
if align.enabled: DiffX.value,DiffY.value,DiffZ.value = x,y,z
if options.use_illuminator: illuminator_on.value = illuminator_was_inserted
if options.open_laser_safety_shutter: laser_safety_shutter_open.value = laser_shutter_was_open
while (illuminator_on.moving or Phi.moving or
DiffX.moving or DiffY.moving or DiffZ.moving) and not task.cancelled:
sleep(0.2)
clear_autorecovery_restore_point()
task.action = action
def save_image(image,filename):
"""Write a PIL image to a file."""
from os.path import dirname,exists; from os import makedirs
dir = dirname(filename)
if dir!= "" and not exists(dir): makedirs(dir)
image.save(filename)
image.filename = filename
def sample_photo_filename(image_number=None,phi=None):
"""Where to save the current sample photo"""
if image_number is None: image_number = task.image_number
if phi is None: phi = Phi.command_value
from os.path import splitext
basename = splitext(filename(image_number))[0]
pathname = basename+"_%g_deg_photo.jpg" % phi
return pathname
def sample_photo_last_filename():
for i in range(task.image_number,0,-1):
for phi in sample_photo.phis:
if exists(sample_photo_filename(i,phi)):
return sample_photo_filename(i,phi)
return ""
def sample_photo_current_image():
global sample_photo_current_image_
if not "sample_photo_current_image_" in globals():
from PIL import Image
if sample_photo_last_filename():
image = Image.open(sample_photo_last_filename())
else: image = Image.new('RGB',(1360,1024))
sample_photo_current_image_ = image
return sample_photo_current_image_
def sample_photo_set_current_image(image):
global sample_photo_current_image_
sample_photo_current_image_ = image
def generate_autorecovery_restore_point(name,motor_names):
"""Generate an auto-recovery file, in case 'lauecollect' crashes during a
beam check.
motor_names: list of Python variable names"""
s = "operation = %r\n" % name
for motor_name in motor_names:
motor = eval(motor_name)
if hasattr(motor,"command_value"): value = motor.command_value
else: value = motor.value
s += "%s.value = %r\n" % (motor_name,value)
if not exists(settingsdir()): makedirs(settingsdir())
file(settingsdir()+"/lauecollect_autorecovery.py","w").write(s)
def clear_autorecovery_restore_point():
"Undo 'generate_autorecovery_restore_point'"
filename = settingsdir()+"/lauecollect_autorecovery.py"
if exists(filename): remove(filename)
def trigger_autorecovery():
"""Something left in a messy state (cancelled? creashed?)"""
task.autorecovery_needed = True
def sign(x):
if x>0: return 1
if x<0: return -1
return 0
def functions(module):
"Generates a list of all callable function that are members of a module"
function = type(functions)
fnames = []
for name in dir(module):
if type(module.__dict__[name]) == function:
fname = name
args = module.__dict__[name].func_code.co_varnames
fname += "("
for arg in args: fname += (arg+",")
fname = fname.strip(",")
fname += ")"
fnames.append(fname)
return fnames
def check_beamline_status():
"""Test a series of conditions that needs to be met before data collection
can start:
Undulators closed, front end shutter open, ...
"""
U23gap = U23.value; U27gap = U27.value
bad = (U23gap > 29 and U27gap > 29)
if bad:
message = "U23 at %.3f, U27 at %.3f mm\n" % (U23gap,U27gap)
message += "Change to U23 at %.3f, U27 at %.3f mm?" % \
(checklist.U23,checklist.U27)
dlg = wx.MessageDialog(None,message,"Undulators",wx.OK|wx.CANCEL|
wx.ICON_WARNING)
dlg.CenterOnParent()
OK = (dlg.ShowModal() == wx.ID_OK)
dlg.Destroy()
if OK:
U23.value = checklist.U23
U27.value = checklist.U27
while (U23.moving or U27.moving) and not task.cancelled:
sleep(0.1)
U23.stop() ; U27.stop()
state = xray_safety_shutters_open.value
if state != "open":
permit = xray_safety_shutters_enabled.value
if not permit: state += ", no permit"
OK = (state == "open")
def debug_logfile():
"""File name error messages."""
from tempfile import gettempdir
return gettempdir()+"/lauecollect_debug.log"
def timestamp(seconds=None):
"""Current date and time as formatted ASCII text, precise to 1 ms
seconds: time elapsed since 1 Jan 1970 00:00:00 UST"""
if seconds is None: seconds = time()
from datetime import datetime
timestamp = str(datetime.fromtimestamp(seconds))
return timestamp[:-3] # omit microsconds
def progress(message):
"""Report progress to be display by the GUI"""
task.comment = message
if message:
info(message)
def debug(message):
"""Print debug mesage"""
global debug_last_message
if message == debug_last_message: return
debug_last_message = message
from logging import debug
debug(message)
debug_last_message = ""
def round_next(x,step):
"""Rounds x up or down to the next multiple of step."""
if step == 0: return x
return round(x/step)*step
def round_up(x,step):
"""Rounds x up to the next multiple of step."""
from math import ceil
if step == 0: return x
return ceil(float(x)/float(step))*step
def toint(x):
"""Try to convert x to an integer number without rasing an exception."""
try: return int(x)
except: return x
def round_down(x,step):
"""Rounds x down to the next multiple of step."""
from math import floor
if step == 0: return x
return floor(float(x)/float(step))*step
def module_dir():
"directory of the current module"
from os.path import dirname
module_dir = dirname(module_path())
if module_dir == "": module_dir = "."
return module_dir
def module_path():
"full pathname of the current module"
from sys import path
from os import getcwd
from os.path import basename,exists
from inspect import getmodulename,getfile
# 'getfile' retreives the source file name name compiled into the .pyc file.
pathname = getfile(lambda x: None)
if exists(pathname): return pathname
# The module might have been compiled on a different machine or in a
# different directory.
pathname = pathname.replace("\\","/")
filename = basename(pathname)
dirs = [dir for dir in [getcwd()]+path if exists(dir+"/"+filename)]
if len(dirs) == 0: warn("pathname of file %r not found" % filename)
dir = dirs[0] if len(dirs) > 0 else "."
pathname = dir+"/"+filename
return pathname
def UNIX_pathname(pathname):
"""This converts the pathname of a file on a network file server from
the local format to the format used on a UNIX compter.
e.g. "//id14bxf/data" in Windows maps to "/net/id14bxf/data" on Unix"""
if not pathname: return pathname
# Try to expand a Windows drive letter to a UNC name.
try:
import win32wnet
# Convert "J:/anfinrud_0811/Data" to "J:\anfinrud_0811\Data".
pathname = pathname.replace("/","\\")
pathname = win32wnet.WNetGetUniversalName(pathname)
except: pass
# Convert separators from DOS style to UNIX style.
pathname = pathname.replace("\\","/")
if pathname.find("//") == 0: # //server/share/directory/file
parts = pathname.split("/")
if len(parts) >= 4:
server = parts[2] ; share = parts[3]
path = ""
for part in parts[4:]: path += part+"/"
path = path.rstrip("/")
if not exists("//"+server+"/"+share) and exists("/net/"+server+"/"+share):
pathname = "/net/"+server+"/"+share+"/"+path
return pathname
# Get the last save parameters.
reload_settings()
# Go to the first image
##task.image_number = first_image_number() # slow!
def alignment_survey():
for phi in range(30,360,30):
Phi.value = phi; Phi.wait()
align_sample()
def load_variable_sequence(filename):
"""Load data colelction parameters from a spreadsheet table"""
global sequence
from table import table
sequence = table(filename,separator="\t")
for name in sequence.columns:
set_variable_sequence(name,sequence[name])
save_settings()
def set_variable_sequence(name,values):
"""Load data collection parameters from a spreadsheet table"""
if name == "delay":
variable_set_choices(name,list(seconds(list(values))))
elif name == "laser_on":
variable_set_choices("laser_on",list(values))
elif name == "xray_on":
options.xray_on = list(values)
elif name == "translation_mode":
translate.modes = list(values)
elif name == "chopper_mode":
chopper.modes = list(values)
elif name == "pump_on":
pump.on = list(values)
"""This is to run the modules as a stand-alone program.
This code is only executed when the file is passed a run-time argument to
the Python interpreter."""
if __name__ == '__main__':
from pdb import pm # for debugging
import logging
logging.basicConfig(level=logging.DEBUG,
format="%(asctime)s %(levelname)s: %(message)s",
##filename=debug_logfile()
)
image_numbers = collection_pass(1) # for debugging
from thread import start_new_thread
##print('start_new_thread(collect_dataset,())')
##print('collect_dataset()')
print('image_numbers = collection_pass(1)')
print('timing_system_start_images(image_numbers)')
<file_sep>Enabled.action = {
False: 'freeze_intervention.enabled = False',
True: 'freeze_intervention.enabled = True'}
Enabled.defaults = {
'Enabled': False, 'Label': '?'
}
Enabled.properties = {
'BackgroundColour': [
('green', 'freeze_intervention.enabled == False'),
('red', 'freeze_intervention.enabled == True'),
('grey80', 'freeze_intervention.enabled not in [True,False]'),
],
'Enabled': [(True, 'freeze_intervention.enabled in [True,False]')],
'Value': [
(True, 'freeze_intervention.enabled == True'),
(False, 'freeze_intervention.enabled == False'),
],
'Label': [
('Enabled', 'freeze_intervention.enabled == True'),
('Disabled', 'freeze_intervention.enabled == False'),
('?', 'freeze_intervention.enabled not in [True,False]'),
]
}
Active.action = {
False: 'freeze_intervention.active = False',
True: 'freeze_intervention.active = True'}
Active.defaults = {
'Enabled': False, 'Label': '?'
}
Active.properties = {
'BackgroundColour': [
('green', 'freeze_intervention.active == False'),
('red', 'freeze_intervention.active == True'),
('grey80', 'freeze_intervention.active not in [True,False]'),
],
'Enabled': [(True, 'freeze_intervention.active in [True,False]')],
'Value': [
(True, 'freeze_intervention.active == True'),
(False, 'freeze_intervention.active == False'),
],
'Label': [
('Active', 'freeze_intervention.active == True'),
('Not active', 'freeze_intervention.active == False'),
('?', 'freeze_intervention.active not in [True,False]'),
]
}
<file_sep>Size = (801, 737)
Position = (457, 32)
ScaleFactor = 0.33
ZoomLevel = 1.0
Orientation = 0
Mirror = True
NominalPixelSize = 0.000526
filename = '/root/Desktop/hekstra_screenshots/E65_a_precollect..jpg'
ImageWindow.Center = (680, 512)
ImageWindow.ViewportCenter = (0.3568830303030303, 0.2685150303030303)
ImageWindow.crosshair_color = (255, 255, 0)
ImageWindow.boxsize = (0.04, 0.34)
ImageWindow.box_color = (0, 0, 255)
ImageWindow.show_box = True
ImageWindow.Scale = [(0.34032199999999996, -0.14201999999999998), (0.22460199999999997, 0.05996400000000001)]
ImageWindow.show_scale = False
ImageWindow.scale_color = (255, 0, 0)
ImageWindow.crosshair_size = (0.025, 0.025)
ImageWindow.show_crosshair = True
ImageWindow.show_profile = False
ImageWindow.show_FWHM = False
ImageWindow.show_center = False
ImageWindow.calculate_section = False
ImageWindow.profile_color = wx.Colour(255, 0, 255, 255)
ImageWindow.FWHM_color = (255, 255, 0)
ImageWindow.center_color = (0, 255, 0)
ImageWindow.ROI = [[-0.099414, -0.100992], [0.10783, 0.106252]]
ImageWindow.ROI_color = wx.Colour(255, 255, 0, 255)
ImageWindow.show_saturated_pixels = False
ImageWindow.mask_bad_pixels = False
ImageWindow.saturation_threshold = 233
ImageWindow.saturated_color = (255, 0, 0)
ImageWindow.linearity_correction = False
ImageWindow.bad_pixel_threshold = 233
ImageWindow.bad_pixel_color = (0, 0, 0)
ImageWindow.show_grid = False
ImageWindow.grid_type = u'x'
ImageWindow.grid_color = (82, 82, 82)
ImageWindow.grid_x_spacing = 0.055
ImageWindow.grid_x_offset = 0.03070000000000002
ImageWindow.grid_y_spacing = 1.0
ImageWindow.grid_y_offset = 0.0
<file_sep>MEAN.filename = '/net/mx340hs/data/anfinrud_1903/Archive/NIH.SAMPLE_FROZEN_OPTICAL.MEAN.txt'
STDEV.filename = '//mx340hs/data/anfinrud_1903/Archive/NIH.SAMPLE_FROZEN_OPTICAL.STDEV.txt'<file_sep>"""
This is to remote control the sample translation stage for high repetinion
rate time-resolved WAXS experiments.
The stage is a linear motor with 25 mm travel, controlled by an Aerotech
Soloist MP server motor controller with an Etherner interface.
<NAME>, NIH, 24 Sep 2008 - 15 Nov 2014
"""
__version__ = "3.3.3"
import socket # TCP/IP communication
from numpy import nan,isnan
from DB import dbput,dbget
from logging import debug
class SampleStage(object):
"""Linear motor sample translations stage for time-resolved WAXS"""
from Ensemble import SampleZ as motor
from Ensemble_triggered_motion import triggered_motion
version = __version__
unit = "mm"
name = "sample stage"
verbose_logging = True
def get_position(self):
"""Current position in mm"""
return self.motor.value
def set_position(self,position):
# Change the command position of axis 2 only
# (nan is ignored)
self.motor.command_value = position
position = property(get_position,set_position,
doc="""current position in mm, moves the stage if assigned""")
value = position
def get_command_position(self):
"""Nominal target position in mm, is different from actual position
while moving"""
return self.motor.command_value
command_position = property(get_command_position,set_position,
doc="""current position in mm, moves the stage if assigned""")
def get_moving(self):
return self.motor.moving
def set_moving(self,value):
if not moving: self.motor.moving = value
moving = property(get_moving,set_moving,doc="""Tell whether the stage is
currently moving. If assigned False, stops the stage.""")
def stop(self):
"""Cancels current move (and disables external trigger)."""
self.moving = False
def get_calibrated(self):
return self.motor.homed
def set_calibrated(self,value):
self.motor.home = value
calibrated = property(get_calibrated,set_calibrated,
doc="Has the encoder has been set to zero at the home switch? "+
"Runs calibration if False and assigned the value True.")
def calibrate(self):
"""Drives stage to the home switch and sets enoder to zero"""
self.calibrated = True
def get_at_high_limit(self):
"""Is the stage at end of travel?"""
return self.motor.at_high_limit
at_high_limit = property(get_at_high_limit)
def get_at_low_limit(self):
"""Is the stage at end of travel?"""
return self.motor.at_low_limit
at_low_limit = property(get_at_low_limit)
def get_trigger_enabled(self):
"""Move stage on rising edge of digital input?"""
return self.triggered_motion.trigger_enabled
def set_trigger_enabled(self,value):
self.triggered_motion.trigger_enabled = value
trigger_enabled = property(get_trigger_enabled,set_trigger_enabled)
def get_timer_enabled(self):
"""Move the stage periodically, based on an internal timer?"""
return self.triggered_motion.timer_enabled
def set_timer_enabled(self,value):
self.triggered_motion.timer_enabled = value
timer_enabled = property(get_timer_enabled,set_timer_enabled)
def get_timer_period(self):
"""At which frequency to move based on internal timer?"""
return self.triggered_motion.timer_period
def set_timer_period(self,value):
self.triggered_motion.timer_period = value
timer_period = property(get_timer_period,set_timer_period)
def get_auto_return(self):
return self.triggered_motion.auto_return
def set_auto_return(self,value):
self.triggered_motion.auto_return = value
auto_return = property(get_auto_return,set_auto_return,doc="On external"+
" trigger, does the stage return to start when it reaches a travel limit?")
def get_return_time(self):
"""Time needed to move from the end to the start position or the travel
range"""
from math import sqrt
a = self.acceleration
start,end = self.start_position,self.end_position
s = abs(end-start)
return 2*sqrt(s/a)
def set_return_time(self,t):
"""Change the acceleration to acheive the specified return time"""
from numpy import nan
start,end = self.start_position,self.end_position
s = abs(end-start)
a = 4*s/t**2
##debug("sample stage: acceleration = %r" % a)
self.acceleration = a
return_time = property(get_return_time,set_return_time)
def travel_time(self,start,end):
"""How long does it take to move from start to end?"""
from math import sqrt
a = self.acceleration
s = abs(end-start)
return 2*sqrt(s/a)
def get_enabled(self):
"""Holding current applied and feedback loop active?"""
return self.motor.enabled
def set_enabled(self,value):
self.motor.enabled = value
enabled = property(get_enabled,set_enabled)
drive_enabled = enabled
def get_speed(self):
"""Speed in triggered mode in mm/s"""
return self.motor.speed
def set_speed(self,value):
self.motor.speed = value
speed = property(get_speed,set_speed)
def get_acceleration(self):
"""Acceleration in non-triggered mode in mm/s2"""
return self.motor.acceleration
def set_acceleration(self,value):
self.motor.acceleration = value
acceleration = property(get_acceleration,set_acceleration)
acceleration_in_triggered_mode = acceleration
def get_homed(self):
"""Is the axis homed?"""
return self.motor.homed
def set_homed(self,value):
self.motor.homed = value
homed = property(get_homed,set_homed)
def get_homing(self):
"""Is the axis currently executing the "find home" calibration?"""
return self.motor.homing
def set_homing(self,value):
self.motor.homing = value
homing = property(get_homing,set_homing)
def get_low_limit(self):
"""End of travel in negative direction in mm"""
return self.motor.low_limit
def set_low_limit(self,value):
self.motor.low_limit = value
low_limit = property(get_low_limit,set_low_limit)
def get_high_limit(self):
"""end of travel in positive direction in mm"""
return self.motor.high_limit
def set_high_limit(self,value):
self.motor.high_limit = value
high_limit = property(get_high_limit,set_high_limit)
def get_limits(self):
"""travel range in mm"""
return self.low_limit,self.high_limit
def set_limits(self,limits):
self.low_limit = limits[0]
self.high_limit = limits[1]
limits = property(get_limits,set_limits)
def get_trigger_count(self):
"""Number if trigger pulses detected"""
return self.triggered_motion.trigger_count
def set_trigger_count(self,value):
self.triggered_motion.trigger_count = value
trigger_count = property(get_trigger_count,set_trigger_count,
doc="""Number if trigger pulses detected""")
def get_step_count(self):
"""Number of triggered motions executed"""
return self.triggered_motion.step_count
def set_step_count(self,value):
self.triggered_motion.step_count = value
step_count = property(get_step_count,set_step_count,
doc="""Number of triggered motions executed.""")
def get_firmware_version(self):
return self.triggered_motion.version
firmware_version = property(get_firmware_version,
doc="""Release number of software running on motion controller""")
@property
def status(self):
"""Informational message for diagnostics."""
try: value = self.motor.value
except: value = nan
if isnan(value): return "Ensemble IOC not running"
if self.firmware_version == "":
return "AeroBasic program not loaded on Ensemble"
if not self.triggered_motion.enabled:
return "AeroBasic program not running on Ensemble"
return "OK"
@property
def online(self):
"""Is instrument usable?"""
try: value = self.motor.value
except: value = nan
return not isnan(value)
def update(self):
"""Update the step size and travel range for the current temperature"""
# Download positions into the controller.
##from numpy import array,concatenate
##Z = concatenate([self.positions]*self.repeats)
self.triggered_motion.Z.enabled = 1
self.triggered_motion.Z.trigger_divisor = 1
self.triggered_motion.Z.relative_move = 0
self.triggered_motion.Z.positions = self.positions
self.triggered_motion.enabled = True
@property
def positions(self):
"""Where the stage stops after triggered transtation.
list of z values."""
# Calculate the positions.
from numpy import arange
stepsize = abs(self.stepsize)
if self.end_position < self.start_position: stepsize *= -1
nsteps = (self.end_position - self.start_position)/stepsize
z = self.start_position+arange(0,nsteps+1)*stepsize
return z
def get_start_position(self):
"""Amplitude of motion executed on external trigger"""
if not self.temperature_correction: return self.normal_start_position
else: return self.temperature_corrected_start_position
def set_start_position(self,value):
if not self.temperature_correction: self.normal_start_position = value
else: self.temperature_corrected_start_position = value
start_position = property(get_start_position,set_start_position)
def get_end_position(self):
"""Amplitude of motion executed on external trigger"""
if not self.temperature_correction: return self.normal_end_position
else: return self.temperature_corrected_end_position
def set_end_position(self,value):
if not self.temperature_correction: self.normal_end_position = value
else: self.temperature_corrected_end_position = value
end_position = property(get_end_position,set_end_position)
def get_travel(self):
"""On exernal trigger, the stage is stepping between these two
positions. (start,end) tuple"""
return self.start_position,self.end_position
def set_travel(self,(start,end)):
self.start_position,self.end_position = start,end
travel = property(get_travel,set_travel)
def get_stepsize(self):
"""Amplitude of motion executed on external trigger"""
if self.steps == 0: return 0.2
if self.end_position == self.start_position: return 0.2
return (self.end_position-self.start_position)/self.steps
def set_stepsize(self,stepsize):
from numpy import isnan,floor
if isnan(stepsize): return
if stepsize == 0: return
self.steps = floor((self.end_position-self.start_position)/stepsize)
stepsize = property(get_stepsize,set_stepsize)
def get_home_position(self):
"""Used for setup and alignment"""
try: return float(dbget("sample_translation.home"))
except ValueError: return 0.0
def set_home_position(self,value):
dbput("sample_translation.home",repr(value))
home_position = property(get_home_position,set_home_position)
def get_park_position(self):
"""Predefined position used for data collection"""
try: return float(dbget("sample_translation.park"))
except ValueError: return -12.5
def set_park_position(self,value):
dbput("sample_translation.park",repr(value))
park_position = property(get_park_position,set_park_position)
def get_normal_start_position(self):
"""Start position at calibration temperature"""
try: return float(dbget("sample_translation.start_position"))
except ValueError: return -2.0
def set_normal_start_position(self,value):
dbput("sample_translation.start_position",repr(value))
normal_start_position = property(get_normal_start_position,
set_normal_start_position)
def get_normal_end_position(self):
"""Start position at calibration temperature"""
try: return float(dbget("sample_translation.end_position"))
except ValueError: return 10.0
def set_normal_end_position(self,value):
dbput("sample_translation.end_position",repr(value))
normal_end_position = property(get_normal_end_position,
set_normal_end_position)
def get_steps(self):
"""Start position at calibration temperature"""
try: return int(dbget("sample_translation.steps"))
except ValueError: return 50
def set_steps(self,value):
from numpy import rint
value = int(rint(value))
dbput("sample_translation.steps",repr(value))
steps = nsteps = property(get_steps,set_steps)
def get_auto_reverse(self):
try: return bool(int(dbget("sample_translation.auto_reverse")))
except ValueError: return False
def set_auto_reverse(self,value):
dbput("sample_translation.auto_reverse",repr(int(value)))
auto_reverse = property(get_auto_reverse,set_auto_reverse)
def get_move_when_idle(self):
"""Keep moving te stage when not triggered"""
try: return bool(int(dbget("sample_translation.move_when_idle")))
except ValueError: return False
def set_move_when_idle(self,value):
dbput("sample_translation.move_when_idle",repr(int(value)))
move_when_idle = property(get_move_when_idle,set_move_when_idle)
def get_temperature_correction(self):
"""Use temperatrue to adjust start and end position and stepsize?"""
try: return bool(int(dbget("sample_translation.temperature_correction")))
except ValueError: return False
def set_temperature_correction(self,value):
dbput("sample_translation.temperature_correction",repr(int(value)))
temperature_correction = property(get_temperature_correction,
set_temperature_correction)
def get_calibration_temperature_1(self):
"""Temperature at which 'calibrated stepsize' and
'calibrated starting position' are the actual stepsize and starting
positions"""
try: return float(dbget("sample_translation.calibration_temperature_1"))
except ValueError: return 20.0
def set_calibration_temperature_1(self,value):
dbput("sample_translation.calibration_temperature_1",repr(value))
calibration_temperature_1 = property(get_calibration_temperature_1,
set_calibration_temperature_1)
def get_calibrated_start_position_1(self):
"""Start position at calibration temperature"""
try: return float(dbget("sample_translation.calibrated_start_position_1"))
except ValueError: return -2.0
def set_calibrated_start_position_1(self,value):
dbput("sample_translation.calibrated_start_position_1",repr(value))
calibrated_start_position_1 = property(get_calibrated_start_position_1,
set_calibrated_start_position_1)
def get_calibrated_end_position_1(self):
"""Start position at calibration temperature"""
try: return float(dbget("sample_translation.calibrated_end_position_1"))
except ValueError: return 10.0
def set_calibrated_end_position_1(self,value):
dbput("sample_translation.calibrated_end_position_1",repr(value))
calibrated_end_position_1 = property(get_calibrated_end_position_1,
set_calibrated_end_position_1)
def get_calibration_temperature_2(self):
"""Temperature at which 'calibrated stepsize' and
'calibrated starting position' are the actual stepsize and starting
positions"""
try: return float(dbget("sample_translation.calibration_temperature_2"))
except ValueError: return 40.0
def set_calibration_temperature_2(self,value):
dbput("sample_translation.calibration_temperature_2",repr(value))
calibration_temperature_2 = property(get_calibration_temperature_2,
set_calibration_temperature_2)
def get_calibrated_start_position_2(self):
"""Start position at calibration temperature"""
try: return float(dbget("sample_translation.calibrated_start_position_2"))
except ValueError: return -2.0
def set_calibrated_start_position_2(self,value):
dbput("sample_translation.calibrated_start_position_2",repr(value))
calibrated_start_position_2 = property(get_calibrated_start_position_2,
set_calibrated_start_position_2)
def get_calibrated_end_position_2(self):
"""Start position at calibration temperature"""
try: return float(dbget("sample_translation.calibrated_end_position_2"))
except ValueError: return 10.0
def set_calibrated_end_position_2(self,value):
dbput("sample_translation.calibrated_end_position_2",repr(value))
calibrated_end_position_2 = property(get_calibrated_end_position_2,
set_calibrated_end_position_2)
def get_temperature(self):
"""In degrees Celsius. Measured by temperature controller"""
from temperature_controller import temperature_controller
# Use the set point for reproducebilty rather than te measured
# temperature.
return temperature_controller.setT.value
def set_temperature(self,value):
from temperature_controller import temperature_controller
temperature_controller.setT.value = value
temperature = property(get_temperature,set_temperature)
def get_temperature_corrected_start_position(self):
"""Interpolated start_position for the current temperature"""
T = self.temperature
T1,T2 = self.calibration_temperature_1,self.calibration_temperature_2
x1,x2 = self.calibrated_start_position_1,self.calibrated_start_position_2
x = x1+(x2-x1)/(T2-T1)*(T-T1)
return x
def set_temperature_corrected_start_position(self,x):
offset = x - self.temperature_corrected_start_position
self.calibrated_start_position_1 += offset
self.calibrated_start_position_2 += offset
temperature_corrected_start_position = property(
get_temperature_corrected_start_position,
set_temperature_corrected_start_position)
def get_temperature_corrected_end_position(self):
"""Interpolated start_position for the current temperature"""
T = self.temperature
T1,T2 = self.calibration_temperature_1,self.calibration_temperature_2
x1,x2 = self.calibrated_end_position_1,self.calibrated_end_position_2
x = x1+(x2-x1)/(T2-T1)*(T-T1)
return x
def set_temperature_corrected_end_position(self,x):
offset = x - self.temperature_corrected_end_position
self.calibrated_end_position_1 += offset
self.calibrated_end_position_2 += offset
temperature_corrected_end_position = property(
get_temperature_corrected_end_position,
set_temperature_corrected_end_position)
def get_repeats(self):
"""Start position at calibration temperature"""
try: return int(dbget("sample_translation.repeats"))
except ValueError: return 1
def set_repeats(self,value):
dbput("sample_translation.repeats",repr(value))
repeats = property(get_repeats,set_repeats)
@property
def address(self):
"""Network identifier"""
return ""
def log_error(self,message):
"""For error messages.
Display the message and append it to the error log file.
If verbose logging is enabled, it is also added to the transcript."""
from sys import stderr
if len(message) == 0 or message[-1] != "\n": message += "\n"
t = timestamp()
file(self.error_logfile,"a").write("%s: %s" % (t,message))
##stderr.write("%s: %s: %s" % (t,self.ip_address,message))
##self.log(message)
def get_error_logfile(self):
"""File name error messages."""
from tempfile import gettempdir
return gettempdir()+"/sample_translation_error.log"
error_logfile = property(get_error_logfile)
def log(self,message):
"""For non-critical messages.
Append the message to the transcript, if verbose logging is enabled."""
if not self.verbose_logging: return
if len(message) == 0 or message[-1] != "\n": message += "\n"
t = timestamp()
file(self.logfile,"a").write("%s: %s" % (t,message))
def get_logfile(self):
"""File name for transcript if verbose logging is enabled."""
from tempfile import gettempdir
return gettempdir()+"/sample_translation.log"
logfile = property(get_logfile)
def timestamp():
"""Current date and time as formatted ASCII text, precise to 1 ms"""
from datetime import datetime
timestamp = str(datetime.now())
return timestamp[:-3] # omit microsconds
sample_stage = SampleStage()
cancelled = True # to top "run_test"
delay_time = 0 # 2.5 to simulate detector readout
repeat_count = 4 # number of strokes before delay
def run_test():
"""Stand-alone operation simulating Lauecollect"""
from instrumentation import transon,tmode,waitt,pulses,mson,laseron
from time import sleep,time
from numpy import rint
global cancelled; cancelled = False
# Make sure laser and X-ray are not firing
old_laseron = laseron.value; old_mson = mson.value; old_tmode = tmode.value
laseron.value = False; mson.value = False
tmode.value = 1 # counted
transon.value = 1 # Tell FPGA to output trigger pulses for stage.
sample_stage.timer_enabled = False
sample_stage.update()
sample_stage.step_count = 1
sample_stage.position = sample_stage.start_position
while sample_stage.moving: sleep(0.05)
sample_stage.trigger_enabled = True
while not cancelled and sample_stage.homed:
pulses.value = sample_stage.nsteps+1 # Start triggering
wait_time = sample_stage.nsteps*waitt.value + sample_stage.return_time\
+ 0.2
t0 = time()
while time()-t0 < wait_time and not cancelled: sleep(0.02)
if not sample_stage.homed: cancelled = True
sample_stage.trigger_enabled = False
pulses.value = 0
laseron.value = old_laseron; mson.value = old_mson; tmode.value = old_tmode
def start_test():
"""Start stand-alone operation simlating Lauecollect"""
global cancelled
cancelled = False
from thread import start_new_thread
start_new_thread(run_test,())
def stop_test():
"""Stop stand-alone operation simlating Lauecollect"""
global cancelled
cancelled = True
sample_stage.trigger_enabled = False
from instrumentation import pulses
pulses.value = 0
def test_running():
return not cancelled
if __name__ == '__main__': # test program
from pdb import pm
import logging
##logging.basicConfig(level=logging.DEBUG,format="%(asctime)s: %(message)s")
self = sample_stage
print 'self.update()'
print 'self.triggered_motion.pos'
<file_sep>"""
Redirect statdard output and standard error output
Author: <NAME>
Data created: 2017-11-14
Date last modified: 2019-03-16
"""
__version__ = "1.1.1" # Issue: self.output.write exception
class redirector(object):
"""Saves a copy of standard output or standard error output to a file and
Adds a timestamp if needed.
Usage: sys.stderr = redirector(sys.stderr)"""
lock = {}
def __init__(self,output,filename):
"""output: sys.stdout or sys.stderr
filename: absolute pathname
"""
from thread import allocate_lock
self.filename = filename
self.output = output
self.name = filename # for compatibility with "stream" objects
if not filename in self.lock: self.lock[filename] = allocate_lock()
def write(self,message):
if not hasattr(self.output,"output"):
try: self.output.write(message)
except: pass # printing an error message could cause a loop
if message not in ["","\n"]:
log_message = message
if not log_message.endswith("\n"): log_message += "\n"
if not has_timestamp(message):
if self.output_name: log_message = self.output_name+" "+log_message
log_message = timestamp()+" "+log_message
try:
with self.lock[self.filename]:
try: file(self.filename,"ab").write(log_message)
except: pass # printing an error message could cause a loop
except:
try: file(self.filename,"ab").write(log_message)
except: pass # printing an error message could cause a loop
@property
def output_name(self):
"""'<stdout>' or '<stderr>'"""
output_name = getattr(self.output,"name","")
output_name = output_name.strip("<>")
output_name = output_name.upper()
return output_name
def __repr__(self):
return "redirector(%r,%r)" % (self.output,self.filename)
def redirect1(logfile_basename):
"""Redirect stdout and stderr to a file
logfile_basename: filename without directort, extension ".log" will be added"""
import sys
sys.stdout = file(stdout_filename(logfile_basename),"ab")
sys.stderr = file(stderr_filename(logfile_basename),"ab")
def redirect(logfile_basename,level="DEBUG",
format="%(asctime)s %(levelname)s: %(message)s"):
"""Redirect stdout and stderr to a file
logfile_basename: filename without directort, extension ".log" will be added"""
import sys
sys.stdout = redirector(sys.stdout,log_filename(logfile_basename))
sys.stderr = redirector(sys.stderr,log_filename(logfile_basename))
from logging_filename import log_to_file,suppress_logging_to_stderr
suppress_logging_to_stderr()
log_to_file(
filename=sys.stderr,
level=level,
format=format,
)
def log_filename(logfile_basename):
from tempfile import gettempdir
filename = gettempdir()+"/"+logfile_basename+".log"
return filename
def stdout_filename(logfile_basename):
from tempfile import gettempdir
filename = gettempdir()+"/"+logfile_basename+"_stdout.log"
return filename
def stderr_filename(logfile_basename):
from tempfile import gettempdir
filename = gettempdir()+"/"+logfile_basename+"_stderr.log"
return filename
def has_timestamp(message):
""""""
return message.startswith("20")
def timestamp():
"""Current date and time as string in ISO format"""
from datetime import datetime
return str(datetime.now())
if __name__ == "__main__":
from logging import debug,info,warn,error
import logging
import sys
from logging_filename import * # for testing
print('logging.basicConfig(level=logging.DEBUG)')
print('logging.getLoggerClass().root.level = logging.DEBUG')
print('redirect("test")')
print('print("test")')
print('debug("debug")')
print('info("info")')
print('warn("warn")')
print('id(sys.stderr)')
<file_sep>#!/bin/env python
"""
CA Strip Chart
by <NAME> and <NAME>
23 May 2018 - Oct 26 2018
last updated: March 18 2019
The strip chart interacts with Channel Archiver to receive all archived data.
After the data is received, it uses channel access to update its' circular buffers.
2.0.2 -
3.0.0 - the code is competable with python 2.7 and 3.7
3.0.1 - fixed competability with wxPython 3 and 4
"""
__version__ = "3.0.1"
from optparse import OptionParser
from time import time, sleep,localtime,strftime,clock
import numpy as np
import sys
from struct import unpack
import wx
#import StringIO
from pdb import pm
import traceback
import PIL
import io
import matplotlib
matplotlib.use('WxAgg')
##import matplotlib.pyplot as plt
##from matplotlib.backends.backend_wxagg import FigureCanvasWxAgg as FCW
##from matplotlib.figure import Figure
#SMALL_SIZE = 8
#matplotlib.rc('font', size=SMALL_SIZE)
#matplotlib.rc('axes', titlesize=SMALL_SIZE)
from logging import error,warn,info,debug
if sys.version_info[0] ==3:
#from persistent_property3 import persistent_property #Python 3.7 competable library
from _thread import start_new_thread #Python 3.7 competable library
else:
#from persistent_property import persistent_property
from thread import start_new_thread
import autoreload
from persistent_property3 import persistent_property
class ClientGUI(wx.Frame):
def __init__(self):
self.create_GUI()
def create_GUI(self):
#This function creates buttons with defined position and connects(binds) them with events that
#This function creates buttons with defined position and connects(binds) them with events that
#####Global start variable####
self.local_time = time()
self.draw_flag = True
self.smooth_factor = 1
self.redraw_timer_value = 400.0
self.frequency = 1 #this is actually frequency, not time
self.time_list = [10*self.frequency,30*self.frequency,60*self.frequency,60*2*self.frequency,60*5*self.frequency,
60*10*self.frequency,60*30*self.frequency,60*60*self.frequency,
60*2*60*self.frequency,60*6*60*self.frequency,60*12*60*self.frequency,60*24*60*self.frequency]
self.time_range = 60
self.txt_font_size = 10
self.arg2 = 10
self.environment = 0 #APS is 0, NIH is 1; localhost is 2
self.DicObjects = {} #this is a dictionary with all different objects in GUI
##Create Frame ans assign panel
frame = wx.Frame.__init__(self, None, wx.ID_ANY, "CA Strip Chart", pos = (0,0))
self.panel = wx.Panel(self, wx.ID_ANY, style=wx.BORDER_THEME,size = (400,70), pos = (0,0))
###########################################################################
##MENU STARTS: for the GUI
###########################################################################
file_item = {}
about_item = {}
self.calib_item = {}
self.opt_item = {}
menubar = wx.MenuBar()
fileMenu = wx.Menu()
file_item[2] = fileMenu.Append(wx.ID_EXIT, 'Quit', 'Quit application')
self.Bind(wx.EVT_MENU, self.OnQuit, file_item[2])
aboutMenu = wx.Menu()
about_item[0]= aboutMenu.Append(wx.ID_ANY, 'About')
self.Bind(wx.EVT_MENU, self._on_client_about, about_item[0])
menubar.Append(fileMenu, '&File')
menubar.Append(aboutMenu, '&About')
self.SetMenuBar(menubar)
self.Centre()
self.Show(True)
###########################################################################
###MENU ENDS###
###########################################################################
sizer = wx.GridBagSizer(5, 1)
self.live_checkbox = wx.CheckBox(self.panel, id=wx.ID_ANY, label="Live", style=0, validator=wx.DefaultValidator, name='LiveCheckBoxNameStr')
sizer.Add( self.live_checkbox, pos=(0, 0), flag=wx.TOP|wx.LEFT, border=5)
self.live_checkbox.SetValue(False)
self.live_checkbox.Enable()
text5 = wx.StaticText(self.panel, label="time")
sizer.Add(text5, pos=(0, 1), flag=wx.TOP|wx.LEFT, border=5)
self.time_dropdown_list = ['10 s','30 s', '1 min', '2 min', '5 min' , '10 min' , '30 min','1 hr','2 hr','6 hr', '12 hr', '24 hr']#, 'max']
self.time_choice = wx.Choice(self.panel,choices = self.time_dropdown_list)
sizer.Add(self.time_choice, pos=(0,2), span = (1,1), flag=wx.LEFT|wx.TOP, border=5)
self.time_choice.Bind(wx.EVT_CHOICE, self._on_change_time_press)
self.time_choice.SetSelection(1)
self.PV_names = ['NIH:TEMP.RBV',
'NIH:TEMP.VAL',
'NIH:SAMPLE_FROZEN_OPT_RGB.MEAN',
'NIH:CHILLER.RBV',
'NIH:CHILLER.VAL',
'NIH:SAMPLE_FROZEN_OPT_RGB.STDEV',
'NIH:SAMPLE_FROZEN_OPT2.MEAN',
'NIH:TEMP.I',
'NIH:TEMP.P',
'NIH:CHILLER.fault_code',
'NIH:Pressure_Upstream',
'NIH:Pressure_Downstream',
'NIH:OASIS_DL.RBV',
'NIH:OASIS_DL.VAL',
'NIH:OASIS_DL.FLT',
'NIH:SAMPLE_FROZEN_OPTICAL.MEAN',
'NIH:SAMPLE_FROZEN_OPTICAL2.MEAN',
'NIH:SAMPLE_FROZEN_OPTICAL.STDEV',
'NIH:SAMPLE_FROZEN_XRAY.SPOTS',
]
self.PV_choice = wx.Choice(self.panel,choices = self.PV_names)
sizer.Add(self.PV_choice, pos=(1,0), span = (1,3), flag=wx.LEFT|wx.TOP, border=5)
self.PV_choice.SetSelection(1)
self.graph_number = ['0','1','2','3']
self.graph_choice = wx.Choice(self.panel,choices = self.graph_number)
sizer.Add(self.graph_choice, pos=(1,4), span = (1,1), flag=wx.LEFT|wx.TOP, border=5)
self.graph_choice.Bind(wx.EVT_CHOICE, self._on_plotting_choice)
self.graph_choice.SetSelection(1)
self.live_checkbox.SetValue(False)
sizer.AddGrowableCol(2)
self.panel.SetSizer(sizer)
self.bitmapfigure = wx.StaticBitmap(self.panel)#, bitmap=bmp1)
sizer.Add(self.bitmapfigure, pos=(2,0), span=(8,6), flag = wx.EXPAND)#,
debug('after add bitmapfigure')
self.Centre()
self.Show(True)
self.panel.SetSizer(sizer)
self.Layout()
self.panel.Layout()
#self.Fit()
self.redraw_timer = wx.Timer(self)
self.Bind(wx.EVT_TIMER, self.on_redraw_timer, self.redraw_timer)
self.redraw_timer.Start(self.redraw_timer_value)
stripchart.draw()
def _on_client_about(self,event):
"Called from the Help/About"
from os.path import basename
from inspect import getfile
filename = getfile(lambda x: None)
info = basename(filename)+" version: "+__version__+"\n"+__doc__
dlg = wx.MessageDialog(self,info,"About",wx.OK|wx.ICON_INFORMATION)
dlg.CenterOnParent()
dlg.ShowModal()
dlg.Destroy()
def _on_server_about(self,event):
wx.MessageBox('This is information about the server', 'Server Info',
wx.OK | wx.ICON_INFORMATION)
def OnQuit(self, event):
for i in range(len(stripchart)):
i.kill
self.Close()
def _on_change_ip_press(self,event):
info("Dropdown IP menu: selected %s , New IP address : %r" % (self.ip_dropdown_list[1][self.IP_choice.GetSelection()],self.ip_dropdown_list[0][self.IP_choice.GetSelection()]))
client.ip_address_server = self.ip_dropdown_list[0][self.IP_choice.GetSelection()]
self.live_checkbox.SetValue(False)
self.live_checkbox.Disable()
def _on_plotting_choice(self,event):
PV = self.PV_names[self.PV_choice.GetSelection()]
graph = int(self.graph_number[self.graph_choice.GetSelection()])
try:
stripchart[graph].kill()
except:
error(traceback.format_exc())
stripchart.replace(position = graph, PV = PV)
if stripchart.stripchart[graph].running == False:
stripchart.stripchart[graph].running = True
def _on_change_time_press(self,event):
self.time_list = [10,30,60,60*2,60*5,60*10,60*30,60*1*60,2*60*60,6*60*60,12*60*60,24*60*60]
self.time_range = self.time_list[self.time_choice.GetSelection()]
info('self time_range selected %r' % (self.time_range))
if self.time_range == 10:
self.smooth_factor = 1
self.redraw_timer.Start(self.redraw_timer_value)
elif self.time_range == 30:
self.smooth_factor = 1
self.redraw_timer.Start(self.redraw_timer_value)
elif self.time_range == 1*60:
self.smooth_factor = 1
self.redraw_timer.Start(self.redraw_timer_value*1.2)
elif self.time_range == 2*60:
self.smooth_factor = 1
self.redraw_timer.Start(self.redraw_timer_value*5)
elif self.time_range == 5*60:
self.smooth_factor = 1
self.redraw_timer.Start(self.redraw_timer_value*10)
elif self.time_range == 10*60:
self.smooth_factor = 1
self.redraw_timer.Start(self.redraw_timer_value*10)
elif self.time_range == 0.5*3600:
self.smooth_factor = 1
self.redraw_timer.Start(self.redraw_timer_value*20)
else:
self.smooth_factor = 1
self.redraw_timer.Start(self.redraw_timer_value*20)
stripchart.draw()
def _on_command_list_select(self,event):
info('commands from the list selected')
def _set_response(self,response_arg):
self.local_time = response_arg[1]
self.DicObjects['server time'].SetLabel(strftime("%Y-%m-%d %H:%M:%S", localtime(self.local_time)))
def method_result(self,method = 'window'):
if method == 'window':
self.DicObjects['result'].SetLabel(str(self.result))
def _on_server_comm(self,event):
pass
def _on_save_file_press(self,event):
#msgpack_packb([time(),], default=m.encode)
np.savetxt('CA_strip_chart'+str(time())+stripchart.PV+'.csv',np.transpose(buffer.buffer), delimiter=',' , fmt='%1.4e')
def mthd_buttons(self, event):
"""
This method is an event handler. It cross refences the event Id and an Id stored in a dictionary to determine what to do.
"""
self.live_checkbox.SetValue(True)
self.live_checkbox.Enable()
#################################################################################
########### Plotting
#################################################################################
def on_redraw_timer(self, event):
debug('on_redraw_timer')
if self.live_checkbox.IsChecked() and not stripchart.drawing: #plot only if the live checkbox is checked
#start_new_thread(self.draw,(event,))
start_new_thread(stripchart.draw,())
#stripchart.draw()
def smooth(self, y, step = 1): #this is a smoothing function that helps speed up plotting
if step == 1:
y_out = y
else:
y_out = np.zeros(len(y)/step)
for i in range(len(y_out)):
if i == 0:
y_out[i] = np.mean(y[0:int((1)*step)])
elif i == len(y_out)-1:
y_out[i] = np.mean(y[int((i)*step):])
else:
y_out[i] = np.mean(y[int((i)*step):int((i+1)*step)])
return y_out
def draw(self,event):
"""
shows the bitmap generated in the
"""
def buf2wx (buf):
import PIL
image = PIL.Image.open(buf)
width, height = image.size
return wx.Bitmap.FromBuffer(width, height, image.tobytes())
def buf2wx_3020(buf):
import PIL
image = PIL.Image.open(buf)
width, height = image.size
return wx.BitmapFromBuffer(width, height, image.tobytes())
## try:
## self.figurebuf1 = self.draw_figure1(self.dic_lst)
## except:
## error(traceback.format_exc())
## try:
## self.figurebuf2 = self.draw_figure2(self.dic_lst)
## except:
## error(traceback.format_exc())
if wx.__version__[0] == '3':
self.bitmapfigure.SetBitmap(buf2wx_3020(stripchart.figurebuf))
elif wx.__version__[0] == '4':
self.bitmapfigure.SetBitmap(buf2wx(stripchart.figurebuf))
#self.bitmap1.SetPosition((0,0))
#self.bitmap2.SetPosition((500,0))
#self.Refresh()
self.panel.Layout()
self.panel.Fit()
#self.panel.Refresh()
self.Layout()
self.Fit()
class StripChart(object):
selected_CA_values = persistent_property('selected_CA_values', ['NIH:TEMP.RBV',
'NIH:CHILLER.RBV',
'NIH:TEMP.I',
'NIH:SAMPLE_FROZEN_OPTICAL2.MEAN'])
#selected_CA_values = persistent_property('selected_CA_values', ['','NIH:CHILLER.RBV','','NIH:SAMPLE_FROZEN_OPTICAL.MEAN'])
class StripRecorder(object):
def __init__(self,PV,buffersize = 120000):
from circular_buffer_LL import server
self.running = False
if PV == 'NIH:TEMP.RBV':
buffersize = 240000
self.buffer = server(size = (2,buffersize), var_type = 'float64')
from numpy import zeros, nan,asarray
self.PV = PV
self.arr = zeros((2,1)) + nan
try:
buff = asarray(self.get_data(PV,time()-3600*24,3600*24))
self.buffer.append(buff)
except:
error(traceback.format_exc())
if len(PV) != 0:
self.start()
self.drawing = False
def start(self):
#if sys.version_info[0] ==3:
from CA3 import camonitor
#else:
#from CA import camonitor
self.running = True
camonitor(self.PV,callback=self.callback)
def callback(self,pvname,value,char_value):
from time import time
self.arr[0,0] = time()
self.arr[1,0] = value
self.buffer.append(self.arr)
def get_data(self,PV,from_t,duration_t):
if sys.version_info[0] ==3:
from channel_archiver3 import channel_archiver
else:
from channel_archiver import channel_archiver
from numpy import asarray
print('uploading data from CA for PV = %r' % PV)
return asarray(channel_archiver.history(PV,from_t,from_t+duration_t))
def kill(self):
del self
def __init__(self):
self.stripchart = ['','','','']
def add(self,position,PV = 'NIH:TEMP.RBV' , buffersize = 240000):
self.stripchart[position] = self.StripRecorder(PV = PV,buffersize = buffersize)
self.selected_CA_values[position] = PV
def replace(self,position = 0, PV = 'NIH:TEMP.RBV' , buffersize = 240000):
self.stripchart[position] = self.StripRecorder(PV = PV,buffersize = buffersize)
self.selected_CA_values[position] = PV
def pop(self,position):
try:
self.stripchart[position].kill()
except:
info('nothing to kill')
def chart(self,time_range = 60):
from matplotlib.figure import Figure
from matplotlib import pyplot, rc
from matplotlib.backends.backend_wxagg import FigureCanvasWxAgg as FCW
SMALL_SIZE = 8
rc('font', size=SMALL_SIZE)
rc('axes', titlesize=SMALL_SIZE)
from numpy import searchsorted, nanargmin, nan
dpi = 100
figure = Figure(figsize=(4,6),dpi = dpi)#figure((4, 6), dpi=dpi)
axes = []
axes.append(figure.add_subplot(411))
axes.append(figure.add_subplot(412))
axes.append(figure.add_subplot(413))
axes.append(figure.add_subplot(414))
self.draw_flag = False
local_time = time()
buffer = []
x = []
y = []
index = 0
for sc in self.stripchart:
buff = sc.buffer.buffer
pointer = sc.buffer.pointer
debug('buff = %r, pointer = %r' %(buff.shape,pointer))
try:
plot_from = nanargmin(abs(buff[0] - (local_time-time_range)))
except Exception as err:
error(err)
plot_from = -1
if plot_from is nan:
plot_from = 0
plot_to = pointer
#print('PV: %r , plot_from %r, plot_to %r and time ranfe = %r' % (sc.PV,plot_from, plot_to, self.time_range))
if pointer>plot_from:
x.append(buff[0,plot_from:plot_to])
y.append(buff[1,plot_from:plot_to])
else:
x.append(np.concatenate((buff[0,plot_from:],buff[0,0:plot_to])))
y.append(np.concatenate((buff[1,plot_from:],buff[1,0:plot_to])))
from numpy import log10
for index in range(len(stripchart.stripchart)):
axes[index].cla()
if index == 3:
axes[index].plot(x[index],y[index],'ob', markersize = 1)
axes[3].set_yscale('log')
else:
axes[index].plot(x[index],y[index],'ob', markersize = 1)
axes[index].set_title(stripchart.stripchart[index].PV)
axes[3].set_xlabel("time, seconds")
for index in range(len(stripchart.stripchart)):
axes[index].set_xticklabels([])
##
for index in range(len(stripchart.stripchart)):
try:
axes[index].set_xlim([local_time - time_range,local_time])
except Exception as err:
error(traceback.format_exc(err))
for index in range(len(stripchart.stripchart)):
axes[index].grid()
divider = 5 #this is a tick divider, meaning how many ticks we have in plots. 5 tick = 6 div is a good choice
step = (time_range)/divider
range_lst = []
for i in range(divider+1):
range_lst.append(local_time-time_range+step*i)
label_lst = []
## if self.time_choice.GetSelection() == 0 or self.time_choice.GetSelection() == 1 or self.time_choice.GetSelection() == 2 or self.time_choice.GetSelection() == 3:
time_format = '%H:%M:%S'
## elif self.time_choice.GetSelection() == 4 or self.time_choice.GetSelection() == 5 or self.time_choice.GetSelection() == 6:
## time_format = '%H:%M'
## else:
## time_format = '%H:%M:%S'
for i in range(len(range_lst)-1):
label_lst.append(strftime(time_format, localtime(range_lst[i])))
i=i+1
label_lst.append(strftime('%H:%M:%S' , localtime(range_lst[i])))
from numpy import asarray
for index in range(len(stripchart.stripchart)):
axes[index].set_xticks(range_lst)
axes[3].set_xticklabels(label_lst)
axes[3].set_xlabel("local time")
self.draw_flag = True
figure.tight_layout()
buf = io.BytesIO()
debug('buf = %r' % buf)
try:
figure.savefig(buf, format='jpg')
except:
error(traceback.format_exc())
buf.seek(0)
return buf
def draw(self):
debug('draw called')
self.drawing = True
try:
time_range = frame.time_range
except:
time_range = 60.0
self.figurebuf = self.chart(time_range = time_range)
try:
wx.CallAfter(frame.draw,(0,))
except:
error(traceback.format_exc())
self.drawing = False
# Run the main program
if __name__ == "__main__":
stripchart = StripChart()
for i in range(4):
PV = stripchart.selected_CA_values[i]
stripchart.add(position = i, PV = PV , buffersize = 240000)
#stripchart.append(StripChart(PV = 'NIH:TEMP.RBV' , buffersize = 5600))
#stripchart.append(StripChart(PV = 'NIH:SAMPLE_FROZEN_OPT_RGB.MEAN_TOP' , buffersize = 1000))
#stripchart.append(StripChart(PV = 'NIH:SAMPLE_FROZEN_OPT_RGB.MEAN_BOTTOM' , buffersize = 1000))
#stripchart.append(StripChart(PV = 'NIH:SAMPLE_FROZEN_OPT_RGB.MEAN_DIFF' , buffersize = 1000))
import logging
from tempfile import gettempdir
logging.basicConfig(filename=gettempdir()+'/CA_strip_chart.log',
level=logging.WARN, format="%(asctime)s %(levelname)s: %(message)s")
#Create an instance with a ring buffer
#start the socket
#Create the GUI frane and show it
app = wx.App(False)
frame = ClientGUI()
frame.Show()
#Start main GUI loop
app.MainLoop()
<file_sep>"""Author: <NAME>
Date created: 2019-03-18
Date modified: 2019-03-18
"""
__version__ = "1.0"
def sorted_lists(lists):
"""Sort lists by order of first list"""
from numpy import argsort
order = argsort(lists[0])
def reorder(list,order): return [list[i] for i in order]
sorted_lists = [reorder(list,order) for list in lists]
return sorted_lists
def sorted_description(description):
description = ",".join(sorted(description.split(",")))
return description
def diff(s1,s2):
from difflib import context_diff,ndiff
s1 = s1.splitlines(True)
s2 = s2.splitlines(True)
report = context_diff(s1,s2)
report = [l for l in report if l[0] != " " and l[1] == " "]
report = "".join(report).rstrip("\n")
return report
from Ensemble_SAXS_pp_old import Ensemble_SAXS,Sequence
Ensemble_SAXS.cache_size = 0
description_old = sorted_description(Sequence().description)
registers_old,counts_old = sorted_lists(Sequence().register_counts)
from Ensemble_SAXS_pp import Ensemble_SAXS,Sequence
Ensemble_SAXS.cache_size = 0
description = sorted_description(Sequence().description)
registers,counts = sorted_lists(Sequence().register_counts)
diff_report = diff(description_old.replace(",","\n"),description.replace(",","\n"))
if diff_report: print(diff_report)
print("Description matches: %s" % (description_old == description))
print("Registers match: %s" % (registers_old == registers))
print("Counts match: %s" % (counts_old == counts))
<file_sep>"""<NAME>, May 1, 2015 - May 1, 2015"""
from ftplib import FTP
from io import BytesIO
from struct import pack
data = ""
data += pack(">bbHIII",0x03,0x000,0x0001,0xF0FFB044,0x00000001,0x00000000)
data += pack(">bbHIII",0x03,0x000,0x0001,0xF0FFB044,0x00000001,0x00000001)
##file("/tmp/sequence.bin","w").write(data) # for debugging
f = BytesIO()
f.write(data)
f.seek(0)
ftp = FTP("pico25.niddk.nih.gov","root","root")
##ftp.storbinary ("STOR /tmp/sequence.bin",f) # for debugging
ftp.storbinary ("STOR /dev/sequencer",f)
ftp.close()
<file_sep>"""
Measure the transmission of te WAXS/SAXS sample cell over the translation range
used for scattering data collection.
Setup: DS PIN diode, mounted on detector support, 2 mm Al attenuator taped in front
(to avoid saturating the response). DS PIN diode -> Mini-Circuits bias Tee, 9 V bias ->
WaveSurfer oscilloscope in control Hutch CH2.
<NAME>, 10 Oct 2010
"""
from id14 import id14b_wavesurfer,GonY,mson
import lauecollect_advanced as lauecollect
from numpy import *
I0 = id14b_wavesurfer.measurement(1)
DS_PIN = id14b_wavesurfer.measurement(2)
def measure_T():
print "offset..."
mson.value = 0 # disable X-ray beam
lauecollect.single_image()
I0_offset,DS_PIN_offset = I0.average,DS_PIN.average
mson.value = 1 # reenable X-ray beam
print "reference..."
GonY.value = 4.096-1; GonY.wait() # bypassing sample cell
lauecollect.single_image()
I00,DS_PIN0 = I0.average,DS_PIN.average
print "sample..."
GonY.value = 4.096; GonY.wait() # X-ray beam through sample cell
lauecollect.single_image()
I01,DS_PIN1 = I0.average,DS_PIN.average
T = ((DS_PIN1-DS_PIN_offset)/(I01-I0_offset)) / ((DS_PIN0-DS_PIN_offset)/(I01-I0_offset))
print "transmission %.4f" % T
return T
def average_T():
global N,T
N = 5
T = zeros(N)
for i in range(0,N): T[i] = measure_T()
print "T = %.4f+/-%.4f" % (average(T),std(T)/sqrt(N-1))
# helium purged capillary: T = 0.9076+/-0.0023
# water filled capillary: T = 0.7841+/-0.0012
<file_sep>"""Test communication timing
<NAME> Nov 2, 2015 - Nov 3, 2015"""
from temperature_controller_driver import temperature_controller as T
from time import time,sleep
def double_command():
""""""
T.port.write('MEAS:T?\n')
T.port.write('MEAS:T?\n')
def double_command_OK(delay):
"""delay: delay between two commands in seconds"""
T.port.write('MEAS:T?\n')
sleep(delay)
T.port.write('MEAS:T?\n')
T.port.timeout=0.1
reply=T.port.read(100)
passed = reply.count("\n") == 2
return passed
def delay_OK(delay):
"""delay: delay between two commands in seconds"""
T.port.write('MEAS:T?\n')
reply = T.port.readline()
sleep(delay)
passed = "\n" in reply and "Ready" not in reply
return passed
def test(procedure,delay):
"""delay: delay between two commands in seconds"""
from sys import stderr
OK = 0; attempts = 0
try:
while True:
attempts += 1
OK += procedure(delay)
if attempts % 20 == 0: stderr.write("%d/%d OK\n" % (OK,attempts))
except KeyboardInterrupt: return
print('test(double_command_OK,0.1)')
print('test(delay_OK,0)')
print('double_command();test(delay_OK,0)')
<file_sep>"""EPICS IOC prototype
Author: <NAME>
Date created: 2019-05-18
Date last modified: 2019-05-13
"""
__version__ = "1.1" # added: run
from logging import debug,warn,info,error
class IOC(object):
name = "sample"
prefix = "NIH:SAMPLE."
from persistent_property import persistent_property
from numpy import inf
scan_period = persistent_property("scan_period",2.0)
property_names = []
def run(self):
self.running = True
from sleep import sleep
while self.running: sleep(0.25)
from thread_property_2 import thread_property
@thread_property
def running(self):
info("Starting IOC: Prefix: %s ..." % self.prefix)
from CAServer import casget,casput,casdel
from time import time
from sleep import sleep
self.monitors_setup()
while not self.running_cancelled:
t = time()
for name in self.property_names:
if time() - self.last_updated(name) > self.update_period(name):
PV_name = self.prefix+name.upper()
value = getattr(self,name)
##info("Update: %s=%r" % (PV_name,value))
casput(PV_name,value,update=False)
self.set_update_time(name)
if not self.running_cancelled: sleep(t+self.min_update_period-time())
casdel(self.prefix)
last_updated_dict = {}
def set_update_time(self,name):
from time import time
self.last_updated_dict[name] = time()
def last_updated(self,name): return self.last_updated_dict.get(name,0)
def update_period(self,name):
from numpy import inf
period = getattr(self,name+"_update_period",inf)
period = min(period,self.scan_period)
return period
@property
def min_update_period(self):
update_periods = [self.update_period(name) for name in self.property_names]
min_update_period = min(update_periods) if len(update_periods) > 0 else self.scan_period
return min_update_period
def monitors_setup(self):
"""Monitor client-writable PVs."""
from CAServer import casmonitor,casput
for name in self.property_names:
PV_name = self.prefix+name.upper()
casmonitor(PV_name,callback=self.monitor)
def monitor(self,PV_name,value,char_value):
"""Handle PV change requests"""
info("%s = %r" % (PV_name,value))
from CAServer import casput
for name in self.property_names:
if PV_name == self.prefix+name.upper():
setattr(self,name,value)
casput(PV_name,getattr(self,name))
<file_sep>"""
List active processes
Author: <NAME>
Date created: Nov 10, 2017
"""
__version__ = "1.0"
from logging import debug,info,warn,error
def PIDs():
"""Process IDs of all running processes, as list of integers"""
from ctypes import windll,c_ulong,byref,sizeof
PIDs = (c_ulong*512)()
size_of_PIDs = c_ulong()
windll.psapi.EnumProcesses(byref(PIDs),sizeof(PIDs),byref(size_of_PIDs))
nPIDs = size_of_PIDs.value/sizeof(c_ulong())
pidProcess = sorted([int(i) for i in PIDs][:nPIDs])
return pidProcess
def processes():
from process_information import ProcessInformation
processes = {}
for PID in PIDs():
command_line = ""
try: command_line = ProcessInformation(PID).command_line
except Exception,msg: warn("PID %s: %s" % (PID,msg))
processes[PID] = command_line
return processes
if __name__ == '__main__':
from pdb import pm
from time import time
print('t=time(); x=PIDs(); time()-t')
print('t=time(); x=processes(); time()-t')
print(r'print "\n".join(processes().values())')
<file_sep>CustomView = [0, 1, 2, 3, 4, 5, 7, 8, 10, 11, 13, 15]
view = 'Custom'<file_sep>line0.timing_system.channels.hsc.delay = 4.97e-06
line0.Phase [s] = 5.4527e-06
line0.ChopX = 36.78
line0.ChopY = 30.11
line0.description = 'S-1t'
line0.updated = '2019-05-30 14:18:48'
line1.timing_system.channels.hsc.delay = 0.0
line1.ChopX = 36.78
line1.ChopY = 31.136
line1.description = 'S-1'
line1.updated = '2019-05-30 14:25:48'
line2.timing_system.channels.hsc.delay = 8.232e-09
line2.ChopX = 36.78
line2.ChopY = 31.0579
line2.description = 'S-3'
line2.updated = '2019-05-30 14:28:12'
line3.timing_system.channels.hsc.delay = 1.372e-08
line3.ChopX = 36.78
line3.ChopY = 30.982499999999998
line3.description = 'S-5'
line3.updated = '2019-05-30 14:28:12'
line4.timing_system.channels.hsc.delay = 3.0184e-08
line4.ChopX = 36.78
line4.ChopY = 30.7563
line4.description = 'S-11'
line4.updated = '2019-05-30 14:28:12'
line5.timing_system.channels.hsc.delay = 6.86e-08
line5.ChopX = 36.78
line5.ChopY = 30.2285
line5.description = 'S-25'
line5.updated = '2019-05-30 14:28:12'
line6.timing_system.channels.hsc.delay = 0.0
line6.ChopX = 36.78
line6.ChopY = 30.555
line6.description = 'H-1'
line6.updated = '2019-05-30 14:19:34'
line7.timing_system.channels.hsc.delay = 0.0
line7.ChopX = 36.78
line7.ChopY = 30.555
line7.description = 'H-56'
line7.updated = '2019-05-30 14:17:51'
line8.timing_system.channels.hsc.delay = 0.0
line8.ChopX = 27.67
line8.ChopY = 30.925
line8.description = 'Bypass'
line8.updated = '2019-05-30 14:17:51'
motor_names = ['ChopX', 'ChopY', 'timing_system.channels.hsc.delay', 'timing_system.p0_shift']
motor_labels = ['X', 'Y', 'Phase', 'P0 Shift']
nrows = 12
formats = ['%+6.4f', '%+6.4f', 'time', 'time']
title = 'High-Speed Julich Chopper Modes'
line9.description = 'S-15'
line9.updated = '2019-05-30 14:28:12'
line9.ChopX = 36.78
line9.ChopY = 30.6055
line9.timing_system.channels.hsc.delay = 4.116e-08
line10.description = 'S-19'
line10.updated = '2019-05-30 14:28:12'
line10.ChopX = 36.78
line10.ChopY = 30.4547
line10.timing_system.channels.hsc.delay = 5.2136e-08
tolerance = [0.002, 0.002, 2.8e-09, 2.8e-09]
command_row = 9
widths = [100, 100, 100]
show_in_list = True
show_stop_button = True
command_rows = [11]
row_height = 21
names = ['X', 'Y', 'phase', 'p0_shift']
line7.timing_system.p0_shift = -1.84e-06
line8.timing_system.p0_shift = 0.0
line9.timing_system.p0_shift = -2.7871134923018455e-13
line6.timing_system.p0_shift = 0.0
line5.timing_system.p0_shift = 0.0
line4.timing_system.p0_shift = 0.0
line3.timing_system.p0_shift = -2.7871134923018455e-13
line2.timing_system.p0_shift = 0.0
line1.timing_system.p0_shift = -2.7871134923018455e-13
line0.timing_system.p0_shift = 0.0
line10.timing_system.p0_shift = 0.0
line11.ChopX = 36.78
line11.updated = '2019-06-01 08:36:18'
line11.ChopY = 30.9071
line11.timing_system.channels.hsc.delay = 1.9170000000000002e-08
line11.timing_system.p0_shift = -2.7871134923018455e-13
line11.description = 'S-7'<file_sep>#!/usr/bin/env python
"""
Control panel to save and restore motor positions.
Author: <NAME>
Date created: 2017-02-17
Date last modified: 2017-02-17
"""
__version__ = "1.0"
from SavedPositionsPanel_2 import SavedPositionsPanel
from instrumentation import laser_optics_modes
class LaserOpticsModesPanel(SavedPositionsPanel):
title = "Laser Optics Modes"
configuration = laser_optics_modes
def __init__(self):
SavedPositionsPanel.__init__(self,
configuration=self.configuration,
title=self.title,
)
if __name__ == '__main__':
from pdb import pm # for debugging
import logging # for debugging
from tempfile import gettempdir
logfile = gettempdir()+"/LaserOpticsModesPanel.log"
logging.basicConfig(level=logging.INFO,filename=logfile,
format="%(asctime)s %(levelname)s: %(message)s")
import wx
app = wx.App(redirect=False)
panel = LaserOpticsModesPanel()
app.MainLoop()
<file_sep>motor_names = ['HLC', 'timing_system.hlcnd']
motor_labels = ['Position', 'Phase']
formats = ['%+6.3f', 'time.6']
nrows = 8
line0.description = 'Bypass'
line0.updated = '30 Oct 16:00'
line1.description = '988-1.5'
line1.updated = '30 May 13:24'
line2.description = '494-1.5'
line2.updated = '30 May 13:24'
line3.description = '247-1.5'
line3.updated = '2019-03-19 11:45:51'
line4.description = '82-1.5'
line4.updated = '2019-03-19 11:47:08'
line5.description = '82-3'
line5.updated = '30 Oct 16:00'
line6.description = '82-6'
line6.updated = '30 Oct 16:00'
line7.description = '82-12'
line7.updated = '30 Oct 16:00'
line0.HLC = 10.0
line0.timing_system.hlcnd = -0.00101829
line1.HLC = 7.0
line1.timing_system.hlcnd = 0.00101829
line2.HLC = 4.5
line2.timing_system.hlcnd = 0.00101829
line3.HLC = 2.0
line3.timing_system.hlcnd = 0.00101829
line4.HLC = -0.5
line4.timing_system.hlcnd = 0.0
line5.HLC = -3.0
line5.timing_system.hlcnd = 0.0
line6.HLC = -5.5
line6.timing_system.hlcnd = 0.0
line7.HLC = -8.0
line7.timing_system.hlcnd = 0.0
line8.description = ''
line8.updated = ''
title = 'Heat-Load Chopper Modes'
tolerance = [0.002, 1e-07]
command_row = 3
show_stop_button = True
command_rows = [3]
row_height = 21<file_sep>import linac
lcls_linac = linac.Linac()
import daq
import socket
daq_hostname = socket.gethostname()
xppdaq = daq.Daq(host=daq_hostname,platform=1,lcls=lcls_linac)
<file_sep>#!/bin/env python
""" This is a python script that will analyse images triggered by the FPGA.
The camera_image_analyzer can get images from the MicroscopeCamera and
convert them to 3D array 1024,1360,4 , where 4 stands for RGB + Total counts.
author: <NAME>
dates: March 10,2018 - March 11, 2018
The coordinate system is the following:
x - downstream positive
y - up positive
z - outboard positive
pixel space:
y (v - vertical) - down positive
z (h - horizontal) - inboard positive
results in:
positive direction in horizontal pixel space results in negative z
positive direction in vertical pixel space results in negative y but positive x
"""
import matplotlib.pyplot as plt
from numpy import mean, transpose, std,array,hypot , abs
from time import sleep, time
import PIL
from persistent_property import persistent_property
from datetime import datetime
from optical_image_analyzer import Image_analyzer
from Ensemble import SampleX, SampleY, SampleZ
from persistent_property import persistent_property
import DB
from logging import error,warn, info,debug
laue_image_analyzer = Image_analyzer(
name = 'LAUE_image_analyzer'
) #for LAUE crystalography
laue_image_analyzer.init(camera_name = 'MicroscopeCamera')
class Laue_find_crystals(object):
def __init__(self):
self.background_flag = False
self.save_every_image = False
laue_image_analyzer.save_every_image = self.save_every_image
self.global_idx = 0
self.injection_idx = 0
self.pixel_size = float(DB.db("MicroscopeCamera.NominalPixelSize"))# in 0.000526mm
self.x_scale = 1 #float(DB.db("MicroscopeCamera.x_scale")) #FIXIT: double check xyz grid
self.y_scale = -1 #float( DB.db("MicroscopeCamera.y_scale")) #FIXIT: double check xyz grid
self.z_scale = -1 #float( DB.db("MicroscopeCamera.z_scale")) #FIXIT: double check xyz grid
def get_camera_orientation(self):
""" returns camera orientation"""
return 'horizontal'
camera_orientation = property(get_camera_orientation)
def get_camera_crosshair(self):
"""returns crosshair position of the microscope camera: FIXIT still under development"""
return (680,512)
camera_crosshair = property(get_camera_crosshair)
def get_xyz_coordinates_crosshair(self):
return (SampleX.value,SampleY.value,SampleZ.value)
xyz_coordinates_crosshair = property(get_xyz_coordinates_crosshair)
def abs_pixel_to_abs_xyz(self,pixel = (680,512)):
"""pixel = (h,v) absolute position of crosshair in pixel space"""
curr_h = pixel[0]
curr_v = pixel[1]
(crosshair_h, crosshair_v) = self.camera_crosshair
(dx,dy,dz) = self.dpixel_to_dxyz()
z = (curr_h-crosshair_h)*dz
x = (curr_v-crosshair_v)*dx
y = (curr_v-crosshair_v)*dy
return (x,y,z)
def dpixel_to_dxyz(self):
from numpy import cos, sin, pi
"""dpixel = (h,v)"""
dh = 1.0 #change vertical
dv = 1.0 #change horizontal
dz = self.z_scale*dh*self.pixel_size
dx = self.x_scale*dv*self.pixel_size*sin(pi/6.0)
dy = self.y_scale*dv*self.pixel_size*cos(pi/6.0)
return (dx,dy,dz)
def get_image(self):
image = laue_image_analyzer.get_image()
return image
def analyse_diff_image(self,curr = None,bckg = None):
from random import random
""" Analyse image and create the list of coordinates"""
self.dic = {}
self.injection_idx +=1
"""This will make a fake dictionary with random number of crystals"""
number = 7
for i in range(number):
self.dic[str(i)] = (round(random(),3)-round(random(),3),
round(random(),3)-round(random(),3),
round(0,3)-round(0,3))
self.global_idx += 1
return self.dic
def run_once(self):
flag = self.get_difference_image()
if flag:
image = laue_image_analyzer.difference_array
self.analyse_diff_image()
self.save_in_file()
res = True
else:
res = False
return res
class TSP_sorting(object):
def __init__(self,dic):
self.order = []
self.sum = []
self.dic = dic
def run_first_time(self):
dist = []
self.order.append('start')
for key in self.dic.keys():
if key != 'start' and key != 'end':
self.order.append(key)
self.calculate_distance_to_origin(self.order)
self.sum = self.calculate_distance(self.order)
def run_once(self):
from random import shuffle
temp_order = self.order[1:-1]
shuffle(temp_order)
new_order = []
new_order.append(self.order[0])
for i in temp_order:
new_order.append(i)
new_order.append(self.order[-1])
new_sum = self.calculate_distance(new_order)
if new_sum < self.sum:
self.sum = new_sum
self.order = new_order
def run(self, timeout = 1):
from random import shuffle
if len(self.order) == 0:
self.run_first_time()
t = time()
while time() - t < timeout:
self.run_once()
def pre_order(self):
pass
def calculate_distance(self,order):
s = 0
for i in range(len(order)-1):
(x1,y1,z1) = self.dic[order[i]]
(x2,y2,z2) = self.dic[order[i+1]]
s = s + ((x2-x1)**2 + (y2-y1)**2 + (z2-z1)**2)**0.5
return s
def calculate_distance_to_origin(self):
dist = []
for key in self.dic.keys():
(x , y , z) = self.dic[key]
dist[1,i] = x**2+y**2+z**2
dist[0,i] = key
return dist
def plot(self):
from numpy import asarray
lst = []
for key in self.order:
lst.append(self.dic[key])
arr = asarray(lst)
print arr
plt.plot(arr[:,0],arr[:,1],'-o')
plt.show()
def save_in_file(self):
import os
folder = "/Ensemble/"
filename = 'PVT_LAUE_Optical_parameters'
f = open(os.getcwd()+ folder + filename + '.abi','w')
f.write('DECLARATIONS\n')
f.write('GLOBAL N_Mode AS INTEGER = '+ str(0)+ '\n')
f.write('GLOBAL N_period AS INTEGER = ' +str(108)+ '\n')
f.write('GLOBAL N_repeat AS INTEGER = '+ str(36)+ '\n')
f.write('GLOBAL N_xtal AS INTEGER = '+str(len(self.dic))+ '\n')
f.write('GLOBAL XYZ() AS DOUBLE = {'+ '\n')
for key in self.dic.keys():
if key != 'msg':
x, y, z = self.dic[key]
f.write('{'+ str(x) + ','
+ str(y) + ',' +
str(z) + '},'+ '\n')
f.write('}'+ '\n')
f.write('END DECLARATIONS'+ '\n')
f.close()
def plot_edges(self):
plt.imshow(laue_image_analyzer.difference_array[:,:,0])
plt.colorbar()
plt.show(self)
def log_start(self, beamtime_name = 'anfinrud_1807', sample_name = 'TEST'):
import os
from time import strftime, localtime, time
from datetime import datetime
self.logtime = time()
self.beamtime_name = beamtime_name
self.sample_name = sample_name
self.log_folder = '//net//mx340hs.cars.aps.anl.gov/data/'+beamtime_name+'/Data/Laue/' + sample_name+'/'
self.filename = self.log_folder + 'experiment_log_file.log'
if os.path.isdir(self.log_folder):
info('folder already exist')
else:
info("folder doesn't exist. Creating one...")
os.mkdir(self.log_folder)
f = open(self.filename ,'w')
#timeRecord = str(datetime.now())
timeRecord = self.logtime
f.write('####This experiment started at: %r and other information %r \r\n'
%(timeRecord,'Other Garbage'))
f.write('time stamp, sample name, injection index, crystal, pos \r\n')
f.close()
def log_append_crystal(self,crystal_dict = {}):
"""
- logs events into a file if self.loggingState == True
- always appends current value to the logVariable_buffers['#key#'] where #key#
can be found in self.logVariables dictionary
"""
from os import makedirs, path
from time import strftime, localtime, time
from datetime import datetime
for key in crystal_dict.keys():
pos = crystal_dict[key]
time_stamp = time()
txt = '%r , %r, %r, %r, %r\n' %(time_stamp,self.sample_name,self.injection_idx,key,pos)
file(self.filename,'a').write(txt)
def log_save_image(self):
pass
laue_find_crystals = Laue_find_crystals()
laue_find_crystals.sample_name = 'TEST'
if __name__ == "__main__":
import logging
from tempfile import gettempdir
logging.basicConfig(#filename=gettempdir()+'/Laue_find_crystals.log',
level=logging.DEBUG, format="%(asctime)s %(levelname)s: %(message)s")
self = laue_find_crystals # for testing
def run_find_xtals( N = 1):
from numpy import asarray
dic = self.analyse_diff_image();
sor = self.TSP_sorting(dic);
sor.run_first_time()
lst = []
for key in sor.order:
lst.append(self.dic[key])
arr = asarray(lst)
#plt.subplot(121)
#plt.plot(arr[:,0],arr[:,1],'-o')
t1 = time();
sor.run(t);
t2 = time();
print t2-t1;
lst = []
for key in sor.order:
lst.append(self.dic[key])
arr = asarray(lst)
#plt.subplot(122)
#plt.plot(arr[:,0],arr[:,1],'-o')
#plt.show()
print lst
print('....LAUE find crystals code.....')
<file_sep>#!/usr/bin/env python
"""High-speed diffractometer
Control panel to save and motor positions.
<NAME> 31 Oct 2013 - 1 Nov 2013"""
__version__ = "1.0"
from saved_positions import SavedPositions
from id14 import SampleX,SampleY,SampleZ,SamplePhi
saved_positions = SavedPositions(
name="goniometer_saved",
motors=[SampleX,SampleY,SampleZ,SamplePhi],
motor_names=["SampleX","SampleY","SampleZ","SamplePhi"],
nrows=13)
<file_sep>#!/bin/env python
"""Extract images and detector readings from an LCLS datastream
Setup: source /reg/g/psdm/etc/ana_env.sh
<NAME>, Jan 22, 2016
<NAME>, Jan 25, 2016 - Mar 2, 2016
"""
from logging import warn,info,debug,error
from time import time
from numpy import nan,inf,isnan
__version__ = "1.0.2" # date_time
class DataStream:
exp_run = None
event_number = -1
serial_number = -1
detector_name = ""
event = None
def image(self,exp_run_event):
"""exp_run_event: contains experiment number, run number and event number
'exp=xppj1216:run=17:event=0' or 'exp=xppj1216:run=17:event=rayonix,0'
"""
return self.detector(exp_run_event,"rayonix:data16")
def detectors(self,exp_run):
"""What are the names of the detectors in the datastream?
exp_run: contains experiment number, run number, e.g. 'exp=xppj1216:run=17'
"""
from psana import DataSource
ds = DataSource(exp_run)
es = ds.env().epicsStore()
names = []
for evt in ds.events():
keys = evt.keys()
for d in keys:
# E.g. d.src(): DetInfo(NoDetector.0:Evr.0), d.alias(): 'evr0'
name = str(d.src()).split("(")[-1].split(")")[0]
if name and not name in names: names += [name]
name = d.alias()
if name and not name in names: names += [name]
for name in es.pvNames():
if not name in names: names += [name]
for name in es.aliases():
if not name in names: names += [name]
return names
def detector(self,exp_run_event,detector_name):
"""exp_run_event: contain experiment number, run number and event number
'exp=xppj1216:run=17:event=0' or 'exp=xppj1216:run=17:event=rayonix,0'
detector_name: detector name e.g. "XppEnds_Ipm0:sum" or "rayonix:data16"
suffix "sum": get the sum of all four channels of a 4-quadrant detector
suffix "channel": get all four channels of a 4-quadrant detector
suffix "channel:0": the first channel of a 4-quadrant detector
suffix "data16": get an image with 16 bit depth
suffix "data16:0,0": get pixle (0,0) of an image
"""
full_detector_name = detector_name
attr = ""
item = None
if detector_name.count(":") == 1:
detector_name,attr = detector_name.split(":")
if detector_name.count(":") == 2:
detector_name,attr,item = detector_name.split(":")
try: item = eval(item)
except: pass
self.find_event(exp_run_event)
if self.event is None: return None
for d in self.event.keys():
# E.g. d.src(): DetInfo(NoDetector.0:Evr.0), d.alias(): 'evr0'
names = str(d.src()).split("(")[-1].split(")")[0],d.alias()
if detector_name in names:
value = self.event.get(d.type(),d.src())
if attr == "": return value
value = getattr(value,attr)()
if item is not None: value = value[item]
return value
# Is detector name an EPICS process variable?
value = self.es.value(full_detector_name)
if value is not None: return value
warn("Detector %r not recorded for event=%s,%s:serial_number=%s" %
(detector_name,self.detector_name,self.event_number,
self.serial_number))
return None
get = detector # shortcut
def timestamp(self,exp_run_event):
"""Seconds since 1970-01-01 00:00:00 UTC"""
from psana import EventId
self.find_event(exp_run_event)
if self.event is not None:
s,ns = self.event.get(EventId).time()
t = s+ns*1e-9
else: t = nan
return t
def fiducial(self,exp_run_event):
"""360-Hz SLAC time stamp, 17-bit integer"""
from psana import EventId
self.find_event(exp_run_event)
if self.event is not None:
i = self.event.get(EventId).fiducials()
else: i = nan
return i
def get_event_number(self,exp_run_event):
"""exp_run_event: contains experiment number, run number and event number
'exp=xppj1216:run=17:event=0' or 'exp=xppj1216:run=17:event=rayonix,0'
Reurn value: 0-based integer.
"""
self.find_event(exp_run_event)
return self.serial_number
def find_event(self,exp_run_event):
"""exp_run_event: contain experiment number, run number and event
number
'exp=xppj1216:run=17:event=0' or 'exp=xppj1216:run=17:event=rayonix,0'
"""
fields = []
event_number = nan; detector_name = ""
for f in exp_run_event.split(':'):
if f.startswith("event="):
detector_event = f.replace("event=","")
if "," in detector_event:
detector_name = ",".join(detector_event.split(",")[0:-1])
event_number = int(detector_event.split(",")[-1])
else: event_number = int(detector_event)
else: fields += [f]
exp_run = ":".join(fields)
if exp_run != self.exp_run or detector_name != self.detector_name \
or event_number < self.event_number:
start = time()
try:
from psana import DataSource
self.ds = DataSource(exp_run)
self.es = self.ds.env().epicsStore()
except Exception,msg:
error('Failed to open datasource: %s: %s' % (exp_run,msg))
return None
self.exp_run = exp_run
self.event_number = -1
self.serial_number = -1
self.detector_name = detector_name
debug('Opened %r in %g seconds' % (exp_run,time()-start))
if event_number == self.event_number: return
for event in self.ds.events():
self.event = event
self.serial_number += 1
# If a detector name is specified, count only event for which
# this detector is recorded.
if detector_name != "":
for d in self.event.keys():
names = str(d.src()).split("(")[-1].split(")")[0],d.alias()
if detector_name in names:
self.event_number += 1
break
else: self.event_number += 1
if event_number == self.event_number:
break
if not (event_number == self.event_number):
error('Event event=%s,%s not found' % (detector_name,event_number))
self.event = None
else:
from psana import EventId
debug('found event=%s,%s:serial_number=%s:fiducial=%s' %
(self.detector_name,self.event_number,self.serial_number,
self.event.get(EventId).fiducials()))
starting_times = {} # starting time for each run
def starting_time(self,exp_run):
"""exp_run: contains experiment number, run number, e.g.
'exp=xppj1216:run=17'"""
from tempfile import gettempdir
from pickle import load,dump
if self.starting_times == {}:
try: self.starting_times = load(file(gettempdir()+"/datastream.starting_times.pkl"))
except: pass
if exp_run in self.starting_times:
return self.starting_times[exp_run]
from psana import DataSource,EventId
try:
ds = DataSource(exp_run)
for event in ds.events():
s,ns = event.get(EventId).time()
t = s+ns*1e-9
debug("%s: %s" % (exp_run,date_time(t)))
break
except Exception,msg:
debug("%s: %s" % (exp_run,msg))
t = nan
self.starting_times[exp_run] = t
dump(self.starting_times,file(gettempdir()+"/datastream.starting_times.pkl","w"))
return t
def exists(self,exp_run):
"""exp_run: contains experiment number, run number, e.g.
'exp=xppj1216:run=17'"""
if exp_run in self.exists_run: return self.exists_run[exp_run]
from psana import DataSource
debug("checking %s" % exp_run)
try: DataSource(exp_run); exists = True
except: exists = False
self.exists_run[exp_run] = exists
return exists
exists_run = {}
def run(self,exp,timestamp):
"""In which run is the given timestamp?
exp: e.g. 'exp=xppj1216'
timestamp: time since 1 Jan 1970 00:00 UTC in seconds
"""
run = 1
exp_run = "%s:run=%d" % (exp,run)
t = self.starting_time(exp_run)
while t <= timestamp:
run += 1
exp_run = "%s:run=%d" % (exp,run)
t = self.starting_time(exp_run)
return run-1
datastream = DataStream()
def timestamp(date_time):
"""Convert a date string to number of seconds since 1 Jan 1970 00:00 UTC
date: e.g. "2016-01-27 12:24:06.302724692-08"
"""
from dateutil.parser import parse
t0 = parse("1970-01-01 00:00:00+0000")
t = parse(date_time)
return (t-t0).total_seconds()
def date_time(seconds,timezone="US/Pacific"):
"""Date and time as formatted ASCII text, precise to 1 ms
seconds: time elapsed since 1 Jan 1970 00:00:00 UTC
e.g. '2016-02-01 19:14:31.707016-08:00' """
from datetime import datetime
import pytz
if not isnan(seconds):
timeUTC = datetime.utcfromtimestamp(seconds)
timezoneLocal = pytz.timezone(timezone)
utc = pytz.utc
timeLocal = utc.localize(timeUTC).astimezone(timezoneLocal)
date_time = str(timeLocal)
# Time zone should be formatted "-0800" not "-08:00"
if date_time.endswith(":00"): date_time = date_time[:-3]+"00"
else: date_time = ""
return date_time
if __name__ == "__main__": # for testing
# Same as running from an interactive Python session.
from time import time
from pdb import pm # for debugging
import logging; logging.basicConfig(level=logging.DEBUG)
self = datastream
exp = "exp=xppj1216:smd:dir=/reg/d/ffb/xpp/xppj1216/xtc:live"
exp_run = exp+":run=310" # 25,48
date = "2016-01-27 12:24:06.302724692-08" # (1453926246, 302724692)
def test():
start = time()
n = 0
for i in range(0,20):
image_id = "%s:event=rayonix,%d" % (exp_run,i)
img = datastream.image(image_id)
if img is not None:
n += 1
info("%s %s" % (image_id,img.shape))
else: info("%s not found" % image_id)
print "%d images, %.1f images/s" % (n,n/(time()-start))
print("test()")
print("datastream.detectors(exp_run)")
print('datastream.find_event("%s:event=rayonix,0")' % exp_run)
print('datastream.detector("%s:event=rayonix,0","XppSb3_Ipm:sum")' % exp_run)
print('datastream.detector("%s:event=rayonix,0","XppEnds_Ipm0:channel:0")' % exp_run)
print('datastream.detector("%s:event=rayonix,0","XPP:TIMETOOL:FLTPOS_PS")' % exp_run)
print('image = datastream.detector("%s:event=rayonix,0","rayonix:data16")' % exp_run)
print('datastream.run(%r,timestamp(%r))' % (exp,date))
<file_sep>from EPICS_motor import motor
SampleX = motor("14IDB:SAMPLEX")
SampleY = motor("14IDB:SAMPLEY")
SampleZ = motor("14IDB:SAMPLEZ")
SamplePhi = motor("14IDB:SAMPLEPHI")
from time import sleep
while True:
SampleX.value,SampleY.value,SampleZ.value = -1,-1,-1
while(SampleX.moving or SampleY.moving or SampleZ.moving): sleep(0.01)
sleep(1)
SampleX.value,SampleY.value,SampleZ.value = 1,1,1
while(SampleX.moving or SampleY.moving or SampleZ.moving): sleep(0.01)
sleep(1)
<file_sep>P3.filename = '//mx340hs/data/anfinrud_1906/Archive/NIH.XRAY_SCOPE.P3.txt'
TRACE_COUNT.filename = '//mx340hs/data/anfinrud_1906/Archive/NIH.XRAY_SCOPE.TRACE_COUNT.txt'<file_sep>#!/usr/bin/env python
# <NAME>, 1 Oct 2014 - 2 Jul 2017
from inspect import getfile
from os.path import dirname
def f(): pass
dir=dirname(getfile(f))
if dir == "": dir = "."
execfile(dir+"/WideFieldCamera.py")
<file_sep>#!/usr/bin/env python
"""<NAME>, Dec 13 2017 - Feb 7 2018"""
from CameraViewer import CameraViewer
import wx
__version__ = "1.8"
wx.app = wx.App(redirect=False) # Needed to initialize WX library
viewer = CameraViewer(name="TestBenchCamera")
wx.app.MainLoop()
<file_sep>import zmq
context = zmq.Context()
receiver = context.socket(zmq.PULL)
receiver.bind("tcp://*:12321")
while True:
arr = receiver.recv_pyobj()
print arr.shape,'\n',arr[0:2,0:2]
<file_sep>lxd.adjust_timing_tool = False
lxd.offset = 0<file_sep>"""EPICS IOC interface for software simulated motor
<NAME>, Dec 8, 2015 - Dec 8, 2015"""
__version__ = "1.0"
from sim_motor import sim_motor
class EPICS_sim_motor(sim_motor):
""""""
VAL = sim_motor.command_value
RBV = sim_motor.value
DVAL = sim_motor.command_dial
DRBV = sim_motor.dial
HLM = sim_motor.max
LLM = sim_motor.min
DHLM = sim_motor.max_dial
DLLM = sim_motor.min_dial
def get_DESC(self): return self.name
def set_DESC(self,value): self.name = value
DESC = property(get_DESC,set_DESC)
EGU = sim_motor.unit
def get_DMOV(self): return not self.moving
def set_DMOV(self,value): self.moving = not value
DMOV = property(get_DMOV,set_DMOV)
def get_STOP(self): return not self.moving
def set_STOP(self,value): self.moving = not value
STOP = property(get_STOP,set_STOP)
VELO = sim_motor.speed
DIR = sim_motor.sign
OFF = sim_motor.offset
def get_CNEN(self): return True
def set_CNEN(self,value): pass
CNEN = property(get_CNEN,set_CNEN)
def get_HOMF(self): return False
def set_HOMF(self,value): pass
HOMF = property(get_HOMF,set_HOMF)
def get_HOMR(self): return False
def set_HOMR(self,value): pass
HOMR = property(get_HOMR,set_HOMR)
def get_MSTA(self):
homed = True
status = homed << 15
return status
def set_MSTA(self,value): pass
MSTA = property(get_MSTA,set_MSTA)
if __name__ == "__main__":
from CAServer import register_object
from CA import caget,caput,Record
from EPICS_motor import EPICS_motor
##import logging
##logging.basicConfig(level=logging.DEBUG,format="%(asctime): %(message)s")
m = EPICS_sim_motor()
self = m # for debugging
register_object(m,"NIH:m")
M = EPICS_motor("NIH:m")
<file_sep>CustomView = ['Timing Mode', 'Beamline Mode', 'Logfile', 'X [mrad]', 'Y [V]', 'X Corr. [mrad]', 'Y Corr. [V]', 'X Scan', 'Y Scan', 'X Correction', 'Y Correction']
TimeChart.time_window = 43200.0
beamline_mode = 'Laue'
cancelled = False
log.filename = '/net/mx340hs/data/anfinrud_1906/Logfiles/xray_beam_check.log'
settings.CustomView = ['Timing System', 'Oscilloscope', 'X1 Motor', 'X2 Motor', 'Y Motor', 'X Scan Step [mrad]', 'Y Scan Step [V]', 'X Aperture Motor', 'Y Aperture Motor', 'X Aperture [mm]', 'Y Aperture [mm]', 'X Aperture (scan) [mm]', 'Y Aperture (scan) [mm]', 'X Aperture (norm) [mm]', 'Y Aperture (norm) [mm]']
settings.beamline_mode = 'SAXS/WAXS'
settings.dx_scan = 0.004
settings.dy_scan = 0.2
settings.ms_on_norm = True
settings.timining_mode = 'SAXS/WAXS'
settings.view = 'Custom'
settings.x_aperture_norm = 0.15
settings.xosct_on_norm = nan
settings.y_aperture_norm = 0.07
timining_mode = 'Laue'
view = 'Custom'
x_scan_I = [6.92915866189e-09, 9.88791520972e-09, 6.95770439349e-09]
x_scan_sigI = [5.378070138128513e-10, 7.539464665261584e-10, 5.2746220885051102e-10]
x_scan_started = 0
x_scan_x = [3.7695770334928236, 3.7655770334928236, 3.7615770334928236]
xray_beam_check.settings.CustomView = ['X1 Motor', 'X2 Motor', 'Y Motor', 'X Resolution [mrad]', 'Y Resolution [V]', 'X Scan Step [mrad]', 'Y Scan Step [V]', 'X Aperture Motor', 'Y Aperture Motor', 'X Aperture (scan) [mm]', 'Y Aperture (scan) [mm]', 'X Aperture (norm) [mm]', 'Y Aperture (norm) [mm]']
xray_beam_check.settings.dx_scan = 0.004
xray_beam_check.settings.dy_scan = 0.2
y_scan_I = [6.77999235636e-09, 1.15301317776e-08, 8.49303107761e-09]
y_scan_sigI = [5.278216890849456e-10, 8.843207390215695e-10, 6.420128030999706e-10]
y_scan_started = 0
y_scan_y = [4.069708968261565, 4.269708968261565, 4.469708968261565]
settings.y_aperture_scan = 0.02
settings.x_aperture_scan = 0.06<file_sep>"""
<NAME>, 2 Mar 2011 - 6 Oct 2011
"""
__version__ = "1.2.1"
def find(topdir,name=[],exclude=[]):
"""A list of files on directory 'topdir' matching the patterns given by
'name', excuding those matching thw patterns ''given by 'exclude'"""
from os import walk
import re
if type(name) == str: name = [name]
if type(exclude) == str: exclude = [exclude]
name = [re.compile(glob_to_regex(pattern)) for pattern in name]
exclude = [re.compile(glob_to_regex(pattern)) for pattern in exclude]
file_list = []
for (directory,subdirs,files) in walk(topdir):
for file in files:
pathname = directory+"/"+file
match = any([pattern.match(pathname) for pattern in name]) and\
not any([pattern.match(pathname) for pattern in exclude])
if match: file_list += [pathname]
return file_list
def glob_to_regex(pattern):
"""Convert a 'glob' pattern for file name matching to a regular
expression. E.g. "foo.? bar*" -> "foo\.. \bar.*" """
return "^"+pattern.replace(".","\.").replace("*",".*").replace("?",".")+"$"
if __name__ == "__main__": ##for testing
topdir = "//Femto/C/All Projects/APS/Experiments/2011.02/Analysis/WAXS/Friedrich/run1"
files = find(topdir,name="*.log",exclude=["*/laser_beamcheck.log","*/backup/*"])
for file in files: print(file)
<file_sep>line0.description = 'ps laser (175 mm f.l.)'
line0.updated = '27 Feb 21:00'
line1.description = 'ps laser (250 mm f.l.)'
line1.updated = '02 Nov 15:13'
motor_labels = ['LaserX', 'LaserY', 'LaserZ']
formats = ['%.3f', '%.3f', '%.3f']
nrows = 8
line2.description = 'vis 5:1 (50 mm f.l.)'
line2.updated = '23 May 12:01'
motor_names = ['LaserX', 'LaserY', 'LaserZ']
line0.LaserX = -0.085
line0.LaserY = 5.8
line0.LaserZ = 1.25
line3.description = 'near IR 3:1 (50 mm f.l.)'
line3.updated = '2019-05-30 20:15:01'
line4.description = 'vis 5:1 (CW laser)'
line4.updated = '30 Oct 18:28'
line1.LaserX = -2.3940397135417673
line1.LaserY = -0.6900000000000013
line1.LaserZ = -0.9450000000000429
line2.LaserX = -0.125
line2.LaserY = -2.8
line2.LaserZ = -0.07
line3.LaserX = -1.1650000000000018
line3.LaserY = -4.234999999999999
line3.LaserZ = -0.41100000000000136
line4.LaserX = -1.659
line4.LaserY = -7.2
line4.LaserZ = -1.17
title = 'Laser Optics Modes'
show_in_list = True
command_row = 3
line5.LaserX = -1.749039713541757
line5.LaserY = -6.200000000000001
line5.LaserZ = -1.1450000000000378
line5.updated = '30 Oct 18:28'
line5.description = 'near-IR 3:1 (CW laser)'
line6.LaserX = -1.3940397135417655
line6.LaserY = -7.199999999999998
line6.LaserZ = -1.2350000000000358
line6.updated = '31 Oct 12:42'
line6.description = 'vis 30:250 CW laser'
line7.LaserX = -1.3690397135417651
line7.LaserY = -6.399999999999998
line7.LaserZ = -0.9200000000000426
line7.updated = '30 Oct 19:23'
line7.description = 'ns laser 5:1 (50 mm)'
command_rows = [3]
tolerance = [0.001, 0.001, 0.001]
define_button_label = '20'
row_height = 21
description_width = 180<file_sep>"""Record photos using a Prosilica GigE camera
Author: <NAME>, <NAME>
Date created: 2017-04-012
Date last modified: 2019-02-22
"""
__version__ = "2.4" # temperature
from GigE_camera_client import Camera
from sleep import sleep
from time import time
from os.path import basename
template_APS = "//mx340hs/data/anfinrud_1810/Test/Laue/opt_images/CypA_round2/%s"\
"%r_%r_%s_%r_%r_%r.tiff"
template_APS_temperature = "//mx340hs/data/anfinrud_1810/Test/Laue/opt_images/freezing_T_ramp_NCBD_TAD/%s"\
"%r_%r_%s_%r.pickle"
#template_APS = "C:/CypA/%r"\
# "%r_%r_%r_%r_%r_%r.tiff"
template_APS_MAC = "//volumes/data/anfinrud_1810/Archive/Laue_pictures/%s"\
"%r_%r_%r.tiff"
template_NIH= "//femto/C/All Projects/Crystallization/2019/TRamp-red-laser/"\
"%s_%00d_%r_%r_%r.tiff"
template = template_NIH
delay = 0.0025 #in seconds
i = 0
from EPICS_motor import motor
from instrumentation import temperature
from sample_frozen_optical import sample_frozen_optical as sfo
motorX = motor("NIH:SAMPLEX")
motorY = motor("NIH:SAMPLEY")
motorZ = motor("NIH:SAMPLEZ")
#camera = Camera("Microscope")
camera1 = Camera('MicroscopeCamera')
camera1.acquiring = True
#camera = Camera("MicroscopeCamera")
def record_T_once(l):
from numpy import zeros,flip
from SAXS_WAXS_control import SAXS_WAXS_control
ins = 0#str(SAXS_WAXS_control.inserted)
filename = template % ("Microscope/",time(),l,int(ins),temperature.value)
print("%s" % basename(filename))
img = camera1.RGB_array
gray = sum(img,2)
arr = zeros((4,1024,1360))
for i in range(3):
for j in range(1024):
for k in range(1360):
arr[i,j,k] = img[i,k,j]
i = 3
for j in range(1024):
for k in range(1360):
arr[i,j,k] = gray[k,j]
arr = flip(arr,1)
vector = sfo.get_vector(arr)
sfo.save_obj(vector,filename)
def record_temperature():
from sample_frozen_optical2 import sample_frozen_optical as sfo
from numpy import zeros
try:
l=0
while True:
record_T_once(l)
l += 1
sleep(0.3)
except KeyboardInterrupt: pass
def record(camera_name = 'MicroscopeCamera'):
camera1 = Camera('MicroscopeCamera')
camera1.acquiring = True
camera2 = Camera('WideFieldCamera')
#camera2.ip_address = '192.168.127.12:2001'
camera2.acquiring = True
try:
i=0
while True:
ins = 0
filename = template % ("Microscope/",time(),i,int(ins),temperature.value)
print("%s" % basename(filename))
camera1.save_image(filename)
filename = template % ("WideField/",time(),i,int(ins),temperature.value)
print("%s" % basename(filename))
camera2.save_image(filename)
i += 1
sleep(delay)
except KeyboardInterrupt: pass
def record1(camera_name = 'MicroscopeCamera'):
template_NIH= "//femto/C/All Projects/Crystallization/2019/Lysozyme3/"\
"%s_%r.tiff"
camera1 = Camera('LabMicroscope')
camera1.acquiring = True
i=0
while True:
filename = template % (time(),i)
print("%s" % basename(filename))
camera1.save_image(filename)
i+=1
def server_record(N = 10,camera_name = 'MicroscopeCamera'):
camera = Camera(camera_name)
camera.acquiring = True
# Offload the image saving to the camera server for performance
filenames = [template % i for i in range(N)]
frame_counts = [camera.frame_count+1+i for i in range(len(filenames))]
camera.send("camera.acquire_sequence(%r,%r)" %(frame_counts,filenames))
print("server_record(20)")
print("record(camera_name = 'WideFieldCamera')")
<file_sep># <NAME>, 14 Mar 2014 - 18 Sep 2014
# Version 1.1
# Uncomment the appropriate line below.
from instrumentation_id14 import *
##from instrumentation_NIH import *
##from instrumentation_XPP import *
<file_sep>"""Make a property of a class cached
Usage:
class Banana(object):
def __init__(self): self.color = "green"
@cached
@property
def ripe(self): return True if self.color == "yellow" else False
banana = Banana()
class Banana(object):
def __init__(self): self.color = "green"
def get_ripe(self): return True if self.color == "yellow" else False
def set_ripe(self,value): self.color = "yellow" if value else "green"
ripe = cached(property(get_ripe,set_ripe))
banana = Banana()
class Banana(object):
def __init__(self): self.color = "green"
def get_ripe(self): return True if self.color == "yellow" else False
def set_ripe(self,value): self.color = "yellow" if value else "green"
ripe = property(get_ripe,set_ripe)
class Cached_Banana(Banana):
ripe = cached(Banana.ripe)
banana = Cached_Banana()
Date created: 2017-07-28
Date last modified: 2019-01-24
"""
__authors__ = ["<NAME>"]
__version__ = "1.0.2" # clear cache on set, forcing re-read
from logging import debug,info,warn,error
def cached_property(property_object,timeout=1.0):
"""Make a property cached
timeout: expiration time in seconds
"""
def cached(self,property_object):
from time import time
if not hasattr(self,"__cached_properties__"): return None
if property_object not in self.__cached_properties__: return None
if time() - self.__cached_properties__[property_object]["time"] > timeout:
return None
return self.__cached_properties__[property_object]["value"]
def cache(self,property_object,value):
from time import time
if not hasattr(self,"__cached_properties__"):
self.__cached_properties__ = {}
self.__cached_properties__[property_object] = {"time":time(),"value":value}
def cache_clear(self,property_object):
if hasattr(self,"__cached_properties__"):
del self.__cached_properties__[property_object]
def get(self):
value = cached(self,property_object);
##if value: debug("cached_property: Cached %28.28r" % value)
if value is None:
value = property_object.__get__(self)
##debug("cached_property: Updated %s=%28.28r" % (name(property_object),value))
cache(self,property_object,value)
return value
def name(object):
if hasattr(object,"__doc__"): return object.__doc__
return repr(object)
def set(self,value):
cache_clear(self,property_object)
property_object.__set__(self,value)
cached_property = property(get,set)
return cached_property
cached = cached_property
<file_sep>#!/bin/env python
"""Setup: source /reg/g/psdm/etc/ana_env.sh
"""
from time import time
import zmq
from logging import error,warn,info,debug
context = zmq.Context()
socket = context.socket(zmq.SUB)
servers = ["daq-xpp-mon05","daq-xpp-mon06"]
##servers = ['172.21.38.163','172.21.38.173']
##servers = ["localhost"]
ports = range(12300,12300+12)
for server in servers:
for port in ports: socket.connect("tcp://%s:%d" % (server,port))
socket.setsockopt(zmq.SUBSCRIBE, 'rayonix')
last_fid = 0
while True:
topic = socket.recv()
fid = socket.recv_pyobj()
arr = socket.recv_pyobj()
print("%d (%+d): %r" % (fid,fid-last_fid,arr.shape))
last_fid = fid
<file_sep>CustomView = ['Port', 'High Limit', 'Low Limit']
port_name = '/dev/tty.usbserial'
wait_time = 2.0<file_sep>"""Author: <NAME>, Oct 21, 2015 - Feb 1, 2017
"""
__version__ = "2.4" # sequencer_packets speedup
from pdb import pm # for debugging
from Ensemble_SAXS_pp import Ensemble_SAXS
from timing_system import timing_system,ps,ns,us,ms
from time import sleep,time
from numpy import *
import logging; logging.basicConfig(level=logging.DEBUG,format="%(asctime)s: %(message)s")
self = Ensemble_SAXS # for debugging
##import timing_system as t; t.DEBUG=True
timepoints = [
## 100*ps,178*ps,316*ps,562*ps,
## 1*ns,1.78*ns,3.16*ns,5.62*ns,
10*ns,17.8*ns,31.6*ns,56.2*ns,
100*ns,178*ns,316*ns,562*ns,
1*us,1.78*us,3.16*us,5.62*us,
10*us,17.8*us,31.6*us,56.2*us,
100*us,178*us,316*us,562*us,
1*ms,1.78*ms,3.16*ms,5.62*ms,
10*ms,17.8*ms,31.6*ms,
## 32*timing_system.hsct,64*timing_system.hsct,128*timing_system.hsct,
]
repeats = 40
timepoints=timepoints*repeats
laser_mode = [0,1]
npasses = 2
delays = array([t for t in timepoints for l in laser_mode])
laser_ons = array([l for t in timepoints for l in laser_mode])
image_numbers = arange(1,len(delays)+1)
passes = array([npasses]*len(image_numbers))
##image_numbers = array([62,64,66,68,70])
##delays = delays[image_numbers-1]
##laser_ons = laser_ons[image_numbers-1]
##passes = passes[image_numbers-1]
def start():
timing_system.image_number.value = 0
timing_system.pass_number.value = 0
timing_system.pulses.value = 0
upload()
def upload():
Ensemble_SAXS.acquire(delays,laser_ons,
passes=passes,image_numbers=image_numbers)
def stop(): Ensemble_SAXS.clear_queue()
def forever():
"""Continouly feed the queue, keeping collecting forever"""
while True:
start()
while len(Ensemble_SAXS.queue) > 10: sleep(1)
print("timing_system.ip_address = %r" % timing_system.ip_address)
##print("Ensemble_SAXS.cache_enabled = %r" % Ensemble_SAXS.cache_enabled)
##print("Ensemble_SAXS.queue_length")
##print("Ensemble_SAXS.clear_queue()")
##print("Ensemble_SAXS.cache_size = 0")
##print("upload()")
print("start()")
print("stop()")
<file_sep>import wx
class Notespad(wx.Frame):
UNTITLED = 'Untitled' #
WILDCARD = 'Text Documents (*.txt)|*.txt|Python Documents (*.py)|*.py' #
def __init__(self, *args, **kwargs):
#----------------------------------------------------------- Attributes
self.file_directory = None #
self.file_name = self.UNTITLED #
self.title_string = '{}{} - NotesPad' #
#---------------------------------------------------------- Frame Setup
super(Notespad, self).__init__(*args, **kwargs)
self.CreateStatusBar()
#----------------------------------------------------------- Frame Menu
menubar = wx.MenuBar()
self.SetMenuBar(menubar)
file_menu = wx.Menu()
menu_open = file_menu.Append(wx.ID_OPEN, '&Open',
'Open an existing document')
menu_new = file_menu.Append(wx.ID_NEW, '&New',
'Creates a new document') #
menu_save = file_menu.Append(wx.ID_SAVE, '&Save',
'Saves the active document') #
menu_saveas = file_menu.Append(wx.ID_SAVEAS, 'Save &As',
'Saves the active document with a new name') #
file_menu.AppendSeparator()
menu_exit = file_menu.Append(-1, 'Exit', 'Exit the Application')
menubar.Append(file_menu, '&File')
#--------------------------------------------------- Panel And Controls
panel = wx.Panel(self)
self.txt_ctrl = wx.TextCtrl(panel, style=wx.TE_MULTILINE)
#------------------------------------------------------- Sizer Creation
sizer = wx.BoxSizer(wx.VERTICAL)
sizer.Add(panel, 1, wx.EXPAND)
p_sizer = wx.BoxSizer(wx.VERTICAL)
p_sizer.Add(self.txt_ctrl, 1, wx.EXPAND)
#------------------------------------------------------- Setting Sizers
panel.SetSizer(p_sizer)
self.SetSizer(sizer)
self.Layout()
#---------------------------------------------------------- Event Binds
self.Bind(wx.EVT_MENU, self.on_menu_exit, menu_exit)
self.Bind(wx.EVT_MENU, self.on_menu_open, menu_open)
self.Bind(wx.EVT_MENU, self.on_menu_new, menu_new) #
self.Bind(wx.EVT_MENU, self.on_menu_save, menu_save) #
self.Bind(wx.EVT_MENU, self.on_menu_saveas, menu_saveas) #
#-------------------------------------------------------- Initial State
self.set_title() #
#----------------------------------------------------------- Event Handlers
def on_menu_exit(self, event):
self.Close()
event.Skip()
def on_menu_open(self, event):
self.file_open()
event.Skip()
def on_menu_new(self, event): #
self.file_new() #
event.Skip() #
def on_menu_save(self, event): #
self.file_save() #
event.Skip() #
def on_menu_saveas(self, event): #
self.file_saveas() #
event.Skip() #
#------------------------------------------------------------------ Actions
def file_open(self):
with wx.FileDialog(self, message='Open', wildcard=self.WILDCARD,
style=wx.OPEN) as dlg:
if dlg.ShowModal() == wx.ID_OK:
self.file_directory = dlg.GetDirectory() #
self.file_name = dlg.GetFilename() #
self.file_load() #
def file_load(self): #
full_path = '/'.join((self.file_directory, self.file_name)) #
self.txt_ctrl.LoadFile(full_path) #
self.set_title() #
def file_new(self): #
self.file_directory = None #
self.file_name = self.UNTITLED #
self.txt_ctrl.Clear() #
self.set_title() #
def file_saveas(self): #
with wx.FileDialog(self, message='Save as', wildcard=self.WILDCARD,
style=wx.SAVE) as dlg: #
if dlg.ShowModal() == wx.ID_OK: #
self.file_directory = dlg.GetDirectory() #
self.file_name = dlg.GetFilename() #
self.file_save() #
def file_save(self): #
if self.file_name == self.UNTITLED: #
self.file_saveas() #
else: #
full_path = '/'.join((self.file_directory, self.file_name)) #
self.txt_ctrl.SaveFile(full_path) #
self.set_title() #
def set_title(self): #
is_modified = '*' if self.txt_ctrl.IsModified() else '' #
self.SetTitle(self.title_string.format(is_modified, self.file_name)) #
if __name__ == '__main__':
wx_app = wx.App(False)
frame = Notespad(None)
frame.Show()
wx_app.MainLoop()
<file_sep>from __future__ import with_statement
"""
This is to communicate with an Agilent Windows-based oscilloscope over Ethernet.
The communication uses an RPC-based protocol, named VXI-11.2, that was originally
developped for VXI crates (VME eXtensions for Instrumentation).
<NAME>, 6 Sep 2007 - 11 Jul 2009
"""
from vxi_11 import vxi_11_connection # also requires rpc.py
from thread import allocate_lock
import socket # needed for socket.error
__version__ = "1.7"
NaN = 1e1000/1e1000 # generates Not A Number
class agilent_scope(object):
"This is to communicate with an Agilent Windows-based oscilloscope over Ethernet."
def __init__(self,ip_address):
self.ip_address = ip_address
self.connection = None
# This is to make the query method multi-thread safe.
self.lock = allocate_lock()
def __repr__(self):
return "agilent_scope('"+self.ip_address+"')"
def write(self,command):
"""Sends a command to the instrument using VXI-11.2 protocol"""
with self.lock:
for i in range(0,2):
try:
if self.connection == None:
self.connection = vxi_11_connection(self.ip_address)
self.connection.write (command)
except Exception,message:
self.log("write %r failed: %s" % (command,message))
self.connection = None
return ""
def read(self):
"""Reads a reply from to the instrument using VXI-11.2 protocol"""
with self.lock:
for i in range(0,2):
try:
if self.connection == None:
self.connection = vxi_11_connection(self.ip_address)
err,reason,reply = self.connection.read()
return reply
except Exception,message:
self.log("write %r failed: %s" % (command,message))
self.connection = None
return ""
def query(self,command):
"""Send a command an returns the reply received"""
with self.lock:
for i in range(0,2):
try:
if self.connection == None:
self.connection = vxi_11_connection(self.ip_address)
self.connection.write (command)
err,reason,reply = self.connection.read()
return reply.rstrip("\n")
except Exception,message:
self.log("query %r failed: %s" % (command,message))
self.connection = None
return ""
class measurement_object(object):
"""Implements automatic measurements, including averaging and statistics"""
def __init__(self,scope,n=1): self.scope = scope; self.n = n
def __repr__(self):
return repr(self.scope)+".measurement("+str(self.n)+")"
def get_value(self): return self.float_result(1)
value = property(get_value,doc="last sample (without averaging)")
def get_average(self): return self.float_result(4)
average = property(get_average,doc="averaged value")
def get_max(self): return self.float_result(3)
max = property(get_max,doc="maximum value contributing to average")
def get_min(self): return self.float_result(2)
min = property(get_min,doc="minimum value contributing to average")
def get_stdev(self): return self.float_result(5)
stdev = property(get_stdev,doc="standard deviation of individuals sample")
def get_count(self):
try: return int(float(self.result(6)))
except ValueError: return NaN
count = property(get_count,doc="number of measurement averaged")
def get_name(self):
try: return self.result(0)
except ValueError: return ""
name = property(get_name,doc="string representation of the measurment")
def result(self,index):
"""Reads the measurment results from the oscillscope and extracts one
value. index 0=name,1=current,2=min,3=max,4=mean,5=stdev,6=count"""
reply = self.scope.query (":MEASure:RESults?")
# format <name>,<current>,<min>,<max>,<mean>,<stdev>,<count>[,<name>,...]
fields = reply.split(",")
i = (self.n-1)*7 + index
if i < len(fields): return fields[i]
def float_result(self,index):
"""Reads the measurment results from the oscillscope and extracts one
value as floating point number.
index 1=current,2=min,3=max,4=mean,5=stdev"""
x = self.result(index)
if x == None: return NaN
if x == '9.99999E+37': return NaN
try: return float(x)
except ValueError: return NaN
def start(self): self.scope.start()
def stop(self): self.scope.stop()
def get_time_range(self): return self.scope.time_range
def set_time_range(self,value): self.scope.time_range = value
time_range = property(get_time_range,set_time_range,
doc="horizontal scale min to max (10 div) in seconds")
def measurement(self,n=1): return agilent_scope.measurement_object(self,n)
def start(self):
"""Clear the accumulated average and restart averaging.
Also re-eneables the trigger in case the scope was stopped."""
self.write (":CDISplay")
self.write (":RUN")
def stop(self):
"Freezes the averaging by disabling the trigger of the oscilloscope."
self.write (":STOP")
def get_time_range(self):
try: return float(self.query(":TIMebase:RANGe?"))
except ValueError: return NaN
def set_time_range(self,value): self.write (":TIMebase:RANGe %g" % value)
time_range = property(get_time_range,set_time_range,
doc="horizontal scale min to max (10 div) in seconds")
def get_id(self): return self.query("*IDN?")
id = property(get_id,doc="Model and serial number")
class gated_measurement(object):
"""Common code base for gates measurements.
The Agilent does not support gating on automated measurements.
Gated mesurements are implemented by downloading the waveform and processing
it in client computer memory. The gate is determined by the current position
of the two vertical cursors on the oscilloscope screen.
"""
def __init__(self,scope,channel=1):
self.scope = scope; self.channel = channel
def tstart(self): return float(self.scope.query(":MARKer:TSTArt?"))
def tstop(self): return float(self.scope.query(":MARKer:TSTOp?"))
def get_begin(self): return min(self.tstart(),self.tstop())
def set_begin(self,value): self.scope.write(":MARKer:TSTArt "+str(value))
begin = property(get_begin,set_begin,doc="starting time of integration gate")
def get_end(self): return max(self.tstart(),self.tstop())
def set_end(self,val): self.scope.write(":MARKer:TSTOp "+str(val))
end = property(get_end,set_end,doc="ending time of integration gate")
def tstr(t):
"Convert time given in seconds in more readble format such as ps, ns, ms, s"
try: t=float(t)
except: return "?"
if t != t: return "?" # not a number
if t == 0: return "0"
if abs(t) < 1E-20: return "0"
if abs(t) < 999e-12: return "%.3gps" % (t*1e12)
if abs(t) < 999e-9: return "%.3gns" % (t*1e9)
if abs(t) < 999e-6: return "%.3gus" % (t*1e6)
if abs(t) < 999e-3: return "%.3gms" % (t*1e3)
return "%.3gs" % t
tstr = staticmethod(tstr)
class gated_integral_object(gated_measurement):
"""The Agilent does not support gating on automated measurements.
The "Area" measurement integrates the whole displayed waveform.
Gated integration is implemented by downloading the waveform and processing
it in client computer memory. The integration gate with is determined
by the current position of the two vertical cursors on the oscilloscope
screen.
"""
def __init__(self,scope,channel=1):
agilent_scope.gated_measurement.__init__(self,scope,channel)
self.unit = "Vs"
def get_value(self):
return integral(self.scope.waveform(self.channel),self.begin,self.end)
value = property(get_value,doc="gated integral of waveform")
def get_name(self):
return "int("+str(self.channel)+","+self.tstr(self.begin)+","+self.tstr(self.end)+")"
name = property(get_name,doc="short description")
def gated_integral(self,channel=1):
"Area of waveform between vertical markers"
return agilent_scope.gated_integral_object(self,channel)
class gated_average_object(gated_measurement):
"""Calculates the average of the part of a waveform, enclosed by the two
vertical cursors on the oscilloscope screen."""
def __init__(self,scope,channel=1):
agilent_scope.gated_measurement.__init__(self,scope,channel)
self.unit = "V"
def get_value(self):
return average(self.scope.waveform(self.channel),self.begin,self.end)
value = property(get_value,doc="gated average of waveform")
def get_name(self):
return "ave("+str(self.channel)+","+self.tstr(self.begin)+","+self.tstr(self.end)+")"
name = property(get_name,doc="short description")
def gated_average(self,channel=1):
"Area of waveform between vertical markers"
return agilent_scope.gated_average_object(self,channel)
def waveform(self,channel=1): return self.waveform_16bit(channel)
def waveform_ascii(self,channel=1):
"Downloads waveform data in the form of a list of (t,y) tuples"
self.write(":SYSTEM:HEADER OFF")
self.write(":WAVEFORM:SOURCE CHANNEL"+str(channel))
self.write(":WAVEFORM:FORMAT ASCII")
data = self.query(":WAVeform:DATA?")
# format: <value>,<value>,... example: 5.09E-03,-5.16E-03,...
y = data.split(",")
preamble = self.query(":WAVeform:PREAMBLE?")
xincr = float(preamble.split(",")[4])
xorig = float(preamble.split(",")[5])
waveform = []
for i in range(len(y)): waveform.append((xorig+i*xincr,float(y[i])))
return waveform
def waveform_8bit (self,channel=1):
"""Downloads waveform data in the form of a list of (t,y) tuples.
In contrast to the "waveform" method, this implementation downloads
binary data, not formatted ASCII text, which is faster. (0.0037 s vs 0.120 s
for 20 kSamples)"""
self.write(":SYSTEM:HEADER OFF")
self.write(":WAVEFORM:SOURCE CHANNEL"+str(channel))
self.write(":WAVEFORM:FORMAT BYTE")
data = self.query(":WAVeform:DATA?")
# format: #<n><length><binary data>
# example: #520003...
n = int(data[1:2]) # number of bytes in "length" block
length = int(data[2:2+n]) # number of bytes in waveform data to follow
payload = len(data)-(2+n)
if length > payload:
print "(Waveform truncated from",length,"to",payload,"bytes)"
length = payload
from struct import unpack
bytes = unpack("%db" % length,data[2+n:2+n+length])
preamble = self.query(":WAVeform:PREAMBLE?")
xincr = float(preamble.split(",")[4])
xorig = float(preamble.split(",")[5])
yincr = float(preamble.split(",")[7])
yorig = float(preamble.split(",")[8])
waveform = []
for i in range(length):
waveform.append((xorig+i*xincr,yorig+bytes[i]*yincr))
return waveform
def waveform_16bit (self,channel=1):
"""Downloads waveform data in the form of a list of (t,y) tuples.
In contrast to the "waveform" method, this implementation downloads
binary data, not formatted ASCII text, which is faster. (0.0056 s vs 0.120 s
for 20 kSamples)"""
self.write(":SYSTEM:HEADER OFF")
self.write(":WAVeform:SOURce CHANNEL"+str(channel))
self.write(":WAVeform:FORMat WORD")
self.write(":WAVeform:BYTeorder LSBFirst")
data = self.query(":WAVeform:DATA?")
# format: #<n><length><binary data>
# example: #520003...
n = int(data[1:2]) # number of bytes in "length" block
length = int(data[2:2+n]) # number of bytes in waveform data to follow
payload = (len(data)-(2+n))
if length > payload:
print "(Waveform truncated from",length,"to",payload,"bytes)"
length = payload
nsamples = length/2
from struct import unpack
bytes = unpack("%dh" % nsamples,data[2+n:2+n+nsamples*2])
preamble = self.query(":WAVeform:PREAMBLE?")
xincr = float(preamble.split(",")[4])
xorig = float(preamble.split(",")[5])
yincr = float(preamble.split(",")[7])
yorig = float(preamble.split(",")[8])
waveform = []
for i in range(nsamples):
waveform.append((xorig+i*xincr,yorig+bytes[i]*yincr))
return waveform
def log(self,message):
"Append a message to the log file (/tmp/agilent_scope.log)"
from tempfile import gettempdir
from time import strftime
from sys import stderr
timestamp = strftime("%d-%b-%y %H:%M:%S")
if len(message) == 0 or message[-1] != "\n": message += "\n"
stderr.write("%s %r: %s" % (timestamp,self,message))
logfile = gettempdir()+"/agilent_scope.log"
file(logfile,"a").write(timestamp+" "+message)
def integral(waveform,begin=-1e1000,end=+1e1000):
sum = 0
for i in range(len(waveform)-1):
if waveform[i][0] >= begin and waveform[i][0] <= end:
sum += waveform[i][1]*(waveform[i+1][0]-waveform[i][0])
if len(waveform) > 1:
i = len(waveform)-1
if waveform[i][0] >= begin and waveform[i][0] <= end:
sum += waveform[i][1]*(waveform[i][0]-waveform[i-1][0])
return sum
def average(waveform,begin=-1e1000,end=+1e1000):
sum = 0; n = 0
for i in range(len(waveform)):
if waveform[i][0] >= begin and waveform[i][0] <= end:
sum += waveform[i][1]; n += 1
if n>0: return sum/n
def save_waveform(waveform,filename):
output = file(filename,"w")
for i in range(len(waveform)):
output.write(str(waveform[i][0])+"\t"+str(waveform[i][1])+"\n")
if __name__ == "__main__": # for testing, remove when done
id14b_scope = agilent_scope("id14b-scope.cars.aps.anl.gov")
print id14b_scope.id
<file_sep>from __future__ import with_statement
"""
Remote control of the MAR CCD detector, using <NAME>'s sample remote
control server program "marccd_server_socket" with TCP port number 2222.
Usage example: ccd = marccd("marccd043.cars.aps.anl.gov:2222")
The server is started from the MarCCD software from the Remote Control
control panel with the second parameter ("Server command" or "Device Database
Server") set to "/home/marccdsource/servers/marccd_server_socket", and the third parameter
("Server Arguments" or "Personal Name") set to "2222".
The server understand the following commands:
start - Puts the CCD to integration mode, no reply
readout,0,filename - Reads out the detector, corrects the image and saves it to a file
no reply
readout,1 - reads a new background image, no reply
get_state - reply is integer number containing 6 4-bit fields
bits 0-3: state: 0=idle,8=busy
bits 4-7: acquire
bits 8-11: read
bits 12-15: correct
bits 16-19: write
bits 20-23: dezinger
Each filed contains a 4-bit code, with the following meaning:
0=idle, 1=queued, 2=executing, 4=error
The exception is the 'state' field, which has only 0=idle and 8=busy.
writefile,<filename>,1 - Save the last read image, no reply
set_bin,8,8 - Use 512x512-pixel bin mode, no reply
set_bin,2,2 - Use full readout mode (2048x2048 pixels), no reply
(The 1x1 bin mode with 4096x4096 pixels is not used, because the point-spread
function of the fiber optic taper is large compared to the pixel size)
get_bin - reply is two integer numbers, e.g. "2,2"
get_size_bkg - reply is the number of pixels of current the background image, e.g. "2048,2048"
Reference: MARCCD Software Manual, v 0.10.17 (2006), Appendix 3: The remote mode
of marccd.
<NAME>, NIH, 10 Aug 2007 - APS, 8 Feb 2011
"""
import socket
from time import sleep,time
from thread import allocate_lock
__version__ = "2.0"
class marccd(object):
"""This is to remote control the MAR CCD detector
Using remote protocol version 1"""
def __init__(self,ip_address="marccd043.cars.aps.anl.gov:2222"):
"""ip_address may be given as address:port. If :port is omitted, port
number 2222 is assumed."""
object.__init__(self)
self.timeout = 1.0
if ip_address.find(":") >= 0:
self.ip_address = ip_address.split(":")[0]
self.port = int(ip_address.split(":")[1])
else: self.ip_address = ip_address; self.port = 2222
self.connection = None # network connection
# This is to make the query method multi-thread safe.
self.lock = allocate_lock()
# If this flag is set 'start' automatically reads a background image
# if there is not valid backgournd image.
self.auto_bkg = False
# Whether to save corrected or raw images.
self.save_raw = False
# Keep track of when the detector was last read.
self.last_read = 0.0
# Verbose logging: record verey command and reply in /tmp/marccd.log
self.verbose_logging = False
self.retries = 2 # used in case of communation error
def write(self,command):
"""Sends a command to the oscilloscope that does not generate a reply,
e.g. "ClearSweeps.ActNow()" """
if len(command) == 0 or command[-1] != "\n": command += "\n"
self.log("write %r" % command)
with self.lock: # Allow only one thread at a time inside this function.
for attempt in range(0,self.retries):
try:
if self.connection == None:
self.connection = socket.socket()
self.connection.settimeout(self.timeout)
self.connection.connect((self.ip_address,self.port))
self.connection.sendall (command)
return
except Exception,message:
self.log_error("write %r attempt %d/%d failed: %s" %
(command,attempt+1,self.retries,message))
self.connection = None
def query(self,command):
"""To send a command that generates a reply, e.g. "InstrumentID.Value".
Returns the reply"""
self.log("query %r" % command)
if len(command) == 0 or command[-1] != "\n": command += "\n"
with self.lock: # Allow only one thread at a time inside this function.
for attempt in range(0,self.retries):
try:
if self.connection == None:
self.connection = socket.socket()
self.connection.settimeout(self.timeout)
self.connection.connect((self.ip_address,self.port))
self.connection.sendall (command)
reply = self.connection.recv(4096)
while reply.find("\n") == -1:
reply += self.connection.recv(4096)
self.log("reply %r" % reply)
return reply.rstrip("\n\0")
except Exception,message:
self.log_error("write %r attempt %d/%d failed: %s" %
(command,attempt+1,self.retries,message))
self.connection = None
return ""
def query_long(self,command):
"""To send a command that generates a reply of more than 80 bytes.
Returns the reply"""
self.log("query %r" % command)
if len(command) == 0 or command[-1] != "\n": command += "\n"
with self.lock: # Allow only one thread at a time inside this function.
for attempt in range(0,self.retries):
try:
if self.connection == None:
self.connection = socket.socket()
self.connection.settimeout(self.timeout)
self.connection.connect((self.ip_address,self.port))
self.connection.sendall (command)
reply = self.connection.recv(4096)
self.connection.settimeout(0.1)
while True:
try: reply += self.connection.recv(4096)
except socket.timeout: break
self.log("reply length %r" % len(reply))
return reply
except Exception,message:
self.log_error("write %r attempt %d/%d failed: %s" %
(command,attempt+1,self.retries,message))
self.connection = None
return ""
def state_code(self):
"returns the status code as interger value"
reply = self.query("get_state").strip("\n\0")
try: status = int(reply)
except:
self.log_error("command 'state_code' generated bad reply %r" % reply)
return 0
# bit 8 and 9 of the state code tell whether the task status of "read"
# is either "queued" or "executing"
if (status & 0x00000300) != 0: self.last_read = time()
return status
def is_idle (self):
return (self.state_code() == 0)
def is_integrating (self):
"tells whether the chip is integrating mode (not reading, not clearing)"
# "acquire" field is "executing"
return ((self.state_code() & 0x00000020) != 0)
def is_reading (self):
"tells whether the chip is currently being read out"
# bit 8 and 9 of the state code tell whether the task status of "read"
# is either "queued" or "executing"
return ((self.state_code() & 0x00000300) != 0)
def is_correcting (self):
"tells whether the chip is currently being read out"
# bit 8 and 9 of the state code tell whether the task status of "correct"
# is either "queued" or "executing"
return ((self.state_code() & 0x00003000) != 0)
def state(self):
"readble status information: idle,integating,reading,writing"
try: status = self.state_code()
except: return ""
# bit mask 0x00444440 masks out error flags
if (status & ~0x00444440) == 0: return "idle"
if (status & 0x00000020) != 0: return "integrating"
if (status & 0x00000200) != 0: return "reading"
if (status & 0x00002000) != 0: return "correcting"
if (status & 0x00020000) != 0: return "writing"
if (status & 0x00200000) != 0: return "dezingering"
return ""
def start(self):
"""Puts the detector into inegration mode by stopping the continuous
clearing.
In case the CCD readout is in progess, execution is delayed until the
last readout is finished.
This also acquires a background image, in case there is no valid background
image (after startup or binning changed).
"""
# Wait for the readout of the previous image to finish.
while self.is_reading(): sleep(0.05)
if self.auto_bkg:
# Make sure there is a valid background image. Otherwise, the image
# correction will fail.
self.update_bkg()
self.write("start")
while not self.is_integrating(): sleep (0.05)
def readout(self,filename=None):
"""Reads the detector.
If a filename is given, the image is saved as a file.
The image file is written in background as a pipelined operation.
The function returns immediately.
The pathname of the file is interpreted in file system of the server,
not locally.
If 'save_raw' is true (default: false), the image raw data is saved
rather than the correct image.
"""
if filename != None: self.make_directory(filename)
if not self.save_raw:
if filename != None:
self.write("readout,0,"+remote(filename))
else: self.write("readout,0")
else:
if filename != None:
self.write("readout,3,"+remote(filename))
else: self.write("readout,3")
while not self.is_reading(): sleep(0.05)
self.last_read = time()
def readout_and_save_raw(self,filename):
"""Reads the detector and saves the uncorrected image as a file.
The image file is written in background as a pipelined operation.
The function returns immediately.
The pathname of the file is interpreted in file system of the server,
not locally.
"""
self.make_directory(filename)
self.write("readout,3,"+remote(filename))
self.last_read = time()
def readout_raw(self):
"Reads the detector out without correcting and displaying the image."
self.write("readout,3")
self.last_read = time()
def save_image(self,filename):
"""Saves the last read image to a file.
The pathname of the file is interpreted in file system of the server,
not locally.
"""
self.make_directory(filename)
self.write("writefile,"+remote(filename)+",1")
def save_raw_image(self,filename):
"""Saves the last read image without spatial and uniformity correction
to a file.
The pathname of the file is interpreted in file system of the server,
not locally.
"""
self.make_directory(filename)
self.write("writefile,"+remote(filename)+",0")
def image(self):
"""Returns the last image as 16-bit raw data.
This command required a special version of the MAR CCD server
(/home/marccd/NIH/v1/marccd_server_socket)
"""
return self.query_long("get_image,1")
def raw_image(self):
"""Returns the last read image before correction as 16-bit raw data.
This command required a special version of the MAR CCD server
(/home/marccd/NIH/v1/marccd_server_socket)
"""
return self.query_long("get_image,0")
def read_image(self):
"""Reads the detector and transfers the image without saving to a file.
Returns 16-bit raw data.
This command required a special version of the MAR CCD server
(/home/marccd/NIH/v1/marccd_server_socket)
"""
self.write("readout,0")
sleep(0.2)
while self.is_correcting(): sleep(0.2)
return self.query_long("get_image,1")
self.last_read = time()
def read_raw_image(self):
"""Reads the detector and transfers the image without saving to a file.
Returns 16-bit raw data.
This command required a special version of the MAR CCD server
(/home/marccd/NIH/marccd_server_socket)
"""
self.write("readout,3")
sleep(0.2)
while self.is_reading(): sleep(0.2)
return self.query_long("get_image,0")
self.last_read = time()
def get_bin_factor(self):
try: return int(self.query("get_bin").split(",")[0])
except: return
def set_bin_factor(self,n):
self.write("set_bin,"+str(n)+","+str(n))
# After a bin factor change it takes about 2 s before the new
# bin factor is read back.
t = time()
while self.get_bin_factor() != n and time()-t < 3: sleep (0.1)
bin_factor = property(get_bin_factor,set_bin_factor,
doc="Readout X and Y bin factor")
def read_bkg(self):
"""Reads a fresh the backgound image, which is substracted from every image after
readout before the correction is applied.
"""
self.write("start")
while not self.is_integrating(): sleep(0.05)
self.write("readout,1")
while not self.is_idle(): sleep(0.05)
self.last_read = time()
def image_size(self):
"Width and height of the image in pixels at the current bin mode"
try: return int(self.query("get_size").split(",")[0])
except: return 0
def bkg_image_size(self): # does not work with protocol v1 (timeout)
"""Width and height of the current background image in pixels.
This value is important to know if the bin factor is changed.
If the backgroud image does not have the the same number of pixels
as the last read image the correction as saving to file will fail.
At startup, the background image is empty and this value is 0.
"""
try: return int(self.query("get_size_bkg").split(",")[0])
except: return 0
def update_bkg(self):
"""Updates the backgound image if needed, for instance after the server has
been restarted or after the bin factor has been changed.
"""
if not self.bkg_valid(): self.read_bkg()
def bkg_valid(self):
return self.bkg_image_size() == self.image_size()
# By default verbose logging is enabled. Change when problem solved.
logging = False
def state_info(self,status):
"""Decode the reply of te 'get_state" command.
status is an integer number."""
# reply is integer number containing 6 4-bit fields
# bits 0-3: state: 0=idle,8=busy
# bits 4-7: acquire
# bits 8-11: read
# bits 12-15: correct
# bits 16-19: write
# bits 20-23: dezinger
# Each fieled contains a 4-bit code, with the following meaning:
# 0=idle, 1=queued, 2=executing, 4=error
# The exception is the 'state' field, which has only 0=idle and 8=busy.
if type(status) == str:
try: status = int(status.strip("\n\0"))
except: return "status %r: not an integer" % status
s = ""
if (status & 0x0000000F) != 0:
state = status & 0x0000000F
if state == 8: s += "busy, "
elif state != 0: s += "state %d, " % state
if (status & 0x00000010) != 0: s += "integration queued, "
if (status & 0x00000020) != 0: s += "integrating, "
if (status & 0x00000040) != 0: s += "integration error, "
if (status & 0x00000100) != 0: s += "read queued, "
if (status & 0x00000200) != 0: s += "reading, "
if (status & 0x00000400) != 0: s += "read error, "
if (status & 0x00001000) != 0: s += "correct queued, "
if (status & 0x00002000) != 0: s += "correcting, "
if (status & 0x00004000) != 0: s += "correct error, "
if (status & 0x00010000) != 0: s += "write queued, "
if (status & 0x00020000) != 0: s += "writing, "
if (status & 0x00080000) != 0: s += "write error, "
if (status & 0x00100000) != 0: s += "dezinger queued, "
if (status & 0x00200000) != 0: s += "dezingering, "
if (status & 0x00800000) != 0: s += "dezinger error, "
if (status & 0xFF000000) != 0: s += "(undcoumented bits 24-31 set), "
s = s.strip(", ")
if s == "": s = "idle"
return s
def make_directory(self,filename):
"""Make sure that the directory of teh given filename exists by create it,
if necessary."""
from os.path import exists,dirname; from os import makedirs
if filename == None or filename == "": return
directory = dirname(filename)
if directory == "" or directory == ".": return
if exists(directory): return
try: makedirs(directory)
except Exception,message:
self.log_error("Failed to create directory %r for file %r: %r" %
(directory,filename,message))
def log_error(self,message):
"""For error messages.
Display the message and append it to the error log file.
If verbose logging is enabled, it is also added to the transcript."""
from sys import stderr
if len(message) == 0 or message[-1] != "\n": message += "\n"
t = timestamp()
stderr.write("%s: %s: %s" % (t,self.ip_address,message))
file(self.error_logfile,"a").write("%s: %s" % (t,message))
self.log(message)
def log(self,message):
"""For non-critical messages.
Append the message to the transcript, if verbose logging is enabled."""
if not self.verbose_logging: return
if len(message) == 0 or message[-1] != "\n": message += "\n"
t = timestamp()
file(self.logfile,"a").write("%s: %s" % (t,message))
def get_error_logfile(self):
"""File name error messages."""
from tempfile import gettempdir
return gettempdir()+"/marccd_error.log"
error_logfile = property(get_error_logfile)
def get_logfile(self):
"""File name for transcript if verbose logging is enabled."""
from tempfile import gettempdir
return gettempdir()+"/marccd.log"
logfile = property(get_logfile)
def timestamp():
"""Current date and time as formatted ASCCI text, precise to 1 ms"""
from datetime import datetime
timestamp = str(datetime.now())
return timestamp[:-3] # omit microsconds
def remote(pathname):
"""This converts the pathname of a file on a network file server from
the local format to the format used on the MAR CCD compter.
e.g. "//id14bxf/data" in Windows maps to "/net/id14bxf/data" on Unix"""
if not pathname: return pathname
# Try to expand a Windows drive letter to a UNC name.
try:
import win32wnet
# Convert "J:/anfinrud_0811/Data" to "J:\anfinrud_0811\Data".
pathname = pathname.replace("/","\\")
pathname = win32wnet.WNetGetUniversalName(pathname)
except: pass
# Convert separators from DOS style to UNIX style.
pathname = pathname.replace("\\","/")
if pathname.find("//") == 0: # //server/share/directory/file
parts = pathname.split("/")
if len(parts) >= 4:
server = parts[2] ; share = parts[3]
path = ""
for part in parts[4:]: path += part+"/"
path = path.rstrip("/")
pathname = "/net/"+server+"/"+share+"/"+path
return pathname
if __name__ == "__main__": # for testing
ccd = marccd("marccd043.cars.aps.anl.gov:2222")
ccd.verbose_logging = True
<file_sep>trigger_PV = 'NIH:TIMING.registers.ch7_state.count'
external_trigger = 1<file_sep>CustomView = ['Live image', 'Filename', 'Live filename', 'Refresh interval', 'ADXV status']
view = 'Custom'<file_sep>from pdb import pm
from instrumentation import *
import timing_system
import logging
from tempfile import gettempdir
from logging import debug,error,warn
from time import sleep
logging.basicConfig(level=logging.DEBUG,format="%(asctime)s: %(message)s")
class Laseron_wrapper(object):
""""Work-around for a but in the FPGA firmeware for the "laseron"
register"""
def __init__(self,laseron):
"""laseron: original FPGA register object"""
self.laseron = laseron
def get_value(self): return self.laseron.value
def set_value(self,value):
self.laseron.value = value
if self.laseron.value != value:
# Toggle the bit on and off until the value get accepted.
attempt = 0; attempts = 10
while self.laseron.value != value and attempt<attempts:
self.laseron.value = not value
self.laseron.value = value
attempt += 1
warn("laseron: expected %d,got %d after %r/%r retries" %
(value,self.laseron.value,attempt,attempts))
if self.laseron.value != value:
error("laseron: expected %d, got %d" %
(value,self.laseron.value))
value = property(get_value,set_value)
laseron = Laseron_wrapper(timing_system.laseron1)
def test():
value = True
for i in range(0,100):
timing_system.laseron.value = value
sleep(1)
value = not value
def test2():
value = True
for i in range(0,100):
laseron.value = value
sleep(1)
value = not value
def test1():
value = True
for i in range(0,100):
laseron.value = value
if laseron.value != value:
n = 0
while laseron.value != value and n<10:
laseron.value = not value
laseron.value = value
n += 1
warn("%d. expected %d,got %d, retries=%r"% (i,value,laseron.value,n))
if laseron.value != value: warn("%d. failed to set %d" % value)
sleep(1)
value = not value
print("test()")
<file_sep>title = 'Delay Configuration'
motor_labels = ['list of delays']
names = ['delay']
motor_names = ['collect.delay']
line0.description = 'NIH:H-1_ps'
line1.description = 'NIH:H-56_ps'
line0.collect.delay = 'hsc=H-1, pp=Flythru-4, seq=NIH:i5c1, delays=pairs(-10us, lin_series(-100ps, 75ps, 25ps)+sorted(log_series(100ps, 1us, steps_per_decade=4)+[75ns, 133ns]))'
line1.collect.delay = 'hsc=H-56, pp=Flythru-4, seq=NIH:i1, delays=pairs(-10us, [-10.1us]+log_series(316ns, 17.8ms, steps_per_decade=4))'
line0.updated = '09 Oct 14:06'
line1.updated = '09 Oct 14:07'
widths = [500]
row_height = 54
description_width = 140
nrows = 9
line2.collect.delay = 'hsc=H-1, pp=Flythru-48, seq=NIH:i5c1, delays=pairs(-10us,[-10.1us, -2.8ns,0, 2.8ns]+sort(log_series(5.6ns, 1us, steps_per_decade=4)+[75ns, 133ns]))'
line3.collect.delay = 'hsc=H-56, pp=Flythru-48, seq=NIH:i1, delays=pairs(-10us, [-10.1us]+log_series(316ns, 178ms, steps_per_decade=4))'
line2.description = 'NIH:H-1_ns'
line5.collect.delay = 'hsc=H-56, pp=Flythru-48, seq=NIH:i1, delays=[pairs(-10us, log_series(10ms, 178ms, steps_per_decade=4)]'
line4.collect.delay = u''
line7.collect.delay = u'delays=[[(pp=Period-48, enable=010)]*5, (image=0, pp=Period-144, enable=100), (264+1*144, enable=101), [(image=0, enable=100)]*2, (264+4*144, enable=101), (image=0, enable=100)*4, (264+9*144, enable=101), (image=0, enable=100)*8, (264+18*144, enable=101), (image=0, enable=100)*16, (264+35*144, enable=101), (image=0, enable=100)*32, (264+68*144, enable=101)]'
line6.collect.delay = u'hsc=H-56, pp=Flythru-4, seq=NIH:i1, delays=[-10us, -10us, (264, enable=101, circulate=0), 528, 792, 1056, (-10us, enable=111, circulate=1), -10us]'
line3.description = 'NIH:H-56_ns'
line4.description = 'NIH:S-11'
line5.description = 'NIH:H-56_LT'
line6.description = 'NIH:H-56_Exotic_ps'
line7.description = 'BioCARS:TR-LT'
line2.updated = '09 Oct 20:20'
line6.updated = '09 Oct 20:30'
line7.updated = '09 Oct 20:30'
line5.updated = '09 Oct 20:30'
line3.updated = '09 Oct 20:21'
command_row = 8
show_apply_buttons = True
apply_button_label = 'Select'
define_button_label = 'Update'
show_define_buttons = False
show_stop_button = False
line8.description = 'None'
line8.updated = '23 Oct 19:24'
line8.collect.delay = ' '<file_sep>"""
<NAME>, 18 Mar 2013 - 28 Mar 2013
"""
# Command: 'SETPARM 145,"Enable Trigger."\n'
# Reply: '%\n'
# Command: 'GETPARM(145)\n'
# Reply: '%OK: Trigger is enabled.\n'
__version__ = "0.5"
def query(command):
"""To send a command that generates a reply."""
max_retries = 2
from EPICS_comm import CommPort
port = CommPort("14IDB:SAMPLECOM")
port.timeout = 0.2
# Transmit the command.
# Parameter 145 = UserString0
request = 'SETPARM 145,"%s"\n' % command
reply = port.query(request)
if not reply.startswith("%"):
# Controller did not reply.
if len(reply) == 0: log_error("Request %r: no reply" % request)
else: log_error("Request %r: Reply %r: Expecting '%%'" % (request,reply))
return ""
# Get the reply.
request = "GETPARM(145)\n"
reply = port.query(request)
attempt = 1
if not reply.startswith("%"):
# Controller did not reply.
if len(reply) == 0: log_error("Request %r: no reply" % request)
else: log_error("Request %r: Reply %r: Expecting '%%'" % (request,reply))
return ""
while reply == "%%%s\n" % command:
# Command not yet processed. Give it more time.
if attempt > max_retries: break
log("Command %r: Attempt %d, Reply %r: Command not yet processed" %
(command,attempt,reply))
reply = port.query (request)
attempt += 1
if not reply.startswith("%"):
# Controller did not reply.
if len(reply) == 0: log_error("Request %r: no reply" % request)
else: log_error("Request %r: Reply %r: Expecting '%%'" % (request,reply))
return ""
if not (reply.startswith("%OK: ") or reply.startswith("%?")):
# Command not processed. (SampleTranslation program not running?)
if reply == "%%%s\n" % command:
log_error("Command %r: Attempt %d, reply %r: Command not processed" %
(command,attempt,reply))
else: log_error("Request %r: Reply %r: expecting '%%OK: ...' or '%%?'" % (request,reply))
return ""
if not reply.startswith("%OK: "):
# Command processed, but not understood.
if reply.startswith("%?"):
log_error("Command %r: Reply %r: Command not understood" % (command,reply))
else:
log_error("Command %r: Reply %r: Expecting '%%OK: ...'" % (command,reply))
return ""
reply = reply[5:] # remove "%OK: "
reply = reply.strip("\n")
log("Command %r: Reply %r" % (command,reply))
return reply
def log(message):
from sys import stderr
stderr.write("Info: %s\n" % message)
def log_error(message):
from sys import stderr
stderr.write("Error: %s\n" % message)
if __name__ == "__main__": # for testing
print 'query("Enable Trigger.")'
print 'query("Disable Trigger.")'
<file_sep>Size = (612, 646)
Position = (858, 136)
ScaleFactor = 0.5
ZoomLevel = 1.0
Orientation = 0
Mirror = False
NominalPixelSize = 0.00465
filename = ''
ImageWindow.Center = (656.0, 508.0)
ImageWindow.ViewportCenter = (3.1155, 2.3901)
ImageWindow.crosshair_color = (255, 0, 0)
ImageWindow.boxsize = (0.1, 0.34)
ImageWindow.box_color = (128, 128, 255)
ImageWindow.show_box = True
ImageWindow.Scale = [(-1.325625, -0.21064500000000008), (-1.0256250000000002, -0.21064500000000008)]
ImageWindow.show_scale = True
ImageWindow.scale_color = (255, 0, 0)
ImageWindow.crosshair_size = (0.04, 0.04)
ImageWindow.show_crosshair = True
ImageWindow.show_profile = False
ImageWindow.show_FWHM = False
ImageWindow.show_center = False
ImageWindow.calculate_section = False
ImageWindow.profile_color = (255, 0, 255)
ImageWindow.FWHM_color = (255, 255, 0)
ImageWindow.center_color = (255, 255, 0)
ImageWindow.ROI = [[0.26039999999999996, 0.1674], [-0.3813, -0.2418]]
ImageWindow.ROI_color = (255, 255, 0)
ImageWindow.show_saturated_pixels = False
ImageWindow.mask_bad_pixels = False
ImageWindow.saturation_threshold = 233
ImageWindow.saturated_color = (255, 255, 0, 255)
ImageWindow.linearity_correction = False
ImageWindow.bad_pixel_threshold = 233
ImageWindow.bad_pixel_color = (30, 30, 30)
ImageWindow.show_grid = False
ImageWindow.grid_type = 'xy'
ImageWindow.grid_color = (0, 0, 255)
ImageWindow.grid_x_spacing = 0.055
ImageWindow.grid_x_offset = 0.0006999999999999437
ImageWindow.grid_y_spacing = 1.0
ImageWindow.grid_y_offset = 0.0
show_edge_controls = False
stepsize = 0.01
camera_angle = 60.0
x_scale = -1.0
y_scale = 1.0
z_scale = -1.0
phi_stepsize = 90.0
learn_center = False
click_center_enabled = False
<file_sep>"""Software simulated motor
Author: <NAME>
Date created: 2015-11-03
Date last modified: 2019-05-26
"""
__version__ = "1.2" # sim_EPICS_motor: readback
class sim_motor(object):
from persistent_property import persistent_property
from numpy import inf
stepsize = persistent_property("stepsize",0.001)
target = persistent_property("target",0.0)
speed = persistent_property("speed",10.0)
min_dial = persistent_property("min_dial",0.0)
max_dial = persistent_property("max_dial",100.0)
sign = persistent_property("sign",1)
offset = persistent_property("offset",0.0)
unit = persistent_property("unit","mm")
enabled = persistent_property("enabled",True)
description = persistent_property("description","simulated motor")
move_starting_position = 0.0
move_starting_time = 0.0
def __init__(self,name="sim_motor"):
"""name: string"""
self.name = name
def get_dial(self):
from time import time
if self.target > self.move_starting_position:
direction = 1
else: direction = -1
dial = self.move_starting_position + \
(time() - self.move_starting_time)*self.speed*direction
if direction > 0: dial = min(dial,self.target)
else: dial = max(dial,self.target)
return dial
def set_dial(self,dial): self.command_dial = dial
dial = property(get_dial,set_dial)
def get_moving(self):
from time import time
from numpy import sign
direction = sign(self.target - self.move_starting_position)
dial = self.move_starting_position + \
(time() - self.move_starting_time)*self.speed*direction
moving = dial < self.target if direction > 0 else dial > self.target
return moving
def set_moving(self,value):
if bool(value) == False: self.target = self.dial
moving = property(get_moving,set_moving)
def get_command_dial(self): return self.target
def set_command_dial(self,dial):
from time import time
self.move_starting_position = self.dial
self.move_starting_time = time()
self.target = dial
command_dial = property(get_command_dial,set_command_dial)
def get_value(self): return self.user_from_dial(self.dial)
def set_value(self,value): self.dial = self.dial_from_user(value)
value = property(get_value,set_value)
def get_command_value(self): return self.user_from_dial(self.command_dial)
def set_command_value(self,value): self.command_dial = self.dial_from_user(value)
command_value = property(get_command_value,set_command_value)
def get_min(self):
if self.sign>0: return self.user_from_dial(self.min_dial)
else: return self.user_from_dial(self.max_dial)
def set_min(self,value):
if self.sign>0: self.min_dial = self.dial_from_user(value)
else: self.max_dial = self.dial_from_user(value)
min = property(get_min,set_min)
def get_max(self):
if self.sign>0: return self.user_from_dial(self.max_dial)
else: return self.user_from_dial(self.min_dial)
def set_max(self,value):
if self.sign>0: self.max_dial = self.dial_from_user(value)
else: self.min_dial = self.dial_from_user(value)
max = property(get_max,set_max)
def user_from_dial(self,value): return value * self.sign + self.offset
def dial_from_user(self,value): return (value - self.offset) / self.sign
# EPICS motor record process variables
VAL = command_value
RBV = value
DVAL = command_dial
DRBV = dial
VELO = speed
CNEN = enabled
LLM = min
HLM = max
DLLM = min_dial
DHLM = max_dial
HLS = False
LLS = False
DESC = description
EGU = unit
HOMF = False
HOMR = False
OFF = offset # User and dial coordinate difference
def get_DMOV(self):
"""Done moving?"""
return not self.moving
def set_DMOV(self,value): self.moving = not value
DMOV = property(get_DMOV,set_DMOV)
def get_STOP(self): return not self.moving
def set_STOP(self,value): self.moving = not value
STOP = property(get_STOP,set_STOP)
def get_MSTA(self):
"""Motor status bits:
8 = home
11 = moving
15 = homed"""
status_bits = self.homing<<8|self.moving<<11|self.homed<<15
return status_bits
def set_MSTA(self,value): pass
MSTA = property(get_MSTA,set_MSTA)
def get_DIR(self):
"""User to dial 0=Pos, 1=Neg"""
return 0 if self.sign == 1 else 1
def set_DIR(self,value):
if value == 0: self.sign = 1
if value == 1: self.sign = -1
DIR = property(get_DIR,set_DIR)
def get_ACCL(self):
"""Acceleration time to full speed in seconds"""
T = self.speed/self.acceleration
return T
def set_ACCL(self,T):
self.acceleration = self.speed/T
ACCL = property(get_ACCL,set_ACCL)
C = value # needed for slits
class sim_EPICS_motor(sim_motor):
"""Simulated EPICS motor"""
from persistent_property import persistent_property
__prefix__ = persistent_property("prefix","SIM:MOTOR")
__EPICS_enabled__ = persistent_property("EPICS_enabled",True)
def __init__(self,prefix="SIM:MOTOR",name="sim_motor",
description="simulated motor",unit=None,readback=None):
"""prefix: default name of motor record
name: mnemonic name
readback: PV name for readback value (RBV)
"""
sim_motor.__init__(self,prefix)
self.name = name
if self.__prefix__ == "SIM:MOTOR": self.__prefix__ = prefix
if self.description == "simulated motor": self.description = description
if unit is not None and self.unit == "mm": self.unit = unit
self.readback = readback
self.EPICS_enabled = self.EPICS_enabled
def get_prefix(self):
return self.__prefix__
def set_prefix(self,value):
from CAServer import register_object,unregister_object
self.__prefix__ = value
unregister_object(object=self)
self.name = value
register_object(self,value)
prefix = property(get_prefix,set_prefix)
def get_EPICS_enabled(self):
return self.__EPICS_enabled__
def set_EPICS_enabled(self,value):
self.__EPICS_enabled__ = value
if self.__EPICS_enabled__:
from CAServer import register_object,register_property
register_object(self,self.__prefix__)
if self.readback: register_property(self,"RBV",self.readback)
else:
from CAServer import unregister_object,unregister_property
unregister_object(object=self)
if self.readback: unregister_property(self,"RBV",self.readback)
EPICS_enabled = property(get_EPICS_enabled,set_EPICS_enabled)
if __name__ == "__main__":
import logging
logging.basicConfig(level=logging.DEBUG,format="%(asctime): %(message)s")
motor = sim_EPICS_motor
Slit1H = motor("14IDA:Slit1Hsize",name="Slit1H",description="White beam slits H gap",
readback="14IDA:Slit1Ht2.C")
from CA import caget,caput
print('Slit1H.prefix = %r' % Slit1H.prefix)
print('Slit1H.readback = %r' % Slit1H.readback)
print('Slit1H.EPICS_enabled = %r' % Slit1H.EPICS_enabled)
print('caget(Slit1H.prefix+".VAL")')
print('caget(Slit1H.readback)')
print('caput(Slit1H.readback,Slit1H.VAL)')
print('Slit1H.value += 0.001')
print('Slit1H.value')
<file_sep>"""
Check a dataset collected with PP collect for consistency and completemess
Author: <NAME>
Date created: 2019-03-19
Date last modified: 2019-03-20
"""
__version__ = "1.0"
from logging import debug,info,warn,error
from collect import Collect
class Dataset(Collect):
"""PP Collect generated datset"""
name = "Collect"
@property
def n_expected(self):
"""Number of images attempeted to collect, whether sucessful or not"""
if self.collection_finished: n = self.n
else: n = self.n_finished
return n
@property
def n_finished(self):
"""Number of images attempeted to collect, whether sucessful or not"""
logged = self.logfile_has_entries(self.xray_image_filenames)
from numpy import where
i = where(logged)[0]
n = i[-1]+1 if len(i) > 0 else 0
return n
@property
def collection_finished(self):
from time import time
finished = file_timestamp(self.logfile_name) < time()-20
finished = finished and self.dataset_started
return finished
@property
def logfile_entries_missing(self):
logged = self.logfile_has_entries(self.xray_image_filenames)
logged = logged[0:self.n_expected]
n_missing = sum(logged == False)
return n_missing
@property
def logged(self):
logged = self.logfile_has_entries(self.xray_image_filenames)
logged = logged[0:self.n_expected]
return logged
@property
def xray_image_time_differences(self):
from numpy import array
dt = []
for f in dataset.xray_images_collected:
dt += [file_timestamp(f) - dataset.logfile_timestamp(f)]
dt = array(dt)
return dt
@property
def xray_images_expected(self):
return self.xray_image_filenames[0:self.n_expected]
@property
def xray_images_missing(self):
from exists import exist_files
filenames = self.xray_image_filenames[0:self.n_expected]
return ~exist_files(filenames)
@property
def xray_scope_traces_expected(self):
n_expected = self.n_expected * self.sequences_per_xray_image
return self.xray_scope_trace_filenames[0:n_expected]
@property
def xray_scope_traces_missing(self):
from exists import exist_files
return ~exist_files(self.xray_scope_traces_expected)
@property
def xray_scope_trace_time_differences(self):
N = self.sequences_per_xray_image
sequence = self.sequences[0]
T = sequence.period*sequence.tick_period()
dt = []
for i,f in enumerate(dataset.xray_scope_trace_filenames):
offset = (i % N - (N-1)) * T
dt += [file_timestamp(f) - (dataset.logfile_timestamp(f)+offset)]
from numpy import array
dt = array(dt)
return dt
@property
def laser_scope_traces_expected(self):
n_expected = self.n_expected * self.sequences_per_xray_image
return self.laser_scope_trace_filenames[0:n_expected]
@property
def laser_scope_traces_missing(self):
from exists import exist_files
return ~exist_files(self.laser_scope_traces_expected)
@property
def laser_scope_trace_time_differences(self):
N = self.sequences_per_xray_image
sequence = self.sequences[0]
T = sequence.period*sequence.tick_period()
dt = []
for i,f in enumerate(dataset.laser_scope_trace_filenames):
offset = (i % N - (N-1)) * T
dt += [file_timestamp(f) - (dataset.logfile_timestamp(f)+offset)]
from numpy import array
dt = array(dt)
return dt
@property
def report(self):
report = ""
if self.collection_finished: status = "finished"
elif self.dataset_started: status = "in progress"
else: status = "not started"
report += "Dataset: %s\n" % self.basename
report += "Path: %s\n" % shortened_path(self.directory)
report += "Progress: %s/%s (%s)\n" % (dataset.n_finished,dataset.n,status)
logged = self.logged
report += "Logfile entries: %r/%r \n" % (sum(logged),len(logged))
expected = self.xray_images_expected
collected = self.xray_images_collected
missing = self.xray_images_missing
report += "X-ray image files: %r/%r " % (len(collected),len(expected))
if sum(missing) >= 1:
from numpy import where
first_missing = where(missing)[0][0]
first_file_missing = expected[first_missing]
from os.path import basename
report += "(missing: %d %r" % (first_missing+1,basename(first_file_missing))
if sum(missing) >= 2: report += ", ..."
report += ")"
report += "\n"
expected = self.xray_scope_traces_expected
collected = self.xray_scope_traces_collected
missing = self.xray_scope_traces_missing
report += "X-ray scope traces: %r/%r " % (len(collected),len(expected))
if sum(missing) >= 1:
from numpy import where
first_missing = where(missing)[0][0]
first_file_missing = expected[first_missing]
from os.path import basename
report += "(missing: %d %r" % (first_missing+1,basename(first_file_missing))
if sum(missing) >= 2: report += ", ..."
report += ")"
report += "\n"
expected = self.laser_scope_traces_expected
collected = self.laser_scope_traces_collected
missing = self.laser_scope_traces_missing
report += "Laser scope traces: %r/%r " % (len(collected),len(expected))
if sum(missing) >= 1:
from numpy import where
first_missing = where(missing)[0][0]
first_file_missing = expected[first_missing]
from os.path import basename
report += "(missing: %d %r" % (first_missing+1,basename(first_file_missing))
if sum(missing) >= 2: report += ", ..."
report += ")"
report += "\n"
dt = self.xray_image_time_differences
report += "X-ray image timestaps: offset %.3f s, sdev %.3f s\n" \
% (nanmean(dt),nanstd(dt))
dt = self.xray_scope_trace_time_differences
report += "X-ray scope trace timestaps: offset %.03f s, sdev %.3f s\n" \
% (nanmean(dt),nanstd(dt))
dt = self.laser_scope_trace_time_differences
report += "Laser scope trace timestaps: offset %.03f s, sdev %.3f s\n" \
% (nanmean(dt),nanstd(dt))
report = report.replace("offset nan s","-")
report = report.replace("sdev nan s","-")
report = report.replace(" 0/"," -/")
report = report.replace("/0 ","/- ")
return report
def monitor(self):
"""Keep generating reports"""
import autoreload
from sleep import sleep
from sys import stdout
try:
while True:
report = "\n\n"+self.report+"\n"
report += "[Updating in 10 s... Control-C to end]"
stdout.write(report)
sleep(10)
except KeyboardInterrupt: pass
stdout.write("\n\n")
dataset = Dataset()
def nanmean(a):
from numpy import mean,nan,isnan,any
try:
valid = ~isnan(a)
return mean(a[valid]) if any(valid) else nan
except: return nan
def nanstd(a):
from numpy import std,nan,isnan,any
try:
valid = ~isnan(a)
return std(a[valid]) if any(valid) else nan
except: return nan
def file_timestamp(filename):
from os.path import getmtime
from numpy import nan
try: timestamp = getmtime(filename)
except: timestamp = nan
return timestamp
def shortened_path(pathname,max_length=40):
from os.path import basename,dirname
shortened_path = ""
while len(basename(pathname)+"/"+shortened_path) <= max_length+1:
shortened_path = basename(pathname)+"/"+shortened_path
pathname = dirname(pathname)
shortened_path = shortened_path.rstrip("/")
return shortened_path
if __name__ == "__main__":
from pdb import pm # for debugging
self = dataset # for debugging
##dataset.monitor()
##print("dataset.directory")
print("dataset.xray_image_time_differences")
print("dataset.xray_scope_trace_time_differences")
print("print(dataset.report)")
<file_sep>param.acceleration = 200.0
param.acceleration_distance = 0.010580460659725009
param.acceleration_time = 0.010286136621552821
param.continuous = 1.0
param.distance_of_actual_data_collection = 19.199999999999996
param.first_hole_x = 1.476
param.first_hole_y = -0.121
param.first_hole_z = -23.089
param.first_home_x = -2.1640625
param.first_home_y = -7.10796875
param.first_home_z = -2.60296875
param.full_cycle_clock_ticks = 106.0
param.last_hole_x = 1.586
param.last_hole_y = 0.023
param.last_hole_z = -3.289
param.max_velocity_on_return = 62.96214882184287
param.measure_length = 10176.0
param.number_of_data_points = 96.0
param.repetition_period = 96.0
param.settle_period = 2.0
param.settling_distance_at_speed = 0.39999999999999997
param.settling_time_at_speed = 0.19443646080000002
param.step_size = 0.2
param.time_to_first_xray_pulse = 216.0
param.time_to_reach_half_the_return_distance = 0.31481074410921434
param.total_distance_of_translation = 19.821160921319446
param.total_time_of_translation = 10.274798571061536
param.total_time_to_return = 0.6296214882184287
param.translate_x = 0.1100000000000001
param.translate_y = 0.144
param.translate_z = 19.799999999999997
param.velocity = 2.0572273243105643
<file_sep>#!/usr/bin/env python
"""High-speed diffractometer
Control panel to save and motor positions.
<NAME> 31 Oct 2013 - 26 Sep 2014"""
__version__ = "1.2.1"
from pdb import pm
from SavedPositionsPanel import SavedPositionsPanel
from id14 import SampleX,SampleY,SampleZ,SamplePhi,diffractometer as d
import wx
# Needed to initialize WX library
if not hasattr(wx,"app"): wx.app = wx.App(redirect=False)
panel = SavedPositionsPanel(
title="Fast Diffractometer Saved Positions",
name="goniometer_saved",
motors=[SampleX,SampleY,SampleZ,SamplePhi,
d.ClickCenterX,d.ClickCenterY,d.ClickCenterZ],
motor_names=["SampleX","SampleY","SampleZ","SamplePhi",
"Center X","Center Y","Center Z"],
formats = ["%+6.3f","%+6.3f","%+6.3f","%+8.3f","%+6.3f","%+6.3f","%+6.3f"],
nrows=13)
wx.app.MainLoop()
<file_sep>"""Author: <NAME>
Date created: Oct 21, 2015
Date modified: Jun 15, 2018
"""
__version__ = "2.5" # optimize_queue
from pdb import pm # for debugging
from Ensemble_SAXS_pp import Ensemble_SAXS
from timing_system import timing_system
from timing_sequencer import timing_sequencer
from time import sleep,time
from numpy import *
import logging
logging.basicConfig(level=logging.DEBUG,format="%(asctime)s %(levelname)s: %(message)s")
self = Ensemble_SAXS # for debugging
##import timing_system as t; t.DEBUG=True
ps,ns,us,ms = 1e-12,1e-9,1e-6,1e-3
timepoints = array([
-10*us,-10.1*us,
## -10*us,-2.5*ns,-10*us,0,-10*us,2.5*ns,-10*us,5.62*ns,
## -10*us,10*ns,-10*us,17.8*ns,-10*us,31.6*ns,-10*us,56.2*ns,-10*us,75*ns,
## -10*us,100*ns,-10*us,133*ns,-10*us,178*ns,-10*us,316*ns,-10*us,562*ns,
## -10*us,1*us,-10*us,1.78*us,-10*us,3.16*us,
## -10*us,1*us,-10*us,1.78*us,-10*us,3.16*us,-10*us,5.62*us,
## -10*us,10*us,-10*us,17.8*us,-10*us,31.6*us,-10*us,56.2*us,
## -10*us,100*us,-10*us,178*us,-10*us,316*us,-10*us,562*us,
-10*us,1*ms,-10*us,1.78*ms,-10*us,3.16*ms,-10*us,5.62*ms,
-10*us,10*ms,-10*us,17.8*ms,-10*us,31.6*ms,
])
repeats = 2
timepoints=timepoints*repeats
laser_mode = [1]
npasses = 2
delays = array([t for t in timepoints for l in laser_mode])
laser_ons = array([l for t in timepoints for l in laser_mode])
delays = tile(delays,repeats)
laser_ons = tile(laser_ons,repeats)
image_numbers = arange(1,len(delays)+1)
passes = array([npasses]*len(image_numbers))
##image_numbers = array([62,64,66,68,70])
##delays = delays[image_numbers-1]
##laser_ons = laser_ons[image_numbers-1]
##passes = passes[image_numbers-1]
def update():
Ensemble_SAXS.acquire(delays,laser_ons,
passes=passes,image_numbers=image_numbers)
def start(): Ensemble_SAXS.acquisition_start()
def cancel(): Ensemble_SAXS.acquisition_cancel()
def resume():
update()
timing_sequencer.queue_active = True
def forever():
"""Continouly feed the queue, keeping collecting forever"""
try:
while True:
start()
while len(Ensemble_SAXS.queue) > 10: sleep(1)
finally: cancel()
self = Ensemble_SAXS # for debugging
print("timing_system.ip_address = %r" % timing_system.ip_address)
print('')
print("update()")
print("start()")
print("cancel()")
print("resume()")
<file_sep>#!/bin/env python
"""Check whether the neccessary modules are installed to run the Python code
in the directory
Authors: <NAME>, <NAME>
Date created: 2011-02-11
Date last modified: 2019-02-02
"""
__version__ = "1.1.2" # added "watchdog"
module_names = [
"wx",
"numpy",
"scipy",
"matplotlib",
"PIL",
"pyaudio",
"serial",
"psutil",
"watchdog",
"h5py",
"msgpack",
"msgpack_numpy",
]
def check_module(module_name):
try:
exec("import %s as module" % module_name)
print("%s %s" % (module_name,version(module),))
except ImportError:
print("%s not installed (try: pip install %s)" % (module_name,package_name(module_name)))
except: print("%s installed, but broken" % module_name)
def package_name(module_name):
"""Which name needs to be passed to pip to install a Python module
Normally, the PIP package has the same same, but there are a few exceptions"""
package_name = module_name
if module_name == "wx": package_name = "wxPython"
if module_name == "PIL": package_name = "Image"
return package_name
def version(module):
if hasattr(module,"__version__"): return str(module.__version__)
if hasattr(module,"VERSION"): return str(module.VERSION)
if hasattr(module,"version"): return str(module.version)
try:
exec("import %s.version as module" % module.__name__)
return module.__version__
except: pass
return "?"
for module_name in module_names: check_module(module_name)
<file_sep>RBV.filename = '//mx340hs/data/anfinrud_1903/Archive/NIH.TEMP.RBV.txt'
I.filename = '//mx340hs/data/anfinrud_1903/Archive/NIH.TEMP.I.txt'<file_sep>from xppbeamline import xppevent
events = [
{"code": 95,"comment":"DAQ evt" , "t":range(0,12)},
{"code": 98,"comment":"FPGA start" , "t":[0]},
{"code": 97,"comment":"Rayonix event", "t":[1]},
]
Nt = 12
def setSequence():
i = 0
for t in range(0,Nt):
deltaBeam = 1
for event in events:
if t in event["t"]:
xppevent.setstep(i,event["code"],deltaBeam,comment=event["comment"])
deltaBeam = 0
i += 1
xppevent.setnsteps(i)
while i<20:
xppevent.setstep(i,0,0,comment=" ")
i += 1
xppevent.update()
xppevent.start()
def setSequenceLJ12(nPause=0):
xppevent.setstep(0, 95, 1, comment='DAQ evt')
xppevent.setstep(1, 98, 0, comment='FPGA start')
for i in range(1,12+nPause):
xppevent.setstep(i+1, 95, 1, comment='DAQ evt')
xppevent.setstep(13+nPause, 97, 0, comment='Rayonix event')
xppevent.setnsteps(14+nPause)
xppevent.update()
xppevent.start()
if __name__ == "__main__":
print "setSequenceLJ12()"
print "setSequence()"
<file_sep>from CA import caput,caget,cainfo
class PV (object):
"""EPICS Process Variable"""
def __init__(self,name):
"""name: PREFIX:Record.Field"""
self.name = name
def get_value(self): return caget(self.name)
def set_value(self,value): caput(self.name,value)
value = property(get_value,set_value)
def get_info(self): return cainfo(self.name,printit=False)
info = property(get_info)
def __getattr__(self,name):
##print "__getattr__(%r)" % name
pv = PV(self.name+"."+name)
object.__setattr__(self,name,pv)
return pv
##def __setattr__(self,name,value):
## print "__setattr__(%r,%r)" % (name,value)
## object.__setattr__(self,name,value)
def __repr__(self): return "PV(%r)" % self.name
LDT5948 = temperature_controller = PV("14IDB:LDT5948")
<file_sep>"""Caching of Channel Access
Author: <NAME>
Date created: 2018-10-24
Date last modified: 2018-11-01
"""
__version__ = "1.0"
from logging import debug,info,warn,error
PV_history = {}
max_count = 1000
def CA_history(PV_name):
"""Value of Channel Access (CA) Process Variable (PV)"""
from CA import camonitor
camonitor(PV_name,callback=update)
history = PV_history.get(PV_name,([],[]))
return history
def update(PV_name,value,formatted_value,timestamp):
"""Handle Process Variable (PV) update"""
t,v = PV_history.get(PV_name,([],[]))
t = (t+[timestamp])[-max_count:]
v = (v+[value])[-max_count:]
PV_history[PV_name] = t,v
def filter(history,tmin,tmax):
t,v = history
t_filtered = [ti for ti in t if tmin <= ti <= tmax]
v_filtered = [vi for ti,vi in zip(t,v) if tmin <= ti <= tmax]
history = t_filtered,v_filtered
return history
if __name__ == "__main__":
from pdb import pm # for debugging
import logging # for debugging
from time import time # for timing
logging.basicConfig(
level=logging.DEBUG,
format="%(asctime)s %(levelname)s %(module)s.%(funcName)s: %(message)s",
)
##PV_name = "NIH:TIMING.registers.ch1_trig_count.count"
PV_name = "TESTBENCH:TIMING.registers.ch1_trig_count.count"
PV_names = [
"TESTBENCH:TIMING.registers.ch1_trig_count.count",
"TESTBENCH:TIMING.registers.ch1_acq_count.count",
"TESTBENCH:TIMING.registers.ch1_acq.count",
]
from CA import caget,cainfo,camonitor
from time import sleep
def delays(PV_name,dt=0.01,T=1.0):
from numpy import rint
delays = []
for i in range(0,int(rint(T/dt))):
delays.append(cainfo(PV_name,"timestamp")-time())
sleep(dt)
return delays
print('caget(PV_name)')
print('cainfo(PV_name,["timestamp","value"])')
print('cainfo(PV_name,"timestamp")-time()')
print('CA_history(PV_name)')
print('filter(CA_history(PV_name),time()-10,time())')
print('max(delays(PV_name,0.005,2.5))')
print('for n in PV_names: camonitor(n)')
<file_sep>"""
This is to commuminate with a LeCroy Windows-based oscilloscope over Ethernet.
This module requires the program 'lecroy_scope_server.py' to run locally
on the oscillope. It uses a simple TCP/IP connection, port number 2000, to
communincate with the 'lecroy_scope_server.py' program, which in turn calls
the LeCroyXStreamDSO application running on the oscilloscope via DCOM remote
procedure calls.
The command set is documented in LeCroy's "WaveMaster, WavePro Series Automation
Manual", file "Automation Manual.pdf" in "femto.niddk.nih.gov/APS/Laser Hutch/
Laser Oscilloscope".
A command that modifies a setting of the oscilloscope is, for instance,
"LeCroy.XStreamDSO.Measure.P1.GateStart.Value = 0.95". This sets the low limit of the gate
of measurement P1 to 0.95 divisions. This command generates not reply.
A query that generates a reply would be "LeCroy.XStreamDSO.Measure.P1.GateStart.Value".
This reads back the low limit of the gate of measurement P1.
Each command needs to be terminated by newline charater when sent to the
server. A carriage return character at the end is allowed, but not required.
A quick way to find a command is to launch the "XStream Browser" application
on the oscilloscope PC and browser the command set with the Explorer-like
interface.
Properties listed with type 'Double','Bool','String','Enum' are read by appending
'.Value' to their name and set by appending ' = val' or '.Value = val' to
their name. If 'val' is a string it must be enclosed in double quotes or single
quotes.
Properties list as 'Action' are called by appending ".ActNow()" to their
name, e.g. "LeCroy.XStreamDSO.ClearSweeps.ActNow()".
Properties listed as 'Method' are called by appending "()" with optional
arguments to their name, e.g. "Sleep(1000)".
Commands are not case-sensitive.
Author: <NAME>
Date created: 2008-04-16
Date last modified: 2019-05-28
"""
__version__ = "4.5" # scope trace timestamps
from logging import debug,info,warn,error
from numpy import nan
def value_property(query_string,default_value=nan):
"""A propery object to be used inside a class"""
def get(self):
## Performs a query and returns the result as a number
value = self.query(query_string)
dtype = type(default_value)
if dtype != str:
try: value = dtype(eval(value))
except: value = default_value
return value
def set(self,value): self.send("%s = %r" % (query_string,value))
return property(get,set)
def function(property_name,formula,reverse_formula):
"""A propery object to be used inside a class
formula: e.g. 'x*10'
reverse_formula: e.g. 'x/10.'
"""
def get(self):
x = getattr(self,property_name)
return eval(formula)
def set(self,x): setattr(self,property_name,eval(reverse_formula))
return property(get,set)
def PV_property(name,default_value=nan):
"""EPICS Channel Access Process Variable as class property"""
def get(self):
from CA import caget
value = caget(self.prefix+name.upper())
if value is None: value = default_value
if type(value) != type(default_value):
if type(default_value) == list: value = [value]
else:
try: value = type(default_value)(value)
except: value = default_value
return value
def set(self,value):
from CA import caput
value = caput(self.prefix+name.upper(),value)
return property(get,set)
def PV_method(name):
"""EPICS Channel Access Process Variable as class method"""
def call(self):
from CA import caput
value = caput(self.prefix+name,1)
return call
def PV_object_property(name,default_value=nan):
@property
def PV_object(self):
from CA import PV
return PV(self.prefix+name)
return PV_object
class lecroy_scope(object):
"""This is to communicate with a LeCroy Windows PC-based oscilloscope over
Ethernet."""
from numpy import nan
name = "lecroy_scope"
def __init__(self,default_ip_address_and_port=None,name="lecroy_scope"):
"""name: determines EPICS prefix.
e.g. xray_scope -> NIH:XRAY_SCOPE."""
self.name = name
@property
def prefix(self): return "NIH:"+self.name.upper()+"."
def get_ip_address(self):
from CA import cainfo
return cainfo(self.prefix+"SETUP","IP_address")
def set_ip_address(self,value): pass
ip_address = property(get_ip_address,set_ip_address)
def get_ip_address_and_port(self):
return self.ip_address+":"+self.port
def set_ip_address_and_port(self,ip_address_and_port):
self.port = ip_address_and_port.split(":")[-1]
ip_address_and_port = property(get_ip_address_and_port,set_ip_address_and_port)
from persistent_property import persistent_property
port = persistent_property("port","2000")
@property
def online(self):
online = self.ip_address != ""
return online
def __repr__(self):
return "lecroy_scope(name=%r)" % (self.name,)
def query(self,command):
"""To send a command that generates a reply, e.g. "InstrumentID.Value".
Returns the reply"""
from tcp_client import query
reply = query(self.ip_address_and_port,command).strip("\n")
debug("%s, reply %s" % (torepr(command),torepr(reply)))
return reply
def write(self,command):
"""Sends a command to the oscilloscope that does not generate a reply,
e.g. "LeCroy.XStreamDSO.ClearSweeps.ActNow()" """
debug("%s" % torepr(command))
from tcp_client import send
send(self.ip_address_and_port,command)
send = write
command = write
class gate_object(object):
"""This is to dynaically adjust the "Gate", defining the time range for
and automated measurement. E.g. when you want to measre the rising edge
of a periodic waveform which shift with repect to the trigger."""
def __init__(self,scope,n=1):
"""n=1,2...6 is the waveform parameter number.
The parameter is defined from the "Measure" menu, e.g. P1:delay(C3)."""
self.scope = scope; self.n = n
def __repr__(self):
return repr(self.scope)+".gate("+str(self.n)+")"
class start_object(object):
"""Changes the start of the "Gate" for an automated measurement"""
def __init__(self,gate):
"""n=1,2...6 is the waveform parameter number.
The parameter is defined from the "Measure" menu, e.g. P1:delay(C3)."""
self.scope = gate.scope; self.n = gate.n; self.last_t = None
self.name = "P"+str(self.n)+".start"
self.unit = "s"
def __repr__(self):
return repr(self.scope)+".gate("+str(self.n)+").start"
def get_value(self):
"""returns the last set value"""
if self.last_t != None: return self.last_t # speed up, use cached value
div = self.val("LeCroy.XStreamDSO.Measure.P%s.GateStart" % self.n)
# get the time base in seconds per division
tdiv = self.val("LeCroy.XStreamDSO.Acquisition.Horizontal.HorScale")
t0 = self.val("LeCroy.XStreamDSO.Acquisition.Horizontal.HorOffset")
# convert from divisions (0-10, 5 = center) to time in s
t = (div-5)*tdiv-t0
self.last_t = t
return t
def set_value(self,t):
# get the time base in seconds per division
tdiv = self.val("LeCroy.XStreamDSO.Acquisition.Horizontal.HorScale")
t0 = self.val("LeCroy.XStreamDSO.Acquisition.Horizontal.HorOffset")
# convert from time in seconds to divisions (0-10, 5 = center)
div = (t+t0)/tdiv + 5
if div < 0: div = 0
if div > 10: div = 10
self.scope.write("LeCroy.XStreamDSO.Measure.P"+str(self.n)+".GateStart = "+str(div))
# cache the last value
self.last_t = (div-5)*tdiv-t0
value = property(get_value,set_value,doc="low limit in s")
def val(self,query):
"""Performs a query and returns the result as a number"""
try: return float(self.scope.query(query))
except (ValueError,TypeError): return nan
def get_start(self,n=1): return lecroy_scope.gate_object.start_object(self)
start = property(get_start,doc="low limit of measurement gate")
class stop_object(object):
"""Changes the start of the "Gate" for an automated measurement"""
def __init__(self,gate):
"""n=1,2...6 is the waveform parameter number.
The parameter is defined from the "Measure" menu, e.g. P1:delay(C3)."""
self.scope = gate.scope; self.n = gate.n; self.last_t = None
self.name = "P"+str(self.n)+".stop"
self.unit = "s"
def __repr__(self):
return repr(self.scope)+".gate("+str(self.n)+").start"
def get_value(self):
"returns the last set value"
if self.last_t != None: return self.last_t # speed up, use cached value
div = self.val("LeCroy.XStreamDSO.Measure.P%s.GateStop" % self.n)
# get the time base in seconds per division
tdiv = self.val("LeCroy.XStreamDSO.Acquisition.Horizontal.HorScale")
t0 = self.val("LeCroy.XStreamDSO.Acquisition.Horizontal.HorOffset")
# convert from divisions (0-10, 5 = center) to time in s
t = (div-5)*tdiv-t0
self.last_t = t
return t
def set_value(self,t):
# get the time base in seconds per division
tdiv = self.val("LeCroy.XStreamDSO.Acquisition.Horizontal.HorScale")
t0 = self.val("LeCroy.XStreamDSO.Acquisition.Horizontal.HorOffset")
# convert from time in seconds to divisions (0-10, 5 = center)
div = (t+t0)/tdiv + 5
if div < 0: div = 0
if div > 10: div = 10
self.scope.write("LeCroy.XStreamDSO.Measure.P"+str(self.n)+".GateStop = "+str(div))
# cache the last value
self.last_t = (div-5)*tdiv-t0
value = property(get_value,set_value,doc="low limit in s")
def val(self,query):
"""Performs a query and returns the result as a number"""
try: return float(self.scope.query(query))
except (ValueError,TypeError): return nan
def get_stop(self,n=1): return lecroy_scope.gate_object.stop_object(self)
stop = property(get_stop,doc="low limit of measurement gate")
def gate(self,n=1): return lecroy_scope.gate_object(self,n)
class measurement_object(object):
"""For automated measurements, including averageing and statistics"""
def __init__(self,scope,n=1,type="value"):
"""n=1,2...6 is the waveform parameter number.
The parameter is defined from the "Measure" menu, e.g. P1:delay(C3).
The optional 'type' can by "value","min","max","stdev",or "count".
"""
self.scope = scope; self.n = n; self.type = type
def __repr__(self):
return repr(self.scope)+".measurement("+str(self.n)+")."+self.type
def get_value(self):
n = self.n
if self.type == "value": return self.val("LeCroy.XStreamDSO.Measure.P%d.last.Result.Value" % n)
if self.type == "average": return self.val("LeCroy.XStreamDSO.Measure.P%d.mean.Result.Value" % n)
if self.type == "min": return self.val("LeCroy.XStreamDSO.Measure.P%d.min.Result.Value" % n)
if self.type == "max": return self.val("LeCroy.XStreamDSO.Measure.P%d.max.Result.Value" % n)
if self.type == "stdev": return self.val("LeCroy.XStreamDSO.Measure.P%d.sdev.Result.Value" % n)
if self.type == "count": return self.val("LeCroy.XStreamDSO.Measure.P%d.num.Result.Value" % n)
return nan
value = property(get_value,doc="last sample (without averaging)")
def get_average(self):
n = self.n
if self.type == "value": return self.val("LeCroy.XStreamDSO.Measure.P%d.mean.Result.Value" % n)
if self.type == "average": return self.val("LeCroy.XStreamDSO.Measure.P%d.mean.Result.Value" % n)
if self.type == "min": return self.val("LeCroy.XStreamDSO.Measure.P%d.min.Result.Value" % n)
if self.type == "max": return self.val("LeCroy.XStreamDSO.Measure.P%d.max.Result.Value" % n)
if self.type == "stdev": return self.val("LeCroy.XStreamDSO.Measure.P%d.sdev.Result.Value" % n)
if self.type == "count": return self.val("LeCroy.XStreamDSO.Measure.P%d.num.Result.Value" % n)
return nan
average = property(get_average,doc="accumulated average")
def get_max(self): return self.val("LeCroy.XStreamDSO.Measure.P%d.max.Result.Value" % self.n)
max = property(get_max,doc="maximum value contributing to average")
def get_min(self): return self.val("LeCroy.XStreamDSO.Measure.P%d.min.Result.Value" % self.n)
min = property(get_min,doc="minimum value contributing to average")
def get_stdev(self): return self.val("LeCroy.XStreamDSO.Measure.P%d.sdev.Result.Value" % self.n)
stdev = property(get_stdev,doc="standard deviation of individuals sample")
def get_count(self): return self.val("LeCroy.XStreamDSO.Measure.P%d.num.Result.Value" % self.n)
count = property(get_count,doc="number of measurement averaged")
def get_name(self):
return self.scope.query("LeCroy.XStreamDSO.Measure.P%d.Equation.Value" % self.n)+"."+self.type
name = property(get_name,doc="string representation of the measurement")
def get_unit(self):
return self.scope.query("LeCroy.XStreamDSO.Measure.P%d.num.Result.VerticalUnits.Value")
unit = property(get_unit,doc="unit symbol of measurement (if available)")
def val(self,query):
"""Performs a query and returns the result as a number"""
try: return float(self.scope.query(query))
except (ValueError,TypeError): return nan
def start(self): self.scope.start()
def stop(self): self.scope.stop()
def clear_sweeps(self): self.scope.clear_sweeps()
reset_average = clear_sweeps
reset_statistics = clear_sweeps
def get_gate(self): return self.scope.gate(self.n)
gate = property(get_gate,doc="start of measurment gate")
def get_enabled(self): return self.scope.measurement_enabled
def set_enabled(self,value): self.scope.measurement_enabled = value
enabled = property(get_enabled,set_enabled)
def measurement(self,n=1,type="value"): return lecroy_scope.measurement_object(self,n,type)
P1 = PV_object_property("P1")
P2 = PV_object_property("P2")
P3 = PV_object_property("P3")
P4 = PV_object_property("P4")
P5 = PV_object_property("P5")
P6 = PV_object_property("P6")
P7 = PV_object_property("P7")
P8 = PV_object_property("P8")
def get_measurement_enabled(self):
"""Is the measurement active and usable?"""
try: return eval(self.query("LeCroy.XStreamDSO.Measure.ShowMeasure.Value"))
except: return False
def set_measurement_enabled(self,value):
self.write("LeCroy.XStreamDSO.Measure.ShowMeasure.Value = "+str(value))
measurement_enabled = property(get_measurement_enabled,set_measurement_enabled)
def waveform(self,channel):
"""Recorded voltage values in units of volts.
Channel: 1,2,3, or 4
Return value: tuple"""
result = self.query("LeCroy.XStreamDSO.Acquisition.C%s.Out.Result.DataArray" % channel)
if result == "": return ()
return eval(result)
def save_waveform(self,channel,filename):
"""Generate LeCroy binary waveform file.
channel: 1,2,3, or 4
filename: pathname e.g. '/net/id14bxf/data/anfinrud_1203/test.trc'
Needs to accessible to the oscilloscope computer as
'\\id14bxf\data\anfinrud_1203\test.trc'"""
if filename == "" or filename is None: return
from os.path import exists,dirname; from os import makedirs
directory = dirname(filename)
if directory and not exists(directory): makedirs(directory)
filename = Windows_pathname(filename)
directory = filename[0:filename.rfind("\\")]
self.send("LeCroy.XStreamDSO.SaveRecall.Waveform.SaveTo = 'File'")
self.send("LeCroy.XStreamDSO.SaveRecall.Waveform.SaveSource = 'C%s'" % channel)
self.send("LeCroy.XStreamDSO.SaveRecall.Waveform.WaveFormat = 'Binary'")
# BinarySubFormat is not documented in the "Automation Manual"
# (July 2003) and "Automation Command Reference Manual" Reference
# (2010), but shown as option in the XStream Browser,
# under "LeCroy.XStreamDSO.SaveRecall.Waveform". Choices are "Byte", "Word", or "Auto".
self.send("LeCroy.XStreamDSO.SaveRecall.Waveform.BinarySubFormat = 'Byte'")
self.send("LeCroy.XStreamDSO.SaveRecall.Waveform.WaveformDir = %r" % directory)
# Needed to force update of sequence number?
self.send("LeCroy.XStreamDSO.SaveRecall.Waveform.TraceTitle = '__'")
self.send("LeCroy.XStreamDSO.SaveRecall.Waveform.TraceTitle = '_'")
save_filename = directory+"\\C%s_00000.trc" % channel
self.send("remove(%r)" % (save_filename))
self.send("LeCroy.XStreamDSO.SaveRecall.Waveform.DoSave.ActNow()")
self.send("rename(%r,%r)" % (save_filename,filename))
def acquire_waveforms_to_directory(self,channel,directory="D:\\Waveforms"):
"""automatically acquire a series of waveform files
using auto-save mode
channel: 1,2,3, or 4
directory: Pathname on the oscilloscope computer (remote, Windows)
The waveform filenames will be:
C1Waveform00000.trc, C1Waveform00001.trc, ..."""
from os.path import exists; from os import makedirs
from time import sleep
if not self.exists(directory): self.mkdir(directory)
if not self.exists(directory):
warn("lecroy_scope: Failed to create %r" % directory)
self.send("LeCroy.XStreamDSO.SaveRecall.Waveform.SaveTo = 'File'")
self.send("LeCroy.XStreamDSO.SaveRecall.Waveform.SaveSource = 'C%s'" % channel)
self.send("LeCroy.XStreamDSO.SaveRecall.Waveform.WaveFormat = 'Binary'")
# BinarySubFormat is not documented in the "Automation Manual"
# (July 2003) and "Automation Command Reference Manual" Reference
# (2010), but shown as option in the XStream Browser,
# under "LeCroy.XStreamDSO.SaveRecall.Waveform". Choices are "Byte", "Word", or "Auto".
self.send("LeCroy.XStreamDSO.SaveRecall.Waveform.BinarySubFormat = 'Byte'")
directory = Windows_pathname(directory)
self.send("LeCroy.XStreamDSO.SaveRecall.Waveform.WaveformDir = %r" % directory)
self.send("LeCroy.XStreamDSO.SaveRecall.Waveform.TraceTitle = 'Waveform'")
self.waveform_autosave = "Off" # forces the sequence number to be reset
self.waveform_autosave = "Wrap"
Windows_filenames = []
temp_filenames = []
acquiring_waveforms = PV_property("acquiring_waveforms",0)
auto_acquire = PV_property("auto_acquire",nan)
trigger_counts_history = value_property("scope.trigger_counts_history",[[],[]])
trace_counts_history = value_property("scope.trace_counts_history",[[],[]])
timing_differences = value_property("scope.timing_differences",[])
timing_offset = PV_property("timing_offset",nan)
timing_jitter = PV_property("timing_jitter",nan)
timing_reset = PV_property("timing_reset",0)
def get_waveform_acquisition_channel(self):
"""Which channel to save? 1,2,3, or 4"""
value = self.query("LeCroy.XStreamDSO.SaveRecall.Waveform.SaveSource")
value = value.replace("C","")
try: value = int(value)
except: value = nan
return value
def set_waveform_acquisition_channel(self,value):
"""Which channel to save? 1,2,3, or 4"""
self.send("LeCroy.XStreamDSO.SaveRecall.Waveform.SaveSource = 'C%s'" % value)
waveform_acquisition_channel = property(get_waveform_acquisition_channel,
set_waveform_acquisition_channel)
trace_acquisition_channel = waveform_acquisition_channel
def get_waveform_autosave(self):
"""Save a waveform file at each trigger event?
Return values: 'Off','Wrap','Fill'
'Wrap': old files overwritten
'Fill': no files overwritten"""
value = self.query("LeCroy.XStreamDSO.SaveRecall.Waveform.AutoSave")
return value
def set_waveform_autosave(self,value):
if value == True: value = "Wrap"
if value == False: value = "Off"
self.send("LeCroy.XStreamDSO.SaveRecall.Waveform.AutoSave = %r" % value)
waveform_autosave = property(get_waveform_autosave,set_waveform_autosave)
def exists(self,pathname):
"""Does the file exist on the file system of the oscilloscope computer?"""
reply = self.query("exists(%r)" % pathname)
try: return eval(reply)
except: return False
def remove(self,pathname):
"""Remove a file on the file system of the oscilloscope
computer (remotely)."""
self.send("remove(%r)" % pathname)
def rename(self,old_pathname,new_pathname):
"""Rename a file on the file system of the oscilloscope
computer (remotely)."""
self.send("rename(%r,%r)" % (old_pathname,new_pathname))
def migrate_files(self,source_filenames,destination_filenames):
"""Copy each file in the list 'source_files' to the corresponding file
in 'destination_files', on the file system of the oscilloscope
computer (remotely)."""
self.send("migrate_files(%r,%r)" % (source_filenames,destination_filenames))
@property
def migration_in_progress(self):
"""Are there files remaining to be copied?"""
reply = self.query("migration_in_progress")
try: return eval(reply)
except: return False
@property
def copied(self):
"""Which files are already copied? List of booleans"""
reply = self.query("copied")
try: return eval(reply)
except: return []
@property
def ncopied(self):
"""How many files are remaining to be copied?"""
reply = self.query("sum(copied)")
try: return eval(reply)
except: return 0
def mkdir(self,pathname):
"""Create a directory on the file system of the oscilloscope
computer (remotely)."""
self.send("mkdir(%r)" % pathname)
def rmdir(self,pathname):
"""Remove a directory with all its contents
on the file system of the oscilloscope computer (remotely)."""
self.send("rmdir(%r)" % pathname)
def math_waveform(self,channel):
"""Recorded voltage values in units of volts.
Channel: 1,2,3, or 4
Return value: tuple"""
result = self.query("LeCroy.XStreamDSO.SaveRecall.F%s.Out.Result.DataArray" % channel)
if result == "": return ()
return eval(result)
class channel_object(object):
"""For properties of a specific channel"""
def __init__(self,scope,n):
"""n = 1,2,3, or 4 is the channel number."""
self.scope = scope; self.n = n
def __repr__(self):
return repr(self.scope)+".channel("+str(self.n)+")"
def get_vertical_scale(self):
return float(self.scope.query("LeCroy.XStreamDSO.Acquisition.C%d.VerScale" % self.n))
def set_vertical_scale(self,value):
self.scope.send("LeCroy.XStreamDSO.Acquisition.C%d.VerScale = %s" % (self.n,value))
vertical_scale = property(get_vertical_scale,set_vertical_scale,
doc="Volts/div")
def get_coupling(self):
"""'DC50','DC1M', 'AC1M' or 'Gnd'"""
return self.scope.query("LeCroy.XStreamDSO.Acquisition.C%d.Coupling" % self.n)
def set_coupling(self,value):
self.scope.send("LeCroy.XStreamDSO.Acquisition.C%d.Coupling = %r" % (self.n,value))
coupling = property(get_coupling,set_coupling)
def get_waveform(self):
"""Recorded voltage values, as tuple"""
result = self.scope.query("LeCroy.XStreamDSO.Acquisition.C%s.Out.Result.DataArray" % self.n)
if result == "": return ()
return eval(result)
waveform = property(get_waveform)
def save_waveform(self,filename):
"""Dump oscilloscope trace as LeCroy binary waveform file (recommedned
extension: .trc)"""
self.scope.save_waveform(self.n,filename)
def acquire_waveforms(self,filenames):
"""Automatically acquire a series of waveform files
using auto-save mode.
filenames: list of strings that are absolute pathnames
e.g. '/net/id14bxf/data/anfinrud_1203/test.trc'"""
self.scope.acquire_waveforms(self.n,filenames)
def start_acquiring_waveforms(self):
"""Undo "acquire_waveforms" """
self.scope.start_acquiring_waveforms(self.n)
def stop_acquiring_waveforms(self):
"""Undo "acquire_waveforms" """
self.scope.stop_acquiring_waveforms()
def acquire_waveforms_to_directory(self,directory):
"""Automatically acquire a series of waveform files
using auto-save mode.
directory: absolute pathname
e.g. '/net/id14bxf/data/anfinrud_1203/'"""
self.scope.acquire_waveforms_to_directory(self.n,directory)
def get_trigger_mode(self):
return self.scope.trigger_mode
def set_trigger_mode(self,value):
self.scope.trigger_mode = value
trigger_mode = property(get_trigger_mode,set_trigger_mode)
def get_enhance_resolution(self):
"""Noise Filter: 'None','0.5bits','1bits',...,'3bits'"""
return self.val("LeCroy.XStreamDSO.Acquisition.C%s.EnhanceResType" % self.n,"")
def set_enhance_resolution(self,value):
self.set_val("LeCroy.XStreamDSO.Acquisition.C%s.EnhanceResType" % self.n,value)
enhance_resolution = property(get_enhance_resolution,set_enhance_resolution)
noise_filter = enhance_resolution
def __getattr__(self,name):
"""For properties of coresponding 'lecroy_scope' object"""
return getattr(self.scope,name)
def __setattr__(self,name,value):
"""For properties of corresponding 'lecroy_scope' object"""
if hasattr(self,"scope") and hasattr(self.scope,name):
setattr(self.scope,name,value)
else: object.__setattr__(self,name,value)
def channel(self,n): return self.channel_object(self,n)
@property
def C1(self): return self.channel(1)
@property
def C2(self): return self.channel(2)
@property
def C3(self): return self.channel(3)
@property
def C4(self): return self.channel(4)
ch1 = C1; ch2 = C2; ch3 = C3; ch4 = C4
def start(self):
"""Clear the accumulated average and restart averaging.
Also re-eneables the trigger in case the scope was stopped."""
self.sampling_mode = "RealTime"
self.trigger_mode = "Normal"
self.clear_sweeps()
def stop(self):
"Freezes the averaging by disabling the trigger of the oscilloscope."
self.send("LeCroy.XStreamDSO.Acquisition.TriggerMode = 'Stopped'")
def acquire_sequence(self,ntrigger=1):
"""Record a waveform with a given number of trigger events, using
"sequence" mode. Does not wait for the acquisition to finish.
use 'is_acquiring' to check when the acquisition has finished."""
if ntrigger > 1:
self.sampling_mode = "Sequence"
self.nsegments = ntrigger
else: self.sampling_mode = "RealTime"
self.trigger_mode = "Stop" # Needed?
self.clear_sweeps()
self.trigger_mode = "Normal" # Needed?
def get_is_acquiring(self):
"""Has 'acquire_sequence' finished?"""
return (self.trigger_mode == "Single")
is_acquiring = property(get_is_acquiring)
def trigger_single(self):
"""Trigger the oscilloscope in single shot mode.
Also re-eneables the trigger in case the scope was stopped."""
self.clear_sweeps()
self.trigger_mode = "Single"
def get_trigger_mode(self):
"""'Stopped','Auto','Normal', or 'Single'"""
return self.query("LeCroy.XStreamDSO.Acquisition.TriggerMode")
def set_trigger_mode(self,mode):
self.send("LeCroy.XStreamDSO.Acquisition.TriggerMode = %r" % mode)
trigger_mode = property(get_trigger_mode,set_trigger_mode)
def clear_sweeps(self):
"""Reset average count"""
self.send("LeCroy.XStreamDSO.ClearSweeps.ActNow()")
reset_average = clear_sweeps
reset_statistics = clear_sweeps
def get_sampling_mode(self):
"""'WStream', 'RealTime' or 'Sequence'"""
return self.query("LeCroy.XStreamDSO.Acquisition.Horizontal.SampleMode")
def set_sampling_mode(self,mode):
self.send("LeCroy.XStreamDSO.Acquisition.Horizontal.SampleMode = %r" % mode)
sampling_mode = property(get_sampling_mode,set_sampling_mode)
def get_number_of_segments(self):
"""Number of trigger events to capture. Only valid when using
'Sequence' sampling mode. Minimum 2"""
try: return int(self.query("LeCroy.XStreamDSO.Acquisition.Horizontal.NumSegments"))
except (ValueError,TypeError): return 0
def set_number_of_segments(self,nsegments):
self.send("LeCroy.XStreamDSO.Acquisition.Horizontal.NumSegments = %d" % nsegments)
number_of_segments = property(get_number_of_segments,set_number_of_segments)
nsegments = number_of_segments
sequence_timeout = value_property("LeCroy.XStreamDSO.Acquisition.Horizontal.SequenceTimeout")
sequence_timeout_enabled = value_property("LeCroy.XStreamDSO.Acquisition.Horizontal.SequenceTimeoutEnable",False)
sampling_rate = value_property("LeCroy.XStreamDSO.Acquisition.Horizontal.SampleRate")
time_scale = value_property("LeCroy.XStreamDSO.Acquisition.Horizontal.HorScale")
time_range = function("time_scale","x*10","x/10.")
trigger_delay = value_property("LeCroy.XStreamDSO.Acquisition.Horizontal.HorOffset")
time_offset = trigger_delay # alias
def val(self,query_string,default_value=nan):
"""Performs a query and returns the result as a number"""
value = self.query(query_string)
dtype = type(default_value)
if dtype != str:
try: value = dtype(eval(value))
except: value = default_value
return value
def set_val(self,query_string,value):
"""Change a setting"""
self.send("%s = %r" % (query_string,value))
@property
def software_version(self): return self.id.split(",")[-1]
@property
def id(self): return self.query("LeCroy.XStreamDSO.InstrumentID.Value")
filenames = value_property("scope.filenames",[])
times = value_property("scope.times",[])
trace_filenames = value_property("scope.trace_filenames",{})
def trace_filename(self,i):
reply = self.query("scope.trace_filename(%r)" % i)
return reply
trace_acquisition_running = PV_property("trace_acquisition_running",nan)
trace_count_offset = value_property("scope.trace_count_offset",nan)
trace_count_synchronized = PV_property("trace_count_synchronized",nan)
auto_synchronize = PV_property("auto_synchronize",nan)
def trace_count_synchronize(self):
self.command("scope.trace_count_synchronize()")
trace_count = PV_property("trace_count",0)
timing_system_trigger_count = PV_property("timing_system_trigger_count",0)
trace_count_offset = PV_property("trace_count_offset",0)
emptying_trace_directory = PV_property("emptying_trace_directory",0)
trace_directory_size = PV_property("trace_directory_size",0)
timing_system_trigger_enabled = value_property("scope.timing_system_trigger_enabled",False)
enabled_channels = value_property("scope.enabled_channels",[])
trace_source = value_property("scope.trace_source","")
trace_sources = PV_property("trace_sources",[])
server_version = value_property("version()","")
def save_setup(self,name):
"""Store setup to setup file in Lauecollect directory"""
self.setup_name = name
self.setup_save = True
def recall_setup(self,name):
"""Load setup from setup file in Lauecollect directory"""
self.setup_name = name
self.setup_recall = True
setup_dirname = value_property("LeCroy.XStreamDSO.SaveRecall.Setup.PanelDir","")
setup_basename = value_property("LeCroy.XStreamDSO.SaveRecall.Setup.PanelFilename","")
def get_setup_filename(self):
filename = self.setup_dirname+"\\"+self.setup_basename
from normpath import normpath
filename = normpath(filename)
return filename
def set_setup_filename(self,filename):
from os.path import dirname,basename
dir,file = dirname(filename),basename(filename)
dir = Windows_pathname(dir)
self.setup_dirname = dir
self.setup_basename = file
setup_filename = property(get_setup_filename,set_setup_filename)
@property
def local_setup_dirname(self):
from module_dir import module_dir
return module_dir(self)+"/lecroy_scope/"+self.name
def local_setup_filename(self,name):
return self.local_setup_dirname+"/"+name+".lss"
setup = PV_property("SETUP","")
setups = PV_property("SETUPS",[])
setup_choices = setups
setup_name = PV_property("SETUP_NAME","")
setup_filename = PV_property("SETUP_FILENAME","")
setup_save = PV_property("SETUP_SAVE")
setup_recall = PV_property("SETUP_RECALL")
monitoring_trace_count = value_property("scope.monitoring_trace_count",False)
monitoring_trace_count_allowed = value_property("scope.monitoring_trace_count_allowed",False)
monitoring_trace_count_2 = value_property("scope.monitoring_trace_count_2",False)
monitoring_trig_count = value_property("scope.monitoring_trig_count",False)
monitoring_timing = value_property("scope.monitoring_timing",False)
def Windows_pathname_(pathname):
"""Translate between UNIX-style to Windows-style pathnames, following
Universal Naming Convention.
E.g. "/net/id14bxf/data" to "\\id14bxf\data"""
from os.path import dirname,basename
dir,file = dirname(pathname),basename(pathname)
if dir not in Windows_pathname_cache:
Windows_pathname_cache[dir] = Windows_pathname(dir)
Windows_dir = Windows_pathname_cache[dir]
Win_pathname = Windows_dir+"\\"+file
return Win_pathname
Windows_pathname_cache = {}
def Windows_pathname(pathname):
"""Translate between UNIX-style to Windows-style pathnames, following
Universal Naming Convention.
E.g. "/net/id14bxf/data" to "\\id14bxf\data"""
if pathname == "": return pathname
if not pathname[1:2] == ":":
# Resolve symbolic links. E.g. "/data" to "/net/id14bxf/data"
from os.path import realpath
pathname = realpath(pathname)
# Mac OS X: mount point "/Volumes/share" does not reveal server name.
if pathname.startswith("/Mirror/"):
pathname = pathname.replace("/Mirror/","//")
if pathname.startswith("/Volumes/data"):
pathname = pathname.replace("/Volumes/data","/net/id14bxf/data")
if pathname.startswith("/Volumes/C"):
pathname = pathname.replace("/Volumes/C","/net/femto/C")
# Convert separators from UNIX style to Windows style.
# E.g. "//id14bxf/data/anfinrud_1106" to "\\id14bxf\data\anfinrud_1106"
pathname = pathname.replace("/","\\")
# Try to expand a Windows drive letter to a UNC name.
# E.g. "J:/anfinrud_1106" to "//id14bxf/data/anfinrud_1106"
try:
import win32wnet
pathname = win32wnet.WNetGetUniversalName(pathname)
except: pass
# Convert from UNIX to Windows style.
# E.g. "/net/id14bxf/data/anfinrud_1106" to "//id14bxf/data/anfinrud_1106"
if pathname.startswith("\\net\\"):
parts = pathname.split("\\")
if len(parts) >= 4:
server = parts[2] ; share = parts[3]
pathname = "\\\\"+pathname[5:]
return pathname
def torepr(x,nchars=80):
"""limit string length using ellipses (...)"""
s = repr(x)
if len(s) > nchars: s = s[0:nchars-10-3]+"..."+s[-10:]
return s
if __name__ == "__main__": # for testing
from pdb import pm # for debugging
from time import time # for preformance testing
import CA; from CA import caget,caput,camonitor,cainfo # for debugging
import logging # for debugging
logging.basicConfig(
level=logging.DEBUG,
format="%(asctime)s %(levelname)s %(module)s.%(funcName)s: %(message)s",
)
names = ["SAXS-WAXS","Laue","FPGA diagnostics"]
xray_scope = lecroy_scope(name="xray_scope")
print('')
##print('xray_scope.ip_address_and_port = %r' % xray_scope.ip_address_and_port)
##print('')
##print('xray_scope.setups = %r' % xray_scope.setups)
##print('xray_scope.setup_name = %r' % xray_scope.setup_name)
print('xray_scope.setup_save = True')
for name in names: print('xray_scope.setup = %r' % name)
laser_scope = lecroy_scope(name="laser_scope")
print('')
##print('laser_scope.ip_address_and_port = %r' % laser_scope.ip_address_and_port)
##print('')
##print('laser_scope.setups = %r' % laser_scope.setups)
##print('laser_scope.setup_name = %r' % laser_scope.setup_name)
print('laser_scope.setup_save = True')
for name in names: print('laser_scope.setup = %r' % name)
self = xray_scope # for debugging
##class self: scope = xray_scope # for Scope_Panel
print('')
print('xray_scope.trace_count')
print('xray_scope.timing_system_trigger_count')
print('xray_scope.trace_count_offset')
print('')
print('xray_scope.trace_directory_size')
print('xray_scope.emptying_trace_directory = True')
print('')
print('xray_scope.timing_reset = True')
print('xray_scope.trace_counts_history[0]')
print('xray_scope.trigger_counts_history[0]')
print('xray_scope.timing_differences')
print('xray_scope.timing_jitter')
print('xray_scope.timing_offset')
def report(PV_name,value,string_value):
info("%s=%r" % (PV_name,value))
class myPV:
timestamps = []
values = []
def record(PV_name,value,string_value):
from time import time
t = time()
myPV.timestamps += [t]
myPV.values += [value]
from numpy import diff,average
print('')
print('xray_scope.auto_acquire')
print('')
print('xray_scope.filenames')
print('xray_scope.times')
<file_sep>import time
import zmq
context = zmq.Context()
client = context.socket(zmq.PAIR)
client.connect("tcp://127.0.0.1:12322")
for i in range(0,100):
client.send_pyobj(i)
arr = client.recv_pyobj()
print arr.shape,'\n',arr[0:2,0:2]
time.sleep(1)
<file_sep>from instrumentation_id14 import ccd,pulses,waitt
from time import sleep,time
dir = "/data/pub/friedrich/test/test7"
Nrepeat = 10
Nalign = 200
Ndata = 30
timeout = 3.0
def test():
for j in range(0,Nrepeat):
# Alignnment scan
print("%d Alignment" % (j+1))
ccd.bin_factor = 8; waitt.value = 0.024
filenames = [dir+"/alignment/test_%02d_%03d.mccd" % (j+1,i+1)
for i in range(0,Nalign)]
ccd.acquire_images_triggered(filenames)
pulses.value = Nalign
while pulses.value > 0: sleep(0.05)
sleep(waitt.value)
t0 = time()
while ccd.state() != "idle" and time()-t0 < timeout: sleep(0.05)
if ccd.state() != "idle": print("CCD timeout: state %r" % (ccd.state()))
# Data collection
print("%d Data" % (j+1))
ccd.bin_factor = 2; waitt.value = 0.110
filenames = [dir+"/test_%02d_%03d.mccd" % (j+1,i+1)
for i in range(0,Ndata)]
ccd.acquire_images_triggered(filenames)
pulses.value = Ndata
while pulses.value > 0: sleep(0.05)
sleep(waitt.value)
t0 = time()
while ccd.state() != "idle" and time()-t0 < timeout: sleep(0.05)
if ccd.state() != "idle": print("CCD timeout: state %r" % (ccd.state()))
if __name__ == "__main__": # for testing
print('test()')
<file_sep>RBV.filename = '//mx340hs/data/anfinrud_1906/Archive/14IDC.mir2Th.RBV.txt'<file_sep>"""
Raster scan of a sample holder containing multiple crystals.
The sample holder is a flattened Mylar tubing of about 2 mm width, mounted
horizontally, facing the X-ray beam, with a 30-degree tilt with respect the
vertical.
The scan identifies the location of the crystals based on their X-ray
diffraction properties.
Author: <NAME>
Date created: Feb 13, 2017
Date last modified: Oct 27, 2017
"""
from instrumentation import *
__version__ = "2.4" # lauecollect
from rayonix_detector_continuous_1 import ccd # use old version
from Ensemble import ensemble
from logging import debug,info,warn,error
import glogging as g
class Image_Scan(object):
name = "image_scan"
from persistent_property import persistent_property
from numpy import sin,cos,radians
cx = persistent_property("cx",0.0) # center [mm]
cy = persistent_property("cy",0.0) # center [mm]
cz = persistent_property("cz",0.0) # center [mm]
dx = persistent_property("dx",0.03) # step size [mm] (0.03 -> 0.02)
dy = persistent_property("dy",0.03) # step size [mm] (0.03 -> 0.02)
width = persistent_property("width", 0.3) # range [mm] (0.3 -> 0.12)
height = persistent_property("height",0.9) # range [mm] (0.9 -> 0.6)
# sample carrier tilt to X-ray beam in deg (0 = normal)
phi = persistent_property("phi",-30)
# acquisition rate: timing_system.hlct*2 for ca 40 Hz
dt = persistent_property("dt",0.0244388571428)
start_dt = persistent_property("start_dt",0.0244388571428*2)
control_ms_shutter = persistent_property("control_ms_shutter",False)
motion_controller_enabled = persistent_property("motion_controller_enabled",True)
trigger_scope = persistent_property("trigger_scope",False)
# Analyze only the central part of the images? Which faction?
ROI_fraction = persistent_property("ROI_fraction",0.333)
peak_detection_threshold = persistent_property("peak_detection_threshold",10.0)
subtract_background = persistent_property("subtract_background",False)
start_time = persistent_property("start_time",0) # last time scan was run
cancelled = persistent_property("cancelled",False)
Nanalyzed = 0 # how many images have been processed?
repeat_number = persistent_property("repeat_number",1)
def get_center(self): return self.cx,self.cy,self.cz
def set_center(self,value): self.cx,self.cy,self.cz = value
center = property(get_center,set_center)
def get_position(self): return SampleX.value,SampleY.value,SampleZ.value
def set_position(self,value):
SampleX.value,SampleY.value,SampleZ.value = value
position = property(get_position,set_position)
@property
def moving(self): return any([m.moving for m in SampleX,SampleY,SampleZ])
def get_stepsize(self): return self.dx
def set_stepsize(self,value): self.dx = self.dy = value
stepsize = property(get_stepsize,set_stepsize)
def get_lauecollect_directory(self):
"""location to store files"""
import lauecollect; lauecollect.reload_settings()
directory = lauecollect.param.path
return directory
def set_lauecollect_directory(self,value):
import lauecollect
lauecollect.param.path = value
lauecollect.save_settings()
lauecollect_directory = property(get_lauecollect_directory,set_lauecollect_directory)
collection_directory = persistent_property("collection_directory",
"/net/mx340hs/data/anfinrud_1711/Data/Laue/Test/Test1")
def get_directory(self):
"""location to store files"""
directory = self.collection_directory+"/alignment"
return directory
def set_directory(self,value):
self.collection_directory = value.replace("/alignment","")
directory = property(get_directory,set_directory)
def get_xray_detector_enabled(self):
import lauecollect; lauecollect.reload_settings()
return lauecollect.options.xray_detector_enabled
def set_xray_detector_enabled(self,value):
import lauecollect
lauecollect.options.xray_detector_enabled = value
lauecollect.save_settings()
xray_detector_enabled = property(get_xray_detector_enabled,
set_xray_detector_enabled)
@property
def motors(self):
"""axis names"""
motors = ["X","Y","Z"]
if self.control_ms_shutter: motors += ["msShut_ext"]
return motors
def DX(self,I):
"""Horizontal offset relative to center in mm,
negative = left, positive = right
I: 0-based pixel coordinate, from left, may be an array"""
DX = (I-0.5*(self.NX-1))*self.dx
return DX
def I(self,DX):
"""0-based horizontal pixel coordinate, from left
DX: horizontal offset relative to center in mm,
negative = left, positive = right
may be an array
"""
I = DX/self.dx + 0.5*(self.NX-1)
return I
def DY(self,J):
"""Vertical offset relative to center in mm,
negative = down, positive = up
J: 0-based pixel coordinate, from top, may be an array"""
DY = -(J-0.5*(self.NY-1))*self.dy
return DY
def J(self,DY):
"""0-based vertical pixel coordinate, from top
DY: vertical offset relative to center in mm,
negative = down, positive = up
may be an array
"""
J = -DY/self.dy + 0.5*(self.NY-1)
return J
@property
def scan_IJ(self):
"""list of arrays of integer coordinates for a scan
I: 0-based horozontal pixel coordinate, from left
J: 0-based vertical pixel coordinate, from top
"""
from numpy import array,arange
IP,JP = arange(0,self.NX),arange(0,self.NY)
# In the horizontal direction, alternate direction from line to line.
I = [(IP if j%2==0 else IP[::-1]) for j in range(0,self.NY)]
J = [[j]*self.NX for j in JP]
I,J = array(I).flatten(),array(J).flatten()
IJ = array([I,J])
return IJ
@property
def scan_DXDY(self):
"""list of arrays of DX and DY coordinates for a scan
DY: horizontal direction, orthogonal to X-ray beam
DY: vertical direction, orthogonal to X-ray beam
"""
from numpy import array
I,J = self.scan_IJ
DXDY = array([self.DX(I),self.DY(J)])
return DXDY
@property
def grid_VXVY(self):
"""Scanning velocities at each grid point
VY: horizontal direction, orthogonal to X-ray beam
VY: vertical direction, orthogonal to X-ray beam
"""
from numpy import array
vx = self.dx/self.dt
# In the horizontal direction, alternate direction from line to line.
VX = [[vx if i%2==0 else -vx]*self.NX for i in range(0,self.NY)]
VY = [[0]*self.NX for i in range(0,self.NY)]
VX,VY = array(VX).flatten(),array(VY).flatten()
VX[0] = VX[-1] = 0
VXVY = array([VX,VY])
return VXVY
@property
def scan_XYZ(self):
"""list of arrays of x,y and z coordinates"""
XYZ = self.XYZ(self.scan_DXDY)
return XYZ
def XYZ(self,(DX,DY)):
"""Transform fro m2D to 3D coordinates
DX: horizontal offset relative to center in mm,
negative = left, positive = right; may be an array
DY: vertical offset relative to center in mm,
negative = down, positive = up; may be an array
"""
from numpy import sin,cos,radians,array
X = self.cx+DY*sin(radians(self.phi))
Y = self.cy+DY*cos(radians(self.phi))
Z = self.cz+DX
XYZ = array([X,Y,Z])
return XYZ
@property
def scan_VXVYVZ(self):
"""list of arrays of x,y and z coordinates"""
from numpy import sin,cos,radians,array
VXG,VYG = self.grid_VXVY
VX = VYG*sin(radians(self.phi))
VY = VYG*cos(radians(self.phi))
VZ = VXG
VXVYVZ = array([VX,VY,VZ])
return VXVYVZ
@property
def scan_N(self):
"""How many scan points are there per repeat?"""
return self.NX*self.NY
@property
def scan_Ntot(self):
"""How many scan points are there in all repeats?"""
return self.scan_N*self.repeat_number
def get_NX(self):
"""How many scan points are there in the horizontal direction?"""
from numpy import rint
eps = 1e-6
NX = int(rint((self.width+eps)/self.dx)) + 1
return NX
def set_NX(self,NX): self.width = (NX-1)*self.dx
NX = property(get_NX,set_NX)
def get_NY(self):
"""How many scan points are there in the vertical direction?"""
from numpy import rint
eps = 1e-6
NY = int(rint((self.height+eps)/self.dy)) + 1
return NY
def set_NY(self,NY): self.height = (NY-1)*self.dy
NY = property(get_NY,set_NY)
@property
def scan_T(self):
"""Time for each scan point"""
from numpy import arange
T = self.dt*arange(0,self.scan_N)
return T
@property
def x_PVT(self):
"""Position, velocity and time"""
P,V,T = self.scan_XYZ[0],self.scan_VXVYVZ[0],self.scan_T
return P,V,T
@property
def y_PVT(self):
"""Position, velocity and time"""
P,V,T = self.scan_XYZ[1],self.scan_VXVYVZ[1],self.scan_T
return P,V,T
@property
def z_PVT(self):
"""Position, velocity and time"""
P,V,T = self.scan_XYZ[2],self.scan_VXVYVZ[2],self.scan_T
return P,V,T
@property
def PVT(self):
PVTs = [self.x_PVT,self.y_PVT,self.z_PVT]
if self.control_ms_shutter: PVTs += [ms_shutter.PVT(self.scan_T)]
PVT = self.conbine_trajectories(PVTs)
return PVT
@staticmethod
def conbine_trajectories(PVTs):
from numpy import concatenate,sort,unique,array
# common time points
T = unique(sort(concatenate([PVT[2] for PVT in PVTs])))
P,V = [],[]
for PVT in PVTs:
p,v = self.PV(PVT)
P += [p(T)]
V += [v(T)]
P,V = array(P),array(V)
return P,V,T
@staticmethod
def PV(PVT):
"""Position and velocity as continous functions of time
PVT: tuple of 1-d vectors, positino, velocity, time
return value: tuple of two interpolation functions
"""
from scipy.interpolate import interp1d
from numpy import nan,concatenate
P,V,T = PVT
dt = 1e-3
P2 = interl(P,P+V*dt)
T2 = interl(T,T+dt)
T2 = concatenate(([-1e3],T2,[1e3]))
P2 = concatenate(([P2[0]],P2,[P2[-1]]))
p = interp1d(T2,P2,bounds_error=False,fill_value=nan)
T = concatenate(([-1e3],T,[1e3]))
V = concatenate(([V[0]],V,[V[-1]]))
v = interp1d(T,V,kind="linear",bounds_error=False,fill_value=nan)
return p,v
def acquire(self):
"""Perform a single image scan"""
self.cancelled = False
self.clear()
self.start()
info("Scanning...")
self.wait()
info("Scan completed")
self.finish()
def scan(self):
"""Perform image scan and analyze result"""
self.acquire()
self.analyze()
def start(self):
"""Initial setup for image scan"""
from time import time
self.start_time = time()
self.prepare()
self.acquisition_start()
def clear(self):
"""Remove all iamge files"""
from os.path import exists
from shutil import rmtree
if exists(self.directory):
try: rmtree(self.directory)
except Exception,msg: warn("rmtree: %s: %s" % (self.directory,msg))
def prepare(self):
"""Initial setup for image scan"""
self.motion_controller_start()
self.xray_detector_start()
self.diagnostics_start()
self.timing_system_start()
def timing_system_acquiring(self):
"""Has the timing system started acquiring data?"""
return timing_system.image_number.count > 0 \
or timing_system.pass_number.count > 0
def motion_controller_start(self):
"""Configure motion controller for scan"""
from time import sleep
if self.motion_controller_enabled:
self.jog_xray_shutter()
self.goto_center()
info("Setting up motion controller...")
self.start_program()
def goto_center(self):
from time import sleep
while self.moving: sleep(0.05)
if self.position != self.center:
info("returning to center: %r to %r..." % (self.position,self.center))
self.position = self.center
while self.moving: sleep(0.05)
def jog_xray_shutter(self):
# Because of settling of particles in the ferrofluiidic feed-through
# of te X-ray ms shutter, the first operation might have execessive
# positino error, not compensated by the servo feedback loop
# (ca 3 degreees), leading to only partial transmission of the X-ray
# beam.
# By "jogging" the shutter before first use, the ferro fluid is
# "loosened up" again.
from time import sleep,time
if time() - self.last_jog_xray_shutter > 600:
info("Jogging X-ray shutter")
from ms_shutter import ms_shutter
pos = msShut.value
if pos > ms_shutter.open_pos: step = +10
else: step = -10
msShut.value = pos + step
##while msShut.moving: sleep(0.01)
msShut.value = pos
while msShut.moving: sleep(0.01)
self.last_jog_xray_shutter = time()
last_jog_xray_shutter = persistent_property("last_jog_xray_shutter",0)
def timing_system_start(self):
"""Configure timing system for scan"""
info("Setting up timing system...")
# Timing calibration is different from Lauecollect
timing_sequencer.ms.offset = 0.0105 # 0.0095,0.010,0.0105,0.011,0.0115,[0.012]
# Sample translation trigger needs to be "start_dt" before the first
# X-ray pulse.
timing_sequencer.trans.offset = self.start_dt # 0.005
##timing_sequencer.cache_size = 0 # clear cache
Ntot = self.scan_Ntot
N = self.scan_N
Nr = self.repeat_number
image_numbers = range(1,Ntot+1)
timing_sequencer.queue_active = False # hold off exection till setup complete
timing_system.image_number.count = 0
timing_system.pass_number.count = 0
timing_system.pulses.count = 0
# Restart time for program
Nw = 4 # in dt cycles
# The detector trigger pulse at the beginning of the first image is to
# dump zingers that may have accumuated on the CCD. This image is discarded.
# An extra detector trigger is required after the last image,
# to save the last image.
waitt = ([self.dt]*N+[self.dt]*Nw)*Nr+[self.dt]
burst_waitt = ([self.dt]*N+[self.dt]*Nw)*Nr+[self.dt]
burst_delay = ([0]*N+[0]*Nw)*Nr+[0]
npulses = ([1]*N+[1]*Nw)*Nr+[1]
laser_on = ([0]*N+[0]*Nw)*Nr+[0]
ms_on = ([1]*N+[0]*Nw)*Nr+[0]
trans_on = ([1]+[0]*(N-1+Nw))*Nr+[0]
xdet_on = [1]+([1]*N+[0]*Nw)*Nr
xosct_on = ([1]*N+[0]*Nw)*Nr+[0]
image_numbers = flatten([range(i+1,i+N+1)+[i+N]*Nw for i in range(0,Ntot,N)])+[Ntot]
timing_sequencer.acquire(
waitt=waitt,
burst_waitt=burst_waitt,
burst_delay=burst_delay,
npulses=npulses,
laser_on=laser_on,
ms_on=ms_on,
trans_on=trans_on,
xdet_on=xdet_on,
xosct_on=xosct_on,
image_numbers=image_numbers,
)
def xray_detector_start(self):
"""Configure X-ray area detector
image_numbers: list of 1-based integers
e.g. image_numbers = alignment_pass(1)"""
if self.xray_detector_enabled:
info("Setting up X-ray detector...")
import lauecollect; lauecollect.load_settings()
from ImageViewer import show_images
filenames = self.image_filenames
show_images(filenames)
ccd.bin_factor = lauecollect.align.ccd_bin_factor # Speeds up the acquisition time
def acquisition_start(self):
from time import sleep
filenames = self.image_filenames
xdet_on = timing_sequencer.xdet_on
info("X-ray detector continuously triggered: %r" % xdet_on)
# If the X-ray detector is not continuously triggered...
if not xdet_on: xdet_count = timing_system.xdet_count.count+2 # discard first dummy image
timing_sequencer.queue_active = True
info("Timing system: Waiting for acquisition to start...")
while not self.timing_system_acquiring(): sleep(0.01)
info("Timing system: Acquisition started.")
if xdet_on: xdet_count = timing_system.xdet_count.count+1
info("First image: xdet_count=%r" % xdet_count)
ccd.acquire_images_triggered(filenames,start=xdet_count)
def diagnostics_start(self):
"""Configure diagnostics"""
info("Setting up X-ray oscilloscope...")
xray_trace.acquire_sequence(self.scan_N)
xray_trace.acquire_waveforms(self.xray_trace_filenames)
@property
def xray_trace_filenames(self):
"""List of waveform files"""
filenames = [self.directory+"/%02d_xray_trace.trc" % (repeat+1)
for repeat in range(0,self.repeat_number)]
return filenames
def wait(self):
"""Wait for scan to complete
image_numbers: list of 1-based integers, e.g. image_numbers = alignment_pass(1)"""
from time import sleep
while self.running and not self.cancelled: sleep(0.01)
@property
def running(self):
"""Is scan complete?
image_numbers: list of 1-based integers, e.g. image_numbers = alignment_pass(1)"""
if self.timing_system_running: running = True
elif self.xray_detector_running: running = True
elif self.motion_controller_running: running = True
else: running = False
return running
@property
def timing_system_running(self):
"""Is scan complete?"""
i = timing_system.image_number.count
p = timing_system.pulses.count
info("acquiring image %3d, %d pulses" % (i,p))
running = i < self.scan_Ntot
return running
@property
def xray_detector_running(self):
"""Is scan complete?"""
if self.xray_detector_enabled:
nimages = ccd.nimages
info("X-ray detector: %s images left to save" % nimages)
running = (nimages > 0)
else: running = False
return running
@property
def motion_controller_running(self):
"""Is scan complete?"""
from os.path import basename
if self.motion_controller_enabled:
running = False
##running = (self.position != self.center)
##running = self.program_running == basename(self.program_filename)
else: running = False
return running
def finish(self):
"""End scan"""
self.motion_controller_finish()
self.xray_detector_finish()
self.timing_system_finish()
##self.diagnostics_finish()
def motion_controller_finish(self):
# Return to the center
if self.motion_controller_enabled:
pass
##self.goto_center()
##ensemble.program_filename = "ms-shutter.ab"
def xray_detector_finish(self):
pass
def timing_system_finish(self):
timing_sequencer.queue_active = False
timing_sequencer.queue_length = 0
# Timing calibration is different from Lauecollect
timing_sequencer.ms.offset = 0.013
timing_sequencer.trans.offset = 0.005
timing_sequencer.buffer_size = 0
def get_ms_shutter_enabled(self):
return self.program_running == "ms-shutter.ab"
def set_ms_shutter_enabled(self,value):
if value:
# Timing calibration is different from Lauecollect
timing_sequencer.ms.offset = 0.013
timing_sequencer.trans.offset = 0.005
##timing_sequencer.cache_size = 0 # clear cache
self.program_running = "ms-shutter.ab"
else:
self.program_running = ""
ms_shutter_enabled = property(get_ms_shutter_enabled,set_ms_shutter_enabled)
def diagnostics_finish(self):
"""diagnostics"""
info("Restoring X-ray oscilloscope...")
xray_trace.sampling_mode = "RealTime"
xray_trace.trigger_mode = "Normal"
def start_program(self):
from os.path import basename
from time import sleep
if not self.parameter_file_up_to_date:
self.program_running = ""
while self.program_running: sleep(0.1)
self.update_parameter_file()
if not self.program_running == basename(self.program_filename):
self.program_running = self.program_filename
# Wait for compilation and loading to complete
while not self.program_running == basename(self.program_filename):
sleep(0.1)
def get_program_running(self):
program = ensemble.UserString0 if ensemble.program_running else ""
return program
def set_program_running(self,filename):
from os.path import basename
ensemble.program_filename = basename(filename)
program_running = property(get_program_running,set_program_running)
@property
def program_filename(self):
"""AeroBasic program"""
from normpath import normpath
filename = normpath(ensemble.program_directory)+"/RasterScan.ab"
return filename
@property
def parameter_file_up_to_date(self):
"""Update Aerobasic header file to be included in main program at
compilation time"""
from os.path import basename
parameter_code = dos_text(self.parameter_code)
old_parameter_code = file(self.parameter_filename).read()
up_to_date = parameter_code == old_parameter_code
return up_to_date
def update_parameter_file(self):
"""Update Aerobasic header file to be included in main program at
compilation time"""
from os.path import basename
info("Updating file %r..." % basename(self.parameter_filename))
file(self.parameter_filename,"wb").write(dos_text(self.parameter_code))
@property
def parameter_filename(self):
"""AeroBasic program"""
from normpath import normpath
filename = normpath(ensemble.program_directory)+"/RasterScan_parameters.abi"
return filename
@property
def parameter_code(self):
"""Aerobasic header file to be included in main program at complation"""
s = ""
s += "'Automatically generated by image_scan.py %s\n" % __version__
s += "DECLARATIONS\n"
s += "GLOBAL NR AS INTEGER = %s\n" % self.NY
s += "GLOBAL NC AS INTEGER = %s\n" % self.NX
s += "GLOBAL DZ AS DOUBLE = %s\n" % self.stepsize
s += "GLOBAL NT AS INTEGER = %s\n" % self.NT
s += "GLOBAL NP AS INTEGER = %s\n" % self.NP
s += "END DECLARATIONS\n"
return s
def get_NT(self):
"""Startup delay in multiples of 12 ms"""
from numpy import rint
NT = int(rint(self.start_dt/timing_system.hlct))
return NT
def set_NT(self,NT): self.start_dt = NT*timing_system.hlct
NT = property(get_NT,set_NT)
def get_NP(self):
"""Scan period in multiples of 12 ms"""
from numpy import rint
NP = int(rint(self.dt/timing_system.hlct))
return NP
def set_NP(self,NP): self.dt = NP*timing_system.hlct
NP = property(get_NP,set_NP)
@property
def image_filenames(self):
I,J = self.scan_IJ
X,Y,Z = self.scan_XYZ
dir = self.directory
image_filenames = [[
dir+"/%02d,%02d_%+.3f,%+.3f,%+.3f_%02d.mccd" %
(j,i,x,y,z,repeat+1) for i,j,x,y,z in zip(I,J,X,Y,Z)]
for repeat in range(0,self.repeat_number)]
image_filenames = flatten(image_filenames)
return image_filenames
@property
def logfile(self):
from table import table
from os.path import basename,exists
from time_string import date_time
from numpy import concatenate
if exists(self.log_filename): logfile = table(self.log_filename)
else:
logfile = table()
logfile["date time"] = [date_time(t) for t in self.start_time+self.scan_T]
logfile["filename"] = [basename(f) for f in self.image_filenames]
DX,DY = concatenate([self.scan_DXDY.T]*self.repeat_number).T
logfile["X[mm]"] = DX
logfile["Y[mm]"] = DY
logfile.filename = self.log_filename
return logfile
def generate_logfile(self):
"""Save scan log file"""
self.logfile.save()
@property
def log_filename(self):
filename = self.directory+"/image_scan.log"
return filename
def analyze(self):
"""Process the acquired images"""
self.calculate_FOM()
self.generate_FOM_image()
self.generate_plot()
##self.generate_spot_mask()
def calculate_FOM(self):
"""Process the acquired images"""
from numpy import zeros,sum
from numimage import numimage
from peak_integration import peak_integration_mask
images = self.images
FOM = zeros(self.scan_N)
for self.Nanalyzed in range(0,self.scan_N):
if self.Nanalyzed % 10 == 0:
info("analysis %.f%%" % (float(self.Nanalyzed)/self.scan_N*100))
image = images[self.Nanalyzed]
FOM[self.Nanalyzed] = sum(peak_integration_mask(image)*image)
logfile = self.logfile
logfile["FOM"] = FOM
logfile.save()
def calculate_FOM_Fast(self):
"""Process the acquired images"""
from numpy import zeros,sum,uint32
from peak_integration import peak_integration_mask
images = self.images
sum_image = sum(images.astype(uint32),axis=0)
info("Peak mask of summed image...")
mask = peak_integration_mask(sum_image)
info("FOM...")
FOM = zeros(self.scan_N)
for self.Nanalyzed in range(0,self.scan_N):
FOM[self.Nanalyzed] = sum(mask*images[self.Nanalyzed])
info("FOM done.")
logfile = self.logfile
logfile["FOM"] = FOM
logfile.save()
Nsvd = persistent_property("Nsvd",5)
SVD_rotation = persistent_property("SVD_rotation",False)
@property
def SVD_bases(self):
from numpy.linalg import svd
from numpy import zeros,nan,diag,dot
from SVD_rotation import SVD_rotation_max_V_2D_auto_correlation
images = self.images_ordered
NX,NY,w,h = images.shape
image_data = images.reshape((NX*NY,w*h))
info("SVD...")
U,s,V = svd(image_data.T,full_matrices=False)
# Discard insignificant vectors.
s_all = s
U,s,V = U[:,0:self.Nsvd],s[0:self.Nsvd],V[0:self.Nsvd]
if self.SVD_rotation:
info("SVD rotation...")
US,V = SVD_rotation_max_V_2D_auto_correlation(U,s,V,(self.NX,self.NY),
diagnostics=self.directory+"/SVD rotation scan auto-correlation")
else: US = dot(U,diag(s))
info("SVD done.")
# Restore original shapes.
base_images = US.T.reshape((self.Nsvd,w,h))
base_maps = V.reshape((self.Nsvd,self.NX,self.NY))
return base_maps,s_all,base_images
@property
def SVD_bases(self):
from numpy.linalg import svd
from numpy import zeros,nan,diag,dot
from SVD_rotation import SVD_rotation_min_V_cross_correlation
images = self.images_ordered
NX,NY,w,h = images.shape
image_data = images.reshape((NX*NY,w*h))
info("SVD...")
U,s,V = svd(image_data,full_matrices=False)
# Discard insignificant vectors.
s_all = s
U,s,V = U[:,0:self.Nsvd],s[0:self.Nsvd],V[0:self.Nsvd]
if self.SVD_rotation:
info("SVD rotation...")
U,SV = SVD_rotation_min_V_cross_correlation(U,s,V,
diagnostics=self.directory+"/SVD rotation image cross-correlation")
else: SV = dot(diag(s),V)
info("SVD done.")
# Restore original shapes.
base_maps = U.T.reshape((self.Nsvd,self.NX,self.NY))
base_images = SV.reshape((self.Nsvd,w,h))
return base_maps,s_all,base_images
def generate_SVD_plot(self):
import matplotlib; matplotlib.use("PDF",warn=False) # Turn off Tcl/Tk GUI.
from matplotlib.backends.backend_pdf import PdfPages
from pylab import figure,imshow,plot,title,grid,xlabel,ylabel,xlim,ylim,\
xticks,yticks,legend,gca,rc,cm,colorbar,annotate,subplot,close,\
tight_layout,loglog
from numpy import clip,amin,amax,average,sum
from matplotlib.colors import ListedColormap
maps,s,images = self.SVD_bases
info("Plotting...")
PDF_file = PdfPages(self.directory+"/SVD.pdf")
fig = figure(figsize=(5,5))
loglog(range(1,self.Nsvd+1),s[0:self.Nsvd],".",color="red")
loglog(range(self.Nsvd+1,len(s)+1),s[self.Nsvd:],".",color="blue")
grid()
xlabel("base number")
ylabel("singular value")
tight_layout()
PDF_file.savefig(fig)
for (i,(map,image)) in enumerate(zip(maps,images)):
# SVD components map have abitrary sign.
if abs(amin(map)) > amax(map): map *= -1; image *= -1
fig = figure(figsize=(5,7))
subplot(2,1,1)
title("%d" % (i+1))
imshow(map.T,cmap=cm.gray,interpolation='nearest')
colorbar()
xlim(-0.5,self.NX-0.5)
ylim(-0.5,self.NY-0.5)
subplot(2,1,2)
Imin,Imax = 0.02*amin(image),0.02*amax(image)
imshow(clip(image,Imin,Imax).T,cmap=cm.gray,interpolation='nearest')
colorbar()
PDF_file.savefig(fig)
PDF_file.close()
close("all")
info("Plotting done.")
def generate_FOM_image(self):
"""Save the ccan result in the form of an image"""
self.FOM_image.save()
@property
def FOM_image(self):
"""Scan result presented as image"""
from numimage import numimage
from numpy import rint
logfile = self.logfile
X,Y,FOM = logfile.X,logfile.Y,logfile.FOM
I = rint(self.I(X)).astype(int)
J = rint(self.J(Y)).astype(int)
image = numimage((self.NX,self.NY))
image[I,J] = FOM
image.pixelsize = self.dx
image.filename = self.FOM_image_filename
return image
@property
def FOM_image_filename(self):
filename = self.directory+"/FOM_image.tiff"
return filename
@property
def images_ordered(self):
"""Image data to use for analysis, reordered from scan order to X,Y
order, as 4D numpy array, shape NX x NY x W x H"""
from numpy import zeros,nan
images = self.images
info("Reordering images...")
N,w,h = images.shape
images_ordered = zeros((self.NX,self.NY,w,h))+nan
I,J = self.scan_IJ
for i in range(0,N): images_ordered[I[i],J[i]] = images[i]
return images_ordered
@property
def images(self):
"""Image data to use for analysis in collection order
All images as 3D numpy array, shape Nimages x W x H"""
if self.subtract_background: images = self.background_subtracted_images
else: images = self.image_ROIs
return images
@property
def image_ROIs(self):
"""Image data to use for analysis
All iamges as 3D numpy array, shape Nimage x W x H"""
from numimage import numimage
from numpy import array
info("Mapping images...")
images = [numimage(f) for f in self.image_filenames]
images = [self.ROI(image) for image in images]
info("Loading images...")
images = array(images)
info("Loading images done.")
return images
def ROI(self,image):
"""Region of interest for analysis
image: 2D numpy array"""
from numpy import rint
w,h = image.shape
x = self.ROI_fraction # real number between 0 and 1.0, e.g. 0.333
imin,imax = int(rint(w/2*(1-x))),int(rint(w/2*(1+x)))
ROI = image[imin:imax,imin:imax]
return ROI
def generate_spot_mask(self):
"""Save spot mask from FOM calculation in the form of an image"""
self.spot_mask.save()
@property
def spot_mask(self):
from numpy import zeros,sum,uint32
from peak_integration import spot_mask
from numimage import numimage
images = self.images
sum_image = sum(images.astype(uint32),axis=0)
info("Peak mask of summed image...")
mask = spot_mask(sum_image)
mask = numimage(mask)
mask.filename = self.spot_mask_filename
return mask
@property
def spot_mask_filename(self):
filename = self.directory+"/spot_mask.tiff"
return filename
@property
def crystal_mask(self):
"""bitmap showing location of crystals. 1 = crystal, 0 = no crystal"""
from peak_integration import spot_mask
FOM = self.FOM_image
mask = spot_mask(FOM,self.peak_detection_threshold)
return mask
@property
def crystal_IJ(self):
"""coordinates of crystal centers
I: 0-based horizontal pixel coordinates, from left
J: 0-based vertical pixel coordinates, from top
"""
from scipy.ndimage.measurements import label
from numpy import fromfunction,average,zeros,where
mask = self.crystal_mask
FOM = self.FOM_image
# Find clusters
labelled_mask,n = label(mask)
Is = fromfunction(lambda i,j:i,mask.shape)
Js = fromfunction(lambda i,j:j,mask.shape)
I,J = zeros(n),zeros(n)
for i in range(0,n):
pixels = where(labelled_mask==i+1)
I[i] = average(Is[pixels],weights=FOM[pixels])
J[i] = average(Js[pixels],weights=FOM[pixels])
return I,J
def analyze(self):
from image_analysis import crystal_IJ
self.crystal_IJ = crystal_IJ(self.directory)
self.saved_crystal_positions = self.crystal_XYZ
def get_crystal_IJ(self):
"""coordinates of crystal centers
I: 0-based horizontal pixel coordinates, from left
J: 0-based vertical pixel coordinates, from top
"""
from table import table
from numpy import array
if self.has_crystal_IJ:
data = table(self.crystal_IJ_filename,separator="\t")
IJ = data["I","J"].asarray
else: IJ = array([[],[]],dtype=int)
return IJ
def set_crystal_IJ(self,IJ):
"""X,Y,Z coordinates of crystal centers"""
from table import table
data = table(columns=["I","J"],data=IJ)
data.save(self.crystal_IJ_filename) ##,separator="\t")
crystal_IJ = property(get_crystal_IJ,set_crystal_IJ)
@property
def has_crystal_IJ(self):
from os.path import exists
return exists(self.crystal_IJ_filename)
@property
def crystal_IJ_filename(self):
return self.directory+"/crystal_IJ.txt"
@property
def crystal_DXDY(self):
"""Coordinates of crystal centers as DX,DY"""
I,J = self.crystal_IJ
DX,DY = self.DX(I),self.DY(J)
return DX,DY
@property
def crystal_XYZ(self):
"""X,Y,Z coordinates of crystal centers"""
DX,DY = self.crystal_DXDY
XYZ = self.XYZ((DX,DY))
self.saved_crystal_positions = XYZ
return XYZ
def get_saved_crystal_positions(self):
"""X,Y,Z coordinates of crystal centers"""
from table import table
data = table(self.saved_crystal_positions_filename,separator="\t")
XYZ = data["X","Y","Z"]
return XYZ
def set_saved_crystal_positions(self,XYZ):
"""X,Y,Z coordinates of crystal centers"""
from table import table
data = table(columns=["X","Y","Z"],data=XYZ)
data.save(self.saved_crystal_positions_filename) ##,separator="\t")
saved_crystal_positions = property(get_saved_crystal_positions,set_saved_crystal_positions)
@property
def has_saved_crystal_positions(self):
from os.path import exists
return exists(self.saved_crystal_positions_filename)
@property
def saved_crystal_positions_filename(self):
return self.directory+"/crystal_positions.txt"
def generate_plot(self):
import matplotlib; matplotlib.use("PDF",warn=False) # Turn off Tcl/Tk GUI.
from matplotlib.backends.backend_pdf import PdfPages
from pylab import figure,imshow,plot,title,grid,xlabel,ylabel,xlim,ylim,\
xticks,yticks,legend,gca,rc,cm,colorbar,annotate,close
from matplotlib.colors import ListedColormap
image = self.FOM_image
mask = self.crystal_mask
I,J = self.crystal_IJ
PDF_file = PdfPages(self.directory+"/plot.pdf")
fig = figure(figsize=(5,5))
imshow(image.T,cmap=cm.gray,interpolation='nearest')
colorbar()
cmap = ListedColormap([[0,0,0],[1,0,0]])
imshow(mask.T,alpha=0.5,cmap=cmap,interpolation='nearest')
plot(I,J,"ro")
for n in range(0,len(I)): annotate(str(n),xy=(I[n],J[n]),color="yellow")
xlim(-0.5,self.NX-0.5)
ylim(-0.5,self.NY-0.5)
PDF_file.savefig(fig)
PDF_file.close()
close("all")
def goto_crystal(self,i):
SampleX.value,SampleY.value,SampleZ.value = self.crystal_XYZ[:,i]
def goto_IJ(self,I,J):
SampleX.value,SampleY.value,SampleZ.value = self.XYZ([self.DX(I),self.DY(J)])
@property
def background_subtracted_images(self):
"""Image data to use for analysis
All iamges as 3D numpy array, shape Nimage x W x H"""
from numimage import numimage
from background_image import background_subtracted
from os.path import exists
from numpy import array,where
info("Mapping images...")
filenames = self.image_filenames
images = []
for i in range(0,len(filenames)):
filename = filenames[i]
background_subtracted_filename = filename.replace("/alignment/",
"/alignment/background_subtracted/%r/" % self.ROI_fraction)
if not exists(background_subtracted_filename):
image = self.ROI(numimage(filename))
image = background_subtracted(image)
numimage(image+10).save(background_subtracted_filename)
images += [numimage(background_subtracted_filename)]
info("Loading images...")
images = array(images)
info("Loading images done.")
# offset 10 = 0 counts
images = where(images!=0,images-10.0,0.0)
return images
def collect(self):
"""Instruct Lauecollect to collect data"""
from time import sleep
from os.path import basename
import lauecollect
positions = self.crystal_XYZ.T
for i in range(0,len(positions)):
self.ms_shutter_enabled = True
self.position = positions[i]
while self.moving: sleep(0.1)
lauecollect.param.path = self.collection_directory
file_basename = "%s-%d" % (basename(self.collection_directory),i+1)
lauecollect.param.file_basename = file_basename
lauecollect.collect_dataset()
image_scan = Image_Scan()
def dos_text(text):
"""Convert UNIX to DOS text"""
return text.replace("\n","\r\n")
def interl(a,b):
"""Combine two arrays of the same length alternating their elements"""
from numpy import column_stack,ravel
return ravel(column_stack((a,b)))
def flatten(l):
"""Converta nested to a flat list"""
return [item for sublist in l for item in sublist]
if __name__ == "__main__":
self = image_scan # for debugging
import logging
logging.basicConfig(level=logging.INFO,
format="%(asctime)s %(levelname)s: %(message)s")
g.filename = self.directory+"/debug.pdf"
print('self.center = %.3f,%.3f,%.3f' % self.center)
print('self.center = self.position')
print('self.width,self.height = %.3f,%.3f # 0.500,0.700' % (self.width,self.height))
##print('self.dx,self.dy = %.3f,%.3f' % (self.dx,self.dy))
print('self.stepsize = %.3f' % self.stepsize)
print('self.scan_N = %r' % self.scan_N)
print('self.dt = %r # timing_system.hlct*2' % self.dt)
print('self.start_dt = %r # timing_system.hlct*2' % self.start_dt)
print('self.NX = %r' % self.NX)
print('self.NY = %r' % self.NY)
print('self.NT = %r' % self.NT)
print('self.NP = %r' % self.NP)
print('self.scan_Ntot = %r' % self.scan_Ntot)
##print('self.trigger_scope = %r' % self.trigger_scope)
##print('ensemble.program_directory = %r' % ensemble.program_directory)
##print('self.directory = %r' % self.directory)
print('self.collection_directory = %r' % self.collection_directory)
print('self.lauecollect_directory = %r' % self.lauecollect_directory)
print('self.collection_directory = self.lauecollect_directory')
print('self.repeat_number = %r' % self.repeat_number)
print('')
print('self.ms_shutter_enabled = %r' % self.ms_shutter_enabled)
##print('')
##print('self.subtract_background = %r' % self.subtract_background)
##print('self.ROI_fraction = %r # 0.1667' % self.ROI_fraction)
##print('self.peak_detection_threshold = %r' % self.peak_detection_threshold)
print('')
##print('self.scan()')
print('self.acquire()')
print('self.analyze()')
print('self.crystal_IJ')
print('self.crystal_XYZ')
print('self.goto_crystal(0)')
print('self.collect()')
##print('self.goto_IJ(11,4)')
##print('self.Nsvd = %r' % self.Nsvd)
##print('self.SVD_rotation = %r' % self.SVD_rotation)
##print('self.generate_SVD_plot()')
##print('images = self.background_subtracted_images')
##print('images = self.images')
<file_sep>"""
2D scan of the sample on a regular periodic grid.
For the photocrystallography chip.
<NAME>, Nov 13, 2013 - Dec 6, 2013
"""
from numpy import *
__version__ = "1.0.3"
from DB import dbput,dbget
from linear_fit import linear_fit_coeff
from logging import debug
class Grid(object):
"""Periodic structure"""
def get_n(self):
"""Size of the grid"""
try: value = asarray(eval(dbget("sample_translation_grid.n")))
except: value = array([8,8,10,10])
return value
def set_n(self,value):
dbput("sample_translation_grid.n",asstring(asarray(value).tolist()))
n = property(get_n,set_n)
def get_origin(self):
"""XYZ coordinates of the grid point (0,0,..0).
3D vector"""
try: value = asarray(eval(dbget("sample_translation_grid.origin")))
except: value = array([-4.000,-4.000,0.0])
return value
def set_origin(self,value):
dbput("sample_translation_grid.origin",
asstring(asarray(value).tolist()))
origin = property(get_origin,set_origin)
def get_base_vectors(self):
"""m x (N+1) matrix (m: number of support points, N: number of
dimensions)"""
try: value = asarray(eval(dbget("sample_translation_grid.base_vectors")))
except: value = array([[1.000,0,0],[0,1.000,0],[0.050,0,0],[0,0.05,0]])
return value
def set_base_vectors(self,value):
dbput("sample_translation_grid.base_vectors",
asstring(asarray(value).tolist()))
base_vectors = property(get_base_vectors,set_base_vectors)
def get_support_indices(self):
"""N x 3 matrix (m: number of support points)"""
s = dbget("sample_translation_grid.support_indices")
try: value = atleast_2d(eval(s))
except Exception,details:
debug("sample_translation_grid.support_indices: %s: %s" % (s,details))
value = zeros((0,0),dtype=int)
ndim = len(self.n)
if value.shape[1] != ndim: value = zeros((0,ndim),dtype=int)
return value
def set_support_indices(self,value):
dbput("sample_translation_grid.support_indices",
asstring(asarray(value).tolist()))
support_indices = property(get_support_indices,set_support_indices)
def get_support_xyz(self):
"""m x 3 matrix (N: number of dimensions)"""
s = dbget("sample_translation_grid.support_xyz")
try: value = atleast_2d(eval(s))
except Exception,details:
debug("sample_translation_grid.support_xyz: %s: %s" % (s,details))
value = zeros((0,3))
if value.shape[1] != 3: value = zeros((0,3))
return value
def set_support_xyz(self,value):
dbput("sample_translation_grid.support_xyz",
asstring(asarray(value).tolist()))
support_xyz = property(get_support_xyz,set_support_xyz)
def add_support_point(self,indices,xyz):
"""indices: array of n 0-based integers (e.g. n=4)
xyz: array of three floating point values"""
self.remove_support_indices(indices)
self.remove_support_xyz(xyz)
self.support_indices = concatenate((self.support_indices,[indices]))
self.support_xyz = concatenate((self.support_xyz,[xyz]))
self.fit()
def remove_support_indices(self,indices):
"""indices: array of n 0-based integers (e.g. n=4)"""
keep = ~all(self.support_indices == indices,axis=1)
self.support_indices = self.support_indices[keep]
self.support_xyz = self.support_xyz[keep]
self.fit()
def has_support_indices(self,indices):
"""indices: array of n 0-based integers (e.g. n=4)"""
return any(all(indices == self.support_indices,axis=1))
def remove_support_xyz(self,xyz):
"""xyz: array of three floating point values"""
keep = ~all(self.support_xyz == xyz,axis=1)
self.support_indices = self.support_indices[keep]
self.support_xyz[keep]
def clear_support_points(self):
ndim = len(self.n)
self.support_indices = zeros((0,ndim))
self.support_xyz = zeros((0,3))
def get_Ip(self):
"""Matrix of support point indices (I) with all ones as the first column.
Ip and Bp are related by the equation: Ip.Bp = support_xyz
m x (N+1) matrix (m: number of support points, N: number of dimensions)"""
I = self.support_indices
n = len(self.support_indices)
Ip = column_stack((ones(n),I))
return Ip
Ip = property(get_Ip)
def get_Bp(self):
"""Origin (o) and base vectors (B) as a single matrix.
The origin is in the first row.
Ip and Bp are related by the equation: Ip.Bp = support_xyz
(N+1) x 3 matrix (N: number of dimensions)"""
b = self.base_vectors
o = self.origin
Bp = row_stack((o,b))
return Bp
def set_Bp(self,Bp):
self.origin = Bp[0]
self.base_vectors = Bp[1:]
Bp = property(get_Bp,set_Bp)
@property
def fit_Bp(self):
"""Calculate the grid parameters from the support points"""
Ip = self.Ip
R = self.support_xyz
Bp = linear_fit_coeff(R.T,Ip.T).T
return Bp
@property
def has_sufficient_support_points(self):
"""Are there sufficient support points to calculate the grid
parameters?"""
return not any(isnan(self.fit_Bp))
def fit(self):
"""Calculate the grid parameters from the support points"""
Bp = self.fit_Bp
if not any(isnan(Bp)): self.Bp = Bp
@property
def indices(self):
"""0-based integer coordinates all grid points
(n[0]*n[1]*...*n[N-1]) x N array of 0-based integers"""
return index_list(self.n)
@property
def xyz(self):
"""Positions of all grid points"""
return self.xyz_of_indices(self.indices)
def xyz_of_indices(self,indices):
"""XYZ coordinates of all grid points
indices: ? x N array of 0-based integers"""
o = self.origin
B = self.base_vectors
i = asarray(indices)
R = o + dot(B.T,i.T).T
return R
@property
def npoints(self):
"""total number of grid points"""
return product(self.n)
def point(self,i):
"""i: 0-based index"""
return self.xyz[i%self.npoints,:]
grid = Grid()
def asstring(x):
return repr(x).replace("\n","")
def index_list(dimensions):
"""All indices of all the element of an N x M x ... array
dimensions: tuple (M,N,...)"""
return indices(dimensions).reshape(len(dimensions),product(dimensions)).T
def calibrate_grid_from_saved_positions():
"""Use 'saved motor positons' panel to get calirbation points"""
from fast_diffractometer_saved_positions import saved_positions
grid.clear_support_points()
for i in range(0,saved_positions.nrows):
description = saved_positions.description(i)
if description.startswith("Chip "):
indices = eval(description.replace("Chip ",""))
xyz = saved_positions.position(i)[0:3]
grid.add_support_point(indices,xyz)
if not grid.has_sufficient_support_points:
print("grid: insufficient support points")
grid.fit()
if __name__ == "__main__":
"""for testing"""
self = grid # for debugging
def debug(x): print(x) # for debugging
def xyz(description): return saved_positions.position(description)[0:3]
from id14 import SampleX,SampleY,SampleZ
def current_xyz(): return SampleX.value,SampleY.value,SampleZ.value
def goto((x,y,z)): SampleX.value,SampleY.value,SampleZ.value = x,y,z
print 'grid.n = [8,8,6,6]'
print 'calibrate_grid_from_saved_positions()'
print 'grid.support_indices'
print 'grid.support_xyz'
print 'grid.has_sufficient_support_points'
print 'grid.origin'
print 'grid.base_vectors'
print 'goto(grid.point(0))'
print 'goto(grid.xyz_of_indices([0,0,0,0]))'
print 'goto(grid.xyz_of_indices([5,5,5,5]))'
print """grid.base_vectors = array([
[0, 2.000, 0 ],
[0, 0 , 2.000],
[0, 0.178, 0 ],
[0, 0 , 0.178]])"""
print "grid.origin = array([-3.461,-7.170,-6.396])"
<file_sep># -*- coding: utf-8 -*-
from __future__ import with_statement
"""
This Python Module is for Programming the Hamilton PSD3 Syringe
Drive Module
<NAME>, <NAME>, <NAME>,
11 May 2008 - 14 Mar 2018
PSD3 is jumper-configured to use the Hamilton "Protocol 1/RNO+"
command set, which is used for intruments manufactured by Hamilton
company (diluters,syringe modules,valve positioners).
In this mode device addresses are set automatically,
but the first time after power up the command "1a" needs to
be sent to assign addresses. The PSD3 as first device gets
the address "a".
The RS-232 settings are baud 9600, 7 data bits parity odd,
stop bits: 1, flow control: none. There are no specific
jumpers that configure the RS-232 settings. The settings are
implied by the jumper selecting "Protocol 1/RNO+".
(for the PSD3: dip switches 2-5 all up)
Each command needs to start with an address "a" and terminated
with a <CR>. The command is echoed back, including the carriage
return. If the command does not generate a response, the
reply is only <ACK><CR> (ACK = acknowledge, ASCII 6).
If the command generates a response, the response is preceeded
by <ACK> and terminates with <CR>.
In case of an error they replay is <NAK> (negative acknowledge,
ASCII 21), rather than <ACK>.
The stoke of the Syringe pump is 30 mm which is divided into 1000 steps
with a 1.25 ml syringe, the step size is 1.25 μL
Dead volume of the 8-port valve is 27.4 μL.
Setup:
- Install Pyserial package
http://pypi.python.org/pypi/pyserial
- Install driver for USB-Serial cable, model Prolific PL2303
Mac OS X Driver:
http://www.prolific.com.tw/US/ShowProduct.aspx?p_id=229&pcid=41
In Console, All Messages, the message "PL-2303/X V1.5.1 start, Prolific"
should be generated when the USB-serial cable is connected to the computer,
and the file /dev/tty.usbserial created.
- Assign the communiation port name:
syringe_pump_driver.serial_port_name = "COM4:"
- Create a Desktop shortcut, named "Syringe Pump IOC"
Target: C:\Python27\python.exe syringe_pump.py run_server
Start in: "Z:\All Projects\APS\Instrumentation\Software\Lauecollect"
Usage:
To determine the port being used, execute:
syringe_pump_driver.serial_port_name
syringe_pump2_driver.serial_port_name
To change the port to COM4, execute:
syringe_pump_driver.serial_port_name = "COM3:"
syringe_pump2_driver.serial_port_name = "COM4:"
send("aXR") - Initializes the PSD3
ask("aYQP") - tell the current syringe position in steps
send("aM100R") - moves syringe to abolute position 100 steps
move(In,100,10) - loads from the input port (0) 100 μL at a speed of 10 μL/s
Jumper Settings: PSD3: 1-5 all up
Cabling: NIH-Instrumentation MacBook, USB port -> 3-port USB hub
port 2 -> Prolific 2303 USB-Serial cable -> PSD3 #1 Com-In
port 3 -> Prolific 2303 USB-Serial cable -> PSD3 #2 Com-In
After power cycling the pump, need to execute the command "set_defaults" or rerun
this script.
To use as stand-alone application, run "run_server()" in the console, then
run init()
To operate both syringe pumps synchronously:
p1.volume (returns volume of pump1)
p2.volume (returns volume of pump2)
pc.V (returns combined volume of two pumps)
pc.dV (returns differential volume between two pumps)
p1.volume = 125 (sets volume of pump1 to 125 uL)
p1.volume += 10 (moves pump1 by +10 uL)
"""
from numpy import nan,isnan,ceil
import struct
from thread import allocate_lock,start_new_thread
__version__ = "5.9" # run_server, start_server, stop_server
# Calibration constants
V_syringe = 125.0 # Total capacity of the syringe in uL
syringe_stroke = 30.0 # This linear stroke in mm corresponds to the volume.
# Volume needed to bring sample into the position.
V_center=50 # The length of the fused silica tubing with ID=325μm and
# OD=435μm is 40 cm on both sides (~35μL)
# Volume needed to recover unexposed sample
V_unload=40
# Total volume between the sample port and the syringe (μL).
V_dead=100
# Syringe backoff volume
V_backoff=30
# Syringe Speed
# Three different speeds are used to support various operations. When loading
# liquid samples, S_slow is used. When drawing solutions into the syringe,
# S_medium is used. When emptying the syringe, S_fast is used.
S_slow=0.6 # Slow syringe plunger speed is set to 1 μL/s.
S_medium=5 # Medium syringe plunger speed is set to 5 μL/s.
S_fast=100 # Fast syringe plunger speed is set to 100 μL/s.
# Port Assignment for Syringe Pump
In = "In" # left port labelled "In" for loading the sample
Out = "Out" # right port labelled "Out" for dumping the waste
# Syringe motor parameters
motor_stepsize = syringe_stroke/30000 # mm
maxsteps = syringe_stroke/motor_stepsize*1.05 # high limit of travel in motor steps
V_step = V_syringe/syringe_stroke*motor_stepsize # μL
# Procedural Interface (for backward-compatibility)
def init():
"""This runs the initialization sequence for the pump.
It is needed after power on.
The pump drives the plunger against the
end stop while opening the ouput valve and sets the absolute
position to zero."""
syringe_pump.initialized = True
log_command("init()")
wait()
def init2():
"""This runs the initialization sequence for two pumps.
It is needed after power on.
The pump drives the plunger against the
end stop while opening the ouput valve and sets the absolute
position to zero."""
syringe_pump_combined.initialized = True
log_command("init2()")
wait()
def reload():
"""This sequence reloads the oil for P1 and P2 : Laue oil reload"""
P1.port = 'Out'
P2.port = 'Out'
while(P1.moving or P2.moving): sleep(0.1)
P1.speed = 10
P2.speed = 10
P1.volume = 0
P2.volume = 0
while(P1.moving): sleep(0.1)
P1.speed = 2
P1.volume = 125
while(P2.moving): sleep(0.1)
P1.port = 'In'
P2.speed = 2
P2.volume = 131.25-125
while(P1.moving or P2.moving): sleep(0.1)
P2.port = 'In'
def bubble_remover():
P1.port = 'In'
P2.port = 'In'
while(P1.moving or P2.moving): sleep(0.1)
P2.speed = 1
P1.speed = 1
P1.volume -= 5
sleep(3)
P2.volume += 5
while(P1.moving or P2.moving): sleep(0.1)
def flush():
P1.port = 'Out'
P2.port = 'Out'
while(P1.moving or P2.moving): sleep(0.1)
P1.speed = 10
P2.speed = 4
P1.volume = 0
P2.volume = 130
while(P1.moving or P2.moving): sleep(0.1)
P1.port = 'In'
P2.port = 'In'
while(P1.moving or P2.moving): sleep(0.1)
PC.speed = 2
PC.V = 130
while(P1.moving or P2.moving): sleep(0.1)
P1.port = 'Out'
P2.port = 'Out'
while(P1.moving or P2.moving): sleep(0.1)
P1.speed = 10
P2.speed = 2
P1.volume = 0
P2.volume = 131.25-125
while(P1.moving or P2.moving): sleep(0.1)
P1.speed = 2
P1.volume = 125
while(P1.moving or P2.moving): sleep(0.1)
P1.port = 'In'
P2.port = 'In'
def inflate(s, v):
"""infalte (v: positive) or deflate tubing """
P1.port = 'In'
P2.port = 'In'
while(P1.moving or P2.moving): sleep(0.1)
PC.speed = s
PC.dV += v
while(P1.moving or P2.moving): sleep(0.1)
def flow(t,r,s,v):
"""deflate tube by starting P2 't' seconds before P1;
'r' is ratio of s2/s1 flow rates; s is the speed of P2;
v is volume of P2"""
P1.port = 'In'
P2.port = 'In'
while(P1.moving or P2.moving): sleep(0.1)
P2.speed = s
P1.speed = s/r
P2.volume += v
sleep(t)
#P1.volume -= (v-t*s)/r
P1.volume -= v/r
while(P1.moving or P2.moving): sleep(0.1)
def deliver_old(v1,v2,s1,s2,t):
"""This sequence pushes the plunger of syringe pump 1 by volume v at
speed s and then reloads the syringe"""
p1.port = 'In'
p2.port = 'In'
wait()
p1.speed = s1
p2.speed = s2
wait()
p2.volume -= v2
sleep(t)
p1.volume -= v1
sleep (v2/float(s2)+2.)
p1.port = 'Out'
p2.port = 'Out'
wait()
p1.speed = 10
p2.speed = 10
wait()
p1.volume = 40
p2.volume = 125
wait()
p1.port = 'In'
p2.port = 'In'
def deliver(v1,v2,s1,s2):
"""This sequence pushes the plunger of syringe pump 1 by volume v at
speed s and then reloads the syringe"""
#p1.port = 'In'
p2.port = 'In'
wait()
p1.speed = s1
p2.speed = s2
wait()
p2.volume -= v2
#sleep(t)
p1.volume -= v1
#sleep (v2/float(s2)+2.)
#print "p1.volume = ", p1.volume
#print "p2.volume = ", p2.volume
#p1.port = 'Out'
#p2.port = 'Out'
#wait()
#p1.speed = 10
#p2.speed = 10
#wait()
#p1.volume = 40
#p2.volume = 125
#wait()
#p1.port = 'In'
#p2.port = 'In'
def dispense(v1,v2,s1,s2,b):
"""This sequence pushes the plunger of syringe pumps 1 and 2 by volume v1 and v2 at
speeds s1 and s2, and backs off after the move to relieve the pressure"""
P1.stop()
P2.stop()
#p1.port = 'In'
P2.port = 'In'
while(P1.moving or P2.moving): sleep(0.1)
P1.speed = 1
P2.speed = 1
P1.volume -= b
P2.volume -= b
while(P1.moving or P2.moving): sleep(0.1)
P1.speed = s1
P2.speed = s2
P1.volume -= v1
P2.volume -= v2
while(P1.moving or P2.moving): sleep(0.1)
P1.speed = 1
P2.speed = 1
P1.volume += b
P2.volume += b
def deliver2(v,s):
"""This sequence pushes the plunger of syringe pump 2 by volume v at
speed s and then reloads the syringe"""
p2.port = 'In'
sleep(2)
p2.speed = s
sleep(2)
p2.volume -= v
sleep (v/float(s)+2.)
p2.port = 'Out'
sleep(3)
p2.speed = 10
sleep(2)
p2.volume = 125
sleep((125-p2.volume)/10.+2.)
p2.port = 'In'
def deliver1(v,s):
"""This sequence pushes the plunger of syringe pump 1 by volume v at
speed s """
#p1.port = 'In'
#wait()
p1.speed = s
wait()
p1.volume -= v
#wait()
#sleep (v/float(s)+2.)
#p1.port = 'Out'
#wait()
#p1.speed = 10
#wait()
#p1.volume = 40
#wait()
#p1.port = 'In'
def move(n,l,m):
""" With the valve set to position n, move syringe plunger by l μL at a speed
of m μL/s. Positive move fills the syringe; negative move empties it.
When n = In, valve connects to upstream (Port valve) direction;
when n = Out, valve connects to downstream (Waste container) direction.
"""
log_command("move(%r,%r,%r)" % (n,l,m))
select_syringe_port(n)
set_speed(m)
V = volume()
if isnan(V):
log_error("move(%r,%r,%r): volume unreadable, command not executed" % (n,l,m));
return
set_volume(V+l,m)
def empty(): # 6 seconds
"""Empties the syring pump to the output port"""
log_command("empty()")
select_syringe_port(Out)
set_speed(S_fast)
set_volume(0)
set_volume(V_backoff)
select_syringe_port(In)
# Basic commands
def select_syringe_port(port):
"""switches between input and output port of the syringe pump
port: "In" = left port, used to load sample,
"Out" = right port, used to dump waste"""
syringe_pump.port = port
wait(1)
set_port = select_syringe_port
def syringe_port():
"""Tell which of the three ports of the syring pump is currently active.
"In" = left port, used to load sample,
"Out" = right port, used to dump waste"""
return syringe_pump.port
port = syringe_port
def volume():
"""The current remaining volume of syringe, in units of μL"""
return syringe_pump.read_V
def set_volume(volume,speed=None):
"""Move the plunger until the volume is the given number of μL"""
dV = abs(volume-syringe_pump.setV)
if speed is not None: set_speed(speed)
else: speed = syringe_pump.speed
syringe_pump.setV = volume
wait(dV/speed)
def set_speed(speed):
"""Defines the syringe plunger speed in μL/s."""
syringe_pump.speed = speed
def speed():
"""Tell the currently configured syringe plunger speed in μL/s."""
return syringe_pump.speed
def stop():
"""Cancels current move or program."""
syringe_pump.moving = False
def wait(min_time=2.0):
"""Waits for the current move to complete."""
try:
sleep(min_time)
while busy(): sleep(0.1)
except KeyboardInterrupt:
stop()
raise KeyboardInterrupt
def busy():
"""Is either the syringe drive or valve currently moving?
Return value: True or False"""
return syringe_pump.moving != 0
def status():
"""Displays syringe pump status as clear text"""
code = syringe_pump.status_byte
print ((code>>0) & 1),"Instrument idle, command buffer not empty"
print ((code>>1) & 1),"Syringe Drive Busy"
print ((code>>2) & 1),"Valve Drive Busy"
print ((code>>3) & 1),"Syntax Error"
print ((code>>4) & 1),"Instrument error (valve or syringe)"
print ((code>>5) & 1),"Always 0"
print ((code>>6) & 1),"Always 1"
print ((code>>7) & 1),"Always 0"
def log_error(message):
"""For critical errors. Generate an entry in the error log."""
from sys import stderr,stdout
if len(message) == 0 or message[-1] != "\n": message += "\n"
stderr.write(message)
t = timestamp()
if syringe_pump.log_all: file(error_logfile(),"a").write("%s: %s" % (t,message))
def log_command(message):
"""Add command to command history"""
from sys import stderr,stdout
if len(message) == 0 or message[-1] != "\n": message += "\n"
t = timestamp()
if syringe_pump.log_all: file(command_logfile(),"a").write("%s: %s" % (t,message))
def command_logfile():
"""File name error messages."""
from tempfile import gettempdir
return gettempdir()+"/syringe_commands.log"
def error_logfile():
"""File name error messages."""
from tempfile import gettempdir
return gettempdir()+"/syringe_pump_error.log"
def sleep(dt):
"""Like time.sleep, but interruptable with Control-C.
dt: time in seconds"""
from time import sleep,time
end = time()+dt
while time() < end:
sleep(min(end-time(),0.1))
class SyringePump(object):
"""Hamilton PSD3 Syringe Drive"""
attempts = 5 # Attempts to repeat a command in case it failed, must be >0.
verbose_logging = False # Display log messages in terminal.
log_all = False # Log all communication to a file.
serial_port = None # serial port object
defaults_set = False
from persistent_property import persistent_property
def __init__(self,name="syringe_pump"):
"""name: string"""
self.name = name
# This is to make the query method multi-thread safe.
self.lock = allocate_lock()
def get_serial_port_name(self):
"""Which serial port to use to communication with the pump?
"COM4" for NIH MacBook running Windows
"14IDB:serial16" for BioCARS, VME crate
"14IDB-NIH:serial7" for NIH Linux box
"""
from DB import dbget
port_name = dbget(self.name+".serial_port")
if port_name == "": port_name = "COM4"
return port_name
def set_serial_port_name(self,value):
from DB import dbput
dbput(self.name+".serial_port",value)
serial_port_name = property(get_serial_port_name,set_serial_port_name)
def init_defaults(self):
"""Sets default settings, if not done already"""
if not self.defaults_set: self.set_defaults()
def set_defaults(self):
"""Sets default settings"""
# 1a = use auto-address mode
# after this, the first device, the syring pump is assigned the address "a"
# and the second device, the valve positionioner the address "b"
self.send("1a")
self.send("1a") # In case the first command failed.
# The speed of the backlash correction is still too fast.
# Turn off the backlash correction by setting it to 0 steps (default 6).
self.send("aYSN0")
self.defaults_set = True
def init(self):
"""This runs the initialization sequency for the PSD3 and MVP.
It is needed after power on.
The PSD3 drives the plunger against the
end stop while opening the ouput valve and sets the absolute
position to zero.
The MVP rotates its valve by one turn and stops at position 1."""
self.set_defaults()
self.speed = S_fast #S_fast
# Turn off "backoff" during the "init" sequence by setting is to 0 steps
self.send("aYSB30")
self.send("aYSM5") # full resultion + high resolution step mode: 30,000 steps
self.send("aXR") # initialize PSD3
def get_initialized(self):
"""Has the initialization sequence been run?"""
return not isnan(self.volume)
def set_initialized(self,value):
if value: self.init()
initialized = property(get_initialized,set_initialized)
def get_readback_volume(self):
"""The current remaining volume of syringe, in units of μL"""
for attempt in range(0,self.attempts):
reply = self.ask("aYQP")
if reply == "":
self.log_error("Volume: no reply (attempt %d/%d)"
% (attempt+1,self.attempts))
continue
try: nsteps = int(reply)
except ValueError:
self.log_error("Volume: expecting numeric string, got %r (attempt %d/%d)"
% (reply,attempt+1,self.attempts))
continue
volume = nsteps*V_step # Convert from motor steps to μL.
self.log("Volume: Read %g uL" % volume)
return volume
self.log_error("Volume: read failed (after %d attempts)" % self.attempts)
return nan
readback_volume = property(get_readback_volume)
read_V = readback_volume # shortcut
def get_command_volume(self):
"""The target volume of the last move, in units of uL"""
if not hasattr(self,"last_command_volume"): return self.readback_volume
return self.last_command_volume
def set_command_volume(self,volume):
"""Move the plunger until the volume is the given number of μL"""
nsteps = round(volume/V_step) # convert from μL to motor steps
volume = nsteps*V_step
if nsteps < 0: nsteps = 0
if nsteps > maxsteps: nsteps = maxsteps
self.send("aM%dR" % nsteps) # M = move absolute
volume = nsteps*V_step
self.last_command_volume = volume
command_volume = property(get_command_volume,set_command_volume)
setV = command_volume # shortcut
command_dial = command_volume
volume = property(get_readback_volume,set_command_volume)
V = volume # shortcut
dial = volume
def get_value(self): return self.user_from_dial(self.dial)
def set_value(self,value): self.dial = self.dial_from_user(value)
value = property(get_value,set_value)
def get_command_value(self): return self.user_from_dial(self.command_dial)
def set_command_value(self,value): self.command_dial = self.dial_from_user(value)
command_value = property(get_command_value,set_command_value)
min_dial = persistent_property("min_dial",0.0)
max_dial = persistent_property("max_dial",maxsteps*V_step)
def get_min(self):
if self.sign>0: return self.user_from_dial(self.min_dial)
else: return self.user_from_dial(self.max_dial)
def set_min(self,value):
if self.sign>0: self.min_dial = self.dial_from_user(value)
else: self.max_dial = self.dial_from_user(value)
min = property(get_min,set_min)
def get_max(self):
if self.sign>0: return self.user_from_dial(self.max_dial)
else: return self.user_from_dial(self.min_dial)
def set_max(self,value):
if self.sign>0: self.max_dial = self.dial_from_user(value)
else: self.min_dial = self.dial_from_user(value)
max = property(get_max,set_max)
def user_from_dial(self,value): return value * self.sign + self.offset
def dial_from_user(self,value): return (value - self.offset) / self.sign
sign = persistent_property("sign",1)
offset = persistent_property("offset",0.0)
def get_port(self):
"""Which of the three ports of the syring pump is currently active.
"In" = left port, used to load sample,
"Out" = right port, used to dump waste"""
port = "?"
for attempt in range(0,self.attempts):
reply = self.ask("aLQP")
if reply == '4': port = "Out"
if reply == '1': port = "In"
if port != "?": self.log("Port: %r" % port); return port
self.log_error("Port: got reply %r (attempt %d/%d)" %
(reply,attempt+1,self.attempts))
self.log_error("Port read failed (after %d attempts)" % self.attempts)
return "?"
def set_port(self,port):
"""Switche between input and output port of the syringe pump
port: "In" = left port, used to load sample,
"Out" = right port, used to dump waste"""
if port == "In": self.send("aIR")
elif port == "Out": self.send("aOR")
else: return
port = property(get_port,set_port)
def get_speed(self):
"""Currently configured syringe plunger speed in μL/s."""
# YQS = request syringe drive speed, parameter = divisor of 1000 steps/s
for attempt in range(0,self.attempts):
reply = self.ask("aYQS")
if reply == "":
self.log_error("Speed: no reply (attempt %d/%d)"
% (attempt+1,self.attempts))
continue
try: step_rate = float(reply)
except ValueError:
self.log_error("Speed: expecting numeric string, got %r (attempt %d/%d)"
% (reply,attempt+1,self.attempts))
continue
full_stroke_steps = syringe_stroke/motor_stepsize
speed = full_stroke_steps*V_step/float(step_rate)
self.log("Speed: Read %g uL/s" % speed)
return speed
self.log_error("Speed read failed (after %d attempts)" % self.attempts)
return nan
def set_speed(self,speed):
"""Change plunger speed. Unit: μL/s."""
steps_per_s = speed/V_step
full_stroke_steps = syringe_stroke/motor_stepsize
# YSS = set syringe speed, parameter = divisor of 1000 steps/s
step_rate = round(full_stroke_steps/steps_per_s)
self.send("aYSS%d" % step_rate)
speed = property(get_speed,set_speed)
@property
def firmware_version(self):
"""Firmware version"""
return self.ask("aU")
def stop(self):
"""Cancels current move or program."""
self.send("aKR")
if hasattr(self,"last_command_volume"): del self.last_command_volume
def wait(self):
"""Waits for the current move to complete."""
while self.moving: sleep(0.1)
def get_moving(self):
"""Are either the syringe drive or valve currently busy?"""
x = self.status_byte
if x == 0: return True # read failed, assume moving
# Instrument status byte: bit 1 = syringe drive, 2 = valve drive
moving = (((x>>1) & 1) or ((x>>2) & 1)) != 0
self.log("Moving: %r" % moving)
return moving
def set_moving(self,moving):
if not moving: self.stop()
moving = property(get_moving,set_moving)
@property
def status_byte(self):
"""Instrument status byte"""
for attempt in range(0,self.attempts):
reply = self.ask("aE1")
if reply == "":
self.log_error("Status byte: no reply (attempt %d/%d)"
% (attempt+1,self.attempts))
continue
if len(reply) != 1:
self.log_error("Status byte: expecting 1 char, got %r (attempt %d/%d)"
% (reply,attempt+1,self.attempts))
continue
status_byte, = struct.unpack("B",reply)
self.log("Status byte: %d" % status_byte)
return status_byte
self.log_error("Status byte read failed (after %d attempts)" % self.attempts)
return 0
def send(self,command):
"""Transmit an RS-232 command to the syringe pump, which does not generate a
reply"""
reply = self.ask(command)
if reply:
self.log_error("Info: Command %r generated unexpected reply %r." %
(command,reply))
def ask(self,command):
"""Transmit an RS-232 command to the syringe pump, which generates a reply
and return the reply"""
self.init_communication()
if self.serial_port is None: return ""
if command == "" or command[-1] != "\r": command += "\r"
reply = self.query(command)
if reply == "":
self.log_error("Info: Command %r was not echoed." % command); return ""
if reply.find(command) > 0:
self.log_error("Ignoring extra %r at beginning of %r"\
% (reply[0:reply.find(command)],reply))
if reply.find(command) == -1:
self.log_error("Command %r: expecting echo, got %r" % (command,reply))
return ""
reply = reply[reply.find(command)+len(command):] # remove echo of coinit_communicationmmand
if reply == "":
self.log_error("Command %r not acknowledged." % command); return ""
if reply[0] == chr(21):
self.log_error("Command %r failed." % command); return ""
if reply[0] != chr(6):
self.log_error("Command %r: expecting %r, got %r." %
(command,chr(6),reply[0]))
return ""
reply = reply[1:] # remove <ACK> character.
reply = reply.strip("\r")
if reply: self.log("Command %r, reply %r." % (command,reply))
else: self.log("Command %r, no reply." % command)
return reply
def query(self,command):
"""Send a command to the controller and return the reply"""
with self.lock: # Allow only one thread at a time inside this function.
if hasattr(self.serial_port,"query"):
reply = self.serial_port.query(command)
else:
self.serial_port.write(command)
reply = self.serial_port.read(80)
# Worzk-around for a bug in OS X where te parity bit for odd parity
# is not stripped by the "pyserial" driver.
reply = string_7bit(reply)
return reply
def init_communication(self):
"""Initializes the RS-323 communication"""
if self.serial_port is not None and \
self.serial_port.port == self.serial_port_name: return
if self.serial_port_name.startswith("COM") or \
self.serial_port_name.startswith("/dev/"):
# Assume local port
from serial import Serial
else: from EPICS_serial_CA import Serial
try: self.serial_port = Serial(self.serial_port_name)
except Exception,msg:
self.log_error("serial port %s: %s" % (self.serial_port_name,msg))
return
self.serial_port.baudrate = 9600
self.serial_port.bytesize = 7
self.serial_port.parity = "O"
self.serial_port.stopbits = 1
self.serial_port.rtscts = 0 # Hardware flow control: off
self.serial_port.xonxoff = 0 # Software flow control: off
self.serial_port.dsrdtr = None # Modem handshake: off
self.serial_port.timeout = 0.1
def log(self,message):
"""For non-critical messages.
Timestamp message and append it to the log file"""
from sys import stderr,stdout
if len(message) == 0 or message[-1] != "\n": message += "\n"
t = timestamp()
if self.verbose_logging: stdout.write("%s: Syringe pump: %s" % (t,message))
if self.log_all: file(self.logfile,"a").write("%s: %s" % (t,message))
def log_error(self,message):
"""For error messages.
Display the message and append it to the error log file."""
from sys import stderr
if len(message) == 0 or message[-1] != "\n": message += "\n"
t = timestamp()
stderr.write("%s: Syringe pump: %s" % (t,message))
file(self.error_logfile,"a").write("%s: %s" % (t,message))
if self.log_all: file(self.logfile,"a").write("%s: %s" % (t,message))
def log_command(self,message):
"""Add command to command history"""
from sys import stderr,stdout
if len(message) == 0 or message[-1] != "\n": message += "\n"
t = timestamp()
if self.log_all: file(self.command_logfile,"a").write("%s: %s" % (t,message))
@property
def error_logfile(self):
"""File name error messages."""
from tempfile import gettempdir
return gettempdir()+"/syringe_pump_error.log"
@property
def logfile(self):
"""File name for transcript if verbose logging is enabled."""
from tempfile import gettempdir
return gettempdir()+"/syringe_pump.log"
@property
def command_logfile(self):
"""File name error messages."""
from tempfile import gettempdir
return gettempdir()+"/syringe_commands.log"
def timestamp():
"""Current date and time as formatted ASCCI text, precise to 1 ms"""
from datetime import datetime
timestamp = str(datetime.now())
return timestamp[:-3] # omit microsconds
def isnan(x):
from numpy import isnan
try: return isnan(x)
except TypeError: return True
def number_of_ones(n):
"""number of 1 bits in the number n"""
c = 0
while n:
c += n%2
n /= 2
return c
def parity(n):
"""even: 0, odd: 1"""
return number_of_ones(n) % 2
def odd_parity(string):
"""Which of te characters in string have odd parity?"""
return [parity(ord(c)) for c in string]
def string_7bit(string):
"""Strip hte highest bit of evey character in string"""
s = ""
for c in string: s += chr(ord(c) & 0x7f)
return s
syringe_pump_driver = SyringePump("syringe_pump")
syringe_pump2_driver = SyringePump("syringe_pump2")
class SyringePumpCombined(object):
"""Move two syringe pumps synchronously"""
def __init__(self,name,p1,p2):
"""name: string
p1,p2: syringe_pump instances"""
self.name = name
self.p1 = p1
self.p2 = p2
def get_read_V(self):
"""in units of μL"""
V = (self.p1.value + self.p2.value)/2
return V
read_V = property(get_read_V)
def get_V(self):
"""in units of μL"""
return self.V_from_V1_V2(self.p1.command_value,self.p2.command_value)
def set_V(self,V):
self.p2.speed = self.p1.speed
V1,V2 = self.V1_V2_from_V(V)
# The two commands need to be executed simultaneouly.
start_new_thread(setattr,(self.p1,"command_value",V1))
start_new_thread(setattr,(self.p2,"command_value",V2))
V = property(get_V,set_V)
def get_V_min(self):
"""in units of μL"""
V1_lim,V2_lim = [self.p1.min,self.p1.max],[self.p2.min,self.p2.max]
dV_min = min([self.V_from_V1_V2(V1,V2) for V1 in V1_lim for V2 in V2_lim])
return dV_min
def set_V_min(self,V_min):
self.p1.min,self.p2.min = self.V1_V2_from_V(V_min)
V_min = property(get_V_min,set_V_min)
def get_V_max(self):
"""in units of μL"""
V1_lim,V2_lim = [self.p1.min,self.p1.max],[self.p2.min,self.p2.max]
dV_max = max([self.V_from_V1_V2(V1,V2) for V1 in V1_lim for V2 in V2_lim])
return dV_max
def set_V_max(self,V_max):
self.p1.max,self.p2.max = self.V1_V2_from_V(V_max)
V_max = property(get_V_max,set_V_max)
def V_from_V1_V2(self,V1,V2):
V = (V1+V2)/2
return V
def V1_V2_from_V(self,V):
dV = V - self.V
V1 = self.p1.command_value + dV
V2 = self.p2.command_value + dV
return V1,V2
def get_read_dV(self):
"""in units of μL"""
V = self.p2.value - self.p1.value
return V
read_dV = property(get_read_dV)
def get_dV(self):
"""in units of μL"""
return self.dV_from_V1_V2(self.p1.command_value,self.p2.command_value)
def set_dV(self,dV):
self.p2.speed = self.p1.speed
V1,V2 = self.V1_V2_from_dV(dV)
# The two commands need to be executed simultaneouly.
start_new_thread(setattr,(self.p1,"command_value",V1))
start_new_thread(setattr,(self.p2,"command_value",V2))
dV = property(get_dV,set_dV)
def get_dV_min(self):
"""in units of μL"""
V1_lim,V2_lim = [self.p1.min,self.p1.max],[self.p2.min,self.p2.max]
dV_min = min([self.dV_from_V1_V2(V1,V2) for V1 in V1_lim for V2 in V2_lim])
return dV_min
def set_dV_min(self,dV_min):
self.p1.min,self.p2.min = self.V1_V2_from_dV(dV_min)
dV_min = property(get_dV_min,set_dV_min)
def get_dV_max(self):
"""in units of μL"""
V1_lim,V2_lim = [self.p1.min,self.p1.max],[self.p2.min,self.p2.max]
dV_max = max([self.dV_from_V1_V2(V1,V2) for V1 in V1_lim for V2 in V2_lim])
return dV_max
def set_dV_max(self,V_max):
self.p1.max,self.p2.max = self.V1_V2_from_dV(V_max)
dV_max = property(get_dV_max,set_dV_max)
def dV_from_V1_V2(self,V1,V2):
dV = V2 - V1
return dV
def V1_V2_from_dV(self,dV):
ddV = dV - self.dV
V1 = self.p1.command_value - ddV/2
V2 = self.p2.command_value + ddV/2
return V1,V2
def get_speed(self):
"""Currently configured syringe plunger speed in μL/s."""
return self.p1.speed
def set_speed(self,speed):
self.p1.speed = speed
self.p2.speed = speed
speed = property(get_speed,set_speed)
def get_initialized(self):
"""Currently configured syringe plunger initialized in μL/s."""
return self.p1.initialized and self.p2.initialized
def set_initialized(self,initialized):
start_new_thread(setattr,(self.p1,"initialized",initialized))
start_new_thread(setattr,(self.p2,"initialized",initialized))
initialized = property(get_initialized,set_initialized)
syringe_pump_combined_driver = SyringePumpCombined("syringe_pump_combined",
syringe_pump_driver,syringe_pump2_driver)
def run_server():
"""Serve the Syringe pump up on the network as EPCIS IOC.
Keep running forever."""
from time import sleep
start_server()
while True: sleep(0.25)
def start_server():
"""Serve the Syringe pump up on the network as EPCIS IOC.
Return control when started."""
import CAServer
CAServer.verbose = False
CAServer.verbose_logging = False
print("log: %s" % CAServer.logfile())
for obj in syringe_pump_driver,syringe_pump2_driver,\
syringe_pump_combined_driver:
CAServer.register_object(obj,"NIH:"+obj.name)
def stop_server():
"""Serve the Syringe pump up on the network as EPCIS IOC.
Return control when started."""
import CAServer
print("stopping server")
for obj in syringe_pump_driver,syringe_pump2_driver,\
syringe_pump_combined_driver:
CAServer.unregister_object(obj,"NIH:"+obj.name)
from CA import Record
syringe_pump = Record("NIH:syringe_pump")
syringe_pump2 = Record("NIH:syringe_pump2")
syringe_pump_combined = Record("NIH:syringe_pump_combined")
# Shortcuts:
p = p1 = syringe_pump
p2 = syringe_pump2
pc = syringe_pump_combined
P = P1 = syringe_pump_driver
P2 = syringe_pump2_driver
PC = syringe_pump_combined_driver
##p2.log_all = False
##p1.log_all = False
if __name__ == "__main__":
from pdb import pm
from sys import argv
if "run_server" in argv:
run_server()
from time import sleep
while True: sleep(0.1)
self = PC # for debugging
print('start_server()')
print('stop_server()')
import threading
print('threading.enumerate()')
<file_sep>"""
ILX Lightwave LDT-5948 Precision Temperature Controller
<NAME>, 14 Dec 2009 - Jul 5, 2017
Communication Paramters: 115200 baud, 8 data bits, 1 stop bit, parity: none
flow control: none
2 = TxD, 3 = RxD, 5 = Gnd (DCE = Data Circuit-terminating Equipment)
9600 baud is the factory setting, but can be changed from the fron panel:
MAIN/LOCAL - COMMUNICATION 1/7 - down - RS323 Baud
Possible baud rates are: 1200, 2400, 4800, 9600, 19200, 38400, 57600, 115200,
and 230400.
The controller accpts ASCII text commands. Each command needs to by terminated
with a newline or carriage return character.
Replies are terminated with carriage return and newline.
Command that are not queries generate the reply "Ready".
If a query is not understood, the controller replies with "Ready" as well.
Commands:
*IDN? identification, expecting: "ILX Lightwave,LDT-5948,59481287,01.02.06"
MEASure:Temp? - Report the actual temperature.
SET:Temp? - Report the temperature set point.
SET:Temp 37.0 - Change temperature set point to 37 degrees C.
MEASure:PTE? - Read heater power in W
Cabling: VME crate "iocidb", back panel "14IDB:serial1" -> STRAIGHT TRU
adapter -> black ethernet cable -> STRAIGHT TRU adapter ->
temperature controller
Documentation:
LDT-5900 Series Temperature Controllers User's Guide
www.newport.com/medias/sys_master/images/images/h75/h4e/8797193273374/LDT-59XX-User-Manual.pdf
"""
from __future__ import with_statement
from persistent_property import persistent_property
from logging import warn,debug,info,error
__version__ = "3.0.9" # multi-thread safe history
class Lightwave_Temperature_Controller(object):
"""ILX Lightwave LDT-5948 precision temperature controller"""
name = "lightwave_temperature_controller"
verbose_logging = True
last_reply_time = 0.0
max_time_between_replies = 0.0
def __init__(self):
# Make multithread safe
from thread import allocate_lock
self.__lock__ = allocate_lock()
# When read, read actual temperature, when changed, change set point.
self.actual_temperature = self.property_object(self,"MEAS:T",unit="C",
name="Temperature")
self.nominal_temperature = self.property_object(self,"SET:TEMP",unit="C",
name="set-point")
self.heating_power = self.property_object(self,"MEASure:PTE",unit="W",
name="power")
self.current = self.property_object(self,"MEASure:ITE",unit="A",
name="current")
self.voltage = self.property_object(self,"MEASure:VTE",unit="V",
name="voltage")
# enabled: Is the feed-back loop for regulating the temperature active?
self.enabled = self.property_object(self,"OUTPUT",unit="",
name="enabled")
self.Tmin = self.property_object(self,"LIMIT:TEMP:LOW",unit="C",
name="low-limit")
self.Tmax = self.property_object(self,"LIMIT:TEMP:HIGH",unit="C",
name="high-limit")
self.temperature = self.temperature_object(self)
self.feedback_loop = self.feedback_loop_object(self)
self.status = self.status_object(self)
# Define some shortcuts.
self.T = self.temperature
self.setT = self.nominal_temperature
self.readT = self.actual_temperature
self.P = self.power = self.heating_power
self.I = self.current
self.U = self.voltage
self.on = self.enabled
def get(self,name):
"""Query the numeric value of a parameter.
name: e.g. 'SET:TEMP'"""
from numpy import nan
try: value = float(self.query(name+"?"))
except ValueError: value = nan
if abs(value) >= 9.8e+37: value = nan
##self.record_value(name,value)
return value
def set(self,name,value):
"""Change the value of a parameter.
name: e.g. 'SET:TEMP'"""
self.query("%s %s" % (name,value))
def __getitem__(self,name):
"""Usage: lightwave_temperature_controller['SET:TEMP']"""
return self.get(name)
def __setitem__(self,name,value):
"""Usage: lightwave_temperature_controller['SET:TEMP'] = 22.0"""
self.set(name,value)
def query(self,command):
"""Send a command to the controller and return the reply"""
if not command.endswith("\n"): command = command+"\n"
with self.__lock__: # multithread safe
for attempts in range(0,3):
reply = self.__query__(command)
error = "?" in command and "Ready" in reply
if not error: break
sleep(0.1)
reply = reply.rstrip("\r\n")
return reply
def __query__(self,command):
"""Send a command to the controller and return the reply"""
self.write(command)
reply = self.readline()
return reply
def write(self,command):
"""Send a command to the controller"""
self.init_communications()
if self.port is not None:
self.port.write(command)
self.log_comm("Sent %r" % command)
def readline(self):
"""Read a reply from the controller,
terminated with either new line or carriage return"""
from time import time
if self.port is not None:
try: reply = self.port.readline()
except Exception,msg: warn("readline: %s" % msg); reply = ""
self.log_comm("Read %r" % reply)
else: reply = ""
if reply:
t = time()
self.max_time_between_replies = max(t-self.last_reply_time,self.max_time_between_replies)
self.last_reply_time = t
return reply
def init_communications(self):
"""To do before communncating with the controller"""
from os.path import exists
from serial import Serial
id_query = "*IDN?\n"
if self.port is not None:
try:
self.port.write(id_query)
reply = self.port.readline()
if not self.id_string in reply:
debug("Port %s: %r: reply %r" % (self.__port_name__,id_query,reply))
info("Port %s: lost connection" % self.__port_name__)
self.port = None
self.__port_name__ = ""
except Exception,msg:
debug("%s: %s" % (Exception,msg))
self.port = None
self.__port_name__ = ""
if self.port is None:
port_basename = "COM" if not exists("/dev") else "/dev/tty.usbserial"
for i in range(0,64):
port_name = port_basename+("%d" % i if i>0 else "")
debug("Trying port %s..." % port_name)
try:
temp = Serial(port_name,timeout=self.comm_timeout,
baudrate=self.baudrate.value)
temp.write(id_query)
reply = temp.readline()
debug("Port %s: %r: reply %r" % (port_name,id_query,reply))
if self.id_string in reply:
self.port = temp
self.__port_name__ = port_name
info("Port %s: found %s" % (port_name,self.id_string))
break
except Exception,msg: debug("%s: %s" % (Exception,msg))
id_string = "LDT-5948"
port = None
__port_name__ = ""
def get_port_name(self):
"""Serial port device filename"""
self.init_communications()
return self.__port_name__
def set_port_name(self,value): pass
port_name = property(get_port_name,set_port_name)
def get_id(self): return self.query("*IDN?")
def set_id(self,value): pass
id = property(get_id,set_id)
def instantiate(x): return x()
@instantiate
class baudrate(object):
"""Serial port EPICS record name"""
name = "temperature_contoller.baudrate"
value = persistent_property("value",9600)
def get_comm_timeout(self):
"""For scans, to provide feedback whether the temperature 'motor'
is still 'moving'"""
from DB import dbget
s = dbget("lightwave_temperature_controller.temperature.comm_timeout")
try: return float(s)
except: return 0.2
def set_comm_timeout(self,value):
from DB import dbput
dbput("lightwave_temperature_controller.temperature.moving_timeout",str(value))
comm_timeout = property(get_comm_timeout,set_comm_timeout)
class temperature_object(object):
"""For logging and scanning, can be used as counter"""
unit = "C"
name = "Temp."
def __init__(self,controller):
self.controller = controller
self.last_change = 0
# Define shortcuts
self.T = self.controller.actual_temperature
self.setT = self.controller.nominal_temperature
def get_value(self): return self.T.value
def set_value(self,value):
from time import time
self.controller.enabled.value = True
old_value = self.setT.value
self.setT.value = value
if value != old_value: self.last_change = time()
value = property(get_value,set_value)
@property
def values(self): return self.T.values
@property
def timestamps(self): return self.T.timestamps
@property
def RMS(self): return self.T.RMS
@property
def average(self): return self.T.average
def get_moving(self):
"""Has the actual temperature not yet reached the set point within
tolerance?
For scans, to provide feedback whether the temperature 'motor'
is still 'moving'"""
return self.T.moving
def set_moving(self,value):
"""If value = False, cancel the current temperature ramp."""
if abs(self.setT.value - self.T.value) > self.tolerance:
self.setT.value = self.T.value
moving = property(get_moving,set_moving)
def stop(self):
"""Cancel the current temperature ramp."""
self.moving = False
def get_timeout(self):
"""For scans, to provide feedback whether the temperature 'motor'
is still 'moving'"""
from DB import dbget
s = dbget("lightwave_temperature_controller.temperature.moving_timeout")
try: return float(s)
except: return 0.0
def set_timeout(self,value):
from DB import dbput
dbput("lightwave_temperature_controller.temperature.moving_timeout",str(value))
timeout = property(get_timeout,set_timeout)
def get_tolerance(self):
"""For scans, to provide feedback whether the temperature 'motor'
is still 'moving'"""
from DB import dbget
s = dbget("lightwave_temperature_controller.temperature.tolerance")
try: return float(s)
except: return 3.0
def set_tolerance(self,value):
from DB import dbput
dbput("lightwave_temperature_controller.temperature.tolerance",str(value))
tolerance = property(get_tolerance,set_tolerance)
def __repr__(self): return "lightwave_temperature_controller.temperature_object"
class property_object(object):
"""For logging and scanning, can be used as counter"""
from numpy import array
timestamps = array([])
values = array([])
# How long is the temperature log, in seconds?
history_length = persistent_property("history_length",300)
# Criteria for deciding whether the temperature has stabilized.
stabilization_time = persistent_property("stabilization_time",0.0) # seconds
stabilization_RMS = persistent_property("stabilization_RMS" ,0.0)
def __init__(self,controller,read,unit="",name="",write=""):
"""read: e.g. 'SET:TEMP?'.
If write is omitted, will use 'SET:TEMP' to write."""
self.controller = controller
self.read = read
self.unit = unit
self.name = name
self.write = write
if not self.read.endswith("?"): self.read += "?"
if self.write == "": self.write = self.read.rstrip("?")
# To make history multi-thread safe
from thread import allocate_lock
self.lock = allocate_lock()
def get_value(self):
from numpy import nan
try: value = float(self.controller.query(self.read))
except ValueError: value = nan
if abs(value) >= 9.8e+37: value = nan
self.record_value(value)
return value
def set_value(self,value):
self.controller.query("%s %s" % (self.write,value))
value = property(get_value,set_value)
def record_value(self,value):
with self.lock: # needs to be multi-thread safe
from time import time
from numpy import concatenate
timestamp = time()
# Make sure values and timestamp have the saame length (FS Oct 29, 2016)
N = min(len(self.values),len(self.timestamps))
self.values,self.timestamps = self.values[0:N],self.timestamps[0:N]
# Discard old values.
keep = self.timestamps >= timestamp-self.history_length
self.values,self.timestamps = self.values[keep],self.timestamps[keep]
# Ignore duplicates.
if len(self.values)>0 and value == self.values[-1]: return
self.values = concatenate((self.values,[value]))
self.timestamps = concatenate((self.timestamps,[timestamp]))
@property
def average(self):
from time import time
from numpy import average,nan
dt = self.stabilization_time
values = self.values[self.timestamps > time()-dt]
average = average(values) if len(values)>0 else nan
return average
@property
def RMS(self):
from time import time
from numpy import std,nan
dt = self.stabilization_time
values = self.values[self.timestamps > time()-dt]
RMS = std(values) if len(values)>0 else nan
return RMS
def get_moving(self):
"""Has the value been stable for some time?"""
moving = self.RMS > self.stabilization_RMS
return moving
def set_moving(self,value): pass
moving = property(get_moving,set_moving,doc="This is so it can be"
"scanned like a motor")
def stop(self): pass
class feedback_loop_object(object):
"""Feedback loop parameters.
P = proportional feedback constant
I = integralfeedback constant
D = differential feedback constant"""
def __init__(self,controller):
"""name: one of "P","I","D" """
self.controller = controller
self.unit = ""
self.P = self.parameter(self,"P")
self.I = self.parameter(self,"I")
self.D = self.parameter(self,"D")
def get_PID(self):
from numpy import nan
reply = self.controller.query("PID?")
try: P,I,D = eval(reply)
except: return nan,nan,nan
return round(P,4),round(I,4),round(D,4)
def set_PID(self,(P,I,D)):
self.controller.query("PID %s,%s,%s" % (P,I,D))
PID = property(get_PID,set_PID)
class parameter(object):
def __init__(self,feedback_loop,name):
self.feedback_loop = feedback_loop
self.name = name
def get_value(self):
P,I,D = self.feedback_loop.PID
if self.name == "P": return P
if self.name == "I": return I
if self.name == "D": return D
from numpy import nan
return nan
def set_value(self,value):
P,I,D = self.feedback_loop.PID
if self.name == "P": P = value
if self.name == "I": I = value
if self.name == "D": D = value
self.feedback_loop.PID = P,I,D
value = property(get_value,set_value)
def get_moving(self): return False
def set_moving(self,value): pass
moving = property(get_moving,set_moving,doc="This is so it can be"
"scanned like a motor")
def stop(self): pass
def __repr__(self):
return "lightwave_temperature_controller.feedback_loop."+self.name
def __repr__(self):
return "lightwave_temperature_controller.feedback_loop"
class status_object(object):
"""Diagnostics message"""
def __init__(self,controller):
self.controller = controller
def get_value(self):
"""Diagnostics message"""
reply = self.controller.query("OUTPUT?")
if len(reply) == 0: return "unresponsive"
if reply.strip() == "0": return "Off"
if reply.strip() == "1": return "On"
return "OUTPUT? %r" % reply
value = property(get_value)
@property
def stable(self):
"""Has temperature stabilized?"""
from numpy import array,std
dT = self.stabilization_threshold
nsamples = self.stabilization_nsamples
T = array(self.readT.values[-nsamples:])
setT = self.setT.value
if len(T) > 0:
stable = std(T) < dT and all(abs(T-setT) < dT)
else: stable = False
return stable
stabilization_threshold = persistent_property("stabilization_threshold",0.01)
stabilization_nsamples = persistent_property("stabilization_nsamples",3)
@property
def TIU(self):
"""Temperature, current and voltage, measured simultanously"""
from numpy import nan
reply = self.query("MEAS:T?; MEASure:ITE?; MEASure:VTE?")
try: TIU = eval(reply.replace(";",","))
except: TIU = nan,nan,nan
return TIU
@property
def TIP(self):
"""Temperature, current and power, measured simultanously"""
from numpy import nan
reply = self.query("MEAS:T?; MEASure:ITE?; MEASure:PTE?")
try: TIP = eval(reply.replace(";",","))
except: TIP = nan,nan,nan
return TIP
def get_trigger_enabled(self):
"""Ramp temperature in external trigger?"""
from numpy import nan
reply = self.query("TRIGger:IN:ENABle?")
try: value = eval(reply)
except: value = nan
return value
def set_trigger_enabled(self,value):
self.query("TRIGger:IN:ENABle %d" % toint(value))
trigger_enabled = property(get_trigger_enabled,set_trigger_enabled)
def get_trigger_start(self):
"""Starting value in externally triggered tempeature ramp"""
from numpy import nan
reply = self.query("TRIGger:IN:START?")
try: value = eval(reply)
except: value = nan
return value
def set_trigger_start(self,value):
self.query("TRIGger:IN:START %r" % value)
trigger_start = property(get_trigger_start,set_trigger_start)
def get_trigger_stop(self):
"""Starting value in externally triggered tempeature ramp"""
from numpy import nan
reply = self.query("TRIGger:IN:STOP?")
try: value = eval(reply)
except: value = nan
return value
def set_trigger_stop(self,value):
self.query("TRIGger:IN:STOP %r" % value)
trigger_stop = property(get_trigger_stop,set_trigger_stop)
# When ramping from 20C to 80C, TRIGger:IN:STOP needs to be 20, and
# TRIGger:IN:START 80, otherwise the temperature wraps jumps back to 20
# after it reaches 80.
ramp_from = trigger_stop
ramp_to = trigger_start
def get_trigger_stepsize(self):
"""Starting value in externally triggered tempeature ramp"""
from numpy import nan
reply = self.query("TRIGger:IN:STEPsize?")
try: value = eval(reply)
except: value = nan
return value
def set_trigger_stepsize(self,value):
self.query("TRIGger:IN:STEPsize %r" % value)
trigger_stepsize = property(get_trigger_stepsize,set_trigger_stepsize)
def get_current_low_limit(self):
"""TE current limit"""
from numpy import nan
reply = self.query("LIMit:ITE:LOw?")
try: value = eval(reply)
except: value = nan
return value
def set_current_low_limit(self,value):
self.query("LIMit:ITE:LOw %r" % value)
current_low_limit = property(get_current_low_limit,set_current_low_limit)
def get_current_high_limit(self):
"""TE current limit"""
from numpy import nan
reply = self.query("LIMit:ITE:HIgh?")
try: value = eval(reply)
except: value = nan
return value
def set_current_high_limit(self,value):
self.query("LIMit:ITE:HIgh %r" % value)
current_high_limit = property(get_current_high_limit,set_current_high_limit)
def get_errors(self):
"""Reset error state"""
return self.query("ERRors?")
def set_errors(self,value): pass
errors = property(get_errors,set_errors)
def get_clear_error(self):
"""Reset error state"""
return False
def set_clear_error(self,value):
if value: self.query("*CLS")
clear_error = property(get_clear_error,set_clear_error)
def log(self,message):
"""For non-critical messages.
Append the message to the transcript, if verbose logging is enabled."""
if not self.verbose_logging: return
if len(message) == 0 or message[-1] != "\n": message += "\n"
t = timestamp()
file(self.logfile,"a").write("%s: %s" % (t,message))
def log_error(self,message):
"""For error messages.
Display the message and append it to the error log file.
If verbose logging is enabled, it is also added to the transcript."""
from sys import stderr
if len(message) == 0 or message[-1] != "\n": message += "\n"
t = timestamp()
stderr.write("%s: %s" % (t,message))
file(self.error_logfile,"a").write("%s: %s" % (t,message))
if self.verbose_logging:
file(self.logfile,"a").write("%s: %s" % (t,message))
logging = False
def log_comm(self,message):
"""For error messages.
Display the message and append it to the error log file.
If verbose logging is enabled, it is also added to the transcript."""
if self.logging:
if len(message) == 0 or message[-1] != "\n": message += "\n"
t = timestamp()
file(self.comm_logfile,"a").write("%s: %s" % (t,message))
def get_logfile(self):
"""File name for transcript if verbose logging is enabled."""
from tempfile import gettempdir
return gettempdir()+"/lightwave_temperature_controller.log"
logfile = property(get_logfile)
def get_error_logfile(self):
"""File name error messages."""
from tempfile import gettempdir
return gettempdir()+"/lightwave_temperature_controller_error.log"
error_logfile = property(get_error_logfile)
def get_comm_logfile(self):
"""File name error messages."""
from tempfile import gettempdir
return gettempdir()+"/lightwave_temperature_controller_comm.log"
comm_logfile = property(get_comm_logfile)
def toint(x):
"""Convert x to interger type"""
try: return int(x)
except: return 0
def timestamp():
"""Current date and time as formatted ASCCI text, precise to 1 ms"""
from datetime import datetime
timestamp = str(datetime.now())
return timestamp[:-3] # omit microsconds
lightwave_temperature_controller = Lightwave_Temperature_Controller()
# Define some shortcuts.
SampleT = lightwave_temperature_controller
temperature = lightwave_temperature_controller.temperature
set_point = lightwave_temperature_controller.nominal_temperature
power = lightwave_temperature_controller.power
def test_ramp():
from time import sleep
from numpy import arange
fail_count = 0
T0 = set_point.value
for T in arange(4,111,0.871):
set_point.value = T
setT = set_point.value
print T,setT,abs(setT-T)
if abs(setT - T) > 0.0005: fail_count += 1
if fail_count: print "failed %d times" % fail_count
set_point.value = T0
if __name__ == "__main__":
"""For testing"""
import logging; logging.basicConfig(level=logging.DEBUG)
from time import time,sleep
lightwave_temperature_controller.logging = True
self = lightwave_temperature_controller
print('self.stabilization_nsamples')
##print('lightwave_temperature_controller["SET:TEMP"]')
##print('lightwave_temperature_controller["MEAS:T"]')
<file_sep>Method.value = 'method.command_value'
Method.properties = {
'Enabled': 'True',
'Items': 'method.values',
'BackgroundColour': [
('Pink','method.value != method.command_value'),
('White','method.value == method.command_value'),
]
}
Show_Methods.action = {True: 'self.show_methods()'}
Show_Methods.properties = {'Enabled': 'True'}
File.value = 'collect.basename'
File.properties = {'Enabled': 'True'}
Extension.value = 'collect.xray_image_extension'
Extension.properties = {'Enabled': 'True'}
Description.value = 'collect.description'
Description.properties = {'Enabled': 'True'}
Logfile.value = 'collect.logfile_basename'
Logfile.properties = {'Enabled': 'True'}
Path.value = 'collect.directory'
Path.properties = {'Enabled': 'True'}
Info.properties = {'Label': 'collect.info_message','Enabled': 'True'}
Status.properties = {'Label': 'collect.status_message','Enabled': 'True'}
Actual.properties = {'Label': 'collect.actual_message','Enabled': 'True'}
Generate_Packets.value = 'collect.generating_packets'
Generate_Packets.properties = {
'Enabled': 'True',
'Label': [
('Cancel Generate', 'collect.generating_packets'),
('Cancelled', 'collect.generating_packets and collect.cancelled'),
],
}
Collect_Dataset.value = 'collect.collecting_dataset'
Collect_Dataset.properties = {
'Enabled': [
(True, 'not collect.dataset_complete'),
],
'Label': [
('Cancel Collect', 'collect.collecting_dataset'),
('Cancelled', 'collect.collecting_dataset and collect.cancelled'),
('Resume Dataset', 'len(collect.xray_images_collected) > 0'),
('Dataset Complete', 'collect.dataset_complete'),
],
}
Cancel.action = {True: 'collect.cancelled = True'}
Cancel.properties = {
'Enabled': [(True, 'collect.collecting or collect.generating_packets')],
'Label': [
('Cancelled', 'collect.cancelled'),
],
}
Erase_Dataset.value = 'collect.erasing_dataset'
Erase_Dataset.properties = {
'Enabled': 'not collect.collecting and collect.dataset_started',
'Label': [
('Cancel Erase', 'collect.erasing_dataset'),
('Cancelled', 'collect.erasing_dataset and collect.cancelled'),
],
}
Finish_Series.value = 'collect.finish_series'
Finish_Series.properties = {'Enabled': 'False'}
Finish_Series_Variable.value = 'collect.finish_series_variable'
Finish_Series_Variable.properties = {
'Enabled': 'True',
'Items': 'collect.collection_variables',
}
<file_sep>#!/usr/bin/env python
"""Ice diffraction detection
Authors: <NAME>, <NAME>, <NAME>
Date created: 2017-10-31
Date last modified: 2018-10-31
"""
from logging import debug,warn,info,error
from sample_frozen import sample_frozen
from sample_frozen_optical import sample_frozen_optical
from Panel import BasePanel,PropertyPanel,ButtonPanel,TogglePanel,TweakPanel
import wx
__version__ = "1.4" # ROI
class SampleFrozenPanel(BasePanel):
name = "SampleFrozenPanel"
title = "Sample Frozen"
standard_view = [
"Diffraction Spots",
"Threshold [spots]",
"Deice enabled",
"Deicing",
"Optical Server enabled",
"Optical Intervention enabled",
"Scattering Power",
]
parameters = [
[[TogglePanel, "Aux. Deicing", sample_frozen,"aux_deicing"],{"type":"Not active/Active"}],
[[TogglePanel, "Retracted", sample_frozen,"retract"],{"type":"Inserted/Retracted"}],
[[PropertyPanel,"Diffraction Spots",sample_frozen,"diffraction_spots"],{"read_only":True}],
[[PropertyPanel, "Optical Scattering", sample_frozen_optical,"scattering"],{"read_only":True}],
[[PropertyPanel,"Optical box dim (mm)", sample_frozen_optical,"box_dimensions"],{"choices":[100,50,25,10]}],
[[TogglePanel, "XRay detection", sample_frozen,"running"],{"type":"Off/On"}],
[[TogglePanel, "XRay aux intervention", sample_frozen,"is_intervention_enabled"],{"type":"Off/On"}],
[[TogglePanel, "XRay retract inter.", sample_frozen,"retract_deicing"],{"type":"Off/On"}],
[[TogglePanel, "Optical detection", sample_frozen_optical,"is_running"],{"type":"Off/On"}],
[[TogglePanel, "Optical intervention", sample_frozen_optical,"is_intervention_enabled"],{"type":"Off/Monitoring"}],
[[PropertyPanel,"XRay image ROIX", sample_frozen,"ROIX"],{"choices":[1000,900]}],
[[PropertyPanel,"XRay image ROIY", sample_frozen,"ROIY"],{"choices":[1000,900]}],
[[PropertyPanel,"XRay image WIDTH", sample_frozen,"WIDTH"],{"choices":[150,300,400]}],
[[PropertyPanel,"Retracted time [sec]",sample_frozen,"retracted_time"],{"choices":[1,5,10,20]}],
[[PropertyPanel,"Retracted time opt. [sec]",sample_frozen_optical,"retracted_time"],{"choices":[1,5,10,20]}],
[[PropertyPanel,"Threshold [spots]",sample_frozen,"threshold_N_spts"],{"choices":[1,10,20,50]}],
[[PropertyPanel,"Threshold [counts]",sample_frozen_optical,"scattering_threshold"],{"choices":[5,10,20,50]}],
[[PropertyPanel,"Threshold [Temp. in C]",sample_frozen_optical,"frozen_threshold_temperature"],{"choices":[-20,-18,-15,-10]}],
]
def __init__(self,parent=None):
BasePanel.__init__(self,
parent=parent,
name=self.name,
title=self.title,
icon="Tool",
parameters=self.parameters,
standard_view=self.standard_view,
)
if __name__ == '__main__':
from pdb import pm
import logging
from tempfile import gettempdir
from redirect import redirect
import autoreload
#redirect('SampleFrozenPanelOpt',level="INFO")
#logfile = gettempdir()+"/SampleFrozenPanelOpt.log"
## logging.basicConfig(
## level=logging.INFO,
## format="%(asctime)s %(levelname)s: %(message)s",
## logfile=logfile,
## )
# Needed to initialize WX library
app = wx.App(redirect=False)
panel = SampleFrozenPanel()
#sample_frozen_optical.is_running = True
#sample_frozen.running = True
app.MainLoop()
<file_sep>"""
Platform-independent pathnames
<NAME>, 28 Mar 2014 - 14 Feb 2017
"""
__version__ = "1.1.6" # "darwin" platform (MacOS)
def normpath(pathname):
"""Translate between UNIX-style to Windows-style pathnames, following
Universal Naming Convention.
E.g. "/net/mx340hs/data" to "//mx340hs/data"""
if pathname == "": return pathname
from os.path import exists
pathname = str(pathname)
# Try to expand a Windows drive letter to a UNC name.
# E.g. "J:/anfinrud_1106" to "//mx340hs/data/anfinrud_1106"
try:
import win32wnet # http://sourceforge.net/projects/pywin32
pathname = win32wnet.WNetGetUniversalName(pathname)
except: pass
# Resolve symbolic links. E.g. "/data" to "/net/mx340hs/data"
# E.g. "G:/anfinrud_1403/Logfiles" or "\\mx340hs\data\anfinrud_1403\Logfiles"
import os
if not pathname[1:2] == ":" and not "\\" in pathname \
and not pathname.startswith("//") and not os.name == "nt":
from os.path import realpath
pathname = realpath(pathname)
# Convert separators from Window style to UNIX style.
# E.g. "\\mx340hs\data\anfinrud_1106" to "//mx340hs/data/anfinrud_1106"
pathname = pathname.replace("\\","/")
# Mac OS X: mount point "/Volumes/share" does not reveal server name.
if pathname.startswith("/Volumes/data"):
pathname = pathname.replace("/Volumes/data","/net/mx340hs/data")
if pathname.startswith("/Volumes/Femto"):
pathname = pathname.replace("/Volumes/Femto","/net/femto/C")
if pathname.startswith("/Volumes/C"):
pathname = pathname.replace("/Volumes/C","/net/femto/C")
# Convert from Windows to UNIX style.
# E.g. "//mx340hs/data/anfinrud_1106" to "/net/mx340hs/data/anfinrud_1106"
if pathname.startswith("//"): # //server/share/directory/file
parts = pathname.split("/")
if len(parts) >= 4:
server = parts[2] ; share = parts[3]
path = "/".join(parts[4:])
if not exists("//"+server+"/"+share):
if exists("/net/"+server+"/"+share):
pathname = "/net/"+server+"/"+share+"/"+path
if exists("/net/"+server+"/home/"+share):
pathname = "/net/"+server+"/home/"+share+"/"+path
# Convert from UNIX to Windows style.
# E.g. "/net/mx340hs/data/anfinrud_1106" to "//mx340hs/data/anfinrud_1106"
from sys import platform
if pathname.startswith("/net/") and platform in ("win32","darwin"):
parts = pathname.split("/")
if len(parts) >= 4:
server = parts[2] ; share = parts[3]
path = "/".join(parts[4:])
# E.g. /net/id14b4/home/useridb/NIH/Software
if share == "home" and len(parts)>4:
share = parts[4]
path = "/".join(parts[5:])
pathname = "//"+server+"/"+share+"/"+path
# E.g. "/home/useridb/NIH/Software"
if not pathname.startswith("//") and pathname.startswith("/") and \
platform != "win32" and not pathname.startswith("/net/") and \
not pathname.startswith("/Volumes/"):
from platform import node
hostname = node()
parts = pathname.strip("/").split("/")
dir = "/".join(parts[0:2])
path = "/".join(parts)
if exists("/net/"+hostname+"/"+dir):
pathname = "/net/"+hostname+"/"+path
return pathname
if __name__ == "__main__":
print(normpath("/net/mx340hs/data/anfinrud_1403/Logfiles"))
print(normpath("/data/anfinrud_1403/Logfiles"))
print(normpath("//mx340hs/data/anfinrud_1403/Logfiles"))
print(normpath(r"\\mx340hs\data\anfinrud_1403\Logfiles"))
print(normpath(r"G:\anfinrud_1403\Logfiles"))
print(normpath("/net/id14b4/home/useridb/NIH/Software"))
print(normpath("//id14b4/useridb/NIH/Software"))
print(normpath("/home/useridb/NIH/Software"))
<file_sep>program_filename = NIH-diffractometer_PP.ab
ip_address = 'nih-instrumentation.cars.aps.anl.gov:2000'<file_sep>Size = (1255, 1160)
Position = (39, 26)
ScaleFactor = 1.0
ZoomLevel = 32.0
Orientation = 0
Mirror = False
NominalPixelSize = 0.125
filename = 'Z:\\All Projects\\Crystallization\\2018.08.27.caplilary with crystals inspection\\2018.08.27 CypA 2.jpg'
ImageWindow.Center = (649, 559)
ImageWindow.ViewportCenter = (2.41796875, 2.0)
ImageWindow.crosshair_color = (255, 0, 255)
ImageWindow.boxsize = (0.04, 0.04)
ImageWindow.box_color = (255, 0, 0)
ImageWindow.show_box = False
ImageWindow.Scale = [[0.21944444444444444, -0.0763888888888889], [0.46944444444444444, -0.075]]
ImageWindow.show_scale = True
ImageWindow.scale_color = (255, 0, 0)
ImageWindow.crosshair_size = (0.05, 0.05)
ImageWindow.show_crosshair = False
ImageWindow.show_profile = False
ImageWindow.show_FWHM = False
ImageWindow.show_center = False
ImageWindow.calculate_section = False
ImageWindow.profile_color = (255, 0, 255)
ImageWindow.FWHM_color = (0, 0, 255)
ImageWindow.center_color = (0, 0, 255)
ImageWindow.ROI = [[-0.5194444444444445, -0.3458333333333333], [0.225, 0.19305555555555556]]
ImageWindow.ROI_color = (255, 255, 0)
ImageWindow.show_saturated_pixels = False
ImageWindow.mask_bad_pixels = False
ImageWindow.saturation_threshold = 233
ImageWindow.saturated_color = (255, 0, 0)
ImageWindow.linearity_correction = False
ImageWindow.bad_pixel_threshold = 233
ImageWindow.bad_pixel_color = (30, 30, 30)
ImageWindow.show_grid = False
ImageWindow.grid_type = 'xy'
ImageWindow.grid_color = (0, 0, 255)
ImageWindow.grid_x_spacing = 0.3
ImageWindow.grid_x_offset = 0.0
ImageWindow.grid_y_spacing = 0.5
ImageWindow.grid_y_offset = 0.0
<file_sep>"""
<NAME>, NIH, 3 Feb 2012 - 9 Mar 2012
"""
from lecroy_scope import lecroy_scope
from lecroy_scope_waveform import read_waveform
from time import sleep
from pylab import *
__version__ = "1.1"
id14b_xscope = lecroy_scope("172.16.17.32") # id14b-xscope
xray_trace = id14b_xscope.channel(1)
dir = "/net/id14bxf/data/anfinrud_1203/Test/I0"
filename = dir+"/test1.trc"
print 'xray_trace.acquire_sequence(100)'
print 'xray_trace.is_acquiring'
print 'xray_trace.save_waveform(filename)'
print 't,U = read_waveform(filename)'
print 'plot(t[0:5].T,U[0:5].T,".",ms=5,mew=0); grid(); show()'
<file_sep>"""Time Chart window
Author: <NAME>
Date created: 2016-06-23
Date last modified: 2019-05-10
"""
import wx
from logging import debug,warn,info,error
from EditableControls import ComboBox
__version__ = "1.4" # markersize
class TimeChart(wx.Panel):
"""Time Chart window"""
name = "TimeChart"
from persistent_property import persistent_property
from time import time
time_window = persistent_property("time_window",60.0) # seconds
center_time = persistent_property("center_time",time()-30.0) # seconds
show_latest = persistent_property("show_latest",True)
def __init__(self,parent=None,title="Chart",object=None,
t_name="date time",v_name="value",
axis_label="",refresh_period=1.0,name=None,PV=None,size=(500,500),
*args,**kwargs):
"""title: string
object: has attribute given by t_name,y_name
t_name: e.g. "t_history" or "date time"
v_name: e.g. "x_history", "y_history" or "value"
PV: EPICS process variable name, e.g. 'NIH:TEMP.RBV'
"""
wx.Window.__init__(self,parent,size=size)
self.title = title
if object is not None: self.object = object
self.t_name = t_name
self.v_name = v_name
self.axis_label = axis_label
self.refresh_period = refresh_period
if name is not None: self.name = name
self.PV = PV
# Controls
from matplotlib.figure import Figure
from matplotlib.backends.backend_wxagg import FigureCanvasWxAgg
self.figure = Figure(figsize=(4,3))
self.canvas = FigureCanvasWxAgg(self,-1,self.figure)
style = wx.TE_PROCESS_ENTER
self.PVChoice = ComboBox(self,style=style,size=(120,-1))
self.TimeFraction = wx.ScrollBar(self)
self.TimeFraction.SetScrollbar(800,200,100000,100,True)
# SetScrollbar(position,thumbSize,range,pageSize,refresh)
# [Arguments misnamed "orientation,position,thumbSize,range,refresh"
# in WxPython 2.9.1.1]
choices = ["10s","30s","1min","2min","5min","10min","30min",
"1h","2h","6h","12h","1d","2d","5d"]
self.TimeWindow = ComboBox(self,style=style,choices=choices)
# Callbacks
self.Bind(wx.EVT_COMBOBOX,self.OnPVChoice,self.PVChoice)
self.Bind(wx.EVT_TEXT_ENTER,self.OnPVChoice,self.PVChoice)
events = [
wx.EVT_SCROLL_TOP,wx.EVT_SCROLL_BOTTOM,
wx.EVT_SCROLL_LINEUP,wx.EVT_SCROLL_LINEDOWN,
wx.EVT_SCROLL_PAGEUP,wx.EVT_SCROLL_PAGEDOWN,
wx.EVT_SCROLL_THUMBRELEASE,
wx.EVT_SCROLL_THUMBTRACK,
]
for e in events: self.Bind(e,self.OnTimeFractionChanged,self.TimeFraction)
self.Bind(wx.EVT_COMBOBOX,self.OnTimeWindowChanged,self.TimeWindow)
self.Bind(wx.EVT_TEXT_ENTER,self.OnTimeWindowChanged,self.TimeWindow)
self.Bind(wx.EVT_WINDOW_DESTROY,self.OnDestroy,self)
# Layout
vbox = wx.BoxSizer(wx.VERTICAL)
vbox.Add(self.canvas,proportion=1,flag=wx.EXPAND)
hbox = wx.BoxSizer(wx.HORIZONTAL)
flag = wx.ALIGN_CENTER_VERTICAL
hbox.Add(self.PVChoice,proportion=1,flag=flag)
hbox.Add(self.TimeFraction,proportion=2,flag=wx.EXPAND|flag)
hbox.Add(self.TimeWindow,flag=flag)
vbox.Add(hbox,flag=wx.EXPAND)
self.SetSizer(vbox)
self.SetSizeHints(minW=-1,minH=200,maxW=-1,maxH=-1)
self.Fit()
# Refresh
self.attributes = [self.t_name,self.v_name,"start_time"]
from time import time
self.values = {self.t_name:[],self.v_name:[],"start_time":time()-60}
##self.values = dict([(n,[]) for n in self.attributes])
self.old_values = self.values
from threading import Thread
self.refresh_thread = Thread(target=self.refresh_background,
name=self.name+".refresh")
self.refreshing = False
from wx.lib.newevent import NewEvent
self.EVT_THREAD = NewEvent()[1]
self.Bind(self.EVT_THREAD,self.OnUpdate)
self.thread = Thread(target=self.keep_updated,
name=self.name+".keep_updated")
self.thread.start()
self.UpdateControls()
self.timer = wx.Timer(self)
self.Bind (wx.EVT_TIMER,self.OnTimer,self.timer)
self.timer.Start(1000,oneShot=True)
def get_object(self):
"""logfile object"""
if self.PV is not None:
from channel_archiver import channel_archiver
object = channel_archiver.logfile(self.PV)
else: object = self.__object__
return object
def set_object(self,object):
self.__object__ = object
object = property(get_object,set_object)
__object__ = None
def OnDestroy(self,event):
""""""
info("TimeChart: %s destroyed" % self.name)
def OnTimer(self,event):
"""Perform periodic updates"""
try: self.UpdateControls()
except Exception,msg:
import traceback
error("TimeChart: %s\n%s" % (msg,traceback.format_exc()))
self.timer.Start(1000,oneShot=True)
def keep_updated(self):
"""Periodically refresh the displayed settings."""
##debug("TimeChart: keep_updated: refresh_period %r" % self.refresh_period)
from time import time
from sleep import sleep # interruptible sleep
import traceback
while True:
try:
sleep(self.refresh_period)
self.update()
except wx.PyDeadObjectError: break
except Exception,msg:
error("TimeChart: %s\n%s" % (msg,traceback.format_exc()))
def update(self):
"""Retrigger fresh of chart if data changed."""
# Needs to be called from background thread.
if self.Shown:
self.update_data()
if self.data_changed:
event = wx.PyCommandEvent(self.EVT_THREAD.typeId,self.Id)
# call OnUpdate in GUI thread
wx.PostEvent(self.EventHandler,event)
def refresh(self):
"""Force update"""
from threading import Thread
if not self.refreshing and self.Shown:
self.refresh_thread = Thread(target=self.refresh_background,
name=self.name+".refresh")
self.refreshing = True
self.refresh_thread.start()
def refresh_background(self):
"""Force update"""
self.update_data()
if self.data_changed:
event = wx.PyCommandEvent(self.EVT_THREAD.typeId,self.Id)
wx.PostEvent(self.EventHandler,event) # call OnUpdate in GUI thread
self.refreshing = False
def update_data(self):
"""Retreive status information"""
from numpy import copy
self.old_values = dict((n,copy(self.values[n])) for n in self.values)
##for n in self.attributes: self.values[n] = copy(getattr(self.object,n))
self.values[self.t_name],self.values[self.v_name] = \
self.object.history(self.t_name,self.v_name,
time_range=self.tmin_tmax)
self.values["start_time"] = self.object.start_time
@property
def data_changed(self):
"""Did the last 'update_data' change the data to be plotted?"""
from numpy import array_equal
if sorted(self.values.keys()) != sorted(self.old_values.keys()):
debug("data changed? keys changed")
changed = True
else:
changed = not all([array_equal(self.values[a],self.old_values[a]) \
for a in self.values])
##debug("data changed: %r" % changed)
return changed
def OnUpdate(self,event=None):
"""Handle data changed"""
self.RefreshChart()
def RefreshChart(self):
"""Update the chart"""
##debug("TimeChart: RefreshChart")
from pylab import setp,DateFormatter
from numpy import isnan,nanmax,nanmin,ptp,ceil,floor,array,arange
t_data,v_data = self.values[self.t_name],self.values[self.v_name]
n = min(len(t_data),len(v_data))
t_data,v_data = t_data[0:n],v_data[0:n]
date = days(t_data)
##self.figure.subplots_adjust(bottom=0.4) ##,left=0.2,right=0.97,top=0.92)
self.plot = self.figure.add_subplot(1,1,1)
self.plot.clear()
self.plot.plot(date,v_data,'.',color=[0,0,1],markersize=1)
self.plot.set_xlim(days(self.tmin_tmax))
trange = ptp(self.tmin_tmax)
s,m,h,d = 1,60,3600,86400
steps = array([
0.1*s,0.2*s,0.5*s,
1*s,2*s,5*s,10*s,15*s,30*s,
1*m,2*m,5*m,10*m,15*m,30*m,
1*h,2*h,3*h,6*h,12*h,
1*d,7*d,28*d,
])
dt = trange/10
dt = max(steps[steps <= dt])
if dt < 1*m: date_format = "%H:%M:%S"
elif dt < 1*h: date_format = "%H:%M"
elif dt < 1*d: date_format = "%H"
else: date_format = "%d %H"
self.plot.xaxis.set_major_formatter(DateFormatter(date_format))
self.plot.xaxis_date()
tmin,tmax = ceil(self.tmin/dt)*dt,floor(self.tmax/dt)*dt
self.plot.xaxis.set_ticks(days(arange(tmin,tmax+1e-6,dt)))
setp(self.plot.get_xticklabels(),rotation=90,fontsize=10)
setp(self.plot.get_yticklabels(),fontsize=10)
label = self.axis_label
self.plot.set_ylabel(label)
self.plot.grid()
self.figure.tight_layout() ##rect=[0,0.12,1,1]
self.canvas.draw()
@property
def tmin_tmax(self):
"""Minimum and maximum value of time axis"""
return [self.tmin,self.tmax]
@property
def tmin(self):
"""Minimum value of time axis"""
from time import time
tmin = self.tmax-self.time_window
return tmin
@property
def tmax(self):
"""Maximum value of time axis"""
from time import time
if self.show_latest: tmax = time()
else: tmax = self.center_time + self.time_window/2
return tmax
@property
def start_time(self):
"""Time of earliest data point in seconds since 1970-01-01 00:00:00 UTC"""
return self.values["start_time"]
@property
def full_time_range(self):
"""Full time range from start of logfile to now"""
from time import time
dt = time() - self.start_time
if not dt > 1.0: dt = 1.0
return dt
def UpdateControls(self):
"""Make sure control are up to date"""
from time_string import time_string
text = time_string(self.time_window)
if self.TimeWindow.Value != text: self.TimeWindow.Value = text
self.UpdatePVChoice()
self.UpdateScrollbar()
def UpdatePVChoice(self):
""""""
from channel_archiver import channel_archiver
if self.PV: self.PVChoice.Value = self.PV
else: self.PVChoice.Value = self.object.name
self.PVChoice.Items = channel_archiver.PVs
def OnPVChoice(self,event):
"""Change the process variable to be plotted"""
self.PV = str(self.PVChoice.Value)
self.refresh()
def OnTimeWindowChanged(self,event):
"""Adjust chart x-axis to reflesh the new time range"""
from time_string import seconds
self.time_window = seconds(self.TimeWindow.Value)
## debug("TimeChart: time window changed: %r" % self.time_window)
self.UpdateScrollbar()
self.refresh()
def OnTimeFractionChanged(self,event):
"""Called when time window position is changed"""
debug("start %r, end %r" % (self.start_fraction,self.end_fraction))
self.show_latest = True if self.end_fraction >= 1 else False
debug("show latest %r" % self.show_latest)
center_fraction = (self.start_fraction+self.end_fraction)/2
self.center_time = self.start_time + self.full_time_range * center_fraction
from time_string import date_time
debug("center time %r" % date_time(self.center_time))
self.refresh()
def OnResize(self,event):
self.RefreshChart()
event.Skip() # call default handler
def UpdateScrollbar(self):
from numpy import rint,clip
range = self.TimeFraction.Range
thumbsize_fraction = clip(self.time_window/self.full_time_range,0,1)
thumb_position_fraction = clip((self.tmin - self.start_time)/self.full_time_range,0,1)
pagesize_fraction = 0.5*thumbsize_fraction
thumbsize = int(rint(thumbsize_fraction*range))
thumb_position = int(rint(thumb_position_fraction*range))
pagesize = int(rint(pagesize_fraction*range))
##debug("SetScrollbar(%r,%r,%r,%r)" % (thumb_position,thumbsize,range,pagesize))
self.TimeFraction.SetScrollbar(thumb_position,thumbsize,range,pagesize,
True)
def get_start_fraction(self):
position = self.TimeFraction.ThumbPosition
range = max(self.TimeFraction.Range,1)
return float(position)/range
def set_start_fraction(self,fraction):
fraction = max(0,min(fraction,1))
range = max(self.TimeFraction.Range,1)
self.TimeFraction.ThumbPosition = rint(fraction*range)
start_fraction = property(get_start_fraction,set_start_fraction)
def get_end_fraction(self):
from numpy import rint
position = self.TimeFraction.ThumbPosition
size = self.TimeFraction.ThumbSize
end = position+size
range = max(self.TimeFraction.Range,1.0)
return float(end)/range
def set_end_fraction(self,fraction):
from numpy import rint
fraction = max(0,min(fraction,1))
range = max(self.TimeFraction.Range,1)
size = self.TimeFraction.ThumbSize
self.TimeFraction.ThumbPosition = rint(fraction*range) - size
end_fraction = property(get_end_fraction,set_end_fraction)
def days(seconds):
"""Convert a time stamp from seconds since 1 Jan 1970 0:00 UTC to days
since 1 Jan 1 AD 0:00 localtime
seconds: scalar or array"""
# Determine the offset, which his time zone and daylight saving time
# dependent.
from numpy import mean,isnan,asarray,nan
seconds = asarray(seconds)
try: t = mean(seconds[~isnan(seconds)])
except: t = nan
if not isnan(t):
from datetime import datetime; from pylab import date2num
offset = date2num(datetime.fromtimestamp(t)) - t/86400
else: offset = nan
return seconds/86400 + offset
from Panel import BasePanel
class ArchiveViewer(BasePanel):
name = "ArchiveViewer"
title = "Archive Viewer"
standard_view = ["Data"]
def __init__(self,PV,parent=None):
from channel_archiver import channel_archiver
log = channel_archiver.logfile(PV)
parameters = [
[[TimeChart,"Data"],{"PV":PV,"refresh_period":2}],
]
BasePanel.__init__(self,
name=self.name,
title=self.title,
icon="Archiver",
parent=parent,
parameters=parameters,
standard_view=self.standard_view,
refresh=False,
live=False,
)
if __name__ == "__main__":
from pdb import pm # for debugging
import logging # for debugging
from tempfile import gettempdir
logfile = gettempdir()+"/TimeChart.log"
logging.basicConfig(level=logging.DEBUG,
##filename=logfile,
format="%(asctime)s %(levelname)s: %(message)s")
app = wx.App(redirect=False)
panel = ArchiveViewer('NIH:TEMP.RBV')
self = panel.controls[0]
app.MainLoop()
<file_sep>"""
Cavro Centris Syringe Pump driver
<NAME>, May 31, 2017 - May 10, 2018
RS-323 coummincation oparameters:
9600 baud, 8 bits, no parity, 1 stop bit
Command set:
Commands are single upper case ASCII characters, followed by one or more
comma separated parameters as ASCII-encoded decimal numbers.
Each commad character need to be preceded with "1" (indicating the the command
is destined for the first pump, in case mutiple pumps are connected via CAN).
Commands can be concatenated to a command string. A command string needs to
Start with "/" and end with "\r". Motion commands queue up until the "R" (Run) is
recieved.
Y7,0,0 Home plunger motor with speed 7, leaning it ay position 0.
Then home valve motors clock-wisr mapping "O" (output) to port 2,
leaving the value in position "O".
?18 Report the plunger absolute position in microliters
A100,1 move absolute 100 uL
?37 Report top speed in uL/s
V0.2,1 Set top speed to 0.2 uL/s
?20 Reports valve position ([i], [o], or [b])
I Moves valve to input position via shortest path
O Moves valve to output position via shortest path
B Moves valve to bypass position via shortest path
W7 Initialize plunger drive, 7=speed code
w1,0 Initialize valve drive, 1=number of ports,0=clockwise
?43 Number of pump initializations since last device power up or reset. ([Z],[Y],[W])
?17 Report syringe volume
Documentation:
//femto/C/All Projects/drawings/LCP/Cavro Centris Syringe Pumps/
Cavro Centris Syringe Pumps.pages
Operation Manual Cavro Centris Pump, March 2012, 30038165 Rev B
//femto/C/All Projects/drawings/LCP/Cavro Centris Syringe Pumps/
30038165-B-MANUAL CENTRIS.pdf
Setup:
Assign each pump a unique ID. This ID is sttored innon-volatile memory.
These commands need to be executed only once, after identifying the port
name for each pump, using the Windows Device Manager.
set_id("COM29",1)
set_id("COM30",2)
set_id("COM31",3)
set_id("COM32",4)
Usage:
Continuous flow:
volume[1].speed = 1; volume[1].value = 250
Coordinated operation:
pump.SPMG = 0; volume[0].value,volume[1].value = 0,0; pump.SPMG = 3
"""
__version__ = "1.1.1" # port change via EPICS
from logging import warn,debug,info
class Comm_Ports(object):
"""Cavro Centris Syringe Pumps"""
ports = {}
from numpy import inf
max_time_between_replies = {0:inf,1:inf,2:inf,3:inf}
def discover(self):
"""Find the serial ports for each pump controller"""
from serial import Serial
for port_name in self.available_ports:
debug("Trying self.ports %s..." % port_name)
try:
port = Serial(port_name)
port.timeout = 0.4
port.write("/1?80\r")
reply = port.readline()
debug("self.ports %r: reply %r" % (port_name,reply))
pid = int(reply[6])-1 # get pump id for new_pump
self.ports[pid] = port
info("self.ports %r: found pump %r" % (port_name,pid+1))
except Exception,msg: debug("%s: %s" % (Exception,msg))
for i in self.ports:
debug("p.pump[%d].name = %r" % (i,self.ports[i].name))
@property
def available_ports_old(self):
"""List of device names"""
from os.path import exists
port_basename = "COM" if not exists("/dev") else "/dev/tty.usbserial"
ports = []
for i in range(0,64):
port_name = port_basename+("%d" % i if i>0 else "")
ports += [port_name]
return ports
@property
def available_ports(self):
"""List of device names"""
from serial.tools.list_ports import comports
return [port.device for port in comports()]
def ports_found(self,ids):
"""Are the serial ports known for each pump?
ids: 0-based indices
"""
ports_found = [id in self.ports for id in ids]
return ports_found
def names(self,ids):
"""Are the serial ports known for each pump?
ids: 0-based indices
"""
names = [self.ports[i].name if i in self.ports else "" for i in ids]
return names
def write_read(self,command_dict):
"""Writes commands to multiple pumps with pump ids and commands assembled
in a dictionary.
Returns a dictionary of pump ids and their respective responses."""
if not all(self.ports_found(command_dict.keys())): self.discover()
for pid,command in command_dict.iteritems():
if pid in self.ports:
try: self.ports[pid].write(command)
except Exception,msg:
warn("Pump %s: %s: %s" % (pid,self.ports[pid].name,msg))
del self.ports[pid]
replies = {}
for pid in command_dict:
if pid in self.ports:
reply = self.ports[pid].readline()
if len(reply) > 3:
status = reply[3]
if status not in ["@", "`"]:
warn("command %r generated error %r" % (command_dict[pid], status))
else: reply = ""
replies[pid] = reply
debug("Commands: %r" % command_dict)
debug("Replies: %r" % replies)
return replies
comm_ports = Comm_Ports()
class Volumes(object):
"""<NAME> Syringe Pumps"""
def values(self,ids):
"""Volumes of pumps
ids: list of 0-based indices
"""
from numpy import nan
reply = comm_ports.write_read({id: "/1?18\r" for id in ids})
values = []
for id in reply:
try: values += [float(reply[id][4:-3])]
except: values += [nan]
return values
def set_values(self,ids,values):
"""Volumes in uL
ids: list of 0-based indices
value: list of volumes in uL
"""
self.set_moving(ids,[0]*len(ids)) # stop active motion
comm_ports.write_read(
{id: "".join(["/1A%s,1R\r"%value]) for (id,value) in zip(ids,values)})
def speeds(self,ids):
"""Pumping speeds in uL/s
ids: list of 0-based indices
"""
from numpy import nan
reply = comm_ports.write_read({id: "/1?37\r" for id in ids})
values = []
for id in reply:
try: values += [float(reply[id][4:-3])]
except: values += [nan]
return values
def set_speeds(self,ids,values):
"""Pumping speeds in uL/s
ids: list of 0-based indices
value: list of speeds in uL/s
"""
comm_ports.write_read(
{id: "".join(["/1V%.3f,1F\r"%value]) for (id,value) in zip(ids,values)})
def moving(self,ids):
"""Motion active?
ids: list of 0-based indices
"""
from numpy import nan
# The query (?29) returns the pump status, whose 4th byte is 1 or 0
# (1 is busy)
reply = comm_ports.write_read({id: "/1?29\r" for id in ids})
values = []
for id in reply:
try: values += [int(reply[id][4])]
except: values += [nan]
return values
def set_moving(self,ids,values):
"""Stop motors
ids: list of 0-based indices
value: 0 to stop, 1 to ignore
"""
comm_ports.write_read({id: "/1TR\r" for (id,value) in zip(ids,values)
if not value})
def homed(self,ids):
"""Motor initialized?
ids: list of 0-based indices
"""
homed = [n>0 for n in self.homed_count(ids)]
return homed
def homed_count(self,ids):
"""Motor initialized?
ids: list of 0-based indices
"""
from numpy import nan
reply = comm_ports.write_read({id: "/1?43\r" for id in ids})
values = []
for id in reply:
try: values += [int(reply[id][4:-3])]
except: values += [nan]
return values
def set_homed(self,ids,values):
"""Execute inialization sequence for motors
ids: list of 0-based indices
value: 0 to ignore, 1 to execute home sequence
"""
comm_ports.write_read({id: "/1W7R\r" for (id,value) \
in zip(ids,values) if value})
def low_limits(self,ids):
"""Low limits in uL
ids: list of 0-based indices
"""
return [0]*len(ids)
def high_limits(self,ids):
"""High limits in uL
ids: list of 0-based indices
"""
from numpy import nan
reply = comm_ports.write_read({id: "/1?17\r" for id in ids})
values = []
for id in reply:
try: value = float(reply[id][4:-3])
except: value = nan
values += [value]
return values
def stepsizes(self,ids):
"""Motor increment in uL
ids: list of 0-based indices
"""
high_limits = self.high_limits(ids)
max_counts = self.max_counts(ids)
stepsizes = [V/n for (V,n) in zip(high_limits,max_counts)]
return stepsizes
def max_counts(self,ids):
"""High limits in motor steps
ids: list of 0-based indices
"""
from numpy import nan
reply = comm_ports.write_read({id: "/1?16\r" for id in ids})
values = []
for id in reply:
try: value = int(reply[id][4:-3])
except: value = nan
values += [value]
return values
volumes = Volumes()
class Ports(object):
"""Cavro Centris Syringe Pump Ports"""
numbers = {'o':0,'i':1,'b':2}
def number(self,letter):
from numpy import nan
if letter in self.numbers: number = self.numbers[letter]
else: number = nan
return number
def letter(self,number):
if number in self.numbers.values():
letter = self.numbers.keys()[self.numbers.values().index(number)]
else: letter = 'o'
return letter
def values(self,ids):
"""Status of pump valves as dictionary of one-letter codes
n = ?
ids: list of 0-based indices
"""
replies = comm_ports.write_read({id:"/1?20\r" for id in ids})
values = []
for id in replies:
# 'o'=out,'i'=in,'b'=bypass,'n'=not initialized
try: letter = replies[id][4:-3]
except: letter = ""
value = self.number(letter)
debug("port.value[%r] = %r (%r)" % (id,value,letter))
values += [value]
return values
def set_values(self,ids,values):
"""Volumes in uL
ids: list of 0-based indices
value: list of volumes in uL
"""
##self.set_moving(ids,[0]*len(ids)) # stop active motion
letters = [self.letter(value) for value in values]
comm_ports.write_read(
{id: "".join(["/1%sR\r"%letter.upper()]) for (id,letter) in zip(ids,letters)})
def moving(self,ids): return volumes.moving(ids)
def set_moving(self,ids,values): volumes.set_moving(ids,values)
def homed(self,ids):
"""Motor initialized?
ids: list of 0-based indices
"""
# If the command "?20" (valve position0 returns "n", rather than "i",
# "o" or "b" the valve have not been initialized yet.
from numpy import nan
replies = comm_ports.write_read({id: "/1?20\r" for id in ids})
values = []
for id in replies:
try: value = reply[id][4:-3] != "n"
except: value = nan
values += [value]
return values
def set_homed(self,ids,values):
"""Execute inialization sequence for motor
ids: list of 0-based indices
value: 0 to ignore, 1 to execute home sequence
"""
comm_ports.write_read({id: "/1w1,0R\r" for (id,value) \
in zip(ids,values) if not value})
ports = Ports()
def set_id(port_name,id):
"""Assign a unique ID to a pump controller.
Thsi ID will be stord in non-volatile memory
port_name: e.g. "COM29"
id: 1-based index
"""
write_port(port_name,"/1s0ZA%sR\r" % i)
def write_port(port_name,command):
"""Send a connad to a specific comm port
port_name: e.g. "COM29"
"""
from serial import Serial
port = Serial(port_name)
port.write(command)
class Syringe_Pump_IOC(object):
name = "cavro_centris_syringe_pump_IOC"
from persistent_property import persistent_property
prefix = persistent_property("prefix","NIH:PUMP")
scan_time = persistent_property("scan_time",3.0)
N = persistent_property("N",4) # number of pumps
running = False
from thread import allocate_lock
lock = allocate_lock()
class queue: # command queue
commands = {}
replies = {}
volume_values = {}
volume_speeds = {}
volume_moving = {}
ports_values = {}
port_moving = {}
def get_EPICS_enabled(self):
return self.running
def set_EPICS_enabled(self,value):
from thread import start_new_thread
if value:
if not self.running: start_new_thread(self.run,())
else: self.running = False
EPICS_enabled = property(get_EPICS_enabled,set_EPICS_enabled)
def run(self):
"""Run EPICS IOC"""
from CAServer import casput,casmonitor,casdel
from numpy import isfinite
from time import time
self.running = True
# Initialization
casput(self.prefix+".SCAN",self.scan_time)
casput(self.prefix+".SPMG",3) # 0:Stop,1:Pause,2:Move,3:Go
for i in range(0,self.N):
casput(self.prefix+"%d.AOUT"%(i+1),"") # ASCII output string to device
casput(self.prefix+"%d.AINP"%(i+1),"") # ASCII input string from device
# Static PVs
for i in range(0,self.N):
casput(self.prefix+"%d:VOLUME.DESC"%(i+1),"Pump%d"%(i+1))
casput(self.prefix+"%d:VOLUME.EGU"%(i+1),"uL")
casput(self.prefix+"%d:PORT.DESC"%(i+1),"Valve%d"%(i+1))
casput(self.prefix+"%d:PORT.EGU"%(i+1),"OIB")
casput(self.prefix+"%d:VOLUME.CNEN"%(i+1),1)
casput(self.prefix+"%d:PORT.CNEN"%(i+1),1)
# Monitor client-writable PVs
casmonitor(self.prefix+".SCAN",callback=self.monitor)
casmonitor(self.prefix+".SPMG",callback=self.monitor)
for i in range(0,self.N):
casmonitor(self.prefix+"%d.AOUT"%(i+1),callback=self.monitor)
casmonitor(self.prefix+"%d.AINP"%(i+1),callback=self.monitor)
casmonitor(self.prefix+"%d:VOLUME.VAL"%(i+1),callback=self.monitor)
casmonitor(self.prefix+"%d:VOLUME.VELO"%(i+1),callback=self.monitor)
casmonitor(self.prefix+"%d:PORT.VAL"%(i+1),callback=self.monitor)
casmonitor(self.prefix+"%d:VOLUME.STOP"%(i+1),callback=self.monitor)
casmonitor(self.prefix+"%d:PORT.STOP"%(i+1),callback=self.monitor)
while self.running:
if self.scan_time > 0 and isfinite(self.scan_time):
for i in range(0,self.N):
if comm_ports.max_time_between_replies[i] > 10:
comm_ports.max_time_between_replies[i] = 0
debug("Reading pump %d configuration"%(i+1))
casput(self.prefix+"%d:VOLUME.VAL"%(i+1),volumes.values([i])[0])
casput(self.prefix+"%d:VOLUME.LLM"%(i+1),volumes.low_limits([i])[0])
casput(self.prefix+"%d:VOLUME.HLM"%(i+1),volumes.high_limits([i])[0])
casput(self.prefix+"%d:PORT.VAL"%(i+1),ports.values([i])[0])
t = time()
values = volumes.values(range(0,self.N))
for i in range(0,self.N):
casput(self.prefix+"%d:VOLUME.RBV"%(i+1),values[i])
self.process_command_queue()
values = ports.values(range(0,self.N))
for i in range(0,self.N):
casput(self.prefix+"%d:PORT.RBV"%(i+1),values[i])
self.process_command_queue()
moving = volumes.moving(range(0,self.N))
for i in range(0,self.N):
casput(self.prefix+"%d:VOLUME.DMOV"%(i+1),not moving[i])
casput(self.prefix+"%d:PORT.DMOV"%(i+1),not moving[i])
self.process_command_queue()
speeds = volumes.speeds(range(0,self.N))
for i in range(0,self.N):
casput(self.prefix+"%d:VOLUME.VELO"%(i+1),speeds[i])
self.process_command_queue()
sleep(t+1*self.scan_time-time())
casput(self.prefix+".SCANT",time()-t) # post actual scan time for diagnostics
else:
casput(self.prefix+".SCANT",nan)
sleep(0.1)
casdel(self.prefix)
def monitor(self,PV_name,value,char_value):
"""Handle client changes to PVs"""
with self.lock: # Allow only one thread at a time inside this function.
info("Received request %s=%r" % (PV_name,value))
# Delay execution of client requests storing them in a command queue.
from CAServer import casput
if PV_name == self.prefix+".SCAN":
self.scan_time = value
casput(self.prefix+".SCAN",self.scan_time)
for i in range(0,self.N):
if PV_name == self.prefix+"%d.AOUT"%(i+1):
self.queue.commands[i] = value # queue for execution
elif PV_name == self.prefix+"%d:VOLUME.VAL"%(i+1):
self.queue.volume_values[i] = value # queue for execution
elif PV_name == self.prefix+"%d:VOLUME.VELO"%(i+1):
self.queue.volume_speeds[i] = value # queue for execution
elif PV_name == self.prefix+"%d:VOLUME.STOP"%(i+1):
self.queue.volume_moving[i] = not value # queue for execution
elif PV_name == self.prefix+"%d:PORT.VAL"%(i+1):
self.queue.ports_values[i] = value # queue for execution
elif PV_name == self.prefix+"%d:PORT.STOP"%(i+1):
self.queue.ports_values_moving[i] = not value # queue for execution
info("Command count: %r" % len(self.queue.commands))
def process_command_queue(self):
"""Handle client changes to PVs that where queued up by 'monitor'
in a synchronous ways."""
with self.lock: # Allow only one thread at a time inside this function.
if not self.queue_halted:
from CAServer import casput
if self.queue.commands:
info("Sending commands %r" % self.queue.commands)
replies = comm_ports.write_read(self.queue.commands)
self.analyze_commands(self.queue.commands)
info("Got replies %r" % replies)
for i in replies:
info("Updating %s=%r" % (self.prefix+"%d.AINP"%(i+1),replies[i]))
casput(self.prefix+"%d.AINP"%(i+1),replies[i],update=True)
self.queue.commands = {}
if self.queue.volume_values:
volumes.set_values(self.queue.volume_values.keys(),self.queue.volume_values.values())
V = self.queue.volume_values
for i in V: casput(self.prefix+"%d:VOLUME.VAL"%(i+1),V[i])
self.queue.volume_values = {}
if self.queue.volume_speeds:
volumes.set_speeds(self.queue.volume_speeds.keys(),self.queue.volume_speeds.values())
indices = self.queue.volume_speeds.keys()
speeds = volumes.speeds(indices) # read back values
for i in indices: casput(self.prefix+"%d:VOLUME.VELO"%(i+1),speeds[i])
self.queue.volume_speeds = {}
if self.queue.ports_values:
ports.set_values(self.queue.ports_values.keys(),self.queue.ports_values.values())
p = self.queue.ports_values
for i in p: casput(self.prefix+"%d:PORT.VAL"%(i+1),p[i])
self.queue.ports_values = {}
if self.queue.volume_moving:
volumes.set_moving(self.queue.volume_moving.keys(),self.queue.volume_moving.values())
self.queue.volume_moving = {}
def analyze_commands(self,command_dict):
"""Updaste state info base on serial commands snet directly to the
pump onctroller"""
from CAServer import casput
from parse import parse
for i,command in command_dict.iteritems():
values = parse("/{}A{value:g},1{}",command) # Absolute volume
if values: casput(self.prefix+"%d:VOLUME.VAL"%(i+1),values["value"])
def get_queue_halted(self):
"""Is the execution queue in the IOC currently halteded?"""
from CAServer import casget
return casget(self.prefix+".SPMG") <=1 # 0:Stop,1:Pause,2:Move,3:Go
def set_queue_halted(self,value):
from CAServer import casput
return casput(self.prefix+".SPMG",0 if value else 3)
queue_halted = property(get_queue_halted,set_queue_halted)
syringe_pump_IOC = Syringe_Pump_IOC()
class PumpController(object):
name = "cavro_centris_syringe_pump"
from persistent_property import persistent_property
prefix = persistent_property("prefix","NIH:PUMP")
timeout = 3.0
def write_read(self,command_dict):
"""Writes commands to multiple pumps with pump ids and commands
assembled in a dictionary. (with 1-based indices for the pumps)
Returns a dictionary of pump ids and their respective responses."""
from CA import caput,camonitor
from time import time,sleep
self.replies = {}
self.monitor_ids = command_dict.keys()
for i in command_dict:
camonitor(self.prefix+"%s.AINP"%i,callback=self.monitor)
if len(command_dict) > 1: caput(self.prefix+".SPMG",0) # halt queue
self.replies = {}
for i,command in command_dict.iteritems():
caput(self.prefix+"%s.AOUT"%i,command)
if len(command_dict) > 1: caput(self.prefix+".SPMG",3) # resume queue
t0 = time()
while not all([i in self.replies for i in command_dict]):
if time()-t0 > self.timeout: break
sleep(0.010)
return self.replies
def monitor(self,PV_name,value,char_value):
"""Handle client changes to PVs"""
debug("Got PV update %s=%r",PV_name,value)
for i in self.monitor_ids:
if PV_name == self.prefix+"%s.AINP"%i: self.replies[i] = value
def get_queue_halted(self):
"""Is the execution queue in the IOC currently halteded?"""
from CA import caget
return caget(self.prefix+".SPMG") <=1
def set_queue_halted(self,value):
from CA import caput
return caput(self.prefix+".SPMG",0 if value else 3)
queue_halted = property(get_queue_halted,set_queue_halted)
pump_controller = PumpController()
def alias(name):
"""Make property given by name be known under a different name"""
def get(self): return getattr(self,name)
def set(self,value): setattr(self,name,value)
return property(get,set)
from EPICS_motor import EPICS_motor
class Syringe_Pump(EPICS_motor):
command_value = alias("VAL") # EPICS_motor.command_value not changable
volume = [
EPICS_motor(prefix="NIH:PUMP%d:VOLUME"%(i+1),name="syringe_pump%d"%(i+1)) \
for i in range(0,4)]
port = [
EPICS_motor(prefix="NIH:PUMP%d:PORT"%(i+1),name="syringe_pump%d"%(i+1)) \
for i in range(0,4)]
from CA import Record
pump = Record(prefix="NIH:PUMP")
def sleep(seconds):
"""Delay execution by the given number of seconds"""
# This version of "sleep" does not throw an excpetion if passed a negative
# waiting time, but instead returns immediately.
from time import sleep
if seconds > 0: sleep(seconds)
if __name__ == "__main__":
from pdb import pm # for debugging
import logging;
logging.basicConfig(level=logging.INFO,
format="%(asctime)s %(levelname)s: %(message)s")
##import CAServer; CAServer.LOG = True; CAServer.verbose = True
self = ports # for debugging
from sys import argv
if "run_IOC" in argv: syringe_pump_IOC.run()
else:
print('syringe_pump_IOC.EPICS_enabled = True')
##print('comm_ports.available_ports')
##print('comm_ports.discover()')
##print('pump_controller.write_read({i: "/1?18\\r" for i in [0,1]})')
##print('ports.values([0])')
##print('ports.set_values([0],[0])')
<file_sep>"""
Table jacks of optical table in 14ID-B end station
<NAME>, 10 Nov 2007
"""
from motor import *
TDSY = motor("14IDB:m17") # downstream vertical
TOUTY = motor("14IDB:m18") # outward vertical
TINY = motor("14IDB:m19") # inward vertical
TUSX = motor("14IDB:m20") # upstream horizontal
TDSX = motor("14IDB:m21") # downstream horizontal
TDSZ = motor("14IDB:m22") # downstream along X-ray beam (not used yet)
table_motors = [TUSX,TDSX,TOUTY,TINY,TDSY]
def reset_table():
""" This is to bring the table in a well defined state after it was moved
applying al the backlsh corrections"""
step = 0.1
for m in table_motors: m -= step; m.wait()
for m in table_motors: m += step; m.wait()
<file_sep>#!/usr/bin/env python
"""Efficient vectorized version of "exists".
<NAME>, Dec 2014 - 27 Feb 2017"""
__version__ = "1.0.2" # global var for caching, exist_files returns array
timeout = 10.0
directories = {}
def exist_files(filenames):
"""filenames: list of pathnames
return value: list of booleans"""
from os import listdir
from os.path import exists,dirname,basename
from time import time
from normpath import normpath
from numpy import array
exist_files = []
for f in filenames:
d = dirname(f)
if not d in directories or time() - directories[d]["time"] > timeout:
try: files = listdir(normpath(d) if d else ".")
except OSError: files = []
directories[d] = {"files":files,"time":time()}
exist_files += [basename(f) in directories[d]["files"]]
exist_files = array(exist_files)
return exist_files
<file_sep>#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
Authors: <NAME>, <NAME>, <NAME>, <NAME>
Date created: 12/8/2016 (original)
Date last modified: 05/25/2018
"""
__version__ = "1.3"
from time import sleep,time
from logging import debug,info,warn,error
import logging
from thread import start_new_thread
import traceback
import psutil, os
import platform #https://stackoverflow.com/questions/110362/how-can-i-find-the-current-os-in-python
p = psutil.Process(os.getpid()) #source: https://psutil.readthedocs.io/en/release-2.2.1/
# psutil.ABOVE_NORMAL_PRIORITY_CLASS
# psutil.BELOW_NORMAL_PRIORITY_CLASS
# psutil.HIGH_PRIORITY_CLASS
# psutil.IDLE_PRIORITY_CLASS
# psutil.NORMAL_PRIORITY_CLASS
# psutil.REALTIME_PRIORITYsindows':
if platform.system() == 'Windows':
p.nice(psutil.ABOVE_NORMAL_PRIORITY_CLASS)
elif platform.system() == 'Linux': #linux FIXIT
p.nice(-10) # nice runs from -20 to +12, where -20 the most not nice code(highest priority)
from numpy import nan, mean, std, nanstd, asfarray, asarray, hstack, array, concatenate, delete, round, vstack, hstack, zeros, transpose, split, unique, nonzero, take, savetxt, min, max
from time import time, sleep, clock
import sys
import os.path
import struct
from pdb import pm
from time import gmtime, strftime, time
from logging import debug,info,warn,error
###These are Friedrich's libraries.
###The number3 in the end shows that it is competable with the Python version 3.
###However, some of them were never well tested.
if sys.version_info[0] ==3:
from persistent_property3 import persistent_property
from DB3 import dbput, dbget
from module_dir3 import module_dir
from normpath3 import normpath
else:
from persistent_property import persistent_property
from DB import dbput, dbget
from module_dir import module_dir
from normpath import normpath
from struct import pack, unpack
from timeit import Timer, timeit
import sys
###In Python 3 the thread library was renamed to _thread
if sys.version_info[0] ==3:
from _thread import start_new_thread
else:
from thread import start_new_thread
from datetime import datetime
from precision_sleep import precision_sleep #home-built module for accurate sleep
import msgpack
import msgpack_numpy as m
import socket
import platform
server_name = platform.node()
class server_LL(object):
def __init__(self, name = ''):
"""
to initialize an instance and create main variables
"""
if len(name) == 0:
self.name = 'test_communication_LL'
else:
self.name = name
self.running = False
self.network_speed = 12**6 # bytes per second
self.client_lst = []
def init_server(self):
'''
Proper sequence of socket server initialization
'''
self._set_commands()
self.sock = self.init_socket()
if self.sock is not None:
self.running = True
else:
self.running = False
self._start()
def stop(self):
self.running = False
self.sock.close()
def init_socket(self):
'''
initializes socket for listening, creates sock and bind to '' with a port somewhere between 2030 and 2050
'''
import socket
ports = range(2030,2050)
for port in ports:
try:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.bind(('', port))
self.port = port
sock.listen(100)
flag = True
except:
error(traceback.format_exc())
flag = False
if flag:
break
else:
sock = None
return sock
def _set_commands(self):
"""
Set type definition, the dictionary of command excepted by the server
Standard supported commands:
- "help"
- "init"
- "close"
- "abort"
- "snapshot"
- "subscribe"
- "task"
"""
self.commands = {}
self.commands['help'] = 'help'
self.commands['init'] = 'init'
self.commands['close'] = 'close'
self.commands['abort'] = 'abort'
self.commands['snapshot'] = 'snapshot'
self.commands['subscribe'] = 'subscribe'
self.commands['task'] = 'task'
def _get_commands(self):
"""
returns the dictionary with all supported commands
"""
return self.commands
def _start(self):
'''
creates a separete thread for server_thread function
'''
start_new_thread(self._run,())
def _run(self):
"""
runs the function _run_once in a while True loop
"""
self.running = True
while self.running:
self._run_once()
self.running = False
def _run_once(self):
"""
creates a listening socket.
"""
client, addr = self.sock.accept()
debug('Client has connected: %r,%r' %(client,addr))
self._log_last_call(client, addr)
try:
msg_in = self._receive(client)
except:
error(traceback.format_exc())
msg_in = {b'command':b'unknown',b'message':b'unknown'}
msg_out = self._receive_handler(msg_in,client)
self._send(client,msg_out)
def _transmit_handler(self,command = '', message = ''):
from time import time
res_dic = {}
res_dic[b'command'] = command
res_dic[b'time'] = time()
res_dic[b'message'] = message
return res_dic
def _receive_handler(self,msg_in,client):
"""
the incoming msg_in has N mandatory fields: command, message and time
"""
from time import time
res_dic = {}
#the input msg has to be a dictionary. If not, ignore. FIXIT. I don't know how to do it in Python3
debug('command received: %r' % msg_in)
try:
keys = msg_in.keys()
command = msg_in[b'command']
res_dic['command'] = command
flag = True
if command == b'help':
res_dic['message'] = self.help()
elif command == b'init':
res_dic['message'] = self.dev_init()
elif command == b'close':
res_dic['message'] = self.dev_close()
elif command == b'abort':
res_dic['message'] = self.dev_abort()
elif command == b'snapshot':
res_dic['message'] = self.dev_snapshot()
elif command == b'subscribe':
try:
port = message['port']
err = ''
except:
err = traceback.format_exc()
if len(err) ==0:
res_dic['message'] = self.subscribe(client,port)
else:
res_dic['message'] = 'server needs port number to subscribe'
elif command == b'task':
print(msg_in)
if b'message' in msg_in.keys():
res_dic['message'] = self.task(msg_in[b'message'])
else:
flag = False
err = 'task command does not have message key'
else:
flag = False
err = 'the command %r is not supporte by the server' % command
if not flag:
debug('command is not recognized')
res_dic['command'] = 'unknown'
res_dic['message'] = 'The quote of the day: ... . I hope you enjoyed it.'
res_dic['flag'] = flag
res_dic['error'] = err
else:
res_dic['flag'] = flag
res_dic['error'] = ''
except:
error(traceback.format_exc())
res_dic['command'] = 'unknown'
res_dic['message'] = 'The quote of the day: ... . I hope you enjoyed it.'
res_dic['flag'] = True
res_dic['error'] = ''
res_dic[b'time'] = time()
return res_dic
def _receive(self,client):
"""
descritpion:
client sends 20 bytes with a number of expected package size.
20 bytes will encode a number up to 10**20 bytes.
This will be enough for any possible size of the transfer
input:
client - socket client object
output:
unpacked data
"""
import msgpack
import msgpack_numpy as msg_m
a = client.recv(20)
length = int(a)
debug('initial length: %r' % length)
sleep(0.01)
if length != 0:
msg_in = ''.encode()
while len(msg_in) < length:
debug('length left (before): %r' % length)
msg_in += client.recv(length - len(msg_in))
debug('length left (after): %r' % length)
sleep(0.01)
else:
msg_in = ''
return msgpack.unpackb(msg_in, object_hook=msg_m.decode)
def _send(self,client,msg_out):
"""
descrition:
uses msgpack to serialize data and sends it to the client
"""
debug('command send %r' % msg_out)
msg = msgpack.packb(msg_out, default=m.encode)
length = str(len(msg))
if len(length)!=20:
length = '0'*(20-len(length)) + length
try:
client.sendall(length.encode())
client.sendall(msg)
flag = True
except:
error(traceback.format_exc())
flag = False
return flag
def _connect(self,ip_address,port):
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
server.settimeout(10)
server.connect((ip_address , port))
server.settimeout(None)
debug("Connection success!")
except:
error('%r' %(traceback.format_exc()))
server = None
return server
def _transmit(self,command = '', message = '' ,ip_address = '127.0.0.1',port = 2031):
msg_out = self._transmit_handler(command = command, message = message)
server = self._connect(ip_address = ip_address,port = port)
flag = self._send(server,msg_out)
self.response_arg = self._receive(server)
self._server_close(server)
return self.response_arg
def _server_close(self,server):
server.close()
return server
def _log_last_call(self,client,addr):
self.last_call = [addr,client.getpeername()]
#***************************************************
#*** wrappers for basic response functions *********
#***************************************************
def subscribe(self,port,client):
self.subscribe_lst = [client.getpeername()[0],port]
msg = 'subscribe command received' + str(self.subscribe_lst)
debug(msg)
return msg
def help(self):
debug('help command received')
#***************************************************
#*** wrappers for basic response functions *********
#***************************************************
def help(self):
msg = {}
msg['server name']= self.name
msg['commands'] = self.commands
msg['dev_indicators'] = device.indicators.keys()
msg['dev_controls'] = device.controls.keys()
debug(msg)
return msg
def dev_init(self):
msg = 'init command received'
device.init()
debug(msg)
return msg
def dev_close(self):
msg = 'close command received'
debug(msg)
return msg
def dev_abort(self):
msg = 'abort command received'
debug(msg)
return msg
def dev_snapshot(self):
msg = 'snapshot command received'
debug(msg)
msg = device.snapshot()
return msg
def dev_task(self,msg):
msg = 'task command received: %r' % msg
debug(msg)
return msg
def dev_get_device_indicators(self, indicator = {}):
response = {}
if 'all' in indicator.keys():
response = device.indicators
else:
for key in indicator.keys():
if key in device.indicators.keys():
response[key] = device.indicators[key]
return response
def dev_set_device_indicators(self, control = {}):
for key in controll.keys():
if key in device.controlls.keys():
device.controlls[key] = controll[key]
def dev_get_device_controls(self, control = {}):
response = {}
if 'all' in control.keys():
response = device.controls
else:
for key in controll.keys():
if key in device.controls.keys():
response[key] = device.controls[key]
return response
def dev_set_device_controls(self, control = {}):
for key in control.keys():
if key in device.controls.keys():
device.controls[key] = control[key]
class client_LL(object):
def __init__(self, name = ''):
"""
to initialize an instance and create main variables
"""
if len(name) == 0:
self.name = 'test_client_LL'
else:
self.name = name
self.running = False
self.network_speed = 12**6 # bytes per second
self.client_lst = []
def init_server(self):
'''
Proper sequence of socket server initialization
'''
self._set_commands()
if self.sock is not None:
self.running = True
else:
self.running = False
def stop(self):
self.running = False
self.sock.close()
def _set_commands(self):
"""
Set type definition, the dictionary of command excepted by the server
Standard supported commands:
- "help"
- "init"
- "close"
- "abort"
- "snapshot"
- "subscribe"
- "task"
"""
self.commands = {}
self.commands['help'] = 'help'
self.commands['init'] = 'init'
self.commands['close'] = 'close'
self.commands['abort'] = 'abort'
self.commands['snapshot'] = 'snapshot'
self.commands['subscribe'] = 'subscribe'
self.commands['task'] = 'task'
def _get_commands(self):
"""
returns the dictionary with all supported commands
"""
return self.commands
def _transmit_handler(self,command = '', message = ''):
from time import time
res_dic = {}
res_dic[b'command'] = command
res_dic[b'time'] = time()
res_dic[b'message'] = message
return res_dic
def _receive(self,client):
"""
descritpion:
client sends 20 bytes with a number of expected package size.
20 bytes will encode a number up to 10**20 bytes.
This will be enough for any possible size of the transfer
input:
client - socket client object
output:
unpacked data
"""
import msgpack
import msgpack_numpy as msg_m
a = client.recv(20)
length = int(a)
sleep(0.01)
if length != 0:
msg_in = ''.encode()
while len(msg_in) < length:
msg_in += client.recv(length - len(msg_in))
sleep(0.01)
else:
msg_in = ''
return msgpack.unpackb(msg_in, object_hook=msg_m.decode)
def _send(self,client,msg_out):
"""
descrition:
uses msgpack to serialize data and sends it to the client
"""
debug('command send %r' % msg_out)
msg = msgpack.packb(msg_out, default=m.encode)
length = str(len(msg))
if len(length)!=20:
length = '0'*(20-len(length)) + length
try:
client.sendall(length.encode())
client.sendall(msg)
flag = True
except:
error(traceback.format_exc())
flag = False
return flag
def _connect(self,ip_address,port):
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
server.settimeout(10)
server.connect((ip_address , port))
server.settimeout(None)
debug("Connection success!")
except:
error('%r' %(traceback.format_exc()))
server = None
return server
def _transmit(self,command = '', message = '' ,ip_address = '127.0.0.1',port = 2031):
msg_out = self._transmit_handler(command = command, message = message)
server = self._connect(ip_address = ip_address,port = port)
flag = self._send(server,msg_out)
self.response_arg = self._receive(server)
self._server_close(server)
return self.response_arg
def _server_close(self,server):
server.close()
return server
def _log_last_call(self,client,addr):
self.last_call = [addr,client.getpeername()]
#***************************************************
#*** wrappers for basic response functions *********
#***************************************************
def subscribe(self,port,client):
self.subscribe_lst = [client.getpeername()[0],port]
msg = 'subscribe command received' + str(self.subscribe_lst)
debug(msg)
return msg
class syringe_pump_DL(object):
def __init__(self):
self.name = 'syringe_pump_DL'
def init(self):
from cavro_centris_syringe_pump_LL import driver
driver.discover()
self.indicators = {}
self.controls = {}
self.indicators['positions'] = {}
self.indicators['valves'] = {}
def help(self):
debug('help command received')
def snapshot(self):
response = {}
response['indicators'] = self.indicators
response['controls'] = self.controls
from numpy import random
response['data'] = random.rand(2,100000)
return response
def update_indictors(self):
from cavro_centris_syringe_pump_LL import driver
self.indicators['positions'] = driver.positions(pids = [1,2,3,4])
self.indicators['valves'] = driver.valve_get(pids = [1,2,3,4])
def run_once(self):
from time import sleep
while True:
self.update_indictors()
sleep(1)
def run(self):
start_new_thread(self.run_once,())
server = server_LL(name = 'suringe_pump_server_DL')
client = client_LL(name = 'suringe_pump_client_DL')
from cavro_centris_syringe_pump_LL import driver
device = syringe_pump_DL()
server.init_server()
if __name__ == "__main__":
from tempfile import gettempdir
logging.basicConfig(#filename=gettempdir()+'/suringe_pump_DL.log',
level=logging.DEBUG, format="%(asctime)s %(levelname)s: %(message)s")
print('driver.discover()')
print('driver.prime(1)')
print('driver.prime(3)')
<file_sep>#!/bin/env python
"""Setup: source /reg/g/psdm/etc/ana_env.sh"""
import zmq
import numpy as np
context = zmq.Context()
server = context.socket(zmq.PAIR)
server.bind("tcp://127.0.0.1:12322")
arr = np.zeros([512,512])
while True:
i = server.recv_pyobj()
print i
server.send_pyobj(arr+i)
<file_sep>##from configuration_driver import *
from configuration_client import *
<file_sep>#!/usr/bin/env python
"""Find number of spots and decide if the sample is frozen.
Authors: <NAME>, <NAME>, <NAME>
Date created: 2017-10-31
Date last modified: 2018-10-29
1.4 - uses freeze_intervention from freeze_intervention module
- changed function current_image_file() because i was always getting empty string
as current temp filename
"""
__version__ = "1.4" # uses freeze_intervention from freeze_intervention module
from logging import debug,info,warn,error
class Sample_Frozen(object):
name = "sample_frozen"
from persistent_property import persistent_property
deice_enabled = persistent_property("deice_enabled",False)
threshold_N_spts = persistent_property("threshold_N_spts",10)
running_timestamp = persistent_property("running_timestamp",0)
ROIX = persistent_property("ROIX",1000) #900
ROIY = persistent_property("ROIY",1000) #900
WIDTH = persistent_property("WIDTH",150) #300 #400
CAS_prefix = persistent_property("CAS_prefix",'NIH:SAMPLE_FROZEN_XRAY') #300 #400
intervention_enabled = False
retract_deicing_enabled = False
retracted_time = 20.0
def get_running(self):
from time import time
return time() - self.running_timestamp <= 3.0
def set_running(self,value):
from thread import start_new_thread
from CAServer import casput
if value and not self.running:
casput(self.CAS_prefix+'.RUNNING', value)
self.deice_enabled = True
start_new_thread(self.run,())
else: self.deice_enabled = False
running = property(get_running,set_running)
def get_is_intervention_enabled(self):
from time import time
return self.intervention_enabled
def set_is_intervention_enabled(self,value):
from CAServer import casput
self.intervention_enabled = value
casput(self.CAS_prefix+'.ENABLED', self.intervention_enabled)
is_intervention_enabled = property(get_is_intervention_enabled,set_is_intervention_enabled)
def run(self):
from time import time,sleep
from CAServer import casget,casput
from SAXS_WAXS_control import SAXS_WAXS_control
from temperature_controller import temperature_controller
casput(self.CAS_prefix+'.ENABLED', self.intervention_enabled)
casput(self.CAS_prefix+'.RUNNING', self.deice_enabled)
try:
print('current temperature %r' % temperature_controller.value)
info('current temperature %r' % temperature_controller.value)
except:
warn('could not get temperature')
last_image_file = ""
while self.deice_enabled:
try:
self.intervention_enabled = casget(self.CAS_prefix+'.ENABLED')
except:
error('Failed to get CA %r' % (self.CAS_prefix+'.ENABLED'))
self.intervention_enabled = False
self.running_timestamp = time()
if self.current_image_file != last_image_file:
last_image_file = self.current_image_file
if self.sample_frozen(self.current_image_file) and not self.aux_deicing and self.intervention_enabled and (temperature_controller.value < -5.0) :
self.aux_deicing = True
elif self.sample_frozen(self.current_image_file) and SAXS_WAXS_control.inserted and self.retract_deicing and (temperature_controller.value < -5.0):
SAXS_WAXS_control.retracted = True
sleep(self.retracted_time)
SAXS_WAXS_control.inserted = True
else:
pass
else: sleep(0.25)
@property
def sample_currently_frozen(self):
"""Does te current image show ice diffraction peaks?"""
return self.sample_frozen(self.current_image_file)
@property
def diffraction_spots(self):
"""Does te current image show ice diffraction peaks?"""
return self.diffraction_spots_of_image(self.current_image_file)
def get_deicing(self):
"""Is the motion controller program instructed to run in 'deice' mode?"""
from freeze_intervention import freeze_intervention
return freeze_intervention.active
def set_deicing(self,value):
from freeze_intervention import freeze_intervention
freeze_intervention.active = value
#from Ensemble_client import ensemble
#ensemble.integer_registers[3] = 3 if value else 0
#info("ensemble.integer_registers[3] = %r" % ensemble.integer_registers[3])
aux_deicing = property(get_deicing,set_deicing)
def get_retract(self):
"""Is the motion controller program instructed to run in 'deice' mode?"""
from SAXS_WAXS_control import SAXS_WAXS_control
return SAXS_WAXS_control.retracted
def set_retract(self,value):
from SAXS_WAXS_control import SAXS_WAXS_control
SAXS_WAXS_control.retracted = value
retract = property(get_retract,set_retract)
def get_retract_deicing(self):
from time import time
return self.retract_deicing_enabled
def set_retract_deicing(self,value):
from CAServer import casput
self.retract_deicing_enabled = value
casput(self.CAS_prefix+'.RETRACT_ENABLED', self.retract_deicing_enabled)
retract_deicing = property(get_retract_deicing,set_retract_deicing)
def sample_frozen(self,image_file):
from CAServer import casput
total_spots = self.diffraction_spots_of_image(image_file)
try:
casput(self.CAS_prefix+'.SPOTS',total_spots)
except:
pass
flag = total_spots >= self.threshold_N_spts
return flag
def diffraction_spots_of_image(self,image_file):
from peak_integration import spot_mask
from numimage import numimage
from scipy.ndimage.measurements import label
from os.path import basename
I = numimage(image_file)
ROIX,ROIY,WIDTH = self.ROIX,self.ROIY,self.WIDTH
I = I[ROIX:ROIX+WIDTH,ROIY:ROIY+WIDTH] # part of image
mask = spot_mask(I+20)
##total_spots = mask.sum()
labelled_mask,total_spots = label(mask)
if total_spots > 0: debug("%s: %s spots" % (basename(image_file),total_spots))
return total_spots
@property
def current_image_file(self):
from rayonix_detector_continuous import rayonix_detector
return rayonix_detector.current_temp_filename #<--this function always gives empty string Oct 29 2018
#return rayonix_detector.current_image_filename
sample_frozen = Sample_Frozen()
image_file1 = "/net/mx340hs/data/anfinrud_1711/Data/WAXS/GA/GA-2/xray_images/GA-2_2_75.6C_3_562ns.mccd" # ice
image_file2 = "/net/mx340hs/data/anfinrud_1711/Data/WAXS/GA/GA-2/xray_images/GA-2_2_75.6C_3_-10us.mccd" # no ice
image_file3 = "/net/mx340hs/data/anfinrud_1711/Data/WAXS/GA/GA-2/xray_images/GA-2_2_75.6C_2_-10us.mccd" # no ice
image_file4 = "/net/mx340hs/data/anfinrud_1711/Data/WAXS/GA/GA-2/xray_images/GA-2_2_75.6C_3_-10us-2.mccd" # ice
def test():
# Load a test image.
from time import time
t0 = time()
is_sample_frozen1 = sample_frozen.sample_frozen(image_file1)
t1 = time()
print("time %.3f s" %(t1-t0))
is_sample_frozen2 = sample_frozen.sample_frozen(image_file2)
t2 = time()
print("time %.3f s" %(t2-t1))
is_sample_frozen3 = sample_frozen.sample_frozen(image_file3)
t3 = time()
print("time %.3f s" %(t3-t2))
is_sample_frozen4 = sample_frozen.sample_frozen(image_file4)
print("time %.3f s" %(time()-t3))
print("sample frozen file1: %r" % is_sample_frozen1)
print("sample frozen file2: %r" % is_sample_frozen2)
print("sample frozen file3: %r" % is_sample_frozen3)
print("sample frozen file4: %r" % is_sample_frozen4)
def show_current_image():
from rayonix_detector_continuous import rayonix_detector
image_file = rayonix_detector.current_temp_filename
if image_file: show_image(image_file)
def show_image(image_file):
from time import time
from pylab import figure,imshow,title,show,cm
from numimage import numimage
from peak_integration import spot_mask,peak_integration_mask
from numpy import minimum
from scipy.ndimage.measurements import label
I0 = numimage(image_file)
ROIX,ROIY,WIDTH = sample_frozen.ROIX,sample_frozen.ROIY,sample_frozen.WIDTH
I = I0[ROIX:ROIX+WIDTH,ROIY:ROIY+WIDTH]
# Time the 'peak_integration_mask' function.
t0 = time()
mask = spot_mask(I+20)
info('spot_mask = %.3f [s]' %(time()-t0))
##N_spots = mask.sum()
labelled_mask,N_spots = label(mask)
# Display the image.
chart = figure(figsize=(8,8))
title("%s: %d spots" % (image_file,N_spots))
imshow(minimum(I,1000).T,cmap=cm.jet,origin='upper',interpolation='nearest')
if N_spots != 0:
# Spot integration
t0 = time()
SB_mask = peak_integration_mask(I)
t1 = time()
print "Time to find Spots and generate S_mask (s):",t1-t0
# Perform the spot integration.
print "Integrated intensity: ",sum(I*SB_mask)
# Display 'mask'
chart = figure(figsize=(8,8))
title('SB_mask')
imshow(SB_mask.T,cmap=cm.jet,origin='upper',interpolation='nearest')
show()
if __name__ == "__main__": # for testing
from pdb import pm # for debugging
import logging
logging.basicConfig(level=logging.INFO,
format="%(asctime)s %(levelname)s %(message)s")
self = sample_frozen # for debugging
print('sample_frozen.threshold_N_spts = %r' % sample_frozen.threshold_N_spts)
print('test()')
print('show_current_image()')
print('sample_frozen.diffraction_spots')
print('sample_frozen.sample_currently_frozen')
print('sample_frozen.deice_enabled = %r' % sample_frozen.deice_enabled)
print('sample_frozen.running = True')
print('sample_frozen.deicing')
<file_sep>from pylab import *
from table import table
from datetime import datetime
filename = '//id14bxf/data/anfinrud_1006/Data/Test/Test1/backup/Test1 (corrupted).log'
logfile = table(filename,separator="\t")
def seconds(date_time):
"Convert a date string to number of seconds til 1 Jan 1970."
from time import strptime,mktime
return mktime(strptime(date_time,"%d-%b-%y %H:%M:%S"))
t = map(seconds,logfile.date_time)
nom_delay = logfile.nom_delay
act_delay = logfile.act_delay
dt = act_delay - nom_delay
table(filename,separator="\t")
date = [date2num(datetime.fromtimestamp(x)) for x in t]
plot(date,dt/1e-12,'.')
show()
<file_sep>delay = 'delays=pairs(-10us, [-10.1us, 0]+log_series(562ns, 10ms, steps_per_decade=4))'
description = 'Laser Y = -4.235mm, X-ray 40um (H) x 40um (V), Laser 1443nm, 1.10mJ'
finish_series = False
finish_series_variable = u'Delay'
basename = 'RNA-Hairpin-8BP-AU-Stem-End-1'
power = ''
temperature_wait = 1.0
temperature_idle = 22.0
temperature = 'ramp(low=20,high=24,step=0.5,hold=2,repeat=1)'
scan_points = ''
scan_return = 1.0
scan_relative = 1.0
scan_motor = ''
temperatures = '-15.35, 20.15, 89.15'
collection_order = 'Delay, Repeat=4, Temperature, Repeat=5'
cancelled = False
directory = '/net/mx340hs/data/anfinrud_1906/Data/WAXS/RNA-Hairpin/RNA-Hairpin-8BP/RNA-Hairpin-8BP-AU-Stem-End/RNA-Hairpin-8BP-AU-Stem-End-1'
diagnostics = 'ring_current, bunch_current, temperature'
logfile_basename = 'RNA-Hairpin-8BP-AU-Stem-End-1.log'
scan_origin = -1.1740000000000004
detector_configuration = 'xray_detector, xray_scope, laser_scope'<file_sep>ip_address = 'id14b-xscope.cars.aps.anl.gov:2000'
auto_synchronize = True
auto_acquire = True<file_sep>"""
Remote control of thermoelectric chiller by Solid State Cooling Systems,
www.sscooling.com, via RS-323 interface
Model: Oasis 160
See: Oasis Thermoelectric Chiller Manual, Section 7 "Oasis RS-232
communication", p. 15-16
Settings: 9600 baud, 8 bits, parity none, stop bits 1, flow control none
DB09 connector pin 2 = TxD, 3 = RxD, 5 = Ground
The controller accepts binary commands and generates binary replies.
Commands are have the length of one to three bytes.
Replies have a length of either one or two bytes, depending on the command.
Command byte: bit 7: remote control active (1 = remote control,0 = local control)
bit 6 remote on/off (1 = Oasis running, 0 = Oasis in standby mode)
bit 5: communication direction (1 = write,0 = read)
bits 4-0: 00001: [1] Set-point temperature (followed by 2 bytes: temperature in C * 10)
00110: [6] Temperature low limit (followed by 2 bytes: temperature in C * 10)
00111: [7] Temperature high limit(followed by 2 bytes: temperature in C * 10)
01000: [8] Faults (followed by 1 byte)
01001: [9] Actual temperature (followed by 2 bytes: temperature in C * 10)
The 2-byte value is a 16-bit binary number enoding the temperature in units
of 0.1 degrees Celsius (range 0-400 for 0-40.0 C)
The fault byte is a bit map (0 = OK, 1 = Fault):
bit 0: Tank Level Low
bit 2: Temperature above alarm range
bit 4: RTD Fault
bit 5: Pump Fault
bit 7: Temperature below alarm range
Undocumented commands:
C6: Receive the lower limit. (should receive back C6 14 00)
E6 14 00: Set set point low limit to 2C
C7: Receive the upper limit. (should receive back C7 C2 01)
E7 C2 01: Set set point high limit to 45C
E-mail by <NAME> <<EMAIL>>, May 31, 2016,
"RE: Issue with Oasis 160 (S/N 8005853)"
Cabling:
"NIH-Instrumentation" MacBook Pro -> 3-port USB hub ->
"ICUSB232 SM3" UBS-Serial cable -> Oasis chiller
Setup to run IOC:
Windows 7 > Control Panel > Windows Firewall > Advanced Settings > Inbound Rules
> New Rule... > Port > TCP > Specific local ports > 5064-5070
> Allow the connection > When does the rule apply? Domain, Private, Public
> Name: EPICS CA IOC
Inbound Rules > python > General > Allow the connection
Inbound Rules > pythonw > General > Allow the connection
Authors: <NAME>, <NAME>, <NAME>
Date created: 2009-05-28
Date last modified: 2018-05-21
"""
__version__ = "2.4" # using Serial_Device as base classs
from logging import error,warn,info,debug
from serial_device import Serial_Device
class Oasis_Chiller_Device(Serial_Device):
id_query = "A"
id_reply_length = 3
def id_reply_valid(self,reply):
valid = reply.startswith("A") and len(reply) == 3
debug("Reply %r valid? %r" % (reply,valid))
return valid
def parameter_property(parameter_number,scale_factor=1):
"""A 16-bit parameter"""
def get(self): return self.get_value(parameter_number)/scale_factor
def set(self,value): self.set_value(parameter_number,value*scale_factor)
return property(get,set)
command_value = parameter_property(1,scale_factor=10.0)
value = parameter_property(9,scale_factor=10.0)
low_limit = parameter_property(6,scale_factor=10.0)
high_limit = parameter_property(7,scale_factor=10.0)
P1 = parameter_property(0xD0)
I1 = parameter_property(0xD1)
D1 = parameter_property(0xD2)
P2 = parameter_property(0xD3)
I2 = parameter_property(0xD4)
D2 = parameter_property(0xD5)
def set_factory_PID(self):
"""Reset PID parameters to factory settings"""
self.P1 = 90
self.I1 = 32
self.D1 = 2
self.P2 = 50
self.I2 = 35
self.D2 = 3
@property
def faults(self):
"""Report list of faults as string"""
faults = ""
bits = self.faults_byte
if not isnan(bits):
for i in range(0,8):
if (bits >> i) & 1:
if i in self.fault_names: faults += self.fault_names[i]+", "
else: faults += str(i)+", "
faults = faults.strip(", ")
if faults == "": faults = "none"
if faults == "": faults = " "
debug("Faults %s" % faults)
return faults
fault_names = {
0:"Tank Level Low",
1:"Pump Fault",
2:"Temp above alarm range",
4:"RTD Fault",
5:"Pump Fault",
7:"Temp below alarm range",
}
@property
def fault_code(self):
"""Report faults as number
0: no fault
1: Tank Level Low
2: Pump Fault
3: Temp above alarm range
5: RTD Fault
6: Pump Fault
8: Temp below alarm range
"""
faults_byte = self.faults_byte
if faults_byte == 0: fault_code = 0
else: fault_code = highest_bit(faults_byte)+1
debug("Fault code %s" % fault_code)
return fault_code
@property
def faults_byte(self): return self.get_byte(8)
def get_byte(self,parameter_number):
"""Read an 8-bit value
parameter_number: 0-255
8 = fault
"""
from struct import pack,unpack
from numpy import nan
code = int("01000000",2) | parameter_number
command = pack('B',code)
reply = self.query(command,count=2)
count = nan
if len(reply) != 2:
if len(reply)>0:
warn("%r: expecting 2-byte reply, got %r" % (command,reply))
elif self.connected:
warn("%r: expecting 2-byte reply, got no reply" % command)
else:
reply_code,count = unpack('<BB',reply)
if reply_code != code:
warn("reply %r: expecting 0x%X(%s), got 0x%X(%s)" %
(reply,code,bin(code),reply_code,bin(reply_code)))
count = nan
return count
def get_value(self,parameter_number):
"""Read a 16-bit value
parameter_number: 0-255
1=set point, 6=low limit, 7=high limit, 9=coolant temp.
208-213=PID parameter P1,I1,D1,P2,I2,D2
"""
from struct import pack,unpack
from numpy import nan
code = int("01000000",2) | parameter_number
command = pack('B',code)
reply = self.query(command,count=3)
# The reply is 0xC1 followed by 1 16-bit binary count on little-endian byte
# order. The count is the temperature in degrees Celsius, times 10.
if len(reply) != 3:
if len(reply)>0:
warn("%r: expecting 3-byte reply, got %r" % (command,reply))
elif self.connected:
warn("%r: expecting 3-byte reply, got no reply" % command)
return nan
reply_code,count = unpack('<BH',reply)
if reply_code != code:
warn("reply %r: expecting 0x%X(%s), got 0x%X(%s)" %
(reply,code,bin(code),reply_code,bin(reply_code)))
return nan
return count
def set_value(self,parameter_number,value):
"""Set a 16-bit value"""
from struct import pack,unpack
code = int("01100000",2) | parameter_number
command = pack('<BH',code,int(rint(value)))
reply = self.query(command,count=1)
if len(reply) != 1:
warn("expecting 1, got %d bytes" % len(reply)); return
reply_code, = unpack('B',reply)
if reply_code != code: warn("expecting 0x%X, got 0x%X" % (code,reply_code))
oasis_chiller_device = Oasis_Chiller_Device()
def highest_bit(count):
"""Which is the nost significate bit in the binary number "count" that has been
set? 0-based index"""
highest_bit = -1
for i in range(0,32):
if (count & (1<<i)) != 0: highest_bit = i
return highest_bit
if __name__ == "__main__":
from pdb import pm
import logging
logging.basicConfig(level=logging.DEBUG,
format="%(asctime)s %(levelname)s: %(message)s")
self = oasis_chiller_device
print("self.init_communications()")
print("self.command_value")
print("self.value")
print("self.low_limit")
print("self.high_limit")
<file_sep>"""Prototype for an EPICS motor record to be used as base class.
Documentation: aps.anl.gov/bcda/synApps/motor/R6-7/motorRecord.html
"""
__version__ = "1.0"
class motor_record(object):
"""Prototype for an EPICS motor record to be used as base class"""
def __init__(self,record_name=""):
if record_name != "":
from CAServer_new import register_object
register_object(self,record_name)
def get_VAL(self):
"""Command position"""
return getattr(self,"__VAL__",0.0)
def set_VAL(self,value):
self.__VAL__ = value
VAL = property(get_VAL,set_VAL)
def get_RBV(self):
"""Actual position"""
return self.VAL
RBV = property(get_RBV)
EGU = "mm"
DESC = "Test"
PREC = 4 # number of digits
DIR = 0 # positive or negative user vs dial direction
def get_DMOV(self):
"""Done moving: Has the motor reached the set point within
tolerance?
For scans, to provide feedback whether the temperature 'motor'
is still 'moving'"""
return 0
DMOV = property(get_DMOV)
def get_STOP(self): return 0
def set_STOP(self,value):
"""If value = True, cancel the current move."""
if value == 1: pass
STOP = property(get_STOP,set_STOP)
TWV = 1.0 # Tweak value (step size)
def get_TWR(self): return 0
def set_TWR(self,value):
print value
if value != 0: self.VAL -= self.TWV
TWR = property(get_TWR,set_TWR)
def get_TWF(self): return 0
def set_TWF(self,value):
if value != 0: self.VAL += self.TWV
TWF = property(get_TWF,set_TWF)
PCOF = 0.0
ICOF = 0.0
DCOF = 0.0
if __name__ == "__main__":
"""for testing"""
motor = motor_record("14IDB:SAMPLEX")
# Control panel: medm -x -attach -macro P=NIH:,M=TEST motorx.adl
import CAServer_new; CAServer_new.verbose_logging = True
self = motor
<file_sep>if __name__ == "__main__": # for testing
from instrumentation import *
from numpy import *
from ImageViewer import show_images
from os.path import exists
delays = ["100ps","316ps","1ns"]
filenames = list(array([["/net/mx340hs/data/anfinrud_1403/Test/Sequence-Test/Test2/Test_%s_001.mccd" % d
for d in ["off%d"%(1+i),delays[i]]] for i in range(0,len(delays))]).flatten())
print 'ccd.acquire_images_triggered(filenames)'
print 'ccd.acquire_images(filenames,integration_time=0.8,interval_time=1.0)'
print 'xray_detector_trigger.trigger_once()'
print 'xray_detector_trigger.generate_sequence(1,len(filenames))'
print 'show_images(filenames)'
<file_sep>"""<NAME>, Oct 21, 2015 - Oct 31, 2015
"""
__version__ = "1.4.2"
from pdb import pm # for debugging
from Ensemble_SAXS_pp import Ensemble_SAXS
from timing_system import *
from time import sleep,time
##import logging; logging.basicConfig(level=logging.DEBUG,format="%(asctime)s: %(message)s")
##import timing_system as t; t.DEBUG=True
timepoints = [
100*ps,178*ps,316*ps,562*ps,
1*ns,1.78*ns,3.16*ns,5.62*ns,
10*ns,17.8*ns,31.6*ns,56.2*ns,
100*ns,178*ns,316*ns,562*ns,
1*us,1.78*us,3.16*us,5.62*us,
10*us,17.8*us,31.6*us,56.2*us,
100*us,178*us,316*us,562*us,
1*ms,1.78*ms,3.16*ms,5.62*ms,
10*ms,17.8*ms,31.6*ms,
32/hscf,64/hscf,128/hscf
]
timepoints=timepoints
laser_mode = [0,1]
npasses = 2
delays = [t for t in timepoints for l in laser_mode]
laser_ons = [l for t in timepoints for l in laser_mode]
image_numbers = range(1,len(delays)+1)
passes = [npasses]*len(image_numbers)
def start():
timing_system.image_number.value = 0
timing_system.pass_number.value = 0
timing_system.pulses.value = 0
upload()
def upload():
Ensemble_SAXS.acquire(delays,laser_ons,
passes=passes,image_numbers=image_numbers)
def test():
while True:
start()
while len(Ensemble_SAXS.queue) > 10: sleep(1)
print("timing_system.ip_address = %r" % timing_system.ip_address)
print("Ensemble_SAXS.cache_enabled = %r" % Ensemble_SAXS.cache_enabled)
print("Ensemble_SAXS.queue_length")
print("Ensemble_SAXS.clear_queue()")
print("Ensemble_SAXS.cache_clear()")
print("t=time(); upload(); time()-t")
print("t=time(); start(); time()-t")
print("test()")
<file_sep>title = 'Methods Configuration'
motor_names = ['timing_modes', 'sequence_modes', 'Julich_chopper_modes.value', 'heat_load_chopper_modes.value', 'delay_configuration.value', 'temperature_configuration.value', 'power_configuration', 'scan_configuration', 'collect.collection_order', 'diagnostics_configuration', 'detector_configuration']
names = ['timing_modes', 'sequence', 'hsc', 'hlc', 'delays', 'temperatures', 'power', 'scan', 'collection_order', 'diagnostics', 'detector']
motor_labels = ['PP mode', 'Sequence', 'Julich\nchopper', 'Heat-load\nchopper', 'Delay', 'Temperature', 'Power', 'Scan', 'Collection Order', 'Diagnostics', 'Detectors']
widths = [90, 80, 100, 95, 100, 120, 99, 100, 220, 90, 110]
line0.description = 'NIH:S5_T-ramp'
line1.description = 'NIH:H56_ps'
line0..timing_modes = .modes = u'Flythru-4'
line1..timing_modes = .modes = u'Flythru-4'
row_height = 21
show_apply_buttons = True
apply_button_label = 'Select'
show_define_buttons = True
nrows = 27
line2.description = 'NIH:H1_T-jump_early'
line3.description = 'NIH:S5_T-jump'
line4.description = 'NIH:H1_static_temp_Flythru-48'
line0.updated = '2019-05-08 15:31:17'
line1.updated = '2019-05-21 18:49:09'
line2.updated = '2019-03-25 06:24:56'
line3.updated = '2019-05-08 15:30:20'
line4.updated = '2019-03-20 15:37:27'
line0.timing_modes = 'Flythru-4'
line0.high_speed_chopper_modes.value = u'CH-1'
line0.heat_load_chopper_modes.value = '247-1.5'
line0.delay_configuration.value = ''
line1.timing_modes = 'Flythru-48'
line1.high_speed_chopper_modes.value = 'CH-1'
line1.heat_load_chopper_modes.value = '247-1.5'
line1.delay_configuration.value = 'NIH:H-56_ps'
line2.timing_modes = 'Flythru-48'
line2.high_speed_chopper_modes.value = 'CH-1'
line2.heat_load_chopper_modes.value = '247-1.5'
line2.delay_configuration.value = 'NIH:H-1_ns_linear'
line3.timing_modes = u'Flythru-48'
line3.high_speed_chopper_modes.value = 'CH-56'
line3.heat_load_chopper_modes.value = '247-1.5'
line3.delay_configuration.value = 'NIH:H-56_ns'
line4.timing_modes = 'Flythru-48'
line4.high_speed_chopper_modes.value = u'CH-1'
line4.heat_load_chopper_modes.value = '247-1.5'
line4.delay_configuration.value = ''
command_row = 5
define_button_label = 'Update'
show_stop_button = False
line0.ChemMat_chopper_modes.value = 'CH-56'
line1.ChemMat_chopper_modes.value = 'CH-56'
line2.ChemMat_chopper_modes.value = 'CH-1'
line3.ChemMat_chopper_modes.value = 'CH-56'
line4.ChemMat_chopper_modes.value = 'CH-1'
line5.timing_modes = 'Flythru-48'
line5.ChemMat_chopper_modes.value = 'CH-56'
line5.heat_load_chopper_modes.value = '247-1.5'
line5.delay_configuration.value = 'NIH:single_timepoint'
line5.updated = '2019-06-01 06:50:56'
line0.temperature_configuration.value = 'NIH:ramp-16_120_0.5_30_20'
line1.temperature_configuration.value = 'NIH:Water'
line2.temperature_configuration.value = 'Temp_95.5C'
line3.temperature_configuration.value = 'NIH:RNA-T-jump'
line0.collect.collection_order = 'Temperature, Repeat=3'
line1.collect.collection_order = 'Delay, Repeat=4,Temperature,Repeat=5'
line2.collect.collection_order = 'Delay, Repeat=15, Temperature, Repeat=1'
line3.collect.collection_order = 'Delay, Repeat=5, Temperature, Repeat=1'
line5.temperature_configuration.value = ''
line5.collect.collection_order = 'Delay, Scan_Motor'
line5.description = 'NIH:Overlap_scan_Z'
line6.description = 'NIH:Overlap_scan_X'
line6.timing_modes = 'Flythru-48'
line6.heat_load_chopper_modes.value = '247-1.5'
line6.ChemMat_chopper_modes.value = 'CH-56'
line6.delay_configuration.value = 'NIH:single_timepoint'
line6.collect.collection_order = 'Delay, Scan_Motor'
line6.scan_configuration.value = 'Channel Cut'
line6.scan_configuration = 'NIH:Overlap_scan_X'
line5.diagnostics_configuration = 'SAXS/WAXS'
line0.diagnostics_configuration = 'SAXS/WAXS'
line1.diagnostics_configuration = 'SAXS/WAXS'
line2.diagnostics_configuration = 'SAXS/WAXS'
line3.diagnostics_configuration = 'SAXS/WAXS'
line6.diagnostics_configuration = 'SAXS/WAXS'
line0.sequence_modes = 'NIH:i4'
line2.sequence_modes = 'NIH:i5'
line3.sequence_modes = 'NIH:i4'
line1.sequence_modes = 'NIH:i1'
line4.sequence_modes = 'NIH:i5'
line5.sequence_modes = 'NIH:i1'
line6.sequence_modes = 'NIH:i1'
line7.description = 'NIH:S15_static_temp_Flythru-48'
line7.timing_modes = 'Flythru-48'
line7.sequence_modes = 'NIH:i1'
line7.ChemMat_chopper_modes.value = 'CH-56'
line7.heat_load_chopper_modes.value = '247-1.5'
line7.delay_configuration.value = ''
line7.temperature_configuration.value = 'NIH:Overlap'
line7.collect.collection_order = 'Repeat=16, Temperature'
line7.diagnostics_configuration = 'SAXS/WAXS'
line7.updated = '2019-06-01 06:43:21'
line8.description = 'NIH:S5_static'
line8.updated = '2019-01-31 21:08:07'
line8.timing_modes = 'Flythru-4'
line8.sequence_modes = 'NIH:i3'
line8.ChemMat_chopper_modes.value = 'CS-13'
line8.heat_load_chopper_modes.value = '247-1.5'
line8.delay_configuration.value = ''
line8.temperature_configuration.value = ''
line8.collect.collection_order = 'Repeat=32'
line8.diagnostics_configuration = 'SAXS/WAXS'
line7.scan_configuration = ''
line9.description = 'NIH:S19_static_temp_Flythru-24'
line9.timing_modes = 'Flythru-24'
line9.sequence_modes = 'NIH:i1'
line9.ChemMat_chopper_modes.value = 'CH-56'
line9.heat_load_chopper_modes.value = '247-1.5'
line9.delay_configuration.value = ''
line9.temperature_configuration.value = 'NIH:NCBD'
line9.collect.collection_order = 'Repeat=32, Temperature'
line9.diagnostics_configuration = 'SAXS/WAXS'
line9.updated = '2019-05-08 15:39:23'
line9.power_configuration = ''
line9.scan_configuration = ''
line10.description = 'NIH:H_Power_Laser_on_tr'
line10.updated = '29 Oct 02:26'
line10.power_configuration = ''
line10.timing_modes = 'Stepping-96'
line10.sequence_modes = 'NIH:i1'
line10.ChemMat_chopper_modes.value = 'CH-56'
line10.heat_load_chopper_modes.value = '247-1.5'
line10.delay_configuration.value = 'NIH:CW-longtime'
line10.temperature_configuration.value = 'NIH:PYP'
line10.scan_configuration = ''
line10.collect.collection_order = 'Laser_on=[0,1], Delay,Repeat=5,Temperature,Repeat=5'
line10.diagnostics_configuration = 'SAXS/WAXS'
line11.timing_modes = 'Stepping-24'
line11.sequence_modes = 'NIH:Laser_on/off'
line11.ChemMat_chopper_modes.value = 'CH-56'
line11.heat_load_chopper_modes.value = '247-1.5'
line11.delay_configuration.value = ''
line11.temperature_configuration.value = 'None'
line11.power_configuration = 'NIH:0.5_4_10_1'
line11.scan_configuration = ''
line11.collect.collection_order = 'Laser_on=[0,1],Repeat=4,Power, Repeat=2'
line11.diagnostics_configuration = 'SAXS/WAXS'
line11.updated = '29 Oct 07:02'
line11.description = 'NIH:S_Power_Laser_on'
line12.timing_modes = 'Stepping-24'
line12.sequence_modes = 'NIH:i1c1w9'
line12.ChemMat_chopper_modes.value = 'CH-56'
line12.heat_load_chopper_modes.value = '247-1.5'
line12.delay_configuration.value = ''
line12.temperature_configuration.value = 'NIH:PYP'
line12.power_configuration = 'NIH:0.5_4_10_1'
line12.scan_configuration = ''
line12.collect.collection_order = 'Laser_on=[0,1],Repeat=4,Power, Repeat=2,Temperature, Repeat=10'
line12.diagnostics_configuration = 'SAXS/WAXS'
line12.updated = '31 Oct 22:20'
line12.description = 'NIH:H_Power_Laser_on_c1w9'
line2.power_configuration = ''
line2.scan_configuration = ''
line13.timing_modes = 'Flythru-4'
line13.sequence_modes = 'NIH:TR-SAXS'
line13.ChemMat_chopper_modes.value = 'CH-56'
line13.heat_load_chopper_modes.value = '247-1.5'
line13.delay_configuration.value = 'NIH:TR-LT_Exotic'
line13.temperature_configuration.value = 'NIH:PYP'
line13.power_configuration = 'NIH:0.5_4_10_1'
line13.scan_configuration = ''
line13.collect.collection_order = 'Delay, Repeat=64, Temperature'
line13.diagnostics_configuration = 'SAXS/WAXS'
line13.updated = '03 Nov 13:17'
line13.description = 'NIH:H56_ps_Exotic'
line5.power_configuration = ''
line5.scan_configuration = 'NIH:Overlap_scan_Z'
command_rows = [15]
line6.temperature_configuration.value = ''
line6.power_configuration = ''
line6.updated = '2019-06-01 06:50:54'
line14.timing_modes = 'Flythru-24'
line14.sequence_modes = 'NIH:i1'
line14.ChemMat_chopper_modes.value = 'CH-56'
line14.heat_load_chopper_modes.value = '247-1.5'
line14.delay_configuration.value = ''
line14.temperature_configuration.value = 'NIH:ramp-16_120_0.5_30_20'
line14.power_configuration = ''
line14.scan_configuration = ''
line14.collect.collection_order = 'Temperature, Repeat=3'
line14.diagnostics_configuration = 'SAXS/WAXS'
line14.updated = '2019-05-31 20:02:43'
line14.description = 'NIH:S15_T-ramp'
line15.timing_modes = 'Flythru-48'
line15.sequence_modes = 'NIH:i2'
line15.ChemMat_chopper_modes.value = 'CH-56'
line15.heat_load_chopper_modes.value = '247-1.5'
line15.delay_configuration.value = 'NIH:S-7'
line15.temperature_configuration.value = 'NIH:RNA-4BP'
line15.power_configuration = ''
line15.scan_configuration = ''
line15.collect.collection_order = 'Delay, Repeat=4, Temperature, Repeat=5'
line15.diagnostics_configuration = 'SAXS/WAXS'
line15.updated = '2019-06-03 04:59:04'
line15.description = 'NIH:S7_Tjump'
line16.timing_modes = 'Flythru-48'
line16.sequence_modes = 'NIH:i5'
line16.ChemMat_chopper_modes.value = 'CH-1'
line16.heat_load_chopper_modes.value = '247-1.5'
line16.delay_configuration.value = 'NIH:H-1_ns'
line16.temperature_configuration.value = 'NIH:NCBD_Tjump'
line16.power_configuration = ''
line16.scan_configuration = ''
line16.collect.collection_order = 'Delay, Repeat=3, Temperature, Repeat=3'
line16.diagnostics_configuration = 'SAXS/WAXS'
line16.updated = '2019-05-08 15:45:26'
line16.description = 'NIH:S1_Tjump'
line17.timing_modes = 'Flythru-48'
line17.sequence_modes = 'NIH:i1'
line17.ChemMat_chopper_modes.value = 'CH-56'
line17.heat_load_chopper_modes.value = '247-1.5'
line17.delay_configuration.value = 'NIH:H-56_ns'
line17.temperature_configuration.value = 'NIH:RNA-T-jump'
line17.power_configuration = ''
line17.scan_configuration = ''
line17.collect.collection_order = 'Delay, Repeat=3, Temperature, Repeat=10'
line17.diagnostics_configuration = 'SAXS/WAXS'
line17.updated = '2019-05-08 15:45:23'
line17.description = 'NIH:S19_Tjump-RNA'
line16.detector_configuration = 'SAXS/WAXS'
line17.detector_configuration = 'SAXS/WAXS'
line14.detector_configuration = 'SAXS/WAXS static'
line13.detector_configuration = 'SAXS/WAXS'
line15.detector_configuration = 'SAXS/WAXS'
line12.detector_configuration = 'SAXS/WAXS'
line11.detector_configuration = 'SAXS/WAXS'
line10.detector_configuration = 'SAXS/WAXS'
line0.detector_configuration = 'SAXS/WAXS static'
line1.detector_configuration = 'SAXS/WAXS'
line2.detector_configuration = 'SAXS/WAXS'
line3.detector_configuration = 'SAXS/WAXS'
line4.detector_configuration = 'SAXS/WAXS static'
line5.detector_configuration = 'SAXS/WAXS'
line6.detector_configuration = 'SAXS/WAXS'
line7.detector_configuration = 'SAXS/WAXS static'
line8.detector_configuration = 'SAXS/WAXS static'
line9.detector_configuration = 'SAXS/WAXS static'
line0.scan_configuration = ''
line1.scan_configuration = ''
line3.scan_configuration = ''
line4.scan_configuration = ''
line0.power_configuration = ''
line18.timing_modes = 'Flythru-48'
line18.sequence_modes = 'NIH:i1'
line18.ChemMat_chopper_modes.value = 'CS-5'
line18.heat_load_chopper_modes.value = '247-1.5'
line18.delay_configuration.value = ''
line18.temperature_configuration.value = ''
line18.power_configuration = ''
line18.scan_configuration = 'NIH:Slit-Scan-Y'
line18.collect.collection_order = 'Scan_Motor'
line18.diagnostics_configuration = 'NIH:Slit-Scan'
line18.detector_configuration = 'NIH:Slit-Scan'
line18.updated = '2019-05-08 15:37:15'
line0.Julich_chopper_modes.value = 'S-5'
line1.Julich_chopper_modes.value = 'H-56'
line2.Julich_chopper_modes.value = 'H-1'
line3.Julich_chopper_modes.value = 'S-5'
line4.Julich_chopper_modes.value = 'H-1'
line5.Julich_chopper_modes.value = 'S-15'
line6.Julich_chopper_modes.value = 'S-15'
line7.Julich_chopper_modes.value = 'S-15'
line8.Julich_chopper_modes.value = 'S-5'
line9.Julich_chopper_modes.value = 'S-19'
line10.Julich_chopper_modes.value = 'H-56'
line11.Julich_chopper_modes.value = 'H-56'
line12.Julich_chopper_modes.value = 'H-56'
line13.Julich_chopper_modes.value = 'H-56'
line14.Julich_chopper_modes.value = 'S-15'
line16.Julich_chopper_modes.value = 'S-1'
line15.Julich_chopper_modes.value = 'S-7'
line17.Julich_chopper_modes.value = 'S-19'
line18.Julich_chopper_modes.value = ''
line18.description = 'NIH:Slit-Scan-Y'
line4.temperature_configuration.value = ''
line4.power_configuration = ''
line4.collect.collection_order = 'Repeat=32'
line4.diagnostics_configuration = 'SAXS/WAXS'
line19.timing_modes = 'Flythru-48'
line19.updated = '2019-05-08 15:37:20'
line19.sequence_modes = 'NIH:i1'
line19.Julich_chopper_modes.value = ''
line19.heat_load_chopper_modes.value = '247-1.5'
line19.delay_configuration.value = ''
line19.scan_configuration = 'NIH:Slit-Scan-Z'
line19.diagnostics_configuration = 'NIH:Slit-Scan'
line19.detector_configuration = 'NIH:Slit-Scan'
line19.description = 'NIH:Slit-Scan-Z'
line19.collect.collection_order = 'Scan_Motor'
line20.description = 'NIH:Channel-Cut-Scan'
line20.timing_modes = 'Flythru-24'
line20.updated = '2019-05-08 15:37:52'
line20.Julich_chopper_modes.value = 'S-1'
line20.heat_load_chopper_modes.value = '247-1.5'
line20.detector_configuration = 'NIH:Channel-Cut-Scan'
line20.collect.collection_order = 'Scan_Motor'
line20.diagnostics_configuration = 'NIH:Channel-Cut-Scan'
line20.scan_configuration = 'NIH:Channel-Cut-Scan'
line21.timing_modes = 'Laue-20Hz'
line21.updated = '2019-01-29 17:19:50'
line21.Julich_chopper_modes.value = 'S-1'
line21.heat_load_chopper_modes.value = '82-1.5'
line21.detector_configuration = 'APS:Channel-Cut-Scan'
line21.description = 'APS:Channel-Cut-Scan'
line21.scan_configuration = 'NIH:Channel-Cut-Scan'
line20.sequence_modes = 'NIH:i1'
line22.timing_modes = 'Flythru-4'
line22.updated = '2019-05-08 15:44:58'
line22.sequence_modes = 'NIH:i1'
line22.Julich_chopper_modes.value = 'S-1'
line22.heat_load_chopper_modes.value = '247-1.5'
line22.scan_configuration = ''
line22.collect.collection_order = ''
line22.diagnostics_configuration = ''
line22.detector_configuration = 'NIH:X-Ray Beam Check'
line22.description = 'NIH:X-ray Beam Check'
line23.timing_modes = 'Flythru-24'
line23.updated = '2019-05-31 21:45:39'
line23.sequence_modes = 'NIH:i1'
line23.Julich_chopper_modes.value = 'S-15'
line23.heat_load_chopper_modes.value = '247-1.5'
line23.temperature_configuration.value = 'NIH:static-discrete-temp'
line23.collect.collection_order = 'Repeat=16, Temperature'
line23.diagnostics_configuration = 'SAXS/WAXS'
line23.detector_configuration = 'SAXS/WAXS static'
line23.description = 'NIH:S15_static_temp_Flythru24'
line24.timing_modes = 'Flythru-24'
line24.updated = '2019-06-03 01:42:42'
line24.sequence_modes = 'NIH:i1'
line24.Julich_chopper_modes.value = 'S-15'
line24.heat_load_chopper_modes.value = '247-1.5'
line24.delay_configuration.value = ''
line24.temperature_configuration.value = ''
line24.collect.collection_order = 'Repeat=32'
line24.diagnostics_configuration = 'SAXS/WAXS'
line24.detector_configuration = 'SAXS/WAXS static'
line24.description = 'NIH:S15_static_temp'
line25.timing_modes = 'Flythru-4'
line25.updated = '2019-02-02 22:52:26'
line25.sequence_modes = 'NIH:i5'
line25.Julich_chopper_modes.value = 'S-3'
line25.heat_load_chopper_modes.value = '247-1.5'
line25.temperature_configuration.value = 'NIH:static-discrete-temp'
line25.collect.collection_order = 'Repeat=16, Temperature'
line25.diagnostics_configuration = 'SAXS/WAXS'
line25.detector_configuration = 'SAXS/WAXS static'
line25.description = 'NIH:S3_static'
line26.timing_modes = 'Alio-20Hz'
line26.updated = '2019-02-04 11:44:08'
line26.sequence_modes = 'NIH:i1'
line26.Julich_chopper_modes.value = 'S-5'
line26.heat_load_chopper_modes.value = '247-1.5'
line26.delay_configuration.value = '<NAME>'
line26.temperature_configuration.value = ''
line26.collect.collection_order = 'Delay, Repeat=1'
line26.diagnostics_configuration = '<NAME>'
line26.detector_configuration = '<NAME>'
line26.description = '<NAME>'<file_sep>__version__ = "1.0"
if __name__ == "__main__":
from pdb import pm # for debugging
from timing_system import *
from Ensemble_SAXS import Ensemble_SAXS
from numpy import arange,vectorize
from time import time # for timing
import logging
logging.basicConfig(level=logging.DEBUG,format="%(asctime)s: %(message)s")
##import timing_system; timing_system.DEBUG = True
@vectorize
def round(x,n): return float(("%."+str(n)+"g") % x)
timepoints = round(10**arange(-10,-1.75+1e-6,0.25),3)
laser_modes = [0,1]
delays = [x for x in timepoints for l in laser_modes]
laser_on = laser_modes*len(timepoints)
modes = [Ensemble_SAXS.delay_mode(d) for d in delays]
waitts = [Ensemble_SAXS.delay_waitt(d) for d in delays]
N = len(delays)
variables,value_lists = [],[]
variables += [lxd]; value_lists += [delays]
variables += [laseron]; value_lists += [laser_on]
variables += [mson]; value_lists += [[1]*N]
variables += [xdeton]; value_lists += [[1]*N]
variables += [xoscton]; value_lists += [[1]*N]
variables += [loscton]; value_lists += [[1]*N]
variables += [transc_0];value_lists += [[1]*N]
variables += [transc_1];value_lists += [[1]*N]
variables += [waitt]; value_lists += [waitts]
variables += [Ensemble_SAXS];value_lists += [modes]
##for l in value_lists: l += [0] # After last image, turn everything off.
data = sequencer_stream(variables,value_lists)
print 'timing_system.ip_address = %r' % timing_system.ip_address
print 'timing_sequencer.set_sequence(variables,value_lists,1)'
print 'timing_sequencer.add_sequence(variables,value_lists,1)'
print 'timing_sequencer.enabled'
print 'timing_sequencer.running'
print 'timing_sequencer.queue'
print 'timing_sequencer.clear_queue()'
print 'timing_sequencer.abort()'
<file_sep>#!/bin/bash -l
# The -l (login) option makes sure that the environment is the same as for
# an interactive shell.
localdir=`dirname "$0"`
dir=`cd "${localdir}/../../../../../.."; pwd`
cd "$dir"
exec python "ServersPanel.py" >> ~/Library/Logs/Python.log 2>&1
<file_sep>"""<NAME>, Jan 29, 2016 - Jan 29, 2016"""
from pdb import pm
from logging import warn
try: from rayonix_detector_XPP import ccd
except: warn("module 'rayonix_detector_XPP' not imported")
from timing_sequence import timing_sequencer
from timing_system import timing_system
from ImageViewer import show_images
from xppdaq import xppdaq # for xppdaq.endrun()
__version__ = "1.1"
import logging
from tempfile import gettempdir
logging.basicConfig(level=logging.DEBUG,format="%(asctime)s: %(message)s",
filename=gettempdir()+"/lauecollect_debug.log")
nimages = 20
dir = "/reg/neh/operator/xppopr/experiments/xppj1216/Data/Test/Test3/alignment"
filenames = [dir+"/%03d.mccd" % i for i in range(0,nimages)]
image_numbers = range(1,nimages+1)
laser_on = [0]*nimages
ms_on = [0]*nimages
xatt_on = [1]*nimages
npulses = [10]*nimages
# The first image in frame transfer mode has a lot of zingers and needs to be
# discarded.
# The detector trigger is connected as external trigger to the FPGA.
# The trigger pulse for the first image starts the timing seqence.
filenames = [dir+"/discard.mccd"]+filenames
def test_FPGA():
timing_sequencer.inton_sync = 0
timing_system.image_number.value = 0
timing_system.pulses.value = 0
timing_sequencer.acquire(laser_on=laser_on,ms_on=ms_on,xatt_on=xatt_on,
npulses=npulses,image_numbers=image_numbers)
def test_DAQ():
ccd.acquire_images_triggered(filenames)
show_images(filenames)
def test():
test_FPGA()
test_DAQ()
print("test_FPGA()")
print("test_DAQ()")
print("test()")
<file_sep>stabilization_threshold = 0.05
stabilization_nsamples = 5<file_sep>"""
Python interface to EPICS scans
Process variables:
Positioner Read: 14IDB:scan1.R1PV =
Positioner Write: 14IDB:scan1.R1PV =
DetTriggers: 14IDB:scan1.T1PV =
Start scan: 14IDB:scan1.EXSC (set to 1 momentarily)
"""
<file_sep>#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
Authors: <NAME>, <NAME>, <NAME>, <NAME>
Date created: 12/8/2016 (original)
Date last modified: 05/25/2018
"""
__version__ = "1.3"
from time import sleep,time
from logging import debug,info,warn,error
from thread import start_new_thread
from pdb import pm
# Assign default parameters.
Vol = {1:250,2:250,3:250,4:250} # Volumes of syringes.
Backlash = 100 # Backlash in increments.
V_prime = 25 # Volume needed to purge 2.3 m tubing (49 uL/m).
V_purge = 115 # Volume needed to purge 2.3 m tubing (49 uL/m).
V_inflate = 2 # Volume used to inflate tubing.
V_deflate = 2 # Volume used to deflate tubing.
V_clean = 4.0 # Volume used to advance dlivered xtal droplet
V_flush = 4.0 # Volume used to flush collapsible tubing.
V_injectX = 0.2 # Volume used to advance dlivered xtal droplet
V_injectM = 0.3 #Volume of mother liqour during inject
V_injectR = 0.2 # Volume desired for xtal delivery
V_droplet = 1 #Volume used to load droplets into cappilary
V_plug = 5 #Volume of fluorinert to remove protein from channels
S_pressure = 250 # Speed used to change pressure.
S_load = 50 # Speed used to load syringes.
S_prime = 20 # Speed used to prime capillaries.
S_flush = 68 # Speed used to flush collapsible tubing.
S_flow = 0.07 # Speed used to flow through collapsible tubing.
S_min = 0.002 # Minimum Speed available.
S_flowIX = 1.0 # Speed used for injection of xtals
S_flowIM = 0.5 #Speed of flow for injection cycle
S_flowRV = 0.75 #Speed of flow for reverse part of injection cycle
S_flowS1 = 0.05 #Speed used for small droplet generation
port = [1,2,3,4]
class Cavro_centris_syringe_pump_LL(object):
"""Cavro Centris Syringe Pumps"""
ports = {}
abort_flag = [False,False,False,False]
from numpy import inf
max_time_between_replies = {0:inf,1:inf,2:inf,3:inf}
def discover(self):
"""Find the serial ports for each pump controller"""
self.wait_time = 0.015
from serial import Serial
for port_name in self.available_ports:
debug("Trying self.ports %s..." % port_name)
try:
port = Serial(port_name)
port.baudrate = 9600
port.timeout = 0.4
port.write("/1?80\r")
reply = port.readline()
debug("self.ports %r: reply %r" % (port_name,reply))
pid = int(reply[6]) # get pump id for new_pump
self.ports[pid] = port
info("self.ports %r: found pump %r" % (port_name,pid))
except Exception,msg: debug("%s: %s" % (Exception,msg))
for i in self.ports:
debug("p.pump[%d].name = %r" % (i,self.ports[i].name))
def init(self):
"""Initializes pumps, sets Backlash, loads syringes, and leaves valves set to "O"."""
self.busy_flag = {}
for i in range(1,5):
self.busy_flag[i] = False
t0 = time()
self.write_read({pid: "/1TR\r" for pid in port})
info("Executing init...")
info(" emptying syringes...")
self.write_dic({1: "".join(["/1Y7,0,0IV",str(S_load),",1K",str(Backlash),"A0,1R\r"]),
2: "".join(["/1Z7,0,0IV",str(S_load),",1K",str(Backlash),"A0,1R\r"]),
3: "".join(["/1Y7,0,0IV",str(S_load),",1K",str(Backlash),"A0,1R\r"]),
4: "".join(["/1Z7,0,0IV",str(S_load),",1K",str(Backlash),"A0,1R\r"])})
while self.busy(1,2,3,4): sleep(0.1)
info(" filling syringes...")
self.write_read({1: "".join(["/1A",str(Vol[1]),",1R\r"]),
2: "".join(["/1A",str(Vol[2]),",1R\r"]),
3: "".join(["/1A",str(Vol[3]),",1R\r"]),
4: "".join(["/1A",str(Vol[4]),",1R\r"])})
while self.busy(1,2,3,4): sleep(0.1)
info(" emptying syringes...")
self.write_read({1: "".join(["/1A0,1R\r"]),
2: "".join(["/1A0,1R\r"]),
3: "".join(["/1A0,1R\r"]),
4: "".join(["/1A0,1R\r"])})
while self.busy(1,2,3,4): sleep(0.1)
info(" syringes are initialized, primed, and ready to load.")
info(" time to init (s): %r" % (time()-t0))
def close(self,pids = [1,2,3,4]):
for pid in pids:
try:
self.ports[pid].close()
except Exception as e:
error(e)
@property
def available_ports(self):
"""List of device names"""
from serial.tools.list_ports import comports
return [port.device for port in comports()]
def write(self,pids = [],command = ''):
for pid in pids:
self.ports[pid].flushInput()
debug('write(): pids %r and command = %r' %(pid,command))
self.ports[pid].write(command)
def write_dic(self,dic):
reply = []
for pid in dic:
self.write(pids = [pid], command = dic[pid][0])
info(self.read(pids = [pid], N = dic[pid][1]))
reply.append(True)
return reply
def inquire_dic(self,dic):
"""
"""
from thread import start_new_thread
reply = {}
def inquire_once(reply,pid,dic):
self.write(pids = [pid], command = dic[pid][0])
reply.update(self.read_pid(pid, N = dic[pid][1]))
for pid in dic:
start_new_thread(inquire_once,(reply,pid,dic))
while len(reply) != len(dic):
sleep(self.wait_time)
info(reply)
return reply
def inWaiting(self, pids = []):
reply = {}
if len(pids) ==0:
pids = [1,2,3,4]
for pid in pids:
reply.update({pid: (self.ports[pid].inWaiting())})
return reply
def read_pid(self,pid,N):
from time import time
from thread import start_new_thread
reply = {}
t = time()
while self.inWaiting([pid])[pid] < N:
#info(self.inWaiting()[pid] < N)
sleep(self.wait_time/3.)
#info('READ while: inWaiting: %r with pid = %r' % (self.inWaiting(),pid))
if time() > t + 10:
error('serial port read timeout: time to read = %r' % (time() - t))
break
reply[pid] = self.ports[pid].read(N)
return reply
def read(self,pids = [], N = 0):
from time import time
from thread import start_new_thread
reply = {}
def read_once(reply,pid):
t = time()
while self.inWaiting()[pid] < N:
#info(self.inWaiting()[pid] < N)
sleep(self.wait_time/3.)
#info('READ while: inWaiting: %r with pid = %r' % (self.inWaiting(),pid))
if time() > t + 10:
error('serial port read timeout: time to read = %r' % (time() - t))
break
reply[pid] = self.ports[pid].read(N)
for pid in pids:
start_new_thread(read_once,(reply,pid))
while len(reply) != len(pids):
#print(len(reply),time() - t)
sleep(self.wait_time)
return reply
def readline(self,pids = [], N = 0):
from time import time
reply = {}
sleep(0.05)
for pid in pids:
reply[pid] = self.ports[pid].readline()
return reply
def assign_pids(self):
"""Assigns pump id to each syringe pump according to dictionary; since
pump ids are written to non-volatile memory, need only execute once."""
self.write(pids = [1], command ="/1s0ZA1R\r")
self.write(pids = [2], command = "/1s0ZA2R\r")
self.write(pids = [3], command = "/1s0ZA3R\r")
self.write(pids = [4], command = "/1s0ZA4R\r")
def syringe_setup(self):
"""Specifies the syringe volumes for each pump in the dictionary of
pumps. The command takes effect after power cycling the pumps, and
need only be executed once."""
# U93, U94, U90, U95 -> 50, 100, 250, 500 uL
reply = self.write_dic({1: ["/1U90R\r",7],
2: ["/1U90R\r",7],
3: ["/1U90R\r",7],
4: ["/1U90R\r",7]})
return reply
def busy(self, pids = [1,2,3,4]):
reply = {}
self.write(pids = pids, command = '/1?29R\r')
reply = self.readline(pids) #N = 8
debug('busy(): reply = %r' %reply)
for pid in pids:
if len(reply[pid]) != 8:
debug('len = %r , reply %r' % (len(reply),reply))
try:
if reply[pid][4] == '1':
reply[pid] = True
else:
reply[pid] = False
except Exception as e:
error(e)
debug('reply = %r' % reply)
N = self.ports[pid].inWaiting()
debug('buffer in: %r' % N)
debug('rest of the buffer %r' % self.ports[pid].read(N))
reply[pid] = True
return reply
def abort(self, pids = [1,2,3,4]):
reply = {}
reply = self.inquire_dic({pid: ['/1TR\r',7] for pid in pids})
for pid in pids:
if reply[pid] == '\xff/0`\x03\r\n':
reply[pid] = True
elif reply[pid] == '\xff/0`\x03\r\n':
reply[pid] = False
return reply
def valve_get(self,pids = [1,2,3,4]):
reply = {}
self.write(pids = pids, command = '/1?20R\r')
reply = self.read(pids, N = 8)
for idx in reply:
reply[idx] = reply[idx][4]
return reply
def valve_set(self,dic = {}):
try:
if len(dic) != 0:
for idx in dic:
if dic[idx] == 'i':
dic[idx] = 'I'
elif dic[idx] == 'o':
dic[idx] = 'O'
elif dic[idx] == 'b':
dic[idx] = 'B'
for pid in dic:
self.write(pids = [pid], command = "".join(["/1",str(dic[pid]),"R\r"]))
self.read(pids = [pid], N = 4)
reply = True
else:
reply = False
except Exception as e:
error(e)
reply = False
return reply
def positions(self,pids = [1,2,3,4]):
"""
return positions of syringe pumps in dictionary format
"""
self.write(pids = pids, command = "/1?18R\r")
from time import clock
from numpy import nan
reply = self.readline(pids)
for idx in reply:
number = reply[idx][4:-3]
info('number = %r, clock = %r' % (number, clock()))
try:
reply[idx] = float(number)
except Exception as e:
reply[idx] = nan
error(e)
return reply
def positions_dic(self,dic = {1:0,2:0,3:0,4:0}):
"""
return positions of syringe pumps in dictionary format
"""
reply_dic = {}
return reply
def move_abs(self,pid = 1, position = 0, speed = 25):
"""Move plunger of pump[pid] to absolute position."""
self.abort(pids = [pid])
from time import sleep
self.pos_error = 0.002
position = round(position,3)
if pid == 0:
reply = False
else:
if 0 <= position <= Vol[pid]:
self.write(pids = [pid], command = "".join(["/1J2V",str(speed),",1A",str(position),",1J0R\r"]))
if self.read(pids = [pid], N = 7)[pid][3] == '@':
reply = True
else:
reply = False
else:
info('Position outside of absolute usable range: 0 <= position <= %r' % Vol[pid])
#while not position - self.pos_error <= self.position(pids = [pid])[pid] <= position + self.pos_error:
#sleep(0.1)
reply = False
return reply
def move_rel(self,pid,position,speed=25):
"""Move plunger of pump[pid] to relative position."""
self.abort(pids = [pid])
current = self.position(pids = [pid])[pid]
if 0 <= current + position <= Vol[pid]:
if position < 0:
position = abs(position)
self.write_dic({pid: ["".join(["/1J2V",str(speed),",1D",str(position),",1J0R\r"]),7]})
else:
self.write_dic({pid: ["".join(["/1J2V",str(speed),",1P",str(position),",1J0R\r"]),7]})
else:
info('Position outside of absolute usable range: 0 <= position <= %r' % Vol[pid])
def flow(self,dic = {}):
"""
"""
from thread import start_new_thread
pids = []
for pid in dic:
pids.append(pid)
self.abort(pids)
reply = {}
def flow_pid(reply,pid,dic):
if dic[pid] > 0:
reply.update(self.inquire_dic({pid: ["".join(["/1OV",str(dic[pid]),",1A0,1R\r"]),7]}))
if reply[pid][3] == '@':
reply[pid] = True
else:
reply[pid] = False
elif dic[pid] <0:
reply.update(self.inquire_dic({pid: ["".join(["/1OV",str(abs(dic[pid])),",1A250,1R\r"]),7]}))
if reply[pid][3] == '@':
reply[pid] = True
else:
reply[pid] = False
else:
reply[pid] = self.abort(pids = [pid])[pid]
for pid in dic:
start_new_thread(flow_pid,(reply,pid,dic))
while len(reply) != len(dic):
sleep(self.wait_time)
return reply
def reset(self, pid = [1,2,3,4]):
"""Performs a soft reset on pumps by passing pid number. if left blank, all pumps will soft reset."""
self.inquire_dic({pid: ["/1!R\r",7] for pid in port})
def fill(self,pid,speed = 25):
self.abort(pids=[pid])
self.valve_set({pid: 'i'})
self.move_abs(pid, 0,speed)
while self.busy(pids = [pid])[pid]:
sleep(0.3)
self.move_abs(pid, 250,speed)
while self.busy(pids = [pid])[pid]:
sleep(0.3)
self.valve_set({pid: 'o'})
def prime(self,pid, N = 5, speed = 25):
"""
primes a syringe pump with pid = pid and does it N times
1) aborts execution of any task.
2)
"""
def wait(self,pid):
while self.busy(pids = [pid])[pid]:
sleep(0.3)
sleep(0.1)
self.abort(pids=[pid])
for i in range(N):
self.fill(pid,speed)
wait(self,pid)
def create_low_pressure(self, N = 0, speed = 75):
from time import sleep
from thread import start_new_thread
def run(self,N):
def wait(self):
while self.busy([2])[2]:
sleep(0.2)
for i in range(N):
self.valve_set({2:'o'})
wait(self)
self.move_abs(2,0)
wait(self)
self.valve_set({2:'i'})
wait(self)
self.move_abs(2,250, speed)
wait(self)
self.valve_set({2:'o'})
wait(self)
self.move_abs(2,0)
wait(self)
start_new_thread(run,(self,N))
def create_high_pressure(self, N = 0, speed = 25):
from time import sleep
from thread import start_new_thread
def run(self,N):
from time import sleep
def wait(self, t = 0.5):
while self.busy([2])[2]:
sleep(t)
for i in range(N):
self.valve_set({2:'i'})
wait(self)
self.move_abs(2,0, speed)
wait(self)
self.valve_set({2:'o'})
wait(self)
self.move_abs(2,250)
wait(self)
self.valve_set({2:'i'})
wait(self)
self.move_abs(2,250)
wait(self)
start_new_thread(run,(self,N))
def release_low_pressure(self):
self.valve_set({2:'b'})
def shutdown(self):
self.abort(pids = [1,2,3,4])
self.release_low_pressure()
def flush(self, end_flow = 0.25,speed = 100, t = 0.3):
from time import sleep
self.flow({1:speed*0.1})
sleep(t)
self.flow({1:-0.8*speed*0.1})
sleep(t)
self.flow({1:end_flow})
def inject_crystals(self, liquor_flow = 0.25, crystal_flow = 0.25, t = 2.0):
"""
injects crystals(slowly) from the middle capillary together with flow from two side capillaries.
input parameters:
liquor_flow = 0.25
crystal_flow = 0.25
t = 1.0
sequence:
flows 1 and 3 with liquor_flow and crystal_flow
sleep(t)
flow 1 and 3 with liquor_flow+crystal_flow and -crystal_flow
sleep(1)
abort(3)
flow 1 with liquor_flow speed
"""
from time import sleep
self.flow({1:liquor_flow,3:crystal_flow})
sleep(t)
self.flow({1:liquor_flow+crystal_flow,3:-crystal_flow})
sleep(1)
self.abort([3])
self.flow({1:liquor_flow})
def collapse_crease(self, speed = 10, t = 0.3, end_flow = 0.25,):
"""
"""
from time import sleep
self.flow({1:-speed})
sleep(t)
self.flow({1:speed})
sleep(t)
self.flow({1:end_flow})
def inject(self, end_flow = 0.25):
"""
the inject function does:
1) flush
2) collapse_crease
3) inject_crystals
4) resume flow and end_flow speed
"""
self.flush(end_flow = end_flow)
self.collapse_crease(end_flow = end_flow)
self.inject_crystals()
self.flow({1:end_flow})
driver = Cavro_centris_syringe_pump_LL()
if __name__ == "__main__":
from tempfile import gettempdir
import logging;
logging.basicConfig(#filename=gettempdir()+'/suringe_pump_LL.log',
level=logging.DEBUG, format="%(asctime)s %(levelname)s: %(message)s")
self = driver # for debugging
print("driver.discover()")
print("start_new_thread(driver.prime,(3,2));start_new_thread(driver.prime,(4,2));start_new_thread(driver.prime,(1,2));")
# p.write_read({4:"/1?20R\r"}) # query valve position
# p.write_read({1: "/1IR\r"}) # Move pump1 valve to Input
# p.write_read({2: "/1V0.3,1F\r"}) # Change speed to 0.3 uL/s
# sum(p.positions().values()[:2]) # Returns sum of first two values
<file_sep>x_motor_name = 'SampleX'
y_motor_name = 'SampleY'
z_motor_name = 'SampleZ'
phi_motor_name = 'SamplePhi'
xy_rotating = True
rotation_center = (-0.32668, -0.6098)
calibration_z = 1.2273
samples = []
sample_r = 0.0
support_points = []
GridOffset = 0.0006999999999999437
GridSpacing = 0.055
click_center_x = 0.0
click_center_y = 0.0
click_center_z = 0.0
current_center_x = 0.59004533479473176
current_center_y = 1.1585083487540113
learn_center_history = [{'y': -0.2610485842514396, 'x': 0.4760903347947312, 'phi': -0.0, 'z': 12.336088689787498}]
show_mark_sample_controls = False
mark_sample_function = ''
keep_centered = False
<file_sep>#!/usr/bin/env python
"""This is to run a second instance of the 'DataLogger_HS' application
<NAME>, 18 Jun 2011-30 Mar 2014
<NAME>, 1 Feb 2015 """
__version__ = "1.1"
from DataLogger_HS import DataLogger
import wx
app = wx.App(redirect=False)
win = DataLogger(name="DataLogger_HS2")
app.MainLoop()
<file_sep>"""EPICS Channel Access Process Variable as class property for the client object
Originally designed by F.Schotte and later modified by V.Stadnytskyi.
This version doesn't change PV name to upper case as it was originally done in PV_property.
Author: <NAME>, <NAME>
Date created: 2019-05-18 (originally came from PV_property)
Date last modified: 2019-05-26
"""
__version__ = "1.2" # added alias for PV_property_client
from numpy import nan
def PV_property_client(name,default_value=nan):
"""EPICS Channel Access Process Variable as class property.
this property class doesn't change the name to upper case.
"""
def prefix(self):
prefix = ""
if hasattr(self,"prefix"): prefix = self.prefix
if hasattr(self,"__prefix__"): prefix = self.__prefix__
if prefix and not prefix.endswith("."): prefix += "."
return prefix
def get(self):
from CA import caget
value = caget(prefix(self)+name)
if value is None: value = default_value
if type(value) != type(default_value):
if type(default_value) == list: value = [value]
else:
try: value = type(default_value)(value)
except: value = default_value
return value
def set(self,value):
from CA import caput
value = caput(prefix(self)+name,value)
return property(get,set)
<file_sep>VAL.filename = '//mx340hs/data/anfinrud_1906/Archive/BNCHI.BunchCurrentAI.VAL.txt'<file_sep>from timing_system import timing_system
from time import sleep
delays = (
timing_system.ch1.delay,
timing_system.ch14.delay,
timing_system.ch16.delay,
timing_system.ch18.delay,
)
def shift(dt=1.4e-9):
for d in delays: d.dial += dt
def inc(count=1):
for d in delays: d.count += count
def test(count=10,delay=0):
sleep(delay)
for i in range(count):
inc()
sleep(1)
print('inc(-10)')
print('test(count=10,delay=0)')
<file_sep>"""<NAME>,Oct 21,2015 - Oct 23,2015
"""
__version__ = "1.1"
from Ensemble_SAXS_pp import Ensemble_SAXS
from timing_system import *
from time import sleep
import logging; logging.basicConfig(level=logging.DEBUG,format="%(asctime)s: %(message)s")
delays = [
100*ps,178*ps,316*ps,562*ps,
1*ns,1.78*ns,3.16*ns,5.62*ns,
10*ns,17.8*ns,31.6*ns,56.2*ns,
100*ns,178*ns,316*ns,562*ns,
1*us,1.78*us,3.16*us,5.62*us,
10*us,17.8*us,31.6*us,56.2*us,
100*us,178*us,316*us,562*us,
1*ms,1.78*ms,3.16*ms,5.62*ms,
10*ms,17.8*ms,31.6*ms,
32/hscf,64/hscf,128/hscf
]
laser_modes = [0,1]
all_delays = [t for t in delays for l in laser_modes]
all_laser_modes = [l for t in delays for l in laser_modes]
def test():
while True:
Ensemble_SAXS.add_sequences(all_delays,all_laser_modes)
while len(Ensemble_SAXS.queue) > 10: sleep(1)
print("timing_system.ip_address = %r" % timing_system.ip_address)
print("Ensemble_SAXS.delay = 10e-3")
print("Ensemble_SAXS.queue")
print("Ensemble_SAXS.abort()")
print("test()")
<file_sep>#!/usr/bin/env python
"""Control panel for Cavro Centris Syringe Pumps
<NAME>, Jun 7, 2017 - Jun 8, 2017"""
__version__ = "1.0"
import wx
from MotorPanel import MotorWindow
# Needed to initialize WX library
if not "app" in globals(): app = wx.App(redirect=False)
from cavro_centris_syringe_pump_IOC import volume,port
window = MotorWindow([port,volume],title="Centris Syringe Pumps")
app.MainLoop()
<file_sep>"""
This is a server script that allows the remoly control and monitor a
LeCroy oscilloscope. This script needs to run one the same PC as the
oscilloscope.
This script serves the oscillope up on the network using on TCP port
1860. Multiple concurrent connections are allowed. A client application can
either send send a single command one a TCP connection and then close it,
or kept the connection alive indefinitly and send all commands over than same
connection.
This script works for all of LeCroy's PC-based X-Stream series oscilloscopes,
like WaveSurfer, WaveRunner and WaveMaster series.
Remote control is implemented using the DCOM (Distributes Common Object Model)
interface of the LeCroyXStreamDSO application.
The oscilloscope software has got two remote control interfaces. The classic
GPIB command set is served on TCP port 1861, ecapsulated in packets with binary
VICP (Virtual Instrument Control Protocol) headers. This command set is
described in LeCroy's "WaveRunner 6000A Series Remote Control Manual".
This interterface has the drawback that one one concurret client connection is
supported, there is a two second delay for disconnecting and reconnecting and
some functions of the oscilloscope are not supported, like setting measurement
gates.
The other interface is based on Microsoft's DCOM remote procedure calls. The
command set is documented in LeCroy's "WaveMaster, WavePro Series Automation
Manual", file "Automation Manual.pdf" in "femto.niddk.nih.gov/APS/Laser Hutch/
Laser Oscilloscope".
A command that modifies a setting of the oscilloscope is, for instance,
"Measure.P1.GateStart.Value = 0.95". This sets the low limit of the gate
of measurement P1 to 0.95 divisions. This command generates not reply.
A query that generates a reply would be "Measure.P1.GateStart.Value".
This reads back the low limit of the gate of measurement P1.
Each command needs to be terminated by newline charater when sent to the
server. A carriage return character at the end is allowed, but not required.
A quick way to find a command is to launch the "XStream Browser" application
on the oscilloscope PC and brwoser the command set with the Explorer-like
interface.
Properties listed with type 'Double','Bool','String','Enum' are read by appending
'.Value' to their name and set by appending ' = val' or '.Value = val' to
their name. If 'val' is a string it must be enclosed in double quotes or single
quotes.
Properties list as 'Action' are called by appending ".ActNow()" to their
name, e.g. "ClearSweeps.ActNow()".
Properties listed as 'Method' are called by appending "()" with optional
arguments to their name, e.g. "Sleep(1000)".
Commands are not case-sensitive.
Installation:
Installed Python 2.7.15 (OCt 2018) from python.org in C:/Python27 (default).
Desktop > Computer > Properties > Advanced System Settings > Environment Variables
PATH=...;C:\Python27;C:\Python27\Scripts
C:\> pip install pywin32
C:\> pip install numpy
C:\> pip install wxPython
C:\> pip install psutil
C:\> pip install pyparsing
C:\> pip install pytz
Created a shortcut to \\id14b4\useridb\NIH\Software\lecroy_scope_server.py,
named "LeCroy Scope Server", in the Autostart program group for all users.
Shortcut Properties: Run: Minimized
Example:
Measure.P1.GateStart = 0.95 or Measure.P1.GateStart.Value = 0.95
sets the low limit of the gate of measurement P1 to 0.95 divisions.
Measure.P1.last.Result.Value
Reads the current value of measurement P1
Measure.P1.num.Result.Value
Reads the number of measurement that where averaged.
test:
echo Measure.P1.num.Result.Value | nc -w1 id14l-scope.cars.aps.anl.gov 2000
Author: <NAME>,
Date created: 2008-03-28
Date last modified: 2019-05-28
"""
__version__ = "2.6" # timestamps
from logging import debug,info,warn,error
import traceback
class Lecroy_Scope(object):
"""LeCroy oscilloscope"""
from cached_property import cached_property
from persistent_property import persistent_property
from thread_property_2 import thread_property
# When the trace count reaches 99999, it goes to 100000, then wraps back
# to 00000.
trace_count_wrap_period = 100001
wrap = trace_count_wrap_period
from numpy import nan,inf
def value_property(query_string,default_value=nan,timeout=inf):
"""A propery representing a value that can be read and set"""
def get(self):
value = self.query(query_string)
dtype = type(default_value)
if dtype != str:
try: value = dtype(eval(value))
except: value = default_value
return value
def set(self,value): self.send("%s = %r" % (query_string,value))
value_property = property(get,set,doc=query_string)
from cached_property import cached_property
value_property = cached_property(value_property,timeout)
return value_property
def action_property(command):
"""A propery representing an action that can be executed"""
def get(self): return 0
def set(self,value): self.send(command)
return property(get,set)
def method_property(method):
"""A property representing an method"""
def get(self): return False
def set(self,value):
if value: method(self)
return property(get,set)
trig_count_name = persistent_property("trig_count_name","xosct_trig_count")
acq_count_name = persistent_property("acq_count_name", "xosct_acq_count")
@property
def trig_count(self):
"""Timing system register object"""
from timing_system import timing_system
value = getattr(timing_system,self.trig_count_name)
return value
@property
def acq_count(self):
"""Timing system register object"""
from timing_system import timing_system
value = getattr(timing_system,self.acq_count_name)
return value
# for trace files
channel = 1
trace_filenames = {}
files_to_save = {}
save_traces_running = False
filenames = []
times = []
def __init__(self,name="lecroy_scope"):
self.name = name
auto_synchronize = persistent_property("auto_synchronize",False)
@thread_property
def auto_synchronize_running(self):
from sleep import sleep
while not self.auto_synchronize_running_cancelled:
sleep(10)
if self.auto_synchronize:
if self.monitoring_timing:
if not self.trace_count_synchronized:
self.trace_count_synchronized = True
def get_trace_count_synchronized(self):
synchronized = (
abs(self.trace_count_offset) <= 1 and
abs(self.timing_offset) < 0.18 and
self.timing_jitter < 0.1
)
return synchronized
def set_trace_count_synchronized(self,value):
if value and not self.trace_count_synchronized:
self.timing_reset = True
self.trace_count_offset = 0
trace_count_synchronized = property(get_trace_count_synchronized,
set_trace_count_synchronized)
def trace_count_synchronize(self):
"""Synchronize the timing system's trigger count with the trace
file count"""
self.trace_count_offset = 0
def get_trace_count_offset(self):
offset = self.trace_count - self.timing_system_trigger_count % self.wrap
return offset
def set_trace_count_offset(self,offset):
"""Synchronize the timing system's trigger count with the trace
file count
offset should be zero"""
self.timing_system_trigger_count = self.trace_count - offset
trace_count_offset = property(get_trace_count_offset,set_trace_count_offset)
def get_trace_acquisition_running(self):
return self.trace_acquisition_monitoring and self.save_traces_running
def set_trace_acquisition_running(self,value):
self.trace_acquisition_monitoring = value
self.save_traces_running = value
trace_acquisition_running = \
property(get_trace_acquisition_running,set_trace_acquisition_running)
__trace_acquisition_monitoring__ = False
def get_trace_acquisition_monitoring(self):
return self.trace_acquisition_monitor in self.acq_count.monitors
def set_trace_acquisition_monitoring(self,value):
if bool(value) != self.trace_acquisition_monitoring:
if bool(value) == True:
self.acq_count.monitor(self.trace_acquisition_monitor)
if bool(value) == False:
self.acq_count.monitor_clear(self.trace_acquisition_monitor)
trace_acquisition_monitoring = property(get_trace_acquisition_monitoring,
set_trace_acquisition_monitoring)
timing_system_was_acquiring = False
def trace_acquisition_monitor(self):
"""For filenames of trace files to be saved"""
# First, trig_count updates, immediately followed by acq_count.
from os.path import basename
trig_count = self.timing_system_trigger_count
acq_count = self.timing_system_acq_count
timing_system_acquiring = self.timing_system_acquiring
# Make sure to get the last trace
if timing_system_acquiring or self.timing_system_was_acquiring:
if acq_count in self.trace_filenames:
filename = self.trace_filenames[acq_count]
info("Acquiring %r: trig %r = %r" % (acq_count,trig_count,
basename(filename)))
for i,channel in enumerate(self.enabled_channels):
self.files_to_save[trig_count,i] = self.extended_filename(filename,i)
else: info("Acquiring %r: trig %r (no filename)" % (acq_count,trig_count))
else: info("trig_count=%r" % (trig_count))
self.timing_system_was_acquiring = timing_system_acquiring
def extended_filename(self,filename,i):
"""'test.trc' -> i=0:'test.trc', i=1:'test2.trc',i=2:'test3.trc'"""
if len(self.trace_sources) > 1:
from os.path import splitext
basename,ext = splitext(filename)
filename = "%s_%s%s" % (basename,self.trace_sources[i],ext)
return filename
__save_traces_running__ = False
from threading import Thread
save_traces_task = Thread()
def get_save_traces_running(self):
return self.save_traces_task.isAlive()
def set_save_traces_running(self,value):
if value != self.save_traces_running:
if value:
from threading import Thread
self.save_traces_task = Thread(target=self.save_traces_forever,
name="save_traces_forever")
self.save_traces_task.daemon = True
self.__save_traces_running__ = True
self.save_traces_task.start()
else: self.__save_traces_running__ = False
save_traces_running = property(get_save_traces_running,set_save_traces_running)
def save_traces_forever(self):
from time import sleep
while self.__save_traces_running__:
try: self.save_traces_once()
except Exception,msg: error("%s\n%s",msg,traceback.print_exc())
sleep(0.1)
def save_traces_once(self):
from os.path import exists,basename
from normpath import normpath
for count,i in self.files_to_save.keys():
source = self.trace_filename(i,count)
if exists(source):
destination = self.files_to_save[count,i]
destination = normpath(destination)
info("Saving %r as %r",basename(source),basename(destination))
##info("Saving %r as %r",basename(source),destination)
copy(source,destination)
del self.files_to_save[count,i]
def get_timing_system_acquiring(self):
from timing_system import timing_system
value = timing_system.register_count("acquiring")
return value
def set_timing_system_acquiring(self,value):
from timing_system import timing_system
timing_system.set_register_count("acquiring")
timing_system_acquiring = property(get_timing_system_acquiring,
set_timing_system_acquiring)
def get_timing_system_trigger_count(self):
return self.trig_count.value
def set_timing_system_trigger_count(self,value):
self.trig_count.value = value
timing_system_trigger_count = property(get_timing_system_trigger_count,
set_timing_system_trigger_count)
trigger_count = timing_system_trigger_count
def get_timing_system_acq_count(self):
return self.acq_count.count
def set_timing_system_acq_count(self,value):
self.acq_count.count = value
timing_system_acq_count = property(get_timing_system_acq_count,
set_timing_system_acq_count)
def get_timing_system_trigger_enabled(self):
from Ensemble_SAXS import Ensemble_SAXS
return Ensemble_SAXS.xosct_on
def set_timing_system_trigger_enabled(self,value):
from Ensemble_SAXS import Ensemble_SAXS
Ensemble_SAXS.xosct_on = value
timing_system_trigger_enabled = property(
get_timing_system_trigger_enabled,set_timing_system_trigger_enabled)
def trace_filename(self,i,count):
"""Trace file name on oscilloscope's internal file system
i: trace number, e.g. 0 = CH1, 1 = CH2
count: trigger count (starting with 0)"""
trace_source = self.trace_sources[i]
format = "%s\\%s%s%05.0f.trc"
if self.software_version >= "8.2":
format = "%s\\%s--%s--%05.0f.trc"
filename = format % (self.trace_directory,trace_source,self.trace_title,count)
return filename
def file_trace_count(self,filename):
from os.path import basename,splitext
name = basename(filename)
name = splitext(name)[0]
if name.startswith("C"): name = name[2:]
name = name.replace(self.trace_title,"")
name = name.replace("--","") # for software version 8
try: count = int(name)
except Exception,msg:
warn("%s: %r: %s" % (filename,name,msg))
count = -1
return count
@property
def software_version(self):
ID_string = self.ID_string
software_version = ID_string.split(",")[-1]
return software_version
def get_trace_directory_size(self):
"""Number of saved trace files"""
if not hasattr(self,"__trace_directory_size__"):
self.__trace_directory_size__ = number_of_files(self.trace_directory)
return self.__trace_directory_size__
def set_trace_directory_size(self,value):
if value == 0: self.emptying_trace_directory = True
trace_directory_size = property(get_trace_directory_size,set_trace_directory_size)
trace_count = 0
def value(self,query_string,default_value=nan):
"""Performs a query and returns the result as a specific data type,
e.g. float, matching the given default value"""
value = self.query(query_string)
dtype = type(default_value)
if dtype != str:
try: value = dtype(eval(value))
except: value = default_value
return value
def query(self,query_string):
"""Execute a command that generates a reply"""
if not query_string.startswith("LeCroy.XStreamDSO."):
query_string = "LeCroy.XStreamDSO."+query_string
debug("Evaluating query: '%.800s'" % query_string)
try:
LeCroy = self.COM_object
reply = eval(query_string)
except Exception,x:
if self.report(query_string): error("%r: %s" % (query_string,x))
reply = ""
if reply is not None:
try: reply = str(reply)
except: reply = repr(reply)
else: reply = ""
if self.report(query_string): info("%s? %.800s" % (query_string,reply))
return reply
def send(self,command):
"""Excute a command that does not generate a reply"""
if not command.startswith("LeCroy.XStreamDSO."):
command = "LeCroy.XStreamDSO."+command
LeCroy = self.COM_object
info("Executing command: %.800s" % command)
try: exec(command)
except Exception,x: error("%r: %s" % (command,x))
report_filter = [
"last.Result.Value",
"SaveRecall.Waveform.AutoSave",
".View",
"SaveRecall.Setup.PanelFilename",
"SaveRecall.Waveform.SaveSource",
]
def report(self,query_string):
"""Generate a diagnostics message for this command?"""
self.report_count[query_string] = self.report_count.get(query_string,0)+1
report = True
matches = False
for string in self.report_filter:
if string in query_string: matches = True
if matches and self.report_count[query_string] > 3: report = False
return report
report_count = {}
@property
def COM_object(self):
"""'LeCroy.XStreamDSO' COM object"""
import pythoncom,win32com.client # need to install pywin32
pythoncom.CoInitialize() # needed only when run in a thread
class LeCroy: XStreamDSO = win32com.client.Dispatch("LeCroy.XStreamDSO")
return LeCroy
##COM_object = cached_property(COM_object,inf)
def get_setup(self):
return self.setup_name
def set_setup(self,name):
self.setup_name = name
if self.setup_name != "": self.setup_recall = True
setup = property(get_setup,set_setup)
@property
def setup_choices(self):
from os import listdir
dirname = self.local_setup_dirname
try: files = listdir(dirname)
except Exception,msg: files = []; warn("%s: %s" % (dirname,msg))
files = [file for file in files if not file.startswith(".")]
files = [file for file in files if file.endswith(".lss")]
names = [file.replace(".lss","") for file in files]
return names
setups = setup_choices
def get_setup_name(self):
from os.path import basename
name = basename(self.setup_filename).replace(".lss","")
return name
def set_setup_name(self,name):
self.setup_filename = self.local_setup_filename(name)
setup_name = property(get_setup_name,set_setup_name)
def get_setup_filename(self):
filename = self.setup_dirname+"/"+self.setup_basename
from normpath import normpath
filename = normpath(filename)
return filename
def set_setup_filename(self,filename):
from normpath import normpath
filename = Windows_pathname(normpath(filename))
from os.path import dirname,basename
dir,file = dirname(filename),basename(filename)
self.setup_dirname = dir
self.setup_basename = file
setup_filename = property(get_setup_filename,set_setup_filename)
setup_dirname = value_property("SaveRecall.Setup.PanelDir","")
setup_basename = value_property("SaveRecall.Setup.PanelFilename","",timeout=10)
setup_save = action_property("SaveRecall.Setup.DoSavePanel.ActNow()")
setup_recall = action_property("SaveRecall.Setup.DoRecallPanel.ActNow()")
trace_directory = value_property("SaveRecall.Waveform.WaveformDir","")
trace_title = value_property("SaveRecall.Waveform.TraceTitle","")
trace_source = value_property("LeCroy.XStreamDSO.SaveRecall.Waveform.SaveSource","",timeout=10)
@property
def trace_sources(self):
sources = []
source = self.trace_source
if source == "AllDisplayed": sources = self.enabled_channels
elif source != "": sources = [source]
return sources
channels = "C1","C2","C3","C4"
for channel in channels:
exec('%s_on = value_property("LeCroy.XStreamDSO.Acquisition.%s.View",False,timeout=10)'
% (channel,channel))
@property
def enabled_channels(self):
names = []
for name in self.channels:
if getattr(self,name+"_on",False): names += [name]
return names
measurements = ["P%d" % (i+1) for i in range(0,4)] # may be up to 8
for measurement in measurements:
exec('%s_on = value_property("LeCroy.XStreamDSO.Measure.%s.View",False,timeout=inf)'
% (measurement,measurement))
@property
def enabled_measurements(self):
names = []
for name in self.measurements:
if getattr(self,name+"_on",False): names += [name]
return names
ID_string = value_property("InstrumentID","")
id = ID_string
@property
def local_setup_dirname(self):
from module_dir import module_dir
return module_dir(self)+"/lecroy_scope/"+self.name
def local_setup_filename(self,name):
if name != "": filename = self.local_setup_dirname+"/"+name+".lss"
else: filename = ""
return filename
@thread_property
def emptying_trace_directory(self):
"""Erase all temporary trace files"""
directory = self.trace_directory
filenames = listdir(directory)
self.__trace_directory_size__ = len(filenames)
from os import remove
for i,filename in enumerate(filenames):
if self.emptying_trace_directory_cancelled: break
pathname = directory+"/"+filename
try:
remove(pathname)
except Exception,msg: info("%s: %s" % (pathname,msg))
filenames = listdir(directory)
self.__trace_directory_size__ = len(filenames)
auto_acquire = persistent_property("auto_acquire",False)
@thread_property
def auto_acquire_running(self):
from sleep import sleep
while not self.auto_acquire_running_cancelled:
sleep(10)
if self.auto_acquire:
if not self.acquiring_waveforms: self.acquiring_waveforms = True
def get_acquiring_waveforms(self):
"""Are trace currently being auto-saved?"""
return self.waveform_autosave != "Off"
def set_acquiring_waveforms(self,value):
if value:
mkdir(self.trace_directory)
self.waveform_autosave = "Wrap"
else: self.waveform_autosave = "Off"
acquiring_waveforms = property(get_acquiring_waveforms,set_acquiring_waveforms)
waveform_autosave = value_property("SaveRecall.Waveform.AutoSave","",timeout=10)
def get_monitoring_timing(self):
"""Collecting information to check that trace acquisistion is
synchronized?"""
return self.monitoring_trace_count and self.monitoring_trig_count
def set_monitoring_timing(self,value):
if self.monitoring_trace_count_allowed: self.monitoring_trace_count = value
self.monitoring_trig_count = value
monitoring_timing = property(get_monitoring_timing,set_monitoring_timing)
@method_property
def timing_reset(self):
self.trace_counts_reset = True
self.trigger_counts_reset = True
@thread_property
def monitoring_trace_count(self):
"""Watch trace directory for new files"""
while self.monitoring_trace_count_allowed and not self.monitoring_trace_count_cancelled:
directory = self.trace_directory
from os.path import exists
from time import sleep
if not exists(directory): sleep(1)
else:
# http://timgolden.me.uk/python/win32_how_do_i/watch_directory_for_changes.html
import os
import win32file,win32con
ACTIONS = {
1 : "Created",
2 : "Deleted",
3 : "Updated",
4 : "Renamed from something",
5 : "Renamed to something"
}
FILE_LIST_DIRECTORY = 0x0001
hDir = win32file.CreateFile (
directory,
FILE_LIST_DIRECTORY,
win32con.FILE_SHARE_READ | win32con.FILE_SHARE_WRITE | win32con.FILE_SHARE_DELETE,
None,
win32con.OPEN_EXISTING,
win32con.FILE_FLAG_BACKUP_SEMANTICS,
None,
)
while self.monitoring_trace_count_allowed and not self.monitoring_trace_count_cancelled:
# ReadDirectoryChangesW takes a previously-created handle to a
# directory, a buffer size for results, a flag to indicate whether
# to watch subtrees and a filter of what changes to notify.
#
# Need to up the buffer size to be sure of picking up all events when
# a large number of files were deleted at once.
results = win32file.ReadDirectoryChangesW (
hDir,
1024,
True,
win32con.FILE_NOTIFY_CHANGE_FILE_NAME |
win32con.FILE_NOTIFY_CHANGE_DIR_NAME |
win32con.FILE_NOTIFY_CHANGE_ATTRIBUTES |
win32con.FILE_NOTIFY_CHANGE_SIZE |
win32con.FILE_NOTIFY_CHANGE_LAST_WRITE |
win32con.FILE_NOTIFY_CHANGE_SECURITY,
None,
None,
)
for action_code,filename in results:
action = ACTIONS.get(action_code,"Unknown")
if action != "Deleted": debug("%s: %s" % (filename,action))
if action == "Updated": self.trace_counts_handle(filename)
if action == "Created": self.__trace_directory_size__ += 1
if action == "Deleted": self.__trace_directory_size__ -= 1
def trace_counts_handle(self,filename):
from time import time
t = time()
n = self.file_trace_count(filename)
if n>=0:
debug("Trace count %d" % n)
self.trace_counts_add(n,t)
self.trace_count = n
monitoring_trace_count_allowed = True
trace_counts_dict = {}
@method_property
def trace_counts_reset(self):
self.trace_counts_dict = {}
def trace_counts_add(self,n,t):
self.trace_counts_limit()
self.trace_counts_dict[n] = t
@property
def trace_counts_history(self):
"""list of timestamps plus list of trace counts"""
nt_pairs = self.trace_counts_dict.items()
ts = [t for n,t in nt_pairs]
ns = [n for n,t in nt_pairs]
return ts,ns
def trace_counts_limit(self):
dt = 60
from time import time
t = time()
# Work with a copy, in case the dictionary changes.
trace_counts = dict(self.trace_counts_dict)
for n in trace_counts.keys():
if trace_counts[n] < t-dt: del trace_counts[n]
self.trace_counts_dict = trace_counts
def get_monitoring_trig_count(self):
return self.trigger_counts_handle in self.trig_count.monitors
def set_monitoring_trig_count(self,value):
if bool(value) != self.monitoring_trig_count:
if bool(value) == True:
self.trig_count.monitor(self.trigger_counts_handle)
if bool(value) == False:
self.trig_count.monitor_clear(self.trigger_counts_handle)
monitoring_trig_count = property(get_monitoring_trig_count,set_monitoring_trig_count)
def trigger_counts_handle(self):
from time import time
t = time()
n = self.trig_count.count
self.trigger_counts_add(n,t)
debug("Trigger count %r" % n)
trigger_counts_dict = {}
@method_property
def trigger_counts_reset(self):
self.trigger_counts_dict = {}
def trigger_counts_add(self,n,t):
self.trigger_counts_limit()
self.trigger_counts_dict[n] = t
@property
def trigger_counts_history(self):
"""list of timestamps plus list of trigger counts"""
nt_pairs = self.trigger_counts_dict.items()
ts = [t for n,t in nt_pairs]
ns = [n for n,t in nt_pairs]
return ts,ns
def trigger_counts_limit(self):
dt = 60
from time import time
t = time()
# Work with a copy, in case the dictionary changes.
trigger_counts = dict(self.trigger_counts_dict)
for n in trigger_counts.keys():
if trigger_counts[n] < t-dt: del trigger_counts[n]
self.trigger_counts_dict = trigger_counts
@property
def timing_differences(self):
self.monitoring_timing = True
self.auto_acquire_running = True
self.auto_synchronize_running = True
t,n = self.trace_counts_history; trace_nt = dict(zip(n,t))
t,n = self.trigger_counts_history; trigger_nt = dict(zip(n,t))
dt = []
for trigger_count in trigger_nt:
trace_count = trigger_count % self.wrap
if trace_count in trace_nt:
dt += [trace_nt[trace_count] - trigger_nt[trigger_count]]
return dt
@property
def timing_jitter(self):
# Supress "RuntimeWarning: Degrees of freedom <= 0 for slice."
import numpy; numpy.warnings.filterwarnings('ignore')
from numpy import std
return std(self.timing_differences)
@property
def timing_offset(self):
# Supress "RuntimeWarning: Mean of empty slice"
import numpy; numpy.warnings.filterwarnings('ignore')
from numpy import mean
return mean(self.timing_differences)
class measurement_object(object):
"""For automated measurements, including averageing and statistics"""
def __init__(self,scope,n=1,type="value"):
"""n=1,2...6 is the waveform parameter number.
The parameter is defined from the "Measure" menu, e.g. P1:delay(C3).
The optional 'type' can by "value","min","max","stdev",or "count".
"""
self.scope = scope; self.n = n; self.type = type
def __repr__(self):
return repr(self.scope)+".measurement("+str(self.n)+")."+self.type
def get_value(self):
n = self.n
if self.type == "value": return self.scope.value("LeCroy.XStreamDSO.Measure.P%d.last.Result.Value" % n)
if self.type == "average": return self.scope.value("LeCroy.XStreamDSO.Measure.P%d.mean.Result.Value" % n)
if self.type == "min": return self.scope.value("LeCroy.XStreamDSO.Measure.P%d.min.Result.Value" % n)
if self.type == "max": return self.scope.value("LeCroy.XStreamDSO.Measure.P%d.max.Result.Value" % n)
if self.type == "stdev": return self.scope.value("LeCroy.XStreamDSO.Measure.P%d.sdev.Result.Value" % n)
if self.type == "count": return self.scope.value("LeCroy.XStreamDSO.Measure.P%d.num.Result.Value" % n)
return nan
value = property(get_value,doc="last sample (without averaging)")
def get_average(self):
n = self.n
if self.type == "value": return self.scope.value("LeCroy.XStreamDSO.Measure.P%d.mean.Result.Value" % n)
if self.type == "average": return self.scope.value("LeCroy.XStreamDSO.Measure.P%d.mean.Result.Value" % n)
if self.type == "min": return self.scope.value("LeCroy.XStreamDSO.Measure.P%d.min.Result.Value" % n)
if self.type == "max": return self.scope.value("LeCroy.XStreamDSO.Measure.P%d.max.Result.Value" % n)
if self.type == "stdev": return self.scope.value("LeCroy.XStreamDSO.Measure.P%d.sdev.Result.Value" % n)
if self.type == "count": return self.scope.value("LeCroy.XStreamDSO.Measure.P%d.num.Result.Value" % n)
return nan
average = property(get_average,doc="accumulated average")
def get_max(self): return self.scope.value("LeCroy.XStreamDSO.Measure.P%d.max.Result.Value" % self.n)
max = property(get_max,doc="maximum value contributing to average")
def get_min(self): return self.scope.value("LeCroy.XStreamDSO.Measure.P%d.min.Result.Value" % self.n)
min = property(get_min,doc="minimum value contributing to average")
def get_stdev(self): return self.scope.value("LeCroy.XStreamDSO.Measure.P%d.sdev.Result.Value" % self.n)
stdev = property(get_stdev,doc="standard deviation of individuals sample")
def get_count(self): return self.scope.value("LeCroy.XStreamDSO.Measure.P%d.num.Result.Value" % self.n)
count = property(get_count,doc="number of measurement averaged")
def get_name(self):
return self.scope.query("LeCroy.XStreamDSO.Measure.P%d.Equation.Value" % self.n)+"."+self.type
name = property(get_name,doc="string representation of the measurement")
def get_unit(self):
return self.scope.query("LeCroy.XStreamDSO.Measure.P%d.num.Result.VerticalUnits.Value")
unit = property(get_unit,doc="unit symbol of measurement (if available)")
def start(self): self.scope.start()
def stop(self): self.scope.stop()
def clear_sweeps(self): self.scope.clear_sweeps()
reset_average = clear_sweeps
reset_statistics = clear_sweeps
def get_gate(self): return self.scope.gate(self.n)
gate = property(get_gate,doc="start of measurement gate")
def get_enabled(self): return self.scope.measurement_enabled
def set_enabled(self,value): self.scope.measurement_enabled = value
enabled = property(get_enabled,set_enabled)
def measurement(self,n=1,type="value"): return lecroy_scope.measurement_object(self,n,type)
@property
def P1(self):
from numpy import nan
return self.measurement(1).value if self.P1_on else nan
@property
def P2(self):
from numpy import nan
return self.measurement(2).value if self.P2_on else nan
@property
def P3(self):
from numpy import nan
return self.measurement(3).value if self.P3_on else nan
@property
def P4(self):
from numpy import nan
return self.measurement(4).value if self.P4_on else nan
def update_period(self,name):
"""How often is it recommended to refresh a certein property?"""
from numpy import inf
period = inf
if name in self.enabled_measurements: period = self.min_update_period
if name == "waveform_autosave": period = 10
if name == "trace_sources": period = 10
return period
min_update_period = 0.024
lecroy_scope = Lecroy_Scope()
scope = lecroy_scope
# listen port number of this server script
port = 2000
def run_server():
lecroy_scope_IOC.running = True
# make a threaded server, listen/handle clients forever
server = ThreadingTCPServer(("",port),ClientHandler)
info("Server version %s started, listening on port %d" % (__version__,port))
try: server.serve_forever()
except KeyboardInterrupt: pass
# By default, the "ThreadingTCPServer" class binds to the sever port
# without the option SO_REUSEADDR. The consequence of this is that
# when the server terminates you have to let 60 seconds pass, for the
# socket to leave to "CLOSED_WAIT" state before it can be restarted,
# otherwise the next bind call would generate the error
# 'Address already in use'.
# Setting allow_reuse_address to True makes "ThreadingTCPServer" use to
# SO_REUSEADDR option when calling "bind".
import SocketServer
class ThreadingTCPServer(SocketServer.ThreadingTCPServer):
allow_reuse_address = True
class ClientHandler(SocketServer.BaseRequestHandler):
def handle(self):
"""Called when a client connects. 'self.request' is the client socket"""
info("Accepted connection from "+self.client_address[0])
input_queue = ""
while 1:
# Commands from a client are not necessarily received as one packet
# but each command is terminated by a newline character.
# If 'recv' returns an empty string it means client closed the
# connection.
while input_queue.find("\n") == -1:
try: received = self.request.recv(2*1024*1024)
except Exception,x:
error("%r %r" % (x,str(x)))
received = ""
if received == "": info("Client disconnected"); break
debug("received %8d+%8d = %8d bytes" % (len(input_queue),
len(received),len(input_queue)+len(received)))
input_queue += received
if input_queue == "": break
if input_queue.find("\n") != -1:
end = input_queue.index("\n")
query = input_queue[0:end]
input_queue = input_queue[end+1:]
else: query = input_queue; input_queue = ""
##debug("Command length: %r bytes" % len(query))
query = query.strip("\r ")
LeCroy = scope.COM_object
# Is this a query of a command? Try "eval" first, then "exec".
info("Evaluating query: %.800s" % repr(query))
try: reply = eval(query)
except Exception,x:
error_message = "eval: %r\n%s" % (x,traceback.format_exc())
info("Executing command: '%.800s'" % query)
try: exec(query)
except Exception,x:
error_message += "\nexec: %r\n%s" % (x,traceback.format_exc())
error(error_message)
info("Completed command: '%.800s'" % query)
reply = None
if reply is not None:
try: reply = str(reply)
except: reply = repr(reply)
reply += "\n"
info("Sending reply: %s (%r bytes)" % (repr(reply),len(reply)))
self.request.sendall(reply)
else: info("Command completed. No reply needed.")
info("Closing connection to "+self.client_address[0])
self.request.close()
class Lecroy_Scope_IOC(object):
@property
def name(self): return scope.name
@property
def prefix(self): return "NIH:"+self.name.upper()+"."
from persistent_property import persistent_property
scan_period = persistent_property("scan_period",2.0)
property_names = [
"P1",
"P2",
"P3",
"P4",
"trace_count",
"trace_sources",
"timing_system_trigger_count",
"trace_count_offset",
"trace_directory_size",
"emptying_trace_directory",
"acquiring_waveforms",
"auto_acquire",
"timing_offset",
"timing_jitter",
"timing_reset",
"auto_synchronize",
"trace_count_synchronized",
"trace_acquisition_running",
"setup",
"setups",
"setup_name",
"setup_filename",
"setup_filename",
"setup_save",
"setup_recall",
]
from thread_property_2 import thread_property
@thread_property
def running(self):
info("Starting IOC: Prefix: %s ..." % self.prefix)
from CAServer import casget,casput,casdel
from time import time
from sleep import sleep
self.monitors_setup()
while not self.running_cancelled:
t = time()
for name in self.property_names:
if time() - self.last_updated(name) > self.update_period(name):
PV_name = self.prefix+name.upper()
value = getattr(scope,name)
##info("Update: %s=%r" % (PV_name,value))
casput(PV_name,value,update=False)
self.set_update_time(name)
if not self.running_cancelled: sleep(t+self.min_update_period-time())
casdel(self.prefix)
last_updated_dict = {}
def set_update_time(self,name):
from time import time
self.last_updated_dict[name] = time()
def last_updated(self,name): return self.last_updated_dict.get(name,0)
def update_period(self,name):
period = scope.update_period(name)
period = min(period,self.scan_period)
return period
@property
def min_update_period(self): return scope.min_update_period
def monitors_setup(self):
"""Monitor client-writable PVs."""
from CAServer import casmonitor,casput
for name in self.property_names:
PV_name = self.prefix+name.upper()
casmonitor(PV_name,callback=self.monitor)
def monitor(self,PV_name,value,char_value):
"""Handle PV change requests"""
info("%s = %r" % (PV_name,value))
from CAServer import casput
for name in self.property_names:
if PV_name == self.prefix+name.upper():
setattr(scope,name,value)
casput(PV_name,getattr(scope,name))
lecroy_scope_IOC = Lecroy_Scope_IOC()
def number_of_files(directory):
number_of_files = len(listdir(directory))
info("Number of files in %r: %r" % (directory,number_of_files))
return number_of_files
def monitor_directory(directory):
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
class MyHandler(FileSystemEventHandler):
def on_modified(self, event):
info("%s: %d files" % (directory,number_of_files(directory)))
event_handler = MyHandler()
observer = Observer()
observer.schedule(event_handler,path=directory,recursive=False)
observer.start()
def listdir(directory):
info("Reading directory %r..." % (directory,))
from os import listdir
try: files = listdir(directory)
except Exception,msg:
debug("%r: %s" % (directory,msg))
files = []
info("Reading directory %r done." % (directory,))
return files
from os.path import exists
def getmtime(pathname):
"""The last modification time of a file in seconds since Jan 1, 2015"""
from os.path import exists,getmtime
if not exists(pathname): return 0.0
return getmtime(pathname)
def mtimes(pathnames):
"""The last modification time of a list of files,
in seconds since Jan 1, 2015"""
return [getmtime(f) for f in pathnames]
def rename(source,destination):
"""Rename of move a file."""
if destination == source: return
from os import rename,remove
from os.path import exists,dirname
if exists(destination): remove(destination)
directory = dirname(destination)
if directory and not exists(directory): mkdir(directory)
rename(source,destination)
def copy_files(source_files,destination_files):
"""Copy each file in the list 'source_files' to the corresponding file
in 'destination_files'."""
from thread import start_new_thread
start_new_thread(__copy_files__,(source_files,destination_files))
def __copy_files__(source_files,destination_files):
"""Copy each file in the list 'source_files' to the corresponding file
in 'destination_files'."""
for s,d in zip(source_files,destination_files): copy(s,d)
def migrate_files(source_files,destination_files):
"""Copy each file in the list 'source_files' to the corresponding file
in 'destination_files'.
source_files: list of strings
destination_files: list of strings"""
from thread import start_new_thread
start_new_thread(__migrate_files__,(source_files,destination_files))
def __migrate_files__(source_files,destination_files):
"""Copy each file in the list 'source_files' to the corresponding file
in 'destination_files' and remove the source.
source_files: list of strings
destination_files: list of strings"""
from time import sleep
from os.path import dirname
directory = dirname(source_files[0]) if len(source_files) > 0 else ""
global migrate_directory; migrate_directory = directory
copied = [False]*len(source_files)
while directory == migrate_directory and not all(copied):
for i in range(0,len(source_files)):
if copied[i]: continue
if not exists(source_files[i]):
sleep(1); break # Copying caught up with collection.
copy(source_files[i],destination_files[i])
if exists(destination_files[i]): copied[i] = True
# Make one last attempt after acquisition finished.
for i in range(0,len(source_files)):
if not copied[i]:
copy(source_files[i],destination_files[i])
if exists(destination_files[i]): copied[i] = True
# Clean up.
for i in range(0,len(source_files)):
if copied[i]: remove(source_files[i])
from os import rmdir
rmdir(directory)
migrate_directory = ""
def repr(x,nchars=80):
"""limit string length using ellipses (...)"""
s = __builtins__.repr(x)
if len(s) > nchars: s = s[0:nchars-10-3]+"..."+s[-10:]
return s
migration_in_progress = False
copied = []
count = 0
def copy(source,destination):
"""Create a copy of a file with the same timestamp"""
if destination == source: return
from os import remove
from shutil import copy2
from os.path import exists,dirname
if not exists(source): return
if exists(destination): remove(destination)
directory = dirname(destination)
if directory and not exists(directory): mkdir(directory)
try: copy2(source,destination)
except Exception,msg:
error("Error copying %r to %r: %s" % (source,destination,msg))
def remove(pathname):
"""Delete a file."""
from os.path import exists
if not exists(pathname): return
from os import remove
remove(pathname)
def mkdir(directory):
"""Create a directory"""
from os import makedirs
from os.path import exists
if not exists(directory):
try:
makedirs(directory)
info("Created directory %r" % directory)
except Exception,msg: error("Cannot create %r: %s" % (directory,msg))
def rmdir(pathname):
"""Remove a directory and its contents"""
from os.path import exists
if not exists(pathname): return
from shutil import rmtree
try: rmtree(pathname)
except Exception,msg: debug("%s: %s" % (pathname,msg))
def symlink(filename,linkname):
"""Create a symbolic link.
filename: target name of symblic link. Should be an existing filename.
linkename: name of new symblic link to be created."""
from os import remove
from os.path import exists
if exists(linkname): remove(linkname)
# Replacememnt for os.symlink that is platform independent.
try:
from os import symlink
symlink(filename,linkname)
except ImportError:
import win32file
win32file.CreateSymbolicLink(linkname,filename,0)
# flag 0 = filename
# for backward compatibility with Python 2.4
def any(list):
"""Is any of the elements of the list true?"""
for x in list:
if x: return True
return False
def version():
import lecroy_scope_server
return lecroy_scope_server.__version__
def Windows_pathname(pathname):
"""Translate between UNIX-style to Windows-style pathnames
E.g. "//id14bxf/data" to "\\id14bxf\data"""
pathname = pathname.replace("/","\\")
return pathname
if __name__ == "__main__":
import logging
from tempfile import gettempdir
format = "%(asctime)s %(levelname)s: %(message)s"
logfile = gettempdir()+"/lecroy_scope_server.log"
logging.basicConfig(level=logging.INFO,format=format)
from logging_filename import log_to_file
log_to_file(logfile,"INFO")
scope.name = "xray_scope"
from sys import argv
if len(argv) >= 2: scope.name = argv[1]
info("scope.trig_count_name = %r" % scope.trig_count_name)
info("scope.acq_count_name = %r" % scope.acq_count_name)
##import autoreload
self = scope # for debugging
run_server()
<file_sep>"""
Data base to save and recall motor positions
Author: <NAME>
Date created: 2019-05-24
Date last modified: 2019-05-31
"""
__version__ = "1.0.5" # issue: __builtins__.getattr: 'dict' object has no attribute 'getattr'
# Solution: made setattr, getattr static methods
from logging import debug,info,warn,error
from traceback import format_exc
class Configuration_Server(object):
prefix = "NIH:CONF"
global_properties = [
"configuration_names",
]
configuration_properties = [
"value",
"values",
"command_value",
"title",
"description",
"matching_description",
"closest_descriptions",
"command_description",
"command_rows",
"matching_rows",
"closest_rows",
"n_motors",
"descriptions",
"updated",
"formats",
"nrows",
"name",
"motor_names",
"names",
"motor_labels",
"widths",
"formats",
"tolerance",
"description_width",
"row_height",
"show_apply_buttons",
"apply_button_label",
"show_define_buttons",
"define_button_label",
"show_stop_button",
"serial",
"vertical",
"multiple_selections",
"are_configuration",
"motor_configuration_names",
"are_numeric",
"current_timestamp",
"applying",
"show_in_list",
]
motor_properties = [
"current_position",
"positions",
"positions_match",
]
def run(self):
from time import sleep
while True:
self.update()
sleep(0.02)
def update(self):
from CAServer import casput,casmonitor
from configuration_driver import configuration
for prop in self.global_properties:
PV_name = (self.prefix+"."+prop).upper()
value = self.getattr(configuration,prop,expand=True)
if value is not None:
casput(PV_name,value,update=False)
casmonitor(PV_name,callback=self.monitor)
for conf in configuration.configurations:
for prop in self.configuration_properties:
PV_name = (self.prefix+"."+conf.name+"."+prop).upper()
value = self.getattr(conf,prop,expand=True)
if value is not None:
casput(PV_name,value,update=False)
casmonitor(PV_name,callback=self.monitor)
for prop in self.motor_properties:
for motor_num in range(0,conf.n_motors):
PV_name = (self.prefix+"."+conf.name+".MOTOR"+str(motor_num+1)+"."+prop).upper()
value = self.getitem(self.getattr(conf,prop),motor_num)
if value is not None:
casput(PV_name,value,update=False)
casmonitor(PV_name,callback=self.monitor)
def monitor(self,PV_name,value,char_value):
"""Handle PV change requests"""
info("%s = %r" % (PV_name,value))
from configuration_driver import configuration
from CAServer import casput
for conf in configuration.configurations:
for prop in self.configuration_properties:
if PV_name == (self.prefix+"."+conf.name+"."+prop).upper():
self.setattr(conf,prop,value)
value = self.getattr(conf,prop,expand=True)
if value is not None: casput(PV_name,value,update=False)
for motor_num in range(0,conf.n_motors):
for prop in self.motor_properties:
if PV_name == (self.prefix+"."+conf.name+".MOTOR"+str(motor_num+1)+"."+prop).upper():
self.setitem(self.getattr(conf,prop),motor_num,value)
value = self.getitem(self.getattr(conf,prop),motor_num)
if value is not None: casput(PV_name,value,update=False)
def global_PV_name(self,prop):
return (self.prefix+"."+prop).upper()
def configuration_PV_name(self,conf,prop):
return (self.prefix+"."+conf.name+"."+prop).upper()
def motor_PV_name(self,conf,prop,motor_num):
return (self.prefix+"."+conf.name+".MOTOR"+str(motor_num+1)+"."+prop).upper()
@staticmethod
def getattr(obj,property_name,expand=False):
try: value = getattr(obj,property_name)
except Exception,msg:
error("%s.%s: %s\n%s" % (obj,property_name,msg,format_exc()))
value = None
if expand:
if hasattr(value,"__getitem__"):
try: value = value[:]
except: warn("%s.%s[:]: %s\n%s" % (obj,property_name,msg,format_exc()))
return value
@staticmethod
def setattr(obj,property_name,value):
debug("setattr(%r,%r,%r)" % (obj,property_name,value))
try: setattr(obj,property_name,value)
except Exception,msg:
error("%s.%s = %r: %s\n%s" % (obj,property_name,value,msg,format_exc()))
@staticmethod
def getitem(obj,i):
try: value = obj[i]
except Exception,msg:
error("%s[%r]: %s\n%s" % (obj,i,msg,format_exc()))
value = None
if hasattr(value,"__getitem__"):
try: value = value[:]
except: warn("%s.%s[:]: %s\n%s" % (obj,property_name,msg,format_exc()))
return value
@staticmethod
def setitem(obj,i,value):
debug("setitem(%r,%r,%r)" % (obj,i,value))
try: obj[i] = value
except Exception,msg:
error("%s[%r] = %r: %s\n%s" % (obj,i,value,msg,format_exc()))
configuration_server = Configuration_Server()
if __name__ == '__main__': # for testing
from pdb import pm # for debugging
from time import time # for performance testing
import logging
for h in logging.root.handlers[:]: logging.root.removeHandler(h)
logging.basicConfig(level=logging.DEBUG,
format="%(asctime)s %(levelname)s %(module)s.%(funcName)s: %(message)s",
)
self = configuration_server
print("from configuration_driver import configuration")
print("conf = configuration.configurations[0]")
print("self.getattr(conf,'descriptions')")
print("value = self.getattr(conf,'descriptions')")
print("self.setattr(conf,'descriptions',value)")
print("self.getitem(self.getattr(conf,'current_positions'),0)")
print("self.getitem(self.getattr(conf,'positions'),0)")
print("")
print("configuration_server.update()")
print("t=time(); configuration_server.update(); time()-t")
print("configuration_server.run()")
##print("")
##from CAServer import casget
##print("casget(configuration_server.configuration_PV_name(conf,'descriptions'))")
<file_sep>#!/usr/bin/python
from vxi_11 import *
scope=vxi_11_connection("id14b-scope")
scope.write("*IDN?\n")
print scope.read()
# expecting: (0, 4, 'Agilent Technologies,DSO81204A,MY44000226,05.01.0000\n')
<file_sep>#!/usr/bin/env python
"""EPICS server for ILX Lightwave LDT-5948 Precision Temperature Controller
Author: <NAME>
Date created: 2015-11-03
Date last modified: 2017-06-25
"""
__version__ = "4.7" # renamed: lightwave_temperature_controller
from lightwave_temperature_controller_driver import lightwave_temperature_controller
from persistent_property import persistent_property
from CAServer import casput,casget,casmonitor,casdel
from time import time
from logging import debug,info,warn,error
from thread import start_new_thread
from numpy import isfinite, nan
import platform
computer_name = platform.node()
import os
class Lightwave_Temperature_Controller_IOC(object):
name = "lightwave_temperature_controller_IOC"
prefix = persistent_property("prefix","NIH:LIGHTWAVE")
scan_time = persistent_property("scan_time",0.5)
running = False
prefix = 'NIH:LIGHTWAVE'
def get_EPICS_enabled(self):
return self.running
def set_EPICS_enabled(self,value):
if value:
if not self.running: start_new_thread(self.run,())
else: self.running = False
EPICS_enabled = property(get_EPICS_enabled,set_EPICS_enabled)
def start(self):
"""Start EPICS IOC for temperature controller in background"""
from thread import start_new_thread
start_new_thread(self.run,())
def stop(self):
"""Stop EPICS IOC for temperature controller runninig in background"""
self.running = False
def run(self):
"""Start EPICS IOC for temperature controller (does not return)"""
self.running = True
casput(self.prefix+".SCAN",self.scan_time)
casput(self.prefix+".DESC","Temp")
casput(self.prefix+".EGU","C")
casput(self.prefix+".BAUD",lightwave_temperature_controller.baudrate.value)
# Complex Actions
casput(self.prefix+".ACTION",'')
# Monitor client-writable PVs.
casmonitor(self.prefix+".SCAN",callback=self.monitor)
casmonitor(self.prefix+".BAUD",callback=self.monitor)
casmonitor(self.prefix+".VAL" ,callback=self.monitor)
casmonitor(self.prefix+".CNEN",callback=self.monitor)
casmonitor(self.prefix+".PIDCOF",callback=self.monitor)
casmonitor(self.prefix+".PCOF",callback=self.monitor)
casmonitor(self.prefix+".ICOF",callback=self.monitor)
casmonitor(self.prefix+".DCOF",callback=self.monitor)
casmonitor(self.prefix+".RDBD",callback=self.monitor)
casmonitor(self.prefix+".NSAM",callback=self.monitor)
casmonitor(self.prefix+".IHLM",callback=self.monitor)
casmonitor(self.prefix+".ILLM",callback=self.monitor)
casmonitor(self.prefix+".TENA",callback=self.monitor)
casmonitor(self.prefix+".P1SP",callback=self.monitor)
casmonitor(self.prefix+".P1EP",callback=self.monitor)
casmonitor(self.prefix+".P1SI",callback=self.monitor)
while self.running:
if self.scan_time > 0 and isfinite(self.scan_time):
if lightwave_temperature_controller.max_time_between_replies > 10:
lightwave_temperature_controller.max_time_between_replies = 0
info("Reading configuration")
casput(self.prefix+".COMM",lightwave_temperature_controller.port_name, update = False)
#casput(self.prefix+".VAL",lightwave_temperature_controller.setT.value)
casput(self.prefix+".CNEN",lightwave_temperature_controller.enabled.value, update = False)
casput(self.prefix+".PIDCOF",lightwave_temperature_controller.feedback_loop.PID, update = False)
casput(self.prefix+".PCOF",lightwave_temperature_controller.feedback_loop.P.value, update = False)
casput(self.prefix+".ICOF",lightwave_temperature_controller.feedback_loop.I.value, update = False)
casput(self.prefix+".DCOF",lightwave_temperature_controller.feedback_loop.D.value, update = False)
casput(self.prefix+".RDBD",lightwave_temperature_controller.stabilization_threshold, update = False)
casput(self.prefix+".NSAM",lightwave_temperature_controller.stabilization_nsamples, update = False)
casput(self.prefix+".IHLM",lightwave_temperature_controller.current_high_limit, update = False)
casput(self.prefix+".ILLM",lightwave_temperature_controller.current_low_limit, update = False)
casput(self.prefix+".TENA",lightwave_temperature_controller.trigger_enabled, update = False)
casput(self.prefix+".ID",lightwave_temperature_controller.id, update = False)
casput(self.prefix+".P1SP",lightwave_temperature_controller.trigger_start, update = False)
casput(self.prefix+".P1EP",lightwave_temperature_controller.trigger_stop, update = False)
casput(self.prefix+".P1SI",lightwave_temperature_controller.trigger_stepsize, update = False)
casput(self.prefix+".processID",value = os.getpid(), update = False)
casput(self.prefix+".computer_name",value = computer_name, update = False)
t = time()
casput(self.prefix+".RBV",lightwave_temperature_controller.actual_temperature.value, update = True)
casput(self.prefix+".DMOV",lightwave_temperature_controller.stable, update = False)
sleep(t+0.25*self.scan_time-time())
casput(self.prefix+".I",lightwave_temperature_controller.current.value, update = True)
sleep(t+0.50*self.scan_time-time())
casput(self.prefix+".P",lightwave_temperature_controller.power.value, update = True)
sleep(t+0.75*self.scan_time-time())
##if casget(self.prefix+".TENA"): # Set point may change on trigger.
casput(self.prefix+".VAL",lightwave_temperature_controller.setT.value, update = False)
sleep(t+1.00*self.scan_time-time())
casput(self.prefix+".SCANT",time()-t, update = False) # post actual scan time for diagnostics
else:
casput(self.prefix+".SCANT",nan, update = False)
sleep(0.1)
casdel(self.prefix)
def monitor(self,PV_name,value,char_value):
"""callback for PV change requests"""
debug("%s = %r" % (PV_name,value))
if PV_name == self.prefix+".SCAN":
self.scan_time = value
casput(self.prefix+".SCAN",self.scan_time)
if PV_name == self.prefix+".BAUD":
lightwave_temperature_controller.baudrate.value = value
casput(self.prefix+".BAUD",lightwave_temperature_controller.baudrate.value)
if PV_name == self.prefix+".VAL":
lightwave_temperature_controller.setT.value = value
#recalculate if motor is moving or not. This should allow to use cawait function
casput(self.prefix+".DMOV",lightwave_temperature_controller.stable, update = False)
#update PV:
casput(self.prefix+".VAL",lightwave_temperature_controller.setT.value)
if PV_name == self.prefix+".CNEN":
lightwave_temperature_controller.enabled.value = value
casput(self.prefix+".CNEN",lightwave_temperature_controller.enabled.value)
if PV_name == self.prefix+".PIDCOF":
lightwave_temperature_controller.feedback_loop.PID = value
casput(self.prefix+".PIDCOF",lightwave_temperature_controller.feedback_loop.PID)
casput(self.prefix+".PCOF",lightwave_temperature_controller.feedback_loop.PID[0])
casput(self.prefix+".ICOF",lightwave_temperature_controller.feedback_loop.PID[1])
casput(self.prefix+".DCOF",lightwave_temperature_controller.feedback_loop.PID[2])
if PV_name == self.prefix+".PCOF":
lightwave_temperature_controller.feedback_loop.P.value = value
casput(self.prefix+".PCOF",lightwave_temperature_controller.feedback_loop.P.value)
if PV_name == self.prefix+".ICOF":
lightwave_temperature_controller.feedback_loop.I.value = value
casput(self.prefix+".ICOF",lightwave_temperature_controller.feedback_loop.I.value)
if PV_name == self.prefix+".DCOF":
lightwave_temperature_controller.feedback_loop.D.value = value
casput(self.prefix+".DCOF",lightwave_temperature_controller.feedback_loop.D.value)
if PV_name == self.prefix+".COMM":
lightwave_temperature_controller.port_name.value = value
casput(self.prefix+".COMM",lightwave_temperature_controller.port_name)
if PV_name == self.prefix+".RDBD":
lightwave_temperature_controller.stabilization_threshold = value
casput(self.prefix+".RDBD",lightwave_temperature_controller.stabilization_threshold)
if PV_name == self.prefix+".NSAM":
lightwave_temperature_controller.stabilization_nsamples = value
casput(self.prefix+".NSAM",lightwave_temperature_controller.stabilization_nsamples)
if PV_name == self.prefix+".IHLM":
lightwave_temperature_controller.current_high_limit = value
casput(self.prefix+".IHLM",lightwave_temperature_controller.current_high_limit)
if PV_name == self.prefix+".ILLM":
lightwave_temperature_controller.current_low_limit = value
casput(self.prefix+".ILLM",lightwave_temperature_controller.current_low_limit)
if PV_name == self.prefix+".TENA":
lightwave_temperature_controller.trigger_enabled = value
casput(self.prefix+".TENA",lightwave_temperature_controller.trigger_enabled)
if PV_name == self.prefix+".P1SP":
lightwave_temperature_controller.trigger_start = value
casput(self.prefix+".P1SP",lightwave_temperature_controller.trigger_start)
if PV_name == self.prefix+".P1EP":
lightwave_temperature_controller.trigger_stop = value
casput(self.prefix+".P1EP",lightwave_temperature_controller.trigger_stop)
if PV_name == self.prefix+".P1SI":
lightwave_temperature_controller.trigger_stepsize = value
casput(self.prefix+".P1SI",lightwave_temperature_controller.trigger_stepsize)
lightwave_temperature_controller_IOC = Lightwave_Temperature_Controller_IOC()
def sleep(seconds):
"""Delay execution by the given number of seconds"""
# This version of "sleep" does not throw an excpetion if passed a negative
# waiting time, but instead returns immediately.
from time import sleep
if seconds > 0: sleep(seconds)
if __name__ == "__main__":
from pdb import pm
self = lightwave_temperature_controller # for debugging
import logging;
logging.basicConfig(level=logging.DEBUG,format="%(asctime)s: %(message)s")
import CAServer
##CAServer.LOG = True; CAServer.verbose = True
lightwave_temperature_controller.logging = True
from sys import argv
if "run_IOC" in argv: lightwave_temperature_controller_IOC.run()
print('lightwave_temperature_controller_IOC.prefix = %r' % lightwave_temperature_controller_IOC.prefix)
print('lightwave_temperature_controller_IOC.EPICS_enabled = True')
print('lightwave_temperature_controller_IOC.EPICS_enabled = False')
print('lightwave_temperature_controller_IOC.run()')
print('lightwave_temperature_controller_IOC.start()')
print('lightwave_temperature_controller_IOC.stop()')
<file_sep>clk_src.count = 29
sbclk_src.count = 27
clk_div.count = 0
clk_dfs_mode.count = 1
clk_dll_mode.count = 0
clk_mul.count = 7
clk_shift_stepsize = 8.594e-12
clock_period_external = 2.841441861258077e-09
clock_period_internal = 2.857142857142857e-09
p0_div_1kHz.count = 275
clk_88Hz_div_1kHz.count = 89100
hlc_div = 12
nsl_div = 48
p0fd2.count = 1
p0d2.count = 317
p0_shift.offset = -3.611472605659016e-06
psod3.offset = 7.68e-09
hlcnd.count = 1035645
hlcnd.offset = -0.010752607022907704
hlcad.offset = -0.010752607023
hlctd.offset = 1.1365768090935692e-08
ch1.PP_enabled = True
ch1.input.count = 0
ch1.description = 'X scope trig'
ch1.mnemonic = 'xosct'
ch1.special = ''
ch1.specout.count = 0
ch1.offset_HW = 6.803185418800114e-06
ch1.offset_sign = 1.0
ch1.pulse_length_HW = nan
ch1.offset_PP = nan
ch1.pulse_length_PP = nan
ch1.counter_enabled = 1
ch1.enable.count = 1
ch1.timed = 'probe'
ch1.gated = ''
ch1.override.count = 0
ch1.state.count = 0
ch2.PP_enabled = False
ch2.input.count = 0
ch2.description = 'HLC ext freq'
ch2.mnemonic = 'hlc'
ch2.special = ''
ch2.specout.count = 0
ch2.offset_HW = nan
ch2.offset_sign = 1.0
ch2.pulse_length_HW = nan
ch2.offset_PP = nan
ch2.pulse_length_PP = nan
ch2.counter_enabled = 0
ch2.enable.count = 0
ch2.timed = ''
ch2.gated = ''
ch2.override.count = 0
ch2.state.count = 0
ch3.PP_enabled = False
ch3.input.count = 1
ch3.description = 'HLC enc IN'
ch3.mnemonic = ''
ch3.special = ''
ch3.specout.count = 0
ch3.offset_HW = nan
ch3.offset_sign = 1.0
ch3.pulse_length_HW = nan
ch3.offset_PP = nan
ch3.pulse_length_PP = nan
ch3.counter_enabled = 0
ch3.enable.count = 0
ch3.timed = ''
ch3.gated = ''
ch3.override.count = 0
ch3.state.count = 0
ch4.PP_enabled = False
ch4.input.count = 0
ch4.description = 'HS chop'
ch4.mnemonic = 'hsc'
ch4.special = ''
ch4.specout.count = 0
ch4.offset_HW = -0.0009859719999999999
ch4.offset_sign = -1.0
ch4.pulse_length_HW = nan
ch4.offset_PP = nan
ch4.pulse_length_PP = nan
ch4.counter_enabled = 0
ch4.enable.count = 1
ch4.timed = ''
ch4.gated = ''
ch4.override.count = 0
ch4.state.count = 0
ch5.PP_enabled = False
ch5.input.count = 1
ch5.description = 'HS chop IN'
ch5.mnemonic = ''
ch5.special = ''
ch5.specout.count = 0
ch5.offset_HW = nan
ch5.offset_sign = 1.0
ch5.pulse_length_HW = nan
ch5.offset_PP = nan
ch5.pulse_length_PP = nan
ch5.counter_enabled = 0
ch5.enable.count = 0
ch5.timed = ''
ch5.gated = ''
ch5.override.count = 0
ch5.state.count = 0
ch6.PP_enabled = True
ch6.input.count = 0
ch6.description = 'ms shutter'
ch6.mnemonic = 'ms'
ch6.special = 'ms'
ch6.specout.count = 0
ch6.offset_HW = nan
ch6.offset_sign = 1.0
ch6.pulse_length_HW = nan
ch6.offset_PP = -16.0
ch6.pulse_length_PP = 3.0
ch6.counter_enabled = 0
ch6.enable.count = 0
ch6.timed = 'probe'
ch6.gated = 'probe'
ch6.override.count = 0
ch6.state.count = 0
ch7.PP_enabled = True
ch7.input.count = 0
ch7.description = 'X det trig'
ch7.mnemonic = 'xdet'
ch7.special = ''
ch7.specout.count = 0
ch7.offset_HW = nan
ch7.offset_sign = 1.0
ch7.pulse_length_HW = nan
ch7.offset_PP = -6.0
ch7.pulse_length_PP = 1.0
ch7.counter_enabled = 1
ch7.enable.count = 0
ch7.timed = 'period'
ch7.gated = 'detector'
ch7.override.count = 0
ch7.state.count = 0
ch8.PP_enabled = True
ch8.input.count = 0
ch8.description = 'L cam trig'
ch8.mnemonic = 'lcam'
ch8.special = ''
ch8.specout.count = 0
ch8.offset_HW = 6.822639999999999e-06
ch8.offset_sign = 1.0
ch8.pulse_length_HW = nan
ch8.offset_PP = nan
ch8.pulse_length_PP = nan
ch8.counter_enabled = 0
ch8.enable.count = 0
ch8.timed = 'pump'
ch8.gated = 'pump'
ch8.override.count = 0
ch8.state.count = 0
ch9.PP_enabled = True
ch9.input.count = 0
ch9.description = 'S cam shutter'
ch9.mnemonic = 's1'
ch9.special = ''
ch9.specout.count = 0
ch9.offset_HW = nan
ch9.offset_sign = 1.0
ch9.pulse_length_HW = nan
ch9.offset_PP = -15.0
ch9.pulse_length_PP = 15.0
ch9.counter_enabled = 0
ch9.enable.count = 0
ch9.timed = 'pump'
ch9.gated = 'pump'
ch9.override.count = 0
ch9.state.count = 1
ch10.PP_enabled = True
ch10.input.count = 0
ch10.description = 'S cam LED'
ch10.mnemonic = 'scl'
ch10.special = ''
ch10.specout.count = 0
ch10.offset_HW = nan
ch10.offset_sign = 1.0
ch10.pulse_length_HW = nan
ch10.offset_PP = 0.0
ch10.pulse_length_PP = 72.0
ch10.counter_enabled = 0
ch10.enable.count = 0
ch10.timed = 'period'
ch10.gated = ''
ch10.override.count = 1
ch10.state.count = 0
ch11.PP_enabled = True
ch11.input.count = 0
ch11.description = 'sample trans'
ch11.mnemonic = 'trans'
ch11.special = 'trans'
ch11.specout.count = 0
ch11.offset_HW = nan
ch11.offset_sign = 1.0
ch11.pulse_length_HW = nan
ch11.offset_PP = 0.0
ch11.pulse_length_PP = 3.0
ch11.counter_enabled = 0
ch11.enable.count = 0
ch11.timed = 'period'
ch11.gated = ''
ch11.override.count = 0
ch11.state.count = 0
ch12.PP_enabled = False
ch12.input.count = 0
ch12.description = 'Diagnostics 1'
ch12.mnemonic = ''
ch12.special = ''
ch12.specout.count = 2
ch12.offset_HW = nan
ch12.offset_sign = 1.0
ch12.pulse_length_HW = nan
ch12.offset_PP = nan
ch12.pulse_length_PP = nan
ch12.counter_enabled = 0
ch12.enable.count = 0
ch12.timed = ''
ch12.gated = ''
ch12.override.count = 0
ch12.state.count = 0
ch13.PP_enabled = True
ch13.input.count = 0
ch13.description = 'ps L oscill'
ch13.mnemonic = 'pso'
ch13.special = 'pso'
ch13.specout.count = 1
ch13.offset_HW = nan
ch13.offset_sign = 1.0
ch13.pulse_length_HW = nan
ch13.offset_PP = nan
ch13.pulse_length_PP = nan
ch13.counter_enabled = 0
ch13.enable.count = 0
ch13.timed = 'pump'
ch13.gated = ''
ch13.override.count = 0
ch13.state.count = 0
ch14.PP_enabled = True
ch14.input.count = 0
ch14.description = 'ps L trig'
ch14.mnemonic = 'pst'
ch14.special = ''
ch14.specout.count = 0
ch14.offset_HW = 2.3975699999999997e-06
ch14.offset_sign = 1.0
ch14.pulse_length_HW = nan
ch14.offset_PP = nan
ch14.pulse_length_PP = nan
ch14.counter_enabled = 0
ch14.enable.count = 0
ch14.timed = 'pump'
ch14.gated = 'pump'
ch14.override.count = 0
ch14.state.count = 0
ch15.PP_enabled = True
ch15.input.count = 0
ch15.description = ''
ch15.mnemonic = 'psg'
ch15.special = ''
ch15.specout.count = 0
ch15.offset_HW = nan
ch15.offset_sign = 1.0
ch15.pulse_length_HW = nan
ch15.offset_PP = nan
ch15.pulse_length_PP = nan
ch15.counter_enabled = 0
ch15.enable.count = 0
ch15.timed = 'pump'
ch15.gated = 'pump'
ch15.override.count = 0
ch15.state.count = 0
ch16.PP_enabled = True
ch16.input.count = 0
ch16.description = 'L scope trig'
ch16.mnemonic = 'losct'
ch16.special = ''
ch16.specout.count = 0
ch16.offset_HW = 5.89053e-06
ch16.offset_sign = 1.0
ch16.pulse_length_HW = nan
ch16.offset_PP = nan
ch16.pulse_length_PP = nan
ch16.counter_enabled = 1
ch16.enable.count = 0
ch16.timed = 'pump'
ch16.gated = ''
ch16.override.count = 0
ch16.state.count = 0
ch17.PP_enabled = True
ch17.input.count = 0
ch17.description = 'ns L flash'
ch17.mnemonic = 'nsf'
ch17.special = 'nsf'
ch17.specout.count = 0
ch17.offset_HW = -0.00062272
ch17.offset_sign = 1.0
ch17.pulse_length_HW = nan
ch17.offset_PP = nan
ch17.pulse_length_PP = nan
ch17.counter_enabled = 0
ch17.enable.count = 0
ch17.timed = 'pump'
ch17.gated = ''
ch17.override.count = 0
ch17.state.count = 0
ch18.PP_enabled = True
ch18.input.count = 0
ch18.description = 'ns L Q-sw'
ch18.mnemonic = 'nsq'
ch18.special = ''
ch18.specout.count = 0
ch18.offset_HW = 6.677895511828916e-06
ch18.offset_sign = 1.0
ch18.pulse_length_HW = nan
ch18.offset_PP = nan
ch18.pulse_length_PP = nan
ch18.counter_enabled = 0
ch18.enable.count = 0
ch18.timed = 'pump'
ch18.gated = 'pump'
ch18.override.count = 0
ch18.state.count = 0
ch19.PP_enabled = True
ch19.input.count = 0
ch19.description = 'ns L 2 flash'
ch19.mnemonic = ''
ch19.special = ''
ch19.specout.count = 0
ch19.offset_HW = nan
ch19.offset_sign = 1.0
ch19.pulse_length_HW = nan
ch19.offset_PP = nan
ch19.pulse_length_PP = nan
ch19.counter_enabled = 0
ch19.enable.count = 0
ch19.timed = 'period'
ch19.gated = ''
ch19.override.count = 0
ch19.state.count = 0
ch20.PP_enabled = True
ch20.input.count = 0
ch20.description = 'CW laser'
ch20.mnemonic = 'cwl'
ch20.special = ''
ch20.specout.count = 0
ch20.offset_HW = nan
ch20.offset_sign = 1.0
ch20.pulse_length_HW = nan
ch20.offset_PP = 35.0
ch20.pulse_length_PP = 2.0
ch20.counter_enabled = 0
ch20.enable.count = 0
ch20.timed = 'period'
ch20.gated = ''
ch20.override.count = 0
ch20.state.count = 0
ch21.PP_enabled = True
ch21.input.count = 0
ch21.description = ''
ch21.mnemonic = 's3'
ch21.special = ''
ch21.specout.count = 0
ch21.offset_HW = nan
ch21.offset_sign = 1.0
ch21.pulse_length_HW = nan
ch21.offset_PP = nan
ch21.pulse_length_PP = 2.0
ch21.counter_enabled = 0
ch21.enable.count = 0
ch21.timed = ''
ch21.gated = ''
ch21.override.count = 0
ch21.state.count = 0
ch22.PP_enabled = True
ch22.input.count = 0
ch22.description = ''
ch22.mnemonic = ''
ch22.special = ''
ch22.specout.count = 0
ch22.offset_HW = nan
ch22.offset_sign = 1.0
ch22.pulse_length_HW = nan
ch22.offset_PP = nan
ch22.pulse_length_PP = nan
ch22.counter_enabled = 0
ch22.enable.count = 0
ch22.timed = ''
ch22.gated = ''
ch22.override.count = 0
ch22.state.count = 0
ch23.PP_enabled = True
ch23.input.count = 0
ch23.description = 'S cam trig'
ch23.mnemonic = 'sct'
ch23.special = ''
ch23.specout.count = 0
ch23.offset_HW = nan
ch23.offset_sign = 1.0
ch23.pulse_length_HW = nan
ch23.offset_PP = 0.0
ch23.pulse_length_PP = 1.0
ch23.counter_enabled = 0
ch23.enable.count = 0
ch23.timed = 'period'
ch23.gated = ''
ch23.override.count = 0
ch23.state.count = 0
ch24.PP_enabled = False
ch24.input.count = 0
ch24.description = 'Diagnostics 2'
ch24.mnemonic = ''
ch24.special = ''
ch24.specout.count = 3
ch24.offset_HW = nan
ch24.offset_sign = 1.0
ch24.pulse_length_HW = nan
ch24.offset_PP = nan
ch24.pulse_length_PP = nan
ch24.counter_enabled = 0
ch24.enable.count = 0
ch24.timed = ''
ch24.gated = ''
ch24.override.count = 0
ch24.state.count = 0<file_sep>port = 2223
nimages_to_keep = 999
image_numbers = []
filenames = []<file_sep>#!/usr/bin/env python
"""This is to run a second instance of the 'DataLogger' application
<NAME>, 18 Jun 2011-30 Mar 2014"""
__version__ = "1.1"
from DataLogger import DataLogger
import wx
app = wx.App(redirect=False)
win = DataLogger(name="DataLogger2")
app.MainLoop()
<file_sep>#!/usr/bin/env python
"""Dynamically reload Python modules as needed.
<NAME>, 28 Jan 2015 - 29 Jan 2015"""
from logging import debug,warn
def update_module(module_name):
"""Reload a module if its source file has changed"""
try: exec("import %s as module" % module_name)
except Exception,msg: warn("Loading module %s failed %s" % (module_name,msg)); return
from inspect import getfile
from os.path import getmtime
file = getfile(module)
timestamp = getattr(module,"__timestamp__",0)
source_timestamp = getattr(module,"__source_timestamp__",0)
current_timestamp = getmtime(file)
current_source_timestamp = getmtime(file.replace(".pyc",".py"))
if current_timestamp != timestamp or current_source_timestamp != source_timestamp:
debug("reloading module %s" % module_name)
try: module=reload(module)
except Exception,msg: warn("Reloading module %s failed: %s" % (module_name,msg)); return
module.__timestamp__ = current_timestamp
module.__source_timestamp__ = current_source_timestamp
if __name__ == '__main__':
from pdb import pm
module_name = "Ensemble_SAXS" # for debugging
import logging; logging.basicConfig(level=logging.DEBUG)
print "update_module(module_name)"
<file_sep>"""
Rayonix CCD X-ray detector
<NAME>
Date created: 2016-06-17
Date last modified: 2019-05-31
"""
__version__ = "2.0" # server
from logging import debug,info,warn,error
from rayonix_detector import Rayonix_Detector
from timing_sequencer import timing_sequencer
from Ensemble_SAXS_pp import Ensemble_SAXS
from timing_sequencer import timing_sequencer
from timing_system import timing_system
class Rayonix_Detector_Continous(Rayonix_Detector):
"""Rayonix MX series X-ray Detector, using continuous acquistion mode"""
name = "rayonix_detector_server"
from persistent_property import persistent_property
scratch_directory = persistent_property("scratch_directory",
"/net/mx340hs/data/tmp")
nimages_to_keep = persistent_property("nimages_to_keep",1000)
filenames = persistent_property("filenames",[])
image_numbers = persistent_property("image_numbers",[])
timing_mode = persistent_property("timing_mode","SAXS/WAXS") # SAXS or Laue
timing_modes = ["SAXS/WAXS","Laue"]
auto_start = persistent_property("auto_start",True)
def __init__(self):
Rayonix_Detector.__init__(self)
def acquire_images(self,image_numbers,filenames):
"""Save a series of images
image_numbers: 0-based, matching timing system's 'image_number''"""
self.image_numbers,self.filenames = list(image_numbers),list(filenames)
debug("image_numbers = %.200r" % self.image_numbers)
debug("filenames = %.200r" % self.filenames)
self.xdet_trig_counts = {}
self.acquiring = True
self.trigger_monitoring = True
self.saving_images = True
acquire_images_triggered = acquire_images
def cancel_acquisition(self):
"""Undo 'acquire_images', stop saving images"""
self.image_numbers,self.filenames = [],[]
self.trigger_monitoring = False
__saving_images__ = False
def get_saving_images(self):
return self.__saving_images__
def set_saving_images(self,value):
if bool(value) == True and not self.saving_images:
from thread import start_new_thread
self.__saving_images__ = True
start_new_thread(self.save_images_task,())
if bool(value) == False:
self.saving_images_cancelled = True
self.save_images_cancelled = True
saving_images = property(get_saving_images,set_saving_images)
def save_images_task(self):
from time import sleep
self.saving_images_cancelled = False
while not self.saving_images_cancelled:
self.save_images()
sleep(0.2)
self.__saving_images__ = False
saving_images_cancelled = False
def save_images(self):
"""Check whether the last acquired image needs to be saved and save it.
"""
self.save_images_cancelled = False
from os.path import exists,basename
image_numbers,filenames = self.image_numbers,self.filenames
for (image_number,filename) in zip(image_numbers,filenames):
if self.save_images_cancelled: break
temp_filename = self.temp_filename(image_number=image_number)
if exists(temp_filename):
##debug("rayonix: saving image %r" % image_number)
self.save(temp_filename,filename)
image_numbers.remove(image_number)
filenames.remove(filename)
self.image_numbers,self.filenames = image_numbers,filenames
save_images_cancelled = False
def save(self,temp_filename,filename):
from os.path import exists,basename
if not filename:
debug("rayonix: Discarding %r" % basename(temp_filename))
elif exists(temp_filename) and mtime(temp_filename) != mtime(filename):
from os import makedirs,remove
from shutil import copy2
from os.path import exists,dirname
if not exists(dirname(filename)):
try: makedirs(dirname(filename))
except Exception,msg:
warn("rayonix: makedirs: %r: %s" % (dirname(filename),msg))
try: remove(filename)
except: pass
try:
from os import link
link(temp_filename,filename)
debug("rayonix: Linked %r to %r" % (basename(temp_filename),
basename(filename)))
except Exception,msg: pass
if exists(temp_filename) and not exists(filename):
try:
copy2(temp_filename,filename)
debug("rayonix: Copied %r to %r" % (basename(temp_filename),
basename(filename)))
except Exception,msg:
error("rayonix: Cannot copy %r to %r: %s" %
(temp_filename,filename,msg))
def temp_filename(self,image_number=None,xdet_trig_count=None):
"""Full pathname of image file"""
if image_number is not None:
if image_number in self.xdet_trig_counts:
filename = self.temp_filename(xdet_trig_count=
self.xdet_trig_counts[image_number])
else: filename = ""
if xdet_trig_count is not None:
filename = "%s/%06d.rx" % (self.scratch_directory,xdet_trig_count)
return filename
def get_trigger_monitoring(self):
from timing_system import timing_system
return self.xdet_acq_handle in timing_system.xdet.acq.monitors
def set_trigger_monitoring(self,value):
from timing_system import timing_system
if value != self.trigger_monitoring:
if bool(value) == True:
timing_system.xdet.acq.monitor(self.xdet_acq_handle,
new_thread=False)
if bool(value) == False:
timing_system.xdet.acq.monitor_clear(self.xdet_acq_handle)
trigger_monitoring = property(get_trigger_monitoring,set_trigger_monitoring)
def xdet_acq_handle(self):
# Called when X-ray detector trigger level has changed.
from timing_system import timing_system
from numpy import nan
from os.path import basename
xdet_acq = self.xdet_acq
acquiring = self.timing_system_acquiring
xdet_trig_count = self.xdet_trig_count
xdet_acq_count = self.xdet_acq_count
debug("Got update: xdet_acq = %r (acquiring = %r, "\
"xdet_trig_count = %r, xdet_acq_count %r)"\
% (xdet_acq,acquiring,xdet_trig_count,xdet_acq_count))
if acquiring and xdet_acq == 0: # falling edge
debug("xdet_acq_count %s = xdet_trig_count %s = file %r" % (
xdet_acq_count,
xdet_trig_count,
basename(self.filename(xdet_acq_count))
))
self.xdet_trig_counts[xdet_acq_count] = xdet_trig_count
def timing_system_property(name,default_value=0):
def get(self):
from timing_system import timing_system
from CA import caget
PV_name = eval("timing_system.%s.PV_name" % name)
# Use "caget" to circumvent caching in the "timing_system" module
value = caget(PV_name)
try: value = type(default_value)(value)
except: value = default_value
return value
return property(get)
xdet_acq = timing_system_property("xdet_acq")
timing_system_acquiring = timing_system_property("acquiring")
xdet_acq_count = timing_system_property("xdet_acq_count")
xdet_trig_count = timing_system_property("xdet_trig_count")
xdet_trig_counts = {}
def filename(self,xdet_acq_count):
if xdet_acq_count in self.image_numbers:
i = self.image_numbers.index(xdet_acq_count)
filename = self.filenames[i]
else: filename = ""
return filename
def get_acquiring(self):
value = self.state() == 'acquiring series'
return value
def set_acquiring(self,value):
if self.acquiring != value:
if value: self.start()
else: self.stop()
acquiring = property(get_acquiring,set_acquiring)
def start(self):
"""Start continuous acquistion"""
from time import sleep
if self.trigger_enabled:
self.trigger_enabled = False
while self.trigger_enabled: sleep(0.1)
sleep(0.1)
self.empty_scratch_directory()
self.ignore_first_trigger = False
self.start_series_triggered(n_frames=999999,
filename_base=self.scratch_directory+"/",
filename_suffix=".rx",number_field_width=6)
timing_system.xdet_trig_count.value = 0
timing_system.xdet_trig_count.count = 0
self.trigger_enabled = self.auto_start
self.filenames = {}
self.limit_files_enabled = True
def stop(self):
"""Stop continuous acquistion"""
self.abort()
self.trigger_enabled = False
self.limit_files_enabled = False
def get_trigger_enabled(self):
"""Timing system triggering detector?"""
return self.timing_sequencer.xdet_on
def set_trigger_enabled(self,value):
self.timing_sequencer.xdet_on = value
trigger_enabled = property(get_trigger_enabled,set_trigger_enabled)
@property
def timing_sequencer(self):
return timing_sequencer if self.timing_mode == "Laue" \
else Ensemble_SAXS
def empty_scratch_directory(self):
"""Limit the number of files in the scratch directory"""
from os import remove
for f in self.image_filenames:
try: remove(f)
except Exception,msg: warn("Cannot remove %r: %s" % (f,msg))
from os.path import exists
from os import makedirs
dir = self.scratch_directory
if not exists(dir): makedirs(dir)
def get_limit_files_enabled(self):
return self.limit_files_task_running
def set_limit_files_enabled(self,value):
if value:
if not self.limit_files_task_running:
from thread import start_new_thread
start_new_thread(self.limit_files_task,())
else: self.limit_files_task_running = False
limit_files_enabled = property(get_limit_files_enabled,set_limit_files_enabled)
limit_files_task_running = False
def limit_files_task(self):
from time import sleep
self.limit_files_task_running = True
while self.limit_files_task_running:
self.limit_files()
sleep(0.2)
def limit_files(self):
"""Limit the number of files in the scratch directory"""
from os import remove
files_to_delete = self.image_filenames[0:-self.nimages_to_keep]
for f in files_to_delete:
try: remove(f)
except: pass
@property
def current_image_basename(self):
"""Current image filename without directory"""
from os.path import basename
return basename(self.current_image_filename)
@property
def current_image_filename(self):
"""Current image filename"""
self.monitoring = True
i = self.xdet_acq_count
if i in self.image_numbers:
j = self.image_numbers.index(i)
if 0 <= j < len(self.filenames): filename = self.filenames[j]
else: filename = ""
else: filename = ""
return filename
@property
def nimages(self):
"""How many images left to save?"""
self.monitoring = True
return self.__nimages__
@property
def __nimages__(self):
"""How many images left to save?"""
from numpy import array,sum
nimages = sum(array(self.image_numbers) > self.xdet_acq_count)
return nimages
@property
def last_image_number(self):
"""Last acquired image"""
last_image_number = self.file_image_number(self.last_filename)
return last_image_number
@property
def last_filename(self):
"""File name of last acquired image"""
filenames = self.image_filenames
filename = filenames[-1] if len(filenames) > 0 else ""
return filename
def file_image_number(self,filename):
"""Extract serial number from image pathname"""
from os.path import basename
try: image_number = int(basename(filename).replace(".rx",""))
except: image_number = 0
return image_number
@property
def image_filenames(self):
"""Pathnames of temporarily stored images, sorted by timestamp
as list of strings"""
from os import listdir
from os.path import exists
dir = self.scratch_directory
try: files = listdir(dir)
except: files = []
files = [dir+"/"+f for f in files]
files.sort()
return files
@property
def current_temp_filename(self):
"""Pathnames of last temporarily stored image"""
filenames = self.image_filenames
if len(filenames) > 1: filename = filenames[-1]
else: filename = ""
return filename
def set_bin_factor(self,value):
"""Image size reduction at readout time"""
if value != Rayonix_Detector.get_bin_factor(self):
acquiring = self.acquiring
Rayonix_Detector.set_bin_factor(self,value)
self.acquiring = acquiring
bin_factor = property(Rayonix_Detector.get_bin_factor,set_bin_factor)
def get_live_image(self):
return self.live_image_task_running
def set_live_image(self,value):
if value:
if not self.live_image_task_running:
from thread import start_new_thread
start_new_thread(self.live_image_task,())
else: self.live_image_task_running = False
live_image = property(get_live_image,set_live_image)
live_image_task_running = False
def live_image_task(self):
"""Display a live image"""
from time import sleep
self.live_image_task_running = True
while self.live_image_task_running:
if self.live_image: self.update_live_image()
sleep(0.2)
live_image_filename = ""
def update_live_image(self):
"""Display a live image"""
from ImageViewer import show_image
filename = self.current_temp_filename
if filename and filename != self.live_image_filename:
show_image(filename)
self.live_image_filename = filename
def get_ADXV_live_image(self):
return self.ADXV_live_image_task_running
def set_ADXV_live_image(self,value):
if value:
if not self.ADXV_live_image_task_running:
from thread import start_new_thread
start_new_thread(self.ADXV_live_image_task,())
else: self.ADXV_live_image_task_running = False
ADXV_live_image = property(get_ADXV_live_image,set_ADXV_live_image)
ADXV_live_image_task_running = False
def ADXV_live_image_task(self):
"""Display a live image"""
from time import sleep
self.ADXV_live_image_task_running = True
while self.ADXV_live_image_task_running:
if self.ADXV_live_image: self.update_ADXV_live_image()
sleep(0.2)
ADXV_live_image_filename = ""
def update_ADXV_live_image(self):
"""Display a live image"""
from ADXV_live_image import show_image
filename = self.current_temp_filename
if filename and filename != self.ADXV_live_image_filename:
show_image(filename)
self.ADXV_live_image_filename = filename
rayonix_detector = Rayonix_Detector_Continous()
ccd = rayonix_detector
self = rayonix_detector
def mtime(filename):
"""When was the file modified the last time?
Return value: seconds since 1970-01-01 00:00:00 UTC as floating point number
0 if the file does not exists"""
from os.path import getmtime
try: return getmtime(filename)
except: return 0
from tcp_server import tcp_server
server = tcp_server("rayonix_detector_server",globals=globals(),locals=locals())
def run(): server.run()
if __name__ == "__main__": # for debugging
from pdb import pm
import logging
logging.basicConfig(
level=logging.INFO,
format=
"%(asctime)s "
"%(levelname)s "
"%(funcName)s"
", line %(lineno)d"
": %(message)s"
)
print("server.port = %r" % server.port)
print("server.running = True")
print("run()")
<file_sep>"""Ramp temperature as fast as possible for data collection
<NAME> 4 Jun 2015 - 5 Jun 2015"""
from temperature_controller import temperature_controller
from sleep import sleep
from numpy import ceil
setT,readT = temperature_controller.setT,temperature_controller.readT
T_repeat = 3
Time_array = [10,62,50,80,30] # -20 to 60 Celsius; Mar 1, 2016
Temp_array = [22,-15,55] # -20 to 60 Celsius
Time_array = [10,70,80,105,30] # -15 to 100 Celsius; Mar 1, 2016
Temp_array = [22,-15,100] # -15 to 100 Celsius
#Time_array = [60,90,90,125,60] # -15 to 100 Celsius; Apr 11, 2016
#Temp_array = [22,-15,100] # -15 to 100 Celsius
#Time_array = [60,40,80,100,60] # 0 to 100 Celsius; Apr 30, 2016
#Temp_array = [22,0,100] # 0 to 100 Celsius
#Time_array = [20,20,40,55,60] # 0 to 100 Celsius; Apr 30, 2016
#Temp_array = [22,0,100] # 0 to 100 Celsius
#Time_array = [10,40,28,56,30] # -17 to 52 Celsius; Jun 22, 2016
#Temp_array = [22,-20,60] # -17 to 52 Celsius
#Time_array = [10,40,33,61,30] # -17 to 60 Celsius; Jun 22, 2016
#Temp_array = [22,-20,70] # -17 to 60 Celsius
Time_array = [10,40,60,70,30] # -15 to 100 Celsius; Jun 22, 2016
Temp_array = [22,-20,105] # -15 to 100 Celsius
T_image = 0.238995 #time per stroke in fly-thru mode.
N_images = (sum(Time_array)+sum(Time_array[2:4])*(T_repeat-1))/T_image
def run():
setT.value = Temp_array[0]
sleep(Time_array[0])
setT.value = Temp_array[1]
sleep(Time_array[1])
for i in range(0,T_repeat):
setT.value = Temp_array[2]
sleep(Time_array[2])
setT.value = Temp_array[1]
sleep(Time_array[3])
setT.value = Temp_array[0]
sleep(Time_array[4])
print 'N_images=',int(ceil(N_images))
print 'run()'
<file_sep>#!/usr/bin/env python
"""Controls for control panels
Author: <NAME>,
Date created: 2017-10-31
Date last modified: 2018-10-31
"""
__version__ = "1.0"
from logging import debug,info,warn,error
import wx, wx3_compatibility
class DirectoryControl(wx.Panel):
"""Control panel for SAXS-WAXS Experiments"""
from persistent_property import persistent_property
value = persistent_property("value","")
defaults = persistent_property("defaults",{})
properties = persistent_property("properties",{})
refresh_period = persistent_property("refresh_period",1.0)
def __init__(self,parent,name="DirectoryControl",
locals=None,globals=None,*args,**kwargs):
self.name = name
self.locals = locals
self.globals = globals
wx.Panel.__init__(self,parent)
# Controls
from EditableControls import TextCtrl
self.control = TextCtrl(self,*args,**kwargs)
# Needed for wx.Button on MacOS, because Position defaults to 5,3:
self.control.Position = (0,0)
self.control.Enabled = False
self.button = wx.Button(self,label="Browse...")
# Layout
sizer = wx.BoxSizer(wx.HORIZONTAL)
sizer.Add(self.control,proportion=1)
sizer.Add(self.button,proportion=0)
self.Sizer = sizer
self.Fit()
# Initialization
self.initial = {}
# Callbacks
self.Bind(wx.EVT_BUTTON,self.OnBrowse,self.button)
self.Bind(wx.EVT_TEXT_ENTER,self.OnEnter,self.control)
# Refresh
from numpy import nan
self.values = {}
self.old_values = {}
self.refreshing = False
self.executing = False
from wx.lib.newevent import NewEvent
self.EVT_THREAD = NewEvent()[1]
self.Bind(self.EVT_THREAD,self.OnUpdate)
from threading import Thread
self.thread = Thread(target=self.keep_updated,name=self.name)
self.thread.start()
# Initialization
self.refresh_status()
def OnEnter(self,event):
value = self.control.Value
info("User requested %s = %r" % (self.name,value))
if self.value: self.execute("%s = %r" % (self.value,value))
self.refresh()
def OnBrowse(self,event):
pathname = str(self.control.Value)
from os.path import exists,dirname
while pathname and not exists(pathname): pathname = dirname(pathname)
dlg = wx.DirDialog(self,"Choose a directory:",style=wx.DD_DEFAULT_STYLE)
# ShowModal pops up a dialog box and returns control only after the user
# has selects OK or Cancel.
dlg.Path = pathname
if dlg.ShowModal() == wx.ID_OK:
from normpath import normpath
value = normpath(str(dlg.Path))
if self.value: self.execute("%s = %r" % (self.value,value))
self.control.Value = value
dlg.Destroy()
def execute(self,command):
if not self.executing:
from threading import Thread
self.execute_thread = Thread(target=self.execute_background,
args=(command,),name=self.name+".execute")
self.executing = True
self.execute_thread.start()
def execute_background(self,command):
info("%s: executing %r" % (self.name,command))
try: exec(command,self.locals,self.globals)
except Exception,msg:
if command: warn("%s: %s: %s" % (self.name,command,msg))
event = wx.PyCommandEvent(self.EVT_THREAD.typeId,self.Id)
# call OnUpdate in GUI thread
wx.PostEvent(self.EventHandler,event)
self.executing = False
def keep_updated(self):
"""Periodically refresh the displayed settings."""
from time import time,sleep
while True:
try:
t0 = time()
while time() < t0+self.refresh_period: sleep(0.1)
if self.Shown:
self.update_data()
if self.data_changed:
##debug("keep_updated: data_changed")
event = wx.PyCommandEvent(self.EVT_THREAD.typeId,self.Id)
# call OnUpdate in GUI thread
wx.PostEvent(self.EventHandler,event)
except wx.PyDeadObjectError: break
def refresh(self):
"""Force update"""
from threading import Thread
if not self.refreshing and self.Shown:
self.refresh_thread = Thread(target=self.refresh_background,
name=self.name+".refresh")
self.refreshing = True
self.refresh_thread.start()
def refresh_background(self):
"""Force update"""
self.update_data()
if self.data_changed:
event = wx.PyCommandEvent(self.EVT_THREAD.typeId,self.Id)
wx.PostEvent(self.EventHandler,event) # call OnUpdate in GUI thread
self.refreshing = False
def update_data(self):
"""Retreive status information"""
from copy import deepcopy
from numpy import nan
self.old_values = deepcopy(self.values)
for prop in self.properties:
#StartRasterScan.properties = {
# "Value": [
# (False, "control.scanning == False"),
# (True, "control.scanning == True"),
# ],
#}
if type(self.properties[prop]) == list:
if not prop in self.values: self.values[prop] = {}
for (choice,expr) in self.properties[prop]:
try: value = eval(expr,self.locals,self.globals)
except Exception,msg:
if expr: warn("%s.%s.%s: %s: %s" % (self.name,prop,choice,expr,msg))
value = nan
self.values[prop][choice] = value
#Image.properties = {"Image": "control.camera.RGB_array"}
elif type(self.properties[prop]) == str:
expr = self.properties[prop]
try: value = eval(expr,self.locals,self.globals)
except Exception,msg:
if expr: warn("%s.%s: %s: %s" % (self.name,prop,expr,msg))
value = nan
self.values[prop] = value
if self.value:
try: value = eval(self.value,self.locals,self.globals)
except Exception,msg:
warn("%s: %s: %s" % (self.name,self.value,msg))
value = nan
self.values["value"] = value
@property
def data_changed(self):
"""Did the last 'update_data' change the data to be plotted?"""
changed = (self.values != self.old_values)
return changed
@property
def data_changed(self):
"""Did the last 'update_data' change the data to be plotted?"""
##changed = (self.values != self.old_values)
if sorted(self.values.keys()) != sorted(self.old_values.keys()):
##debug("%r != %r" % (self.values.keys(),self.old_values.keys()))
changed = True
else:
changed = False
for a in self.values:
item_changed = not nan_equal(self.values[a],self.old_values[a])
##debug("%r: changed: %r" % (a,item_changed))
changed = changed or item_changed
##debug("data changed: %r" % changed)
return changed
def OnUpdate(self,event=None):
"""Periodically refresh the displayed settings."""
self.refresh_status()
def refresh_status(self,event=None):
"""Update the controls with current values"""
##debug("refresh_status")
from numpy import isnan
# One-time initialization
for prop in self.properties.keys():
if hasattr(self.control,prop):
if not prop in self.initial:
self.initial[prop] = getattr(self.control,prop)
else: warn("%r has no property %r" % (self.name,prop))
for prop in self.properties.keys():
if hasattr(self.control,prop):
value = self.initial[prop]
if prop in self.defaults: value = self.defaults[prop]
if prop in self.values and prop in self.properties:
#StartRasterScan.properties = {
# "Value": [
# (False, "control.scanning == False"),
# (True, "control.scanning == True"),
# ],
#}
if type(self.properties[prop]) == list:
for choice,expr in self.properties[prop]:
if choice in self.values[prop] \
and not isnan(self.values[prop][choice]) \
and self.values[prop][choice]:
value = choice
break
#Image.properties = {"Image": "control.camera.RGB_array"}
elif type(self.properties[prop]) == str:
value = self.values[prop]
if prop == "ToolTip": value = wx.ToolTip(value)
debug("%s.%s=%r" % (type_name(self.control),prop,value))
if getattr(self.control,prop,None) != value:
try: setattr(self.control,prop,value)
except Exception,msg:
error("%s.%s = %r: %s" % (type_name(self.control),prop,value,msg))
else: warn("%r has no property %r" % (self.name,prop))
if self.value:
prop = "Value"
if hasattr(self.control,prop):
value = ""
if prop in self.initial: value = self.initial[prop]
if prop in self.defaults: value = self.defaults[prop]
if "value" in self.values: value = self.values["value"]
if prop == "ToolTip": value = wx.ToolTip(value)
value = self.control_value(value)
debug("%s.%s=%r" % (type_name(self.control),prop,value))
if getattr(self.control,prop,None) != value:
try: setattr(self.control,prop,value)
except Exception,msg:
error("%s.%s=%r: %s" % (type_name(self.control),prop,value,msg))
else: warn("%r has no property %r" % (self.name,prop))
if self.executing:
self.control.Label = self.control.Label.strip(".")+"..."
def control_value(self,value):
"""Convert the value into the form that can be represented by the
control"""
from numpy import isnan
if self.control_data_type == str and not isinstance(value,str):
if isinstance(value,float) and isnan(value): value = ""
else:
if self.scale:
try: value = value*self.scale
except Exception,msg: error("%r*%r: %s" % (value,self.scale,msg))
try: value = self.format % value
except Exception,msg: error("%r % %r: %s" % (self.format,value,msg))
try: value = str(value)
except Exception,msg:
error("str(%r): %s" % (value,msg))
value=""
if self.control_data_type == bool and not isinstance(value,bool):
try: value = bool(value)
except Exception,msg:
error("bool(%r): %s" % (value,msg))
value=False
return value
@property
def control_data_type(self):
"""Python data type (str,int,bool) that can be represented by the
control"""
type = str
if isinstance(self.control,wx.ToggleButton): type = bool
if isinstance(self.control,wx.CheckBox): type = bool
return type
def type_name(object):
type_name = repr(type(object))
# E.g. <class 'wx._controls.ToggleButton'>
type_name = type_name.strip("<>")
# E.g. class 'wx._controls.ToggleButton'
type_name = type_name.replace("class ","")
# E.g. 'wx._controls.ToggleButton'
type_name = type_name.strip("'")
# E.g. wx._controls.ToggleButton
type_name = type_name.replace("_controls.","")
# E.g. wx.ToggleButton
return type_name
def test_eval(expr,locals=None,globals=None):
return eval(expr,locals,globals)
def test_exec(expr,locals=None,globals=None):
exec(expr,locals,globals)
def nan_equal(a,b):
"""Are to array equal? a and b may contain NaNs"""
import numpy
try: numpy.testing.assert_equal(a,b)
except AssertionError: return False
return True
if __name__ == '__main__':
from pdb import pm
import logging; from tempfile import gettempdir
logfile = gettempdir()+"/SAXS_WAXS_Control_Panel.log"
logging.basicConfig(level=logging.INFO,
format="%(asctime)s %(levelname)s %(module)s.%(funcName)s, line %(lineno)d: %(message)s",
##filename=logfile,
)
import autoreload
from instrumentation import * # passed on in "globals()"
# Needed to initialize WX library
wx.app = wx.App(redirect=False)
frame = wx.Frame(None)
control = DirectoryControl(frame,globals=globals(),locals=locals(),
name="Collect_Panel.Path",
size=(500,-1),
)
frame.Fit()
frame.Show()
wx.app.MainLoop()
<file_sep>"""Platform-indepedent way to generate sound.
<NAME>, 2 Jul 2010 - 28 Feb 2016
Setup:
Install the packages "portaudio" and"pyaudio"
("sudo apt-get install portaudio-dev" or "sudo yum install portaudio-devel"
"sudo pip install pyaudio" or "sudo easy_install pyaudio")
"""
from logging import warn
__version__ = "1.0.1" # volume control
def play_sound(name,volume=4.0):
play_sound_file(module_dir()+"/sounds/"+name+".wav",volume)
def play_sound_file(filename,volume=1.0):
# based on people.csail.mit.edu/hubert/pyaudio/#examples
try: import pyaudio
except ImportError:
warn("pyaudio module not found. Sound not played."); return
import wave
from os.path import exists
if not exists(filename):
print "%s: file not found. Sound not played" % filename; return
wf = wave.open(filename,"rb")
p = pyaudio.PyAudio()
# open stream
stream = p.open(format = p.get_format_from_width(wf.getsampwidth()),
channels = wf.getnchannels(),rate = wf.getframerate(),output = True)
# read data
chunk = 1024
data = wf.readframes(chunk)
# play stream
while data != '':
stream.write(scale(data,volume))
data = wf.readframes(chunk)
stream.close()
p.terminate()
def scale(data,factor):
"""Scale the amplitude of a sound waveform.
data: 16-bit signed integers stereo sound samples, stored as string
scale factor: flotign point number: >1 louder, <1 softer, 1 keep volume
return value: scaled data"""
from numpy import fromstring,int16,clip
values = fromstring(data,int16)
values = clip(values*factor,-2**15,2**15-1).astype(int16)
data = values.tostring()
return data
def module_dir():
"""directory in which the .py file of current module is located"""
from os.path import dirname
return dirname(module_path())
def module_path():
"""Full pathname of the current module"""
from sys import path
from os import getcwd
from os.path import basename,exists
from inspect import getmodulename,getfile
# 'getfile' retreives the source file name name compiled into the .pyc file.
pathname = getfile(lambda x: None)
if exists(pathname): return pathname
# The module might have been compiled on a different machine or in a
# different directory.
pathname = pathname.replace("\\","/")
filename = basename(pathname)
dirs = [dir for dir in [getcwd()]+path if exists(dir+"/"+filename)]
if len(dirs) == 0: print "pathname of file %r not found" % filename
dir = dirs[0] if len(dirs) > 0 else "."
pathname = dir+"/"+filename
return pathname
if __name__ == "__main__": # for testing
print("play_sound('ding',volume=1.0)")
<file_sep>#!/usr/bin/env python
"""High-speed diffractometer.
<NAME>, 31 Oct 2013 - 28 Jan 2016"""
__version__ = "1.0.3"
import wx
from MotorPanel import MotorWindow
# Needed to initialize WX library
if not "app" in globals(): app = wx.App(redirect=False)
from Ensemble import SampleX,SampleY,SampleZ,SamplePhi
window = MotorWindow([SampleX,SampleY,SampleZ,SamplePhi],
title="Fast Diffractometer")
app.MainLoop()
<file_sep>"""Caching
Author: <NAME>
Date created: 2018-10-24
Date last modified: 2018-10-31
"""
__version__ = "1.0.1" # only update file if changed
from logging import debug,info,warn,error
class Cache(object):
def __init__(self,name="cache"):
self.name = name
def set(self,key,data):
"""Temporarily store binary data for fast restreival
key: string"""
if data != self.get(key) or not self.exists(key):
from os.path import exists,dirname
from os import makedirs
filename = self.filename(key)
if not exists(dirname(filename)): makedirs(dirname(filename))
try: file(filename,"wb").write(data)
except Exception,msg: warn("%s: %s" % (filename,msg))
def get(self,key):
"""Retreive temporarily stored binary data
key: string"""
filename = self.filename(key)
try: data = file(filename,"rb").read()
except: data = ""
return data
def exists(self,key):
"""Retreive temporarily stored binary data
key: string"""
from os.path import exists
return exists(self.filename(key))
def clear(self):
"""Erase temporarily stored binary data"""
from shutil import rmtree
try: rmtree(self.dir)
except: pass
def get_size(self):
"""How many cached data objects are there?"""
from os import listdir
try: return len(listdir(self.dir))
except: return 0
def set_size(self,value):
if value == 0: self.clear()
size = property(get_size,set_size)
def filename(self,key):
"""Where to store the data associated with key"""
# If the key exceeds 254 characters, it needs to be shortened
# by hashing, otherwise the file system would not allow it
# to be used as a filename.
key = key.replace(":","_")
key = key.replace("/","_")
filename = self.dir+"/"+key
return filename
@property
def dir(self):
"""Where to store temparary files"""
from tempfile import gettempdir
basedir = gettempdir()
dir = basedir+"/"+self.name
return dir
if __name__ == "__main__":
from pdb import pm # for debugging
import logging # for debugging
from time import time # for timing
logging.basicConfig(
level=logging.DEBUG,
format="%(asctime)s %(levelname)s %(module)s.%(funcName)s: %(message)s",
)
cache = Cache("CA")
PV_name = "NIH:TIMING.registers.cmcnd.count"
print('cache.get(PV_name) # should be 20228')
print('cache.set(PV_name,"20228")')
<file_sep>Nsvd = 8
ROI_fraction = 0.3333
SVD_rotation = True
analysis_fraction = 0.333
control_ms_shutter = True
cx = 0.98
cy = -0.725
cz = 0.808
dx = 0.025
dy = 0.025
height = 1.2
motion_controller_enabled = True
peak_detection_threshold = 300
start_time = 1509976589.864669
started = 1487706597.964051
subtract_background = False
width = 0.6
cancelled = False
dt = 0.024304557104457086
start_dt = 0.024304557104457086
last_jog_xray_shutter = 1509976247.872744
repeat_number = 1
repeat_count = 0
collection_directory = '/net/mx340hs/data/anfinrud_1711/Data/Laue/CypA/CypA-5'<file_sep>"""<NAME>, May 1, 2015 - May 7, 2015"""
from ftplib import FTP
from telnetlib import Telnet
from io import BytesIO
from struct import pack
data = ""
for i in range(0,10*1000/2):
data += pack(">bbHIII",0x03,0x000,0x0001,0xF0FFB044,0x00000001,0x00000000)
data += pack(">bbHIII",0x03,0x000,0x0001,0xF0FFB044,0x00000001,0x00000001)
f = BytesIO()
f.write(data)
f.seek(0)
ftp = FTP("pico25.niddk.nih.gov","root","root")
ftp.storbinary ("STOR /tmp/sequence.bin",f)
ftp.close()
telnet = Telnet("pico25.niddk.nih.gov")
telnet.read_until("login: ")
telnet.write("root\n")
telnet.read_until("Password: ")
telnet.write("root\n")
telnet.read_until("# ")
telnet.write("/bin/cat < /tmp/sequence.bin > /dev/sequencer &\n")
telnet.read_until("# ")
telnet.write("exit\n")
transcript = telnet.read_all()
telnet.close()
def abort():
telnet = Telnet("pico25.niddk.nih.gov")
telnet.read_until("login: ")
telnet.write("root\n")
telnet.read_until("Password: ")
telnet.write("root\n")
telnet.read_until("# ")
telnet.write("killall cat\n")
telnet.read_until("# ")
telnet.close()
<file_sep>"""
Run on "mond" node "daq-xpp-mon05.pcdsn" or "daq-xpp-mon06.pcdsn".
Only one instance can run per node.
Setup:
source /reg/g/psdm/etc/ana_env.sh
DAQ Control - (uncheck) Record Run - Begin Running
<NAME>, Jan 22, 2016
"""
import time
import zmq
from psana import *
from logging import info,warn,debug
ds = DataSource('shmem=XPP.0:stop=no')
src = Source('rayonix')
context = zmq.Context()
sender = context.socket(zmq.PUSH)
sender.connect("tcp://172.21.22.71:12323")
for evt in ds.events():
debug("Waiting for event...")
raw = evt.get(Camera.FrameV1,src)
debug("Got event")
if raw is None: continue
data = raw.data16()
t = evt.get(EventId).fiducials()
print('Sending array data: %r,%r' % (t,data.shape))
sender.send_pyobj(data)
<file_sep>"""
How to access the PEB of another process with python ctypes
https://stackoverflow.com/questions/35106511/how-to-access-the-peb-of-another-process-with-python-ctypes
Answered Jan 31 '16 at 3:57 eryksun
The following example has the ctypes definitions that are required to query and
use ProcessBasicInformation for a given process that has the same architecture
(i.e. native 64-bit or WOW64 32-bit). It includes a class that demonstrates
usage and provides properties for the process ID, session ID, image path,
command line, and the paths for loaded modules.
The example uses a RemotePointer subclass of ctypes._Pointer, along with an
RPOINTER factory function. This class overrides __getitem__ to facilitate
dereferencing a pointer value in the address space of another process. The
index key is a tuple of the form index, handle[, size]. The optional size
parameter (in bytes) is useful for sized strings such as NTAPI UNICODE_STRING,
e.g. ustr.Buffer[0, hProcess, usrt.Length]. Null-terminated strings are not
supported, since ReadProcessMemory requires a sized buffer.
The logic for walking the loader data is in the private _modules_iter method,
which walks the loaded modules using the in-memory-order linked list. Note that
InMemoryOrderModuleList links to the InMemoryOrderLinks field of the
LDR_DATA_TABLE_ENTRY structure, and so on for each link in the list.
The module iterator has to adjust the base address for each entry by the offset
to this field. In the C API this would use the CONTAINING_RECORD macro.
The ProcessInformation constructor defaults to querying the current process if
no process ID or handle is provided. If the call status is an error or warning
(i.e. negative NTSTATUS), it calls NtError to get an instance of OSError, or
WindowsError prior to 3.3.
I have, but did not include, a more elaborate version of NtError that calls
FormatMessage to get a formatted error message, using ntdll.dll as the source
module. I can update the answer to include this version upon request.
The example was tested in Windows 7 and 10, using 32-bit and 64-bit versions
of Python 2.7 and 3.5. For the remote process test, the subprocess module is
used to start a 2nd Python instance. An event handle is passed to the child
process for synchronization. If the parent process doesn't wait for the child
process to finish loading and set the event, then the child's loader data may
not be completely initialized when read.
"""
import ctypes
from ctypes import wintypes
ntdll = ctypes.WinDLL('ntdll')
kernel32 = ctypes.WinDLL('kernel32', use_last_error=True)
# WINAPI Definitions
PROCESS_VM_READ = 0x0010
PROCESS_QUERY_INFORMATION = 0x0400
ERROR_INVALID_HANDLE = 0x0006
ERROR_PARTIAL_COPY = 0x012B
PULONG = ctypes.POINTER(wintypes.ULONG)
ULONG_PTR = wintypes.LPVOID
SIZE_T = ctypes.c_size_t
def _check_bool(result, func, args):
if not result:
raise ctypes.WinError(ctypes.get_last_error())
return args
kernel32.ReadProcessMemory.errcheck = _check_bool
kernel32.ReadProcessMemory.argtypes = (
wintypes.HANDLE, # _In_ hProcess
wintypes.LPCVOID, # _In_ lpBaseAddress
wintypes.LPVOID, # _Out_ lpBuffer
SIZE_T, # _In_ nSize
ctypes.POINTER(SIZE_T)) # _Out_ lpNumberOfBytesRead
kernel32.CloseHandle.errcheck = _check_bool
kernel32.CloseHandle.argtypes = (wintypes.HANDLE,)
kernel32.GetCurrentProcess.restype = wintypes.HANDLE
kernel32.GetCurrentProcess.argtypes = ()
kernel32.OpenProcess.errcheck = _check_bool
kernel32.OpenProcess.restype = wintypes.HANDLE
kernel32.OpenProcess.argtypes = (
wintypes.DWORD, # _In_ dwDesiredAccess
wintypes.BOOL, # _In_ bInheritHandle
wintypes.DWORD) # _In_ dwProcessId
class RemotePointer(ctypes._Pointer):
def __getitem__(self, key):
# TODO: slicing
size = None
if not isinstance(key, tuple):
raise KeyError('must be (index, handle[, size])')
if len(key) > 2:
index, handle, size = key
else:
index, handle = key
if isinstance(index, slice):
raise TypeError('slicing is not supported')
dtype = self._type_
offset = ctypes.sizeof(dtype) * index
address = PVOID.from_buffer(self).value + offset
simple = issubclass(dtype, ctypes._SimpleCData)
if simple and size is not None:
if dtype._type_ == wintypes.WCHAR._type_:
buf = (wintypes.WCHAR * (size // 2))()
else:
buf = (ctypes.c_char * size)()
else:
buf = dtype()
nread = SIZE_T()
kernel32.ReadProcessMemory(handle,
address,
ctypes.byref(buf),
ctypes.sizeof(buf),
ctypes.byref(nread))
if simple:
return buf.value
return buf
def __setitem__(self, key, value):
# TODO: kernel32.WriteProcessMemory
raise TypeError('remote pointers are read only')
@property
def contents(self):
# a handle is required
raise NotImplementedError
_remote_pointer_cache = {}
def RPOINTER(dtype):
if dtype in _remote_pointer_cache:
return _remote_pointer_cache[dtype]
name = 'RP_%s' % dtype.__name__
ptype = type(name, (RemotePointer,), {'_type_': dtype})
_remote_pointer_cache[dtype] = ptype
return ptype
# NTAPI Definitions
NTSTATUS = wintypes.LONG
PVOID = wintypes.LPVOID
RPWSTR = RPOINTER(wintypes.WCHAR)
PROCESSINFOCLASS = wintypes.ULONG
ProcessBasicInformation = 0
ProcessDebugPort = 7
ProcessWow64Information = 26
ProcessImageFileName = 27
ProcessBreakOnTermination = 29
STATUS_UNSUCCESSFUL = NTSTATUS(0xC0000001)
STATUS_INFO_LENGTH_MISMATCH = NTSTATUS(0xC0000004).value
STATUS_INVALID_HANDLE = NTSTATUS(0xC0000008).value
STATUS_OBJECT_TYPE_MISMATCH = NTSTATUS(0xC0000024).value
class UNICODE_STRING(ctypes.Structure):
_fields_ = (('Length', wintypes.USHORT),
('MaximumLength', wintypes.USHORT),
('Buffer', RPWSTR))
class LIST_ENTRY(ctypes.Structure):
pass
RPLIST_ENTRY = RPOINTER(LIST_ENTRY)
LIST_ENTRY._fields_ = (('Flink', RPLIST_ENTRY),
('Blink', RPLIST_ENTRY))
class LDR_DATA_TABLE_ENTRY(ctypes.Structure):
_fields_ = (('Reserved1', PVOID * 2),
('InMemoryOrderLinks', LIST_ENTRY),
('Reserved2', PVOID * 2),
('DllBase', PVOID),
('EntryPoint', PVOID),
('Reserved3', PVOID),
('FullDllName', UNICODE_STRING),
('Reserved4', wintypes.BYTE * 8),
('Reserved5', PVOID * 3),
('CheckSum', PVOID),
('TimeDateStamp', wintypes.ULONG))
RPLDR_DATA_TABLE_ENTRY = RPOINTER(LDR_DATA_TABLE_ENTRY)
class PEB_LDR_DATA(ctypes.Structure):
_fields_ = (('Reserved1', wintypes.BYTE * 8),
('Reserved2', PVOID * 3),
('InMemoryOrderModuleList', LIST_ENTRY))
RPPEB_LDR_DATA = RPOINTER(PEB_LDR_DATA)
class RTL_USER_PROCESS_PARAMETERS(ctypes.Structure):
_fields_ = (('Reserved1', wintypes.BYTE * 16),
('Reserved2', PVOID * 10),
('ImagePathName', UNICODE_STRING),
('CommandLine', UNICODE_STRING))
RPRTL_USER_PROCESS_PARAMETERS = RPOINTER(RTL_USER_PROCESS_PARAMETERS)
PPS_POST_PROCESS_INIT_ROUTINE = PVOID
class PEB(ctypes.Structure):
_fields_ = (('Reserved1', wintypes.BYTE * 2),
('BeingDebugged', wintypes.BYTE),
('Reserved2', wintypes.BYTE * 1),
('Reserved3', PVOID * 2),
('Ldr', RPPEB_LDR_DATA),
('ProcessParameters', RPRTL_USER_PROCESS_PARAMETERS),
('Reserved4', wintypes.BYTE * 104),
('Reserved5', PVOID * 52),
('PostProcessInitRoutine', PPS_POST_PROCESS_INIT_ROUTINE),
('Reserved6', wintypes.BYTE * 128),
('Reserved7', PVOID * 1),
('SessionId', wintypes.ULONG))
RPPEB = RPOINTER(PEB)
class PROCESS_BASIC_INFORMATION(ctypes.Structure):
_fields_ = (('Reserved1', PVOID),
('PebBaseAddress', RPPEB),
('Reserved2', PVOID * 2),
('UniqueProcessId', ULONG_PTR),
('Reserved3', PVOID))
def NtError(status):
import sys
descr = 'NTSTATUS(%#08x) ' % (status % 2**32,)
if status & 0xC0000000 == 0xC0000000:
descr += '[Error]'
elif status & 0x80000000 == 0x80000000:
descr += '[Warning]'
elif status & 0x40000000 == 0x40000000:
descr += '[Information]'
else:
descr += '[Success]'
if sys.version_info[:2] < (3, 3):
return WindowsError(status, descr)
return OSError(None, descr, None, status)
NtQueryInformationProcess = ntdll.NtQueryInformationProcess
NtQueryInformationProcess.restype = NTSTATUS
NtQueryInformationProcess.argtypes = (
wintypes.HANDLE, # _In_ ProcessHandle
PROCESSINFOCLASS, # _In_ ProcessInformationClass
PVOID, # _Out_ ProcessInformation
wintypes.ULONG, # _In_ ProcessInformationLength
PULONG) # _Out_opt_ ReturnLength
class ProcessInformation(object):
_close_handle = False
_closed = False
_module_names = None
def __init__(self, process_id=None, handle=None):
if process_id is None and handle is None:
handle = kernel32.GetCurrentProcess()
elif handle is None:
handle = kernel32.OpenProcess(PROCESS_VM_READ |
PROCESS_QUERY_INFORMATION,
False, process_id)
self._close_handle = True
self._handle = handle
self._query_info()
if process_id is not None and self._process_id != process_id:
raise NtError(STATUS_UNSUCCESSFUL)
def __del__(self, CloseHandle=kernel32.CloseHandle):
if self._close_handle and not self._closed:
try:
CloseHandle(self._handle)
except WindowsError as e:
if e.winerror != ERROR_INVALID_HANDLE:
raise
self._closed = True
def _query_info(self):
info = PROCESS_BASIC_INFORMATION()
handle = self._handle
status = NtQueryInformationProcess(handle,
ProcessBasicInformation,
ctypes.byref(info),
ctypes.sizeof(info),
None)
if status < 0:
raise NtError(status)
self._process_id = info.UniqueProcessId
self._peb = peb = info.PebBaseAddress[0, handle]
self._params = peb.ProcessParameters[0, handle]
self._ldr = peb.Ldr[0, handle]
def _modules_iter(self):
headaddr = (PVOID.from_buffer(self._peb.Ldr).value +
PEB_LDR_DATA.InMemoryOrderModuleList.offset)
offset = LDR_DATA_TABLE_ENTRY.InMemoryOrderLinks.offset
pentry = self._ldr.InMemoryOrderModuleList.Flink
while pentry:
pentry_void = PVOID.from_buffer_copy(pentry)
if pentry_void.value == headaddr:
break
pentry_void.value -= offset
pmod = RPLDR_DATA_TABLE_ENTRY.from_buffer(pentry_void)
mod = pmod[0, self._handle]
yield mod
pentry = LIST_ENTRY.from_buffer(mod, offset).Flink
def update_module_names(self):
names = []
for m in self._modules_iter():
ustr = m.FullDllName
name = ustr.Buffer[0, self._handle, ustr.Length]
names.append(name)
self._module_names = names
@property
def module_names(self):
if self._module_names is None:
self.update_module_names()
return self._module_names
@property
def process_id(self):
return self._process_id
@property
def session_id(self):
return self._peb.SessionId
@property
def image_path(self):
ustr = self._params.ImagePathName
return ustr.Buffer[0, self._handle, ustr.Length]
@property
def command_line(self):
ustr = self._params.CommandLine
buf = ustr.Buffer[0, self._handle, ustr.Length]
return buf
if __name__ == '__main__':
import os
import sys
import subprocess
import textwrap
class SECURITY_ATTRIBUTES(ctypes.Structure):
_fields_ = (('nLength', wintypes.DWORD),
('lpSecurityDescriptor', wintypes.LPVOID),
('bInheritHandle', wintypes.BOOL))
def __init__(self, *args, **kwds):
super(SECURITY_ATTRIBUTES, self).__init__(*args, **kwds)
self.nLength = ctypes.sizeof(self)
def test_remote(use_pid=True, show_modules=False):
sa = SECURITY_ATTRIBUTES(bInheritHandle=True)
hEvent = kernel32.CreateEventW(ctypes.byref(sa), 0, 0, None)
try:
script = textwrap.dedent(r"""
import sys
import ctypes
kernel32 = ctypes.WinDLL('kernel32')
kernel32.SetEvent(%d)
sys.stdin.read()""").strip() % hEvent
cmd = '"%s" -c "%s"' % (sys.executable, script)
proc = subprocess.Popen(cmd, stdin=subprocess.PIPE,
close_fds=False)
try:
kernel32.WaitForSingleObject(hEvent, 5000)
if use_pid:
pi = ProcessInformation(proc.pid)
else:
pi = ProcessInformation(handle=int(proc._handle))
assert pi.process_id == proc.pid
assert pi.image_path == sys.executable
assert pi.command_line == cmd
assert pi.module_names[0] == sys.executable
if show_modules:
print('\n'.join(pi.module_names))
finally:
proc.terminate()
finally:
kernel32.CloseHandle(hEvent)
print('Test 1: current process')
pi = ProcessInformation()
assert os.getpid() == pi.process_id
assert pi.image_path == pi.module_names[0]
print('Test 2: remote process (Handle)')
test_remote(use_pid=False)
print('Test 3: remote process (PID)')
test_remote(show_modules=True)
<file_sep>"""
Automatically adjust the set point of the Oasis thermoelectric chiller,
according to the set point of the ILX LightWave LTD-5948 precision temperature
controller. AKA slave the chiller to temperature controller
Authors: <NAME>, <NAME>
Date created: 2018-02-22
Date last modified: 2018-05-22
1.1 - changed Tmin to -30 (from -25).
1.2 - if T < 22, keep oasis at 2*C, if above 22C slave linearly
1.3 - The autotune happens only if the new set oasis set temperature is
- different from the previous one. There is no need to submit new set
- temperature command if it is equal to the current one.
"""
__version__ = "1.4" # lightwave_temperature_controller
from lightwave_temperature_controller import lightwave_temperature_controller
from oasis_chiller import oasis_chiller
from CAServer import casput,casdel
from time import clock, time, sleep
Told = T = lightwave_temperature_controller.command_value
t= told = oasis_chiller.command_value
tstart = time()
circular_buffer = []
def run():
from time import sleep
casput("NIH:CHILLER.AUTOTUNE",1)
while True:
autotune()
sleep(5)
def autotune():
"""Adjust the set point of the Oasis chiller.
autotune only if the new set poitn for the oasis is different
from the previous one. There is no need to autotune every 5 seconds if
set temperature for the oasis is the same.
"""
global Told,T,told,t, circular_buffer
T = lightwave_temperature_controller.command_value
if len(circular_buffer) == 0:
circular_buffer.append(T)
circular_buffer.append(T)
if len(circular_buffer) >3:
circular_buffer.pop(0)
t = oasis_chiller_set_point(Told,T)
if t != told:
oasis_chiller.command_value = t
#print('autotune: t new %r, t old %r, time: %r' %(t,told,round(time()-tstart,0)))
Told = T
told = t
def oasis_chiller_set_point(Told,T, mode = '2 states'):
"""Which temperature to set the chiller to?
T = temperature controller point
t = oasis temperature point
default mode:
keeps oasis temperature(t) at 8*C(oasis_t) if T <=22.0
and uses linear interpolation if T >22.0.
2 states mode:
keeps oasis at oasis_t temperature
If the change in the TEC set temperature is positive
oasis temperature will be set to 45*C, if negative - 4*C
If constant, it will use linear interpolation to calculate
the oasis set temperature
"""
from numpy import clip
set_t = oasis_chiller.command_value
oasis_t_low = oasis_t= 8.0
oasis_t_high = oasis_t_max = 45.0
TEC_T = 60.0
TEC_T_max = 60.0
T2 = T
#if len(circular_buffer)>2:
# circular_buffer.append()
#else:
if mode == '2 states':
if T>Told and (circular_buffer[1]>circular_buffer[0]):
t = oasis_t_high
elif (T < Told) and (circular_buffer[1]<circular_buffer[0]):
t = oasis_t_low
else:
if T < TEC_T:
t = oasis_t_low
elif T >= TEC_T:
t = oasis_t_high
else:
if T>Told and (circular_buffer[1]>circular_buffer[0]):
t = oasis_t_high
elif (T < Told) and (circular_buffer[1]<circular_buffer[0]):
t = oasis_t_low
else:
if T < TEC_T:
t = oasis_t_low
elif T >= TEC_T_max:
t = oasis_t_high
else:
Tmin,Tmax = TEC_T,TEC_T_max
tmin,tmax = oasis_t_low,oasis_t_high
t = (T-Tmin)/(Tmax-Tmin)*(tmax-tmin)+tmin
t = clip(t,tmin,tmax)
t = round(t,1)
return t
if __name__ == "__main__":
print('oasis_chiller_set_point(%r)' % lightwave_temperature_controller.command_value)
print('run()')
<file_sep>#!/bin/env python
"""Setup: source /reg/g/psdm/etc/ana_env.sh
Open a port to psana via SSh Tunneling.
ssh -Nx -L localhost:12322:psana1508:12322 psdev &
"""
import zmq
from logging import info,warn,debug
class DataStream:
def __init__(self,address):
context = zmq.Context()
self.client = context.socket(zmq.PAIR)
self.client.connect(address)
def image(self,image_id):
"""image_id: string"""
print("DataStream: requesting %r" % image_id)
self.client.send_pyobj(image_id)
return self.client.recv_pyobj()
##address = "tcp://127.0.01:12322" # requires SSH Tunnel
address = "tcp://psana1508.pcdsn:12322"
datastream = DataStream(address)
if __name__ == "__main__": # for testing
from time import time
run = "exp=xppj1216:run=17:smd:dir=/reg/d/ffb/xpp/xppj1216/xtc:live"
def test():
start = time()
n = 0
for i in range(0,20):
image_id = "%s:%d" % (run,i)
info("getting image %r" % image_id)
img = datastream.image(image_id)
if img is not None:
n += 1
info("%s\n%s"%(img.shape,img[0:2,0:2]))
else: info("None")
print "%d images, %.1f images/s" % (n,n/(time()-start))
print("test()")
<file_sep>"""Aerotech Ensemble Motion Controller
Communication via Aeroch's C library interface using a proprietary
protocol by Aerotech.
<NAME>, Apr 12, 2013 - Mar 8, 2018"""
from array_wrapper import ArrayWrapper
from DB import dbget,dbput
from logging import debug,info,warn,error
from pdb import pm # for debugging
__version__ = "3.0" # auxiliary_task
class Ensemble(object):
handle = None
library = None
max_integer_registers = 50
max_floating_point_registers = 512
library_path = r'C:\Program Files (x86)\Aerotech\Ensemble\CLibrary\Bin'
library_name = "EnsembleC.dll"
def load_library(self):
if self.library is None:
from os import environ
if not self.library_path in environ["PATH"]:
environ["PATH"] = self.library_path+";"+environ["PATH"]
import ctypes
try: self.library = ctypes.windll.LoadLibrary(self.library_name)
except Exception,details:
self.library = None
if not hasattr(self,"library_load_failed"):
error('ctypes.windll.LoadLibrary(%r): %s' % (self.library_name,details))
error("This module needs to be running on operating system Windows.")
self.library_load_failed = True
def connect(self):
"""Establish a connection to the controller"""
self.load_library()
if self.library is None: return
if self.handle is not None: return
from ctypes import byref,c_void_p,c_int,POINTER
if self.library is not None and self.handle is None:
handles = POINTER(c_void_p)()
handle_count = c_int()
success = self.library.EnsembleConnect(byref(handles),
byref(handle_count))
if success and handle_count.value >= 1:
self.handle = handles.contents
else: error("Unable to connect to Ensemble controller")
def disconnect(self):
"""Undo 'connect'"""
if self.library is None: return
if self.handle is None: return
from ctypes import c_void_p,POINTER
handles = POINTER(c_void_p)()
handles.contents = self.handle
success = self.library.EnsembleDisconnect(handles)
if success == True: self.handle = None
else: error("disconnect failed")
def get_connected(self):
"""Is a communication link with the controller established?"""
return self.library is not None and self.handle is not None
def set_connected(self,value):
if value: self.connect()
else: self.disconnect()
connected = property(get_connected,set_connected)
@property
def naxes(self):
"""How many axes does the controller control?"""
return bin(self.axis_mask).count("1")
@property
def axis_mask(self):
"""Bitmask: 1 for every axis that is available in the controller,
strating from the least significant bit"""
self.connect()
if not self.connected: return 0
from ctypes import byref,c_int
c_value = c_int()
success = self.library.EnsembleInformationGetAxisMask (self.handle,byref(c_value))
if success != True: error("axis mask failed")
return c_value.value
def get_fault(self,axis_number):
"""Axis faults as integer with 28 bits
e.g. bit 0: PositionError, bit 27: VoltageClamp
0 indicates not fault"""
self.connect()
if not self.connected: from numpy import nan; return nan
from ctypes import byref,c_int,c_double
c_value = c_double()
AxisFault = 4 # EnsembleCommonStructures.h, STATUSITEM
success = self.library.EnsembleStatusGetItem(self.handle,c_int(axis_number),
c_int(AxisFault),byref(c_value))
if success != True: error("get fault failed, axis %r" % axis_number)
value = int(c_value.value)
return value
def get_fault_count(self): return self.naxes
def _get_faults(self):
return ArrayWrapper(self,"fault",method="single")
def _set_faults(self,values): pass
faults = property(_get_faults,_set_faults)
def _get_fault(self):
"""Is any axis on a fault state?"""
return any(self.faults)
def set_fault(self,value):
if value: self.clear_all_faults
fault = property(_get_fault,set_fault)
def clear_all_faults(self):
"""Clear fault state for all axis.
(This has the side effect of cancelling all active incompleted moves)."""
self.connect()
if not self.connected: return
success = self.library.EnsembleAcknowledgeAll(self.handle)
if success != True: error("clear all faults failed")
def clear_faults(self,axis_numbers):
"""Clear fault state.
axis_numbers: list of 0-based integers
"""
self.connect()
if not self.connected: return
# Attempting to clear faults on currently "active" axes confuses the
# Ensemble controller.
# Thus, only clear faults for axis that are currently in "fault" state.
from numpy import asarray,atleast_1d
axis_numbers = atleast_1d(axis_numbers)
axis_numbers = axis_numbers[asarray(self.faults[axis_numbers]) != 0]
if len(axis_numbers) == 0: return
from ctypes import c_int
axis_mask = 0
for i in axis_numbers: axis_mask |= (1 << i)
success = self.library.EnsembleMotionFaultAck(self.handle,
c_int(axis_mask))
if success != True: error("clear faults failed")
def get_nominal_value(self,axis_number):
"""Target of current or last move"""
self.connect()
if not self.connected: from numpy import nan; return nan
from ctypes import byref,c_int,c_double
c_value = c_double()
PositionCommand = 0 # EnsembleCommonStructures.h, STATUSITEM
self.library.EnsembleStatusGetItem(self.handle,c_int(axis_number),
c_int(PositionCommand),byref(c_value))
value = c_value.value
return value
def get_nominal_value_count(self): return self.naxes
def _get_nominal_values(self):
return ArrayWrapper(self,"nominal_value",method="single")
def _set_nominal_values(self,values): pass
nominal_values = property(_get_nominal_values,_set_nominal_values)
def get_command_value(self,axis_number):
"""Target of current or last move"""
command_value = \
self.destination_values[axis_number] if self.moving[axis_number] \
else self.nominal_values[axis_number]
return command_value
def get_command_values(self,axis_numbers):
"""Target of current or last move
axis_numbers: list of integers"""
from numpy import where
moving = self.moving[axis_numbers]
nominal_values = self.nominal_values[axis_numbers]
destination_values = self.destination_values[axis_numbers]
command_values = where(moving,destination_values,
nominal_values)
return command_values
def set_command_values(self,axis_numbers,values):
"""Move axis
axis_numbers: list of integers
values: target positions"""
# Ignore values that are NaN.
from numpy import atleast_1d,isnan,asarray
axis_numbers,values = atleast_1d(axis_numbers),atleast_1d(values)
valid = ~isnan(values)
axis_numbers,values = axis_numbers[valid],values[valid]
# Ignore axis that are already in position.
old_values = self.command_values[axis_numbers]
valid = abs(values-old_values) >= 0.001
axis_numbers,values = axis_numbers[valid],values[valid]
if len(axis_numbers) == 0: return
self.connect()
if not self.connected: return
self.clear_faults(axis_numbers)
##self.clear_faults(axis_numbers[~asarray(self.moving[axis_numbers])])
# Make sure "EnsembleMotionMoveAbs" will not wait for motion to be done.
from ctypes import byref,c_int,c_double,ARRAY
waittype = 0 # EnsembleCommonStructures.h, WAITTYPE, WAITTYPE_NoWait
success = self.library.EnsembleMotionWaitMode(self.handle,
c_int(waittype))
if success != True: error("set wait mode failed")
# This is needed for compatibility with the "Ensemble-SAXS.ab" program,
# which uses PLANE and PVT commands.
plane_number = 0
success = self.library.EnsembleMotionSetupPlane(self.handle,
c_int(plane_number))
if success != True: error("set plane 0 failed")
axis_mask = 0
for i in axis_numbers: axis_mask |= (1 << i)
success = self.library.EnsembleMotionSetupReconcile(self.handle,
c_int(axis_mask))
if success != True: error("reconcile failed")
# Start the motion.
speed = 10.0
c_values = ARRAY(c_double,len(axis_numbers))(*values)
speeds = self.speeds[axis_numbers]
c_speeds = ARRAY(c_double,len(axis_numbers))(*speeds)
success = self.library.EnsembleMotionMoveAbs(self.handle,
c_int(axis_mask),c_values,c_speeds)
if success != True: error("set command positions failed")
# Remember destination values.
self.destination_values[axis_numbers] = values
def set_command_values_fast(self,axis_numbers,values):
"""Move axis
axis_numbers: list of integers
values: target positions"""
from ctypes import byref,c_int,c_double,ARRAY
from numpy import atleast_1d,isnan,asarray
axis_numbers,values = atleast_1d(axis_numbers),atleast_1d(values)
if len(axis_numbers) == 0: return
self.connect()
if not self.connected: return
# Start the motion.
speed = 10.0
axis_mask = 0
for i in axis_numbers: axis_mask |= (1 << i)
c_values = ARRAY(c_double,len(axis_numbers))(*values)
speeds = self.speeds[axis_numbers]
c_speeds = ARRAY(c_double,len(axis_numbers))(*speeds)
success = self.library.EnsembleMotionMoveAbs(self.handle,
c_int(axis_mask),c_values,c_speeds)
if success != True: error("set command positions failed")
def get_command_values_count(self): return self.naxes
def _get_command_values(self):
return ArrayWrapper(self,"command_values",method="multiple")
def _set_command_values(self,values): self.command_values[:] = values
command_values = property(_get_command_values,_set_command_values)
def get_command_dial_values(self,axis_numbers):
"""Target of current or last move
axis_numbers: list of integers"""
values = self.command_values[axis_numbers]
return self.user_to_dial(axis_numbers,values)
def set_command_dial_values(self,axis_numbers,dial_values):
"""Move axis
axis_numbers: list of integers
values: target positions"""
values = self.dial_to_user(axis_numbers,dial_values)
self.command_values[axis_numbers] = dial_values
def get_command_dial_values_count(self): return self.naxes
def _get_command_dial_values(self):
return ArrayWrapper(self,"command_dial_values",method="multiple")
def _set_command_dial_values(self,dial_values):
self.command_dial_values[:] = dial_values
command_dial_values = property(_get_command_dial_values,
_set_command_dial_values)
def get_value(self,axis_number):
"""Actual position based on encoder feedback"""
self.connect()
if not self.connected: from numpy import nan; return nan
from ctypes import byref,c_int,c_double
c_value = c_double()
PositionFeedback = 1
self.library.EnsembleStatusGetItem(self.handle,c_int(axis_number),
c_int(PositionFeedback),byref(c_value))
value = c_value.value
return value
def set_value(self,axis_number,values): pass
def get_value_count(self): return self.naxes
def _get_values(self):
return ArrayWrapper(self,"value",method="single")
def _set_values(self,values): self.values[:] = values
values = property(_get_values,_set_values)
def get_destination_values(self,axis_numbers):
"""The end points of the currently active motions"""
from numpy import zeros,nan
if not hasattr(self,"__destination_values__") or \
len(self.__destination_values__) != self.naxes:
self.__destination_values__ = zeros(self.naxes)+nan
return self.__destination_values__[axis_numbers]
def set_destination_values(self,axis_numbers,values):
from numpy import zeros,nan
if not hasattr(self,"__destination_values__") or \
len(self.__destination_values__) != self.naxes:
self.__destination_values__ = zeros(self.naxes)+nan
self.__destination_values__[axis_numbers] = values
def get_destination_values_count(self): return self.naxes
def _get_destination_values(self):
return ArrayWrapper(self,"destination_values",method="multiple")
def _set_get_destination_values(self,values): self.destination_values[:] = values
destination_values = property(_get_destination_values,_set_get_destination_values)
def get_dial_values(self,axis_numbers):
"""Target of current or last move
axis_numbers: list of integers"""
values = self.values[axis_numbers]
return self.user_to_dial(axis_numbers,values)
def set_dial_values(self,axis_numbers,values): pass
def get_dial_values_count(self): return self.naxes
def _get_dial_values(self):
return ArrayWrapper(self,"dial_values",method="multiple")
def _set_dial_values(self,dial_values): self.dial_values[:] = dial_values
dial_values = property(_get_dial_values,_set_dial_values)
def get_moving(self,axis_number):
"""Actual position based on encoder feedback"""
self.connect()
if not self.connected: from numpy import nan; return nan
if not self.get_enabled(axis_number): return False
from ctypes import byref,c_int,c_double
c_value = c_double()
AxisStatus = 3 # EnsembleCommonStructures.h, STATUSITEM
self.library.EnsembleStatusGetItem(self.handle,c_int(axis_number),
c_int(AxisStatus),byref(c_value))
value = c_value.value
InPositionBit = 2 # EnsembleCommonStructures.h, AXISSTATUSBITS
MoveActiveBit = 3 # EnsembleCommonStructures.h, AXISSTATUSBITS
in_position = (int(value) & 1<<InPositionBit) != 0
move_active = (int(value) & 1<<MoveActiveBit) != 0
return move_active ##not in_position
def set_moving(self,axis_number,value):
"""Stop the motion of the given axis, if value is False"""
if value: return
# Ignore values that are NaN.
from numpy import isnan
if isnan(value): return
self.connect()
from ctypes import c_int
axis_mask = (1 << axis_number)
self.library.EnsembleMotionAbort(self.handle,c_int(axis_mask))
def moving_count(self): return self.naxes
def _get_moving(self):
return ArrayWrapper(self,"moving",method="single")
def _set_moving(self,values): self.moving[:] = values
moving = property(_get_moving,_set_moving)
def get_speed(self,axis_number):
return self.parameter("DefaultSpeed",axis_number)
def set_speed(self,axis_number,value):
# Ignore values that are NaN.
from numpy import isnan
if isnan(value): return
return self.set_parameter("DefaultSpeed",value,axis_number)
def speed_count(self): return self.naxes
def _get_speeds(self):
return ArrayWrapper(self,"speed",method="single")
def _set_speeds(self,values): self.speeds[:] = values
speeds = property(_get_speeds,_set_speeds)
def get_acceleration(self,axis_number):
return self.parameter("DefaultRampRate",axis_number)
def set_acceleration(self,axis_number,value):
# Ignore values that are NaN.
from numpy import isnan
if isnan(value): return
return self.set_parameter("DefaultRampRate",value,axis_number)
def acceleration_count(self): return self.naxes
def _get_accelerations(self):
return ArrayWrapper(self,"acceleration",method="single")
def _set_accelerations(self,values): self.accelerations[:] = values
accelerations = property(_get_accelerations,_set_accelerations)
def get_enabled(self,axis_number):
"""Actual position based on encoder feedback"""
self.connect()
if not self.connected: from numpy import nan; return nan
from ctypes import byref,c_int,c_double
c_value = c_double()
AxisStatus = 3 # EnsembleCommonStructures.h, STATUSITEM
self.library.EnsembleStatusGetItem(self.handle,c_int(axis_number),
c_int(AxisStatus),byref(c_value))
value = c_value.value
EnabledBit = 0 # EnsembleCommonStructures.h, AXISSTATUSBITS
value = (int(value) & 1<<EnabledBit) != 0
return value
def set_enabled(self,axis_number,value):
"""Turn on the holding current.
value: if True turn on, if False turn off the holding current"""
# Ignore values that are NaN.
from numpy import isnan
if isnan(value): return
self.connect()
if not self.connected: return
from ctypes import c_int
axis_mask = (1 << axis_number)
if value:
self.clear_faults([axis_number])
self.library.EnsembleMotionEnable(self.handle,c_int(axis_mask))
else: self.library.EnsembleMotionDisable(self.handle,c_int(axis_mask))
def enabled_count(self): return self.naxes
def _get_enabled(self):
return ArrayWrapper(self,"enabled",method="single")
def _set_enabled(self,values): self.enabled[:] = values
enabled = property(_get_enabled,_set_enabled)
def get_homing(self,axis_number):
"""Actual position based on encoder feedback"""
self.connect()
if not self.connected: from numpy import nan; return nan
from ctypes import byref,c_int,c_double
c_value = c_double()
AxisStatus = 3 # EnsembleCommonStructures.h, STATUSITEM
self.library.EnsembleStatusGetItem(self.handle,c_int(axis_number),
c_int(AxisStatus),byref(c_value))
value = c_value.value
HomingBit = 14 # EnsembleCommonStructures.h, AXISSTATUSBITS
value = (int(value) & 1<<HomingBit) != 0
return value
def set_homing(self,axis_number,value):
"""Calibrate the motor by driving it past its home switch.
value: if True start home run, if False cancel home run"""
# Ignore values that are NaN.
from numpy import isnan
if isnan(value): return
self.connect()
if not self.connected: return
self.clear_faults([axis_number])
# Make sure "EnsembleMotionHome" will not wait for motion to be done.
# (However, the wait mode does not seem to have any effect when using
# the "EnsembleMotionHome" command.)
from ctypes import byref,c_int,c_double,ARRAY
waittype = 0 # EnsembleCommonStructures.h, WAITTYPE, WAITTYPE_NoWait
success = self.library.EnsembleMotionWaitMode(self.handle,
c_int(waittype))
if success != True: error("set wait mode failed")
axis_mask = (1 << axis_number)
if value:
success = self.library.EnsembleMotionHome(self.handle,c_int(axis_mask))
if success != True: error("home failed")
else:
success = self.library.EnsembleMotionAbort(self.handle,c_int(axis_mask))
if success != True: error("abort failed")
def homing_count(self): return self.naxes
def _get_homing(self):
return ArrayWrapper(self,"homing",method="single")
def _set_homing(self,values): self.homing[:] = values
homing = property(_get_homing,_set_homing)
def get_homed(self,axis_number):
"""Actual position based on encoder feedback"""
self.connect()
if not self.connected: from numpy import nan; return nan
from ctypes import byref,c_int,c_double
c_value = c_double()
AxisStatus = 3 # EnsembleCommonStructures.h, STATUSITEM
self.library.EnsembleStatusGetItem(self.handle,c_int(axis_number),
c_int(AxisStatus),byref(c_value))
value = c_value.value
HomedBit = 1 # EnsembleCommonStructures.h, AXISSTATUSBITS
value = (int(value) & 1<<HomedBit) != 0
return value
def set_homed(self,axis_number,value):
# Ignore values that are NaN.
from numpy import isnan
if isnan(value): return
# If value is True, Home the axis, if not already done.
if value and not self.homed[axis_number]:
debug("self.homing[%r] = True..." % axis_number)
self.homing[axis_number] = True
debug("self.homing[%r] = %r" % (axis_number,self.homing[2]))
def homed_count(self): return self.naxes
def _get_homed(self):
return ArrayWrapper(self,"homed",method="single")
def _set_homed(self,values): self.homed[:] = values
homed = property(_get_homed,_set_homed)
def get_at_low_dial_limits(self,axis_number):
"""It the stage hitting the end of travel switch?"""
self.connect()
if not self.connected: from numpy import nan; return nan
from ctypes import byref,c_int,c_double
c_value = c_double()
AxisStatus = 3 # EnsembleCommonStructures.h, STATUSITEM
self.library.EnsembleStatusGetItem(self.handle,c_int(axis_number),
c_int(AxisStatus),byref(c_value))
value = c_value.value
CCwEndOfTravelLimitInputBit = 23 # EnsembleCommonStructures.h, AXISSTATUSBITS
value = (int(value) & 1<<CCwEndOfTravelLimitInputBit) != 0
return value
def set_at_low_dial_limits(self,axis_number,value): pass
def at_low_dial_limits_count(self): return self.naxes
def _get_at_low_dial_limits(self):
return ArrayWrapper(self,"at_low_dial_limits",method="single")
def _set_at_low_dial_limits(self,values): self.at_low_dial_limits[:] = values
at_low_dial_limits = property(_get_at_low_dial_limits,_set_at_low_dial_limits)
def get_at_high_dial_limits(self,axis_number):
"""Actual position based on encoder feedback"""
self.connect()
if not self.connected: from numpy import nan; return nan
from ctypes import byref,c_int,c_double
c_value = c_double()
AxisStatus = 3 # EnsembleCommonStructures.h, STATUSITEM
self.library.EnsembleStatusGetItem(self.handle,c_int(axis_number),
c_int(AxisStatus),byref(c_value))
value = c_value.value
CwEndOfTravelLimitInputBit = 22 # EnsembleCommonStructures.h, AXISSTATUSBITS
value = (int(value) & 1<<CwEndOfTravelLimitInputBit) != 0
return value
def set_at_high_dial_limits(self,axis_number,value): pass
def at_high_dial_limits_count(self): return self.naxes
def _get_at_high_dial_limits(self):
return ArrayWrapper(self,"at_high_dial_limits",method="single")
def _set_at_high_dial_limits(self,values): self.at_high_dial_limits[:] = values
at_high_dial_limits = property(_get_at_high_dial_limits,_set_at_high_dial_limits)
def get_at_low_limits(self):
"""Soft limit."""
from numpy import where
values = where(self.signs[:]>=0,
self.at_low_dial_limits[:],self.at_high_dial_limits[:])
return values
def set_at_low_limits(self,values): pass
def get_at_low_limits_count(self): return self.naxes
def _get_at_low_limits(self):
return ArrayWrapper(self,"at_low_limits",method="all")
def _set_at_low_limits(self,values): pass
at_low_limits = property(_get_at_low_limits,_set_at_low_limits)
def get_at_high_limits(self):
"""Soft limit."""
from numpy import where
values = where(self.signs[:]>=0,
self.at_high_dial_limits[:],self.at_low_dial_limits[:])
return values
def set_at_high_limits(self,values): pass
def get_at_high_limits_count(self): return self.naxes
def _get_at_high_limits(self):
return ArrayWrapper(self,"at_high_limits",method="all")
def _set_at_high_limits(self,values): pass
at_high_limits = property(_get_at_high_limits,_set_at_high_limits)
def parameter(self,parameter_name,axis_number=0):
"""Configuration parameter as floating point number.
parameter_id: integer. see "parameters_IDs"
axis_number: 0-based axis number or 0 for a system parameter"""
parameter_id = self.parameter_ID(parameter_name)
self.connect()
if not self.connected: from numpy import nan; return nan
from ctypes import byref,c_int,c_double
c_value = c_double()
self.library.EnsembleParameterGetValue(self.handle,
c_int(parameter_id),c_int(axis_number),byref(c_value))
value = c_value.value
return value
def set_parameter(self,parameter_name,value,axis_number=0):
"""Change configuration parameter.
parameter_id: integer. see "parameters_IDs"
value: floating point number
axis_number: 0-based axis number or 0 for a system parameter"""
parameter_id = self.parameter_ID(parameter_name)
self.connect()
if not self.connected: from numpy import nan; return nan
from ctypes import byref,c_int,c_double
value = float(value)
self.library.EnsembleParameterSetValue(self.handle,
c_int(parameter_id),c_int(axis_number),c_double(value))
def string_parameter(self,parameter_name,axis_number=0):
"""Configuration parameter as string.
parameter_name: string (see parameterIDs)
axis_number: 0-based axis number or 0 for a system parameter"""
parameter_id = self.parameter_ID(parameter_name)
self.connect()
if not self.connected: return ""
from ctypes import byref,c_int,create_string_buffer
c_value = create_string_buffer(81)
self.library.EnsembleParameterGetValueString (self.handle,
c_int(parameter_id),c_int(axis_number),c_int(80),byref(c_value))
value = c_value.value
return value
def set_string_parameter(self,parameter_name,value,axis_number=0):
"""Change configuration parameter.
parameter_name: string (see parameterIDs)
value: string
axis_number: 0-based axis number or 0 for a system parameter"""
parameter_id = self.parameter_ID(parameter_name)
self.connect()
if not self.connected: from numpy import nan; return nan
from ctypes import byref,c_int,c_char_p
value = str(value)
self.library.EnsembleParameterSetValueString (self.handle,
c_int(parameter_id),c_int(axis_number),c_char_p(value))
def parameter_ID(self,name):
"""Translate parameter name to parameter ID"""
if isinstance(name,basestring): return self.parameter_IDs[name]
else: return name
def get_UserInteger0(self):
return int(self.parameter("UserInteger0"))
def set_UserInteger0(self,value):
self.set_parameter("UserInteger0",value)
UserInteger0 = property(get_UserInteger0,set_UserInteger0)
def get_UserInteger1(self):
return int(self.parameter("UserInteger1"))
def set_UserInteger1(self,value):
self.set_parameter("UserInteger1",value)
UserInteger1 = property(get_UserInteger1,set_UserInteger1)
def get_UserDouble0(self):
return self.parameter("UserDouble0")
def set_UserDouble0(self,value):
self.set_parameter("UserDouble0",value)
UserDouble0 = property(get_UserDouble0,set_UserDouble0)
def get_UserDouble1(self):
return self.parameter("UserDouble1")
def set_UserDouble1(self,value):
self.set_parameter("UserDouble1",value)
UserDouble1 = property(get_UserDouble1,set_UserDouble1)
def get_UserString0(self):
return self.string_parameter("UserString0")
def set_UserString0(self,value):
self.set_string_parameter("UserString0",value)
UserString0 = property(get_UserString0,set_UserString0)
def get_UserString1(self):
return self.string_parameter("UserString1")
def set_UserString1(self,value):
self.set_string_parameter("UserString1",value)
UserString1 = property(get_UserString1,set_UserString1)
def get_unit(self,axis_number):
"""Unit name displayed in "Motion Composer" and "Digital Scope"
Return value: 'mm' or 'deg'"""
return self.string_parameter("UnitsName",axis_number)
def set_unit(self,axis_number,value):
"""Value: 'mm' or 'deg'"""
self.set_string_parameter("UnitsName",value,axis_number)
def unit_count(self): return self.naxes
def get_units(self):
return ArrayWrapper(self,"unit",method="single",dtype="S16")
def set_units(self,values): self.units[:] = values
units = property(get_units,set_units)
def get_name(self,axis_number):
"""Name of the axis displayed in "Motion Composer" and "Digital Scope"
Return value: 'mm' or 'deg'"""
return self.string_parameter("AxisName",axis_number)
def set_name(self,axis_number,value):
"""Value: 'mm' or 'deg'"""
self.set_string_parameter("AxisName",value,axis_number)
def name_count(self): return self.naxes
def get_names(self):
return ArrayWrapper(self,"name",method="single",dtype="S16")
def set_names(self,values): self.names[:] = values
names = property(get_names,set_names)
def get_floating_point_variable_range(self,start,count):
"""Global register variables
start: 0-based index
count: number of variables after start"""
from numpy import array,nan,zeros
self.connect()
if not self.connected: return zeros(count)+nan
from ctypes import byref,c_int,c_double,ARRAY
c_values = ARRAY(c_double,count)()
success = self.library.EnsembleVariableGetGlobalDoubles(self.handle,
c_int(start),c_values,c_int(count))
if success != True: error("get floating point variables failed")
values = array(c_values[:])
return values
def set_floating_point_variable_range(self,start,count,values):
"""Global register variables
start: 0-based index
count: number of variables after start
values: list or array of numbers"""
self.connect()
if not self.connected: return
from ctypes import byref,c_int,c_double,ARRAY
c_values = ARRAY(c_double,count)(*values)
success = self.library.EnsembleVariableSetGlobalDoubles(self.handle,
c_int(start),c_values,c_int(count))
if success != True: error("set floating point variables failed")
def get_floating_point_variables(self,indices):
"""Global register variables
indices: list of integer variables
"""
# Organize indices into groups of consecutive indices.
from numpy import asarray,arange,zeros,nan,argsort,where,roll
indices = asarray(indices)
order = argsort(indices)
indices = indices[order]
i_start = where(indices != roll(indices,1)+1)[0]
i_end = where(indices != roll(indices,-1)-1)[0]+1
counts = i_end-i_start
sorted_values = zeros(len(indices))+nan
for (i,count) in zip(i_start,counts):
sorted_values[i:i+count] = \
self.get_floating_point_variable_range(indices[i],count)
values = zeros(len(indices))+nan
values[order] = sorted_values
return values
def set_floating_point_variables(self,indices,values):
"""Global register variables
indices: list of integer variables
values: list or array of numbers
"""
# Organize indices into groups of consecutive indices.
from numpy import asarray,arange,argsort,asarray,roll,where,atleast_1d
indices = atleast_1d(indices)
values = atleast_1d(values)
order = argsort(indices)
indices,values = indices[order],values[order]
i_start = where(indices != roll(indices,1)+1)[0]
i_end = where(indices != roll(indices,-1)-1)[0]+1
counts = i_end-i_start
for (i,count) in zip(i_start,counts):
self.set_floating_point_variable_range(indices[i],count,
values[i:i+count])
@property
def floating_point_variables_count(self):
count = int(self.parameter("GlobalDoubles"))
count = min(count,self.max_floating_point_registers)
return count
def _get_floating_point_variables(self):
return ArrayWrapper(self,"floating_point_variables",method="multiple")
def _set_floating_point_variables(self,values): self.floating_point_variables[:] = values
floating_point_variables = property(_get_floating_point_variables,_set_floating_point_variables)
floating_point_registers = floating_point_variables
floating_point_registers_count = floating_point_variables_count
def get_integer_variable_range(self,start,count):
"""Global register variables
start: 0-based index
count: number of variables after start"""
from numpy import array,nan,zeros
self.connect()
if not self.connected: return zeros(count)+nan
from ctypes import byref,c_int,ARRAY
c_values = ARRAY(c_int,count)()
success = self.library.EnsembleVariableGetGlobalIntegers(self.handle,
c_int(start),c_values,c_int(count))
if success != True: error("get integer variables failed")
values = array(c_values[:])
return values
def set_integer_variable_range(self,start,count,values):
"""Global register variables
start: 0-based index
count: number of variables after start
values: list or array of numbers"""
from numpy import asarray
values = asarray(values,dtype=int)
self.connect()
if not self.connected: return
from ctypes import byref,c_int,ARRAY
c_values = ARRAY(c_int,count)(*values)
success = self.library.EnsembleVariableSetGlobalIntegers(self.handle,
c_int(start),c_values,c_int(count))
if success != True: error("set integer variables failed")
def get_integer_variables(self,indices):
"""Global register variables
indices: list of 0-based integers"""
# Organize indices into groups of consecutive indices.
from numpy import asarray,arange,zeros,nan,argsort,where,roll
indices = asarray(indices)
order = argsort(indices)
indices = indices[order]
i_start = where(indices != roll(indices,1)+1)[0]
i_end = where(indices != roll(indices,-1)-1)[0]+1
counts = i_end-i_start
sorted_values = zeros(len(indices))+nan
for (i,count) in zip(i_start,counts):
sorted_values[i:i+count] = \
self.get_integer_variable_range(indices[i],count)
values = zeros(len(indices),int)
values[order] = sorted_values
return values
def set_integer_variables(self,indices,values):
"""Global register variables
indices: list of 0-based integers
values: list or array of numbers"""
# Organize indices into groups of consecutive indices.
from numpy import asarray,arange,argsort,asarray,roll,where,atleast_1d
indices = atleast_1d(indices)
values = atleast_1d(values)
order = argsort(indices)
indices,values = indices[order],values[order]
i_start = where(indices != roll(indices,1)+1)[0]
i_end = where(indices != roll(indices,-1)-1)[0]+1
counts = i_end-i_start
for (i,count) in zip(i_start,counts):
self.set_integer_variable_range(indices[i],count,
values[i:i+count])
@property
def integer_variables_count(self):
count = int(self.parameter("GlobalIntegers"))
count = min(count,self.max_integer_registers)
return count
def _get_integer_variables(self):
return ArrayWrapper(self,"integer_variables",method="multiple")
def _set_integer_variables(self,values): self.integer_variables[:] = values
integer_variables = property(_get_integer_variables,_set_integer_variables)
integer_registers = integer_variables
integer_registers_count = integer_variables_count
def enable_camming(self):
"""Activates the camming table named 'test.cmx' stored in the
flash file system of the controller."""
# Run the program "EnableCamming.bcx" stored in the flash file system
# on the controller.
self.run_program("EnableCamming.bcx")
def disable_camming(self):
"""Undo 'enable_camming'"""
self.execute("PROGRAM STOP 1")
def get_camming_enabled(self):
"""Is camming mode currently enabled?"""
return self.program_running()
def set_camming_enabled(self,value):
if value: self.enable_camming()
else: self.disable_camming()
camming_enabled = property(get_camming_enabled,set_camming_enabled)
def get_program_filename(self):
"""Whuch program is currently running as task 1? Empty sting if none."""
# By onverstion each program loads its name into the
# "UserString0" parameter at startup to identify itself.
if self.program_running: return self.UserString0
else: return ""
def set_program_filename(self,filename,task_number=1):
if filename == "": self.stop_program(task_number); return
if filename.endswith(".bcx"): self.run_program(filename,task_number)
if filename.endswith(".ab"): self.run_local_program(filename,task_number)
program_filename = property(get_program_filename,set_program_filename)
def get_auxiliary_task_filename(self):
"""Whcih program is currently running? Empty sting if none."""
# By onverstion each program loads its name into the
# "UserString0" parameter at startup to identify itself.
if self.auxiliary_task_running: return self.UserString1
else: return ""
def set_auxiliary_task_filename(self,filename):
self.set_program_filename(filename,5)
auxiliary_task_filename = property(get_auxiliary_task_filename,
set_auxiliary_task_filename)
def get_auxiliary_task_running(self):
"""Is there a program running in the auxiliary task?"""
return self.get_program_running(5)
def set_auxiliary_task_running(self,value):
"""Start/Stop a program in the auxiliary task
value: True/False"""
return self.get_program_running(value,5)
auxiliary_task_running = property(get_auxiliary_task_running)
def run_program(self,filename,task_number=1):
"""Run a compiled .bcx program stored in the flash file system on the
controller.
filename: e.g. 'EnableCamming.bcx'
task_number: 1 to 5 (5=axiliary task)"""
self.execute('PROGRAM RUN %s, "%s"' % (task_number,filename))
dbput("Ensemble.program_filename",filename)
def execute(self,command):
"""Executes an AeroBasic command in the immediate task.
command: string e.g. 'RET = AXISSTATUS(X) BAND 1'
A function call that return a value must start with 'RET = '
Return value: floating point number"""
self.stop_program()
self.connect()
if not self.connected: return
from ctypes import c_double,byref
c_result = c_double()
success = self.library.EnsembleCommandExecute (self.handle,
command,byref(c_result))
if success != True:
error("command %r: execute failed" % command)
from numpy import nan
return nan
result = c_result.value
return result
def load_program(self,filename,task_number=1):
"""Loads an Aerobasic program. The given Aerobasic file will be
compiled, sent to the drive, and associated with the given task number.
The program is fully loaded and ready to execute.
filename: local file, full pathname ending with '.ab' in DOS format
task_number: 1-5 (5=auxiliary task)"""
from normpath import normpath
filename = normpath(filename)
self.connect()
if not self.connected: return
self.stop_program(task_number)
from ctypes import c_int
success = self.library.EnsembleProgramLoad(self.handle,
c_int(task_number),filename)
if success != True: error("program %r: load failed" % filename)
dbput("Ensemble.program_filename",filename)
def run_local_program(self,filename,task_number=1):
"""Runs an Aerobasic program. The given Aerobasic file will be compiled,
sent to the drive, associated with the given task number, and then
executed.
filename: local file, full pathname ending with '.ab' in DOS format
task_number: 1 to 5 (5=auxliliary task)"""
from normpath import normpath
from os.path import isabs
filename = normpath(filename)
##if isabs(filename): pathname = self.program_directory+"/"+filename
##else: pathname = filename
pathname = self.program_directory+"/"+filename
self.connect()
if not self.connected: return
self.stop_program(task_number)
from ctypes import c_int
success = self.library.EnsembleProgramRun(self.handle,
c_int(task_number),pathname)
if success != True: error("program %r: run failed" % pathname)
dbput("Ensemble.program_filename",filename)
@property
def program_directory(self):
"""Location of Aerobasic programs"""
from module_dir import module_dir
return module_dir(Ensemble)+"/Ensemble"
def start_program(self,task_number=1):
"""Start the execution of an Aerobasic program on a task. The given
task is started, and the associated Aerobasic program is executed.
task_number: 1-5 (5=auxiliary task)"""
self.connect()
if not self.connected: return
from ctypes import c_int
success = self.library.EnsembleProgramStart(self.handle,c_int(task_number))
if success != True: error("program start failed")
def get_program_running(self,task_number=1):
"""Is an Aerobasic program currently running?
task_number: 1-5 (5=auxiliary task)"""
self.connect()
if not self.connected: return
from ctypes import c_int,byref
c_task_state = c_int()
success = self.library.EnsembleProgramGetTaskState(self.handle,
c_int(task_number),byref(c_task_state))
if success != True: error("get task state failed"); return False
task_state = c_task_state.value
running = (task_state == 3)
return running
def set_program_running(self,value,task_number=1):
"""Start/stop a program
task_number: 1-5 (5=auxiliary task)"""
if bool(value) == True: self.start_program(task_number)
if bool(value) == False: self.stop_program(task_number)
program_running = property(get_program_running,set_program_running)
def stop_program(self,task_number=1):
"""Stop the execution of an Aerobasic program on a task.
The given task is stopped immediately, and all motion is aborted.
task_number: 1 to 5 (5=auxiliary task)"""
self.connect()
if not self.connected: return
from ctypes import c_int
success = self.library.EnsembleProgramStop(self.handle,c_int(task_number))
if success != True: error("program stop failed")
def get_analog_output(self):
"""Voltage (-5..+5 V)"""
# Using AOUT(X,1) to readback the voltage does not seem to be supported
# over the ASCII command interface. "AOUT(X,1)" always generates
# "execute failed".
##return self.execute("AOUT(X,1)")
value = dbget("Ensemble.AOUT.X.1")
try: value = float(value)
except ValueError: value = 0.0
return value
def set_analog_output(self,value):
##self.execute("AOUT X,1:%g" % value)
self.connect()
if not self.connected: from numpy import nan; return nan
from ctypes import byref,c_int,c_double,ARRAY
c_value = c_double()
axis = 0
channels = [1]
c_channels = ARRAY(c_int,1)(*channels)
channel_count = 1
values = [value]
c_values = ARRAY(c_double,1)(*values)
value_count = 1
success = self.library.EnsembleIOAnalogOutput(self.handle,
c_int(axis),c_channels,c_int(channel_count),c_values,
c_int(value_count))
if success != True: error("analog output %r failed" % value)
dbput("Ensemble.AOUT.X.1",str(value))
analog_output = property(get_analog_output,set_analog_output)
def dial_to_user(self,indices,dial_values):
"""Convert user to dial values"""
return dial_values*self.signs[indices] + self.offsets[indices]
def user_to_dial(self,indices,user_values):
"""Convert dial to user values"""
return (user_values-self.offsets[indices]) / self.signs[indices]
def get_sign(self,axis_number):
"""Is the direction reversed for this axis? +1 or -1"""
reverse = self.parameter("ReverseMotionDirection",axis_number)
return -1 if reverse else +1
def set_sign(self,axis_number,value):
reverse = 1 if value < 0 else 0
return self.set_parameter("ReverseMotionDirection",reverse,axis_number)
def get_sign_count(self): return self.naxes
def get_signs(self):
return ArrayWrapper(self,"sign",method="single")
def set_signs(self,values): self.signs[:] = values
signs = property(get_signs,set_signs)
def get_offsets(self):
"""Dial-to-user converion sign, maybe either 1 or -1"""
from numpy import zeros,array,isnan,where
try: values = array(eval(dbget("Ensemble.offsets")))
except: values = zeros(self.naxes)
values.resize(self.naxes)
values = where(isnan(values),0.0,values)
return values
def set_offsets(self,values):
# Ignore values that are NaN.
from numpy import asarray,isnan,where
values = asarray(values)
old_values = self.get_offsets()
values = where(~isnan(values),values,old_values)
dbput("Ensemble.offsets",str(list(values)))
def get_offsets_count(self): return self.naxes
def _get_offsets(self):
return ArrayWrapper(self,"offsets",method="all")
def _set_offsets(self,values): self.offsets[:] = values
offsets = property(_get_offsets,_set_offsets)
def get_dial_low_limit(self,axis_number):
return self.parameter("SoftwareLimitLow",axis_number)
def set_dial_low_limit(self,axis_number,value):
return self.set_parameter("SoftwareLimitLow",value,axis_number)
def get_dial_low_limit_count(self): return self.naxes
def get_dial_low_limits(self):
return ArrayWrapper(self,"dial_low_limit",method="single")
def set_dial_low_limits(self,values): self.dial_low_limits[:] = values
dial_low_limits = property(get_dial_low_limits,set_dial_low_limits)
def get_dial_high_limit(self,axis_number):
return self.parameter("SoftwareLimitHigh",axis_number)
def set_dial_high_limit(self,axis_number,value):
return self.set_parameter("SoftwareLimitHigh",value,axis_number)
def get_dial_high_limit_count(self): return self.naxes
def get_dial_high_limits(self):
return ArrayWrapper(self,"dial_high_limit",method="single")
def set_dial_high_limits(self,values): self.dial_high_limits[:] = values
dial_high_limits = property(get_dial_high_limits,set_dial_high_limits)
def get_low_limit(self,axis_number):
"""Soft limit. Disable soft limits by settings this value to nan"""
dial_value = \
self.dial_low_limits[axis_number] if self.signs[axis_number] > 0 \
else self.dial_high_limits[axis_number]
value = self.dial_to_user(axis_number,dial_value)
return value
def set_low_limit(self,axis_number,value):
dial_value = self.user_to_dial(axis_number,value)
if self.signs[axis_number] > 0:
self.dial_low_limits[axis_number] = dial_value
else: self.dial_high_limits[axis_number] = dial_value
def get_low_limit_count(self): return self.naxes
def _get_low_limits(self):
return ArrayWrapper(self,"low_limit",method="single")
def _set_low_limits(self,values): self.low_limits[:] = values
low_limits = property(_get_low_limits,_set_low_limits)
def get_high_limit(self,axis_number):
"""Soft limit. Disable soft limits by settings this value to nan"""
dial_value = \
self.dial_high_limits[axis_number] if self.signs[axis_number] > 0 \
else self.dial_low_limits[axis_number]
value = self.dial_to_user(axis_number,dial_value)
return value
def set_high_limit(self,axis_number,value):
dial_value = self.user_to_dial(axis_number,value)
if self.signs[axis_number] > 0:
self.dial_high_limits[axis_number] = dial_value
else: self.dial_low_limits[axis_number] = dial_value
def get_high_limit_count(self): return self.naxes
def _get_high_limits(self):
return ArrayWrapper(self,"high_limit",method="single")
def _set_high_limits(self,values): self.high_limits[:] = values
high_limits = property(_get_high_limits,_set_high_limits)
def get_has_home(self):
"""Can this motor be homed?"""
from numpy import ones
return ones(self.naxes,bool)
def set_has_home(self): pass
has_home = property(get_has_home,set_has_home)
# Configuration parameter number. See file
# C:\Program Files (x86)\Aerotech\Ensemble\CLibrary\Include\EnsembleParameterId.h
parameter_IDs = {
"ReverseMotionDirection": 1,
"SoftwareLimitLow": 37,
"SoftwareLimitHigh": 38,
"DefaultSpeed": 71,
"DefaultRampRate": 72,
"GlobalIntegers": 124,
"GlobalDoubles": 125,
"UnitsName": 129,
"AxisName": 140,
"UserInteger0": 141,
"UserInteger1": 142,
"UserDouble0": 143,
"UserDouble1": 144,
"UserString0": 145,
"UserString1": 146,
}
ensemble_driver = Ensemble()
class EnsembleMotor(object):
"""Individual axes of the Aerotech Ensemble multi-axis controller"""
# 'stepsize' is to strip unnecessary digits after the decimal point that
# arise from float32 to float64 conversion.
stepsize = 0.0
def __init__(self,axis_number,**kwargs):
self.axis_number = axis_number
for key in kwargs: setattr(self,key,kwargs[key])
def get_command_dial(self):
"""Target position in dial units"""
value = ensemble_driver.command_dial_values[self.axis_number]
value = round_next(value,self.stepsize)
return value
def set_command_dial(self,value):
from numpy import isnan
if isnan(value): return
ensemble_driver.command_dial_values[self.axis_number] = value
command_dial = property(get_command_dial,set_command_dial)
def get_dial(self):
"""Current position in dial units"""
value = ensemble_driver.dial_values[self.axis_number]
value = round_next(value,self.stepsize)
return value
def set_dial(self,value): self.set_command_dial(value)
dial = property(get_dial,set_dial)
def get_command_value(self):
"""Target position in user units"""
value = ensemble_driver.command_values[self.axis_number]
value = round_next(value,self.stepsize)
return value
def set_command_value(self,value):
from numpy import isnan
if isnan(value): return
ensemble_driver.command_values[self.axis_number] = value
command_value = property(get_command_value,set_command_value)
def get_value(self):
"""Current position in user units"""
value = ensemble_driver.values[self.axis_number]
value = round_next(value,self.stepsize)
return value
value = property(get_value,set_command_value)
def get_moving(self):
"""Target position"""
return ensemble_driver.moving[self.axis_number]
def set_moving(self,value):
ensemble_driver.moving[self.axis_number] = value
moving = property(get_moving,set_moving)
def get_enabled(self):
"""Is holding the current turned on?"""
return ensemble_driver.enabled[self.axis_number]
def set_enabled(self,value):
ensemble_driver.enabled[self.axis_number] = value
enabled = property(get_enabled,set_enabled)
def enable():
"""Turn the holding current on."""
self.enabled = True
def disable():
"""Turn the holding current off."""
self.enabled = False
def get_speed(self):
"""How fast does the motor move?"""
return ensemble_driver.speeds[self.axis_number]
def set_speed(self,value):
ensemble_driver.speeds[self.axis_number] = value
speed = property(get_speed,set_speed)
def get_acceleration(self):
"""How fast does the motor move?"""
return ensemble_driver.accelerations[self.axis_number]
def set_acceleration(self,value):
ensemble_driver.accelerations[self.axis_number] = value
acceleration = property(get_acceleration,set_acceleration)
def get_homing(self):
"""Currently performing a home run?"""
return ensemble_driver.homing[self.axis_number]
def set_homing(self,value):
ensemble_driver.homing[self.axis_number] = value
homing = property(get_homing,set_homing)
def get_homed(self):
"""Has home run been done? Is motor calibrated?"""
return ensemble_driver.homed[self.axis_number]
def set_homed(self,value):
ensemble_driver.homed[self.axis_number] = value
homed = property(get_homed,set_homed)
def get_has_home(self):
"""Can this motor be homed?"""
return ensemble_driver.has_home[self.axis_number]
def set_has_home(self,value):
ensemble_driver.has_home[self.axis_number] = value
has_home = property(get_has_home,set_has_home)
def get_sign(self):
"""Dial-to-user converion sign, maybe either 1 or -1"""
return ensemble_driver.signs[self.axis_number]
def set_sign(self,value):
ensemble_driver.signs[self.axis_number] = value
sign = property(get_sign,set_sign)
def get_offset(self):
"""Dial-to-user conversion offset, maybe either 1 or -1"""
from numpy import isnan
return ensemble_driver.offsets[self.axis_number]
def set_offset(self,value):
ensemble_driver.offsets[self.axis_number] = value
offset = property(get_offset,set_offset)
def get_dial_low_limit(self):
"""Soft limit. Disable soft limits by settings this value to nan"""
return ensemble_driver.dial_low_limits[self.axis_number]
def set_dial_low_limit(self,value):
ensemble_driver.dial_low_limits[self.axis_number] = value
dial_low_limit = property(get_dial_low_limit,set_dial_low_limit)
def get_dial_high_limit(self):
"""Soft limit. Disable soft limits by settings this value to nan"""
return ensemble_driver.dial_high_limits[self.axis_number]
def set_dial_high_limit(self,value):
ensemble_driver.dial_high_limits[self.axis_number] = value
dial_high_limit = property(get_dial_high_limit,set_dial_high_limit)
def get_low_limit(self):
"""Soft limit. Disable soft limits by settings this value to nan"""
return ensemble_driver.low_limits[self.axis_number]
def set_low_limit(self,value):
ensemble_driver.low_limits[self.axis_number] = value
low_limit = property(get_low_limit,set_low_limit)
def get_high_limit(self):
"""Soft limit. Disable soft limits by settings this value to nan"""
return ensemble_driver.high_limits[self.axis_number]
def set_high_limit(self,value):
ensemble_driver.high_limits[self.axis_number] = value
high_limit = property(get_high_limit,set_high_limit)
def get_at_low_limit(self):
"""Is the motor at the positive travel end switch currenly?"""
return ensemble_driver.at_low_limits[self.axis_number]
at_low_limit = property(get_at_low_limit)
def get_at_high_limit(self):
"""Is the motor at the negative travel end switch currenly?"""
return ensemble_driver.at_high_limits[self.axis_number]
at_high_limit = property(get_at_high_limit)
def get_name(self):
"""string"""
return ensemble_driver.names[self.axis_number]
def set_name(self,value):
ensemble_driver.names[self.axis_number] = value
name = property(get_name,set_name)
def get_unit(self):
"""'mm' or 'deg'"""
return ensemble_driver.units[self.axis_number]
def set_unit(self,value):
ensemble_driver.units[self.axis_number] = value
unit = property(get_unit,set_unit)
# EPICS motor record process variables
VAL = command_value
RBV = value
DVAL = command_dial
DRBV = dial
VELO = speed
CNEN = enabled
LLM = low_limit
HLM = high_limit
DLLM = dial_low_limit
DHLM = dial_high_limit
HLS = at_high_limit
LLS = at_low_limit
DESC = name
EGU = unit
HOMF = homing
HOMR = homing
OFF = offset # User and dial coordinate difference
def get_DMOV(self):
"""Done moving?"""
return not self.moving
def set_DMOV(self,value): self.moving = not value
DMOV = property(get_DMOV,set_DMOV)
def get_STOP(self): return not self.moving
def set_STOP(self,value): self.moving = not value
STOP = property(get_STOP,set_STOP)
def get_MSTA(self):
"""Motor status bits:
8 = home
11 = moving
15 = homed"""
status_bits = self.homing<<8|self.moving<<11|self.homed<<15
return status_bits
def set_MSTA(self,value): pass
MSTA = property(get_MSTA,set_MSTA)
def get_DIR(self):
"""User to dial 0=Pos, 1=Neg"""
return 0 if self.sign == 1 else 1
def set_DIR(self,value):
if value == 0: self.sign = 1
if value == 1: self.sign = -1
DIR = property(get_DIR,set_DIR)
def get_ACCL(self):
"""Acceleration time to full speed in seconds"""
T = self.speed/self.acceleration
return T
def set_ACCL(self,T):
self.acceleration = self.speed/T
ACCL = property(get_ACCL,set_ACCL)
def round_next (x,step):
"""Rounds x up or down to the next multiple of step."""
if step == 0: return x
x = round(x/step)*step
# Avoid "negative zero" (-0.0), which is different from +0.0 by IEEE standard
if x == 0: x = abs(x)
return x
SampleX_driver = EnsembleMotor(0)
SampleY_driver = EnsembleMotor(1)
SampleZ_driver = EnsembleMotor(2)
SamplePhi_driver = EnsembleMotor(3)
PumpA_driver = EnsembleMotor(4)
PumpB_driver = EnsembleMotor(5)
msShut_driver = EnsembleMotor(6)
# Ensemble client, using EPICS channel access.
from CA import Record
ensemble_client = Record("NIH:ENSEMBLE")
from EPICS_motor import EPICS_motor
SampleX = EPICS_motor("NIH:SAMPLEX",name="SampleX",readback_slop=0.005)
SampleY = EPICS_motor("NIH:SAMPLEY",name="SampleY",readback_slop=0.005)
SampleZ = EPICS_motor("NIH:SAMPLEZ",name="SampleZ",readback_slop=0.005)
SamplePhi = EPICS_motor("NIH:SAMPLEPHI",name="SamplePhi")
PumpA = EPICS_motor("NIH:PUMPA",name="PumpA")
PumpB = EPICS_motor("NIH:PUMPB",name="PumpB")
msShut = EPICS_motor("NIH:MSSHUT",name="msshut",readback_slop=0.09)
# msShut resolution: 360 deg/4000 counts
class EnsembleWrapper(object):
"""This is to make sure that NaNs are subsituted when the Ensembe
driver is offline."""
naxis = 7
def __init__(self,name):
"""name: EPICS record name (prefix), e.g. "NIH:ENSEMBLE" """
self.__record__ = Record(name)
def __getattr__(self,name):
"""Called when '.' is used."""
if name.startswith("__") and name.endswith("__"):
return object.__getattribute__(self,name)
##debug("EnsembleWrapper.__getattr__(%r)" % name)
from numpy import asarray
values = getattr(self.__record__,name)
if values is None: values = self.__default_value__(name)
if isinstance(values,basestring): return values
if not hasattr(values,"__len__"): return values
return asarray(values)
def __setattr__(self,name,value):
"""Called when '.' is used."""
if name.startswith("__") and name.endswith("__"):
object.__setattr__(self,name,value)
##debug("EnsembleWrapper.__setattr__(%r,%r)" % (name,value))
setattr(self.__record__,name,value)
def __default_value__(self,name):
from numpy import zeros,nan
if name == "program_filename": value = ""
elif name == "auxiliary_task_filename": value = ""
elif name == "program_directory": value = ""
elif name == "program_running": value = nan
elif name == "auxiliary_task_running": value = nan
elif name == "fault": value = nan
elif name == "connected": value = nan
elif name.startswith("UserInteger"): value = nan
elif name.startswith("UserDouble"): value = nan
elif name.startswith("UserString"): value = ""
else: value = zeros(self.naxis)+nan
return value
ensemble = EnsembleWrapper("NIH:ENSEMBLE")
class EnsembleMotors(EnsembleWrapper):
"""Multiaxis coordinated motion"""
def axes_numbers(self,axes_names):
from numpy import where
return [where(self.names == name)[0][0] for name in axes_names]
def move(self,axes_names,positions):
"""Perform a coordinated move, on mutiple axs simultaneously.
names: list of strings
positions: list of real numbers"""
values = self.command_values
values[self.axes_numbers(axes_names)] = positions
self.command_values = values
def positions(self,axes_names):
"""Not yet at destination?"""
return self.values[self.axes_numbers(axes_names)]
def are_moving(self,axes_names):
"""Not yet at destination?"""
return self.moving[self.axes_numbers(axes_names)]
ensemble_motors = EnsembleMotors("NIH:ENSEMBLE")
def program_directory():
"""Location of Aerobasic programs"""
from module_dir import module_dir
return module_dir(Ensemble)+"/Ensemble"
def logfile():
"""Log file for protocol transcript if verbose logging is enabled."""
from tempfile import gettempdir
return gettempdir()+"/ensemble.log"
def start_IOC():
"""Serve the Ensemble IPAQ up on the network as EPCIS IOC"""
import CAServer
import logging
logging.basicConfig(level=logging.DEBUG,
format="%(asctime)s %(levelname)s: %(message)s",
##filename=logfile(),
)
##CAServer.verbose_logging = True
##CAServer.verbose = True
CAServer.update_interval = 0.25
##CAServer.DEBUG = True
##CAServer.LOG = True
ensemble_driver.connect()
CAServer.register_object(ensemble_driver, "NIH:ENSEMBLE")
CAServer.register_object(SampleX_driver, "NIH:SAMPLEX")
CAServer.register_object(SampleY_driver, "NIH:SAMPLEY")
CAServer.register_object(SampleZ_driver, "NIH:SAMPLEZ")
CAServer.register_object(SamplePhi_driver,"NIH:SAMPLEPHI")
CAServer.register_object(PumpA_driver, "NIH:PUMPA")
CAServer.register_object(PumpB_driver, "NIH:PUMPB")
CAServer.register_object(msShut_driver, "NIH:MSSHUT")
port = 2000
def start_TCP_server():
from thread import start_new_thread
start_new_thread(run_TCP_server,())
def run_TCP_server():
while startup_TCP_server:
startup_TCP_server()
def startup_TCP_server():
import socket
from sleep import sleep
try:
server = ThreadingTCPServer(("",port),ClientHandler)
info("TCP server listening on port %s." % port)
server.serve_forever()
except socket.error,msg:
error("TCP server on port %s: %s" % (port,msg))
sleep(5)
import SocketServer
class ThreadingTCPServer(SocketServer.ThreadingTCPServer):
# By default, the "ThreadingTCPServer" class binds to the sever port
# without the option SO_REUSEADDR. The consequence of this is that
# when the server terminates you have to let 60 seconds pass, for the
# socket to leave to "CLOSED_WAIT" state before it can be restarted,
# otherwise the next bind call would generate the error
# 'Address already in use'.
# Setting allow_reuse_address to True makes "ThreadingTCPServer" use to
# SO_REUSEADDR option when calling "bind".
allow_reuse_address = True
class ClientHandler(SocketServer.BaseRequestHandler):
def handle(self):
"""Called when a client connects. 'self.request' is the client socket"""
import socket
addr = self.client_address[0]
##debug("TCP server: Accepted connection from %s" % addr)
input_queue = ""
while 1:
# Commands from a client are not necessarily received as one packet
# but each command is terminated by a newline character.
# If 'recv' returns an empty string it means client closed the
# connection.
while input_queue.find("\n") == -1:
try: received = self.request.recv(2*1024*1024)
except socket.error,msg:
errno = msg[0]
if errno == 10054:
##debug("TCP server: client %s disconnected" % addr)
pass
else: info("TCP server: receive from %s: %s" % (addr,msg))
received = ""
if received == "":
##debug("TCP server: client %s disconnected" % addr)
break
input_queue += received
if input_queue == "": break
if input_queue.find("\n") != -1:
end = input_queue.index("\n")
query = input_queue[0:end]
input_queue = input_queue[end+1:]
else: query = input_queue; input_queue = ""
query = query.strip("\r ")
from numpy import array,nan
if query.find("=") >= 0:
ensemble = ensemble_driver
##debug("TCP server: %s: Executing command: '%s'" % (addr,query))
try: exec(query)
except Exception,msg:
error("TCP server: %s: %r: %s" % (addr,query,msg))
else:
ensemble = ensemble_driver
##debug("TCP server: %s: Evaluating query: '%s'" % (addr,query))
try: reply = eval(query)
except Exception,msg:
error("TCP server: %s: %r: %s" % (addr,query,msg))
reply = ""
if reply is not None:
try: reply = repr(reply)
except: reply = str(reply)
reply = reply.replace("\n","") # "\n" = end of reply
reply += "\n"
##debug("TCP server: %s: Sending reply %r" % (addr,reply))
self.request.sendall(reply)
##debug("TCP server: Closing connection to %s" % addr)
self.request.close()
def start_server():
"""Start EPCIS IOC and TCP server returing control"""
start_IOC()
start_TCP_server()
def run_server():
"""Run EPCIS IOC and TCP servers without returing control"""
start_server()
wait()
def wait():
"""Halt execution"""
from time import sleep
while True: sleep(0.1)
if __name__ == "__main__":
# Output error messages to console and file at te same time.
import logging
from tempfile import gettempdir
format = "%(asctime)s %(levelname)s: %(message)s"
logfile = gettempdir()+"/Ensemble.log"
logging.basicConfig(level=logging.DEBUG,format=format)
logger = logging.getLogger()
handler = logging.FileHandler(logfile)
handler.setLevel(logging.DEBUG)
handler.setFormatter(logging.Formatter(format))
logger.addHandler(handler)
from sys import argv
if "run_IOC" in argv or "run_server" in argv: run_server()
# for debugging
self = ensemble_driver
print('start_server()')
from time import time
print('ensemble_driver.program_filename = "PVT_Fly-thru.ab"')
print('ensemble_driver.program_running')
print('ensemble_driver.auxiliary_task_filename = "Freeze_Intervention.ab"')
print('ensemble_driver.auxiliary_task_running')
print('ensemble_driver.UserString1')
print('ensemble.program_filename = "PVT_Fly-thru.ab"')
print('ensemble.program_running')
print('ensemble.UserString1')
print('ensemble.auxiliary_task_filename = "Freeze_Intervention.ab"')
print('ensemble.auxiliary_task_running')
<file_sep>"""<NAME>, 23 Jul 2015 - 25 Sep 2015"""
__version__ = "2.7"
def set_sequence(variables,value_lists):
""""""
timing_sequencer.abort()
from timing_system import timing_system
timing_system.cache += 1 # turn on caching to improve performance
data = []
names = []
for i in range(0,len(value_lists[0])):
names += ["image=%d" % (i+1)]
values = [[l[i]] for l in value_lists]
data += [sequencer_stream(variables,values)]
timing_system.cache -= 1
for i in range(0,len(value_lists[0])):
timing_sequencer.add_to_queue(data[i],name=names[i],autostart=False)
timing_sequencer.start()
if __name__ == "__main__":
from pdb import pm # for debugging
import logging
logging.basicConfig(level=logging.DEBUG,format="%(asctime)s: %(message)s")
##import timing_system; timing_system.DEBUG = True
from timing_system import *
from numpy import *
print 'timing_system.ip_address = %r' % timing_system.ip_address
@vectorize
def round(x,n): return float(("%."+str(n)+"g") % x)
dt = 1/hscf
eps = 1e-6
timepoints = round(10**arange(-9,-1+eps,0.25),3)
laser_modes = [1] # [0,1] = off/on
nrepeat = 5 # pulses per image
waitt_delay = rint(0.2/dt)*dt
delays = array([x for x in timepoints for l in laser_modes])
waitt_delays = maximum(ceil(delays/dt)*dt,waitt_delay)
laser_on = laser_modes*len(timepoints)
always = [1]*len(laser_modes)*len(timepoints)
nrepeats = [nrepeat]*len(laser_modes)*len(timepoints)
variables,value_lists = [],[]
variables += [timing_system.ps_lxd]; value_lists += [delays]
variables += [timing_system.waitt]; value_lists += [waitt_delays]
variables += [timing_system.npulses]; value_lists += [nrepeats]
variables += [timing_system.pst.on]; value_lists += [laser_on]
variables += [timing_system.xosct.on]; value_lists += [always]
variables += [timing_system.losct.on]; value_lists += [always]
variables += [timing_system.ms.on]; value_lists += [always]
##for l in value_lists: l += [0] # After last image, turn everything off.
##data = sequencer_stream(variables,value_lists)
values = [l[0] for l in value_lists]
print 'timing_system.xosct.offset = -6.82e-06'
print 'set_sequence(variables,value_lists)'
print 'timing_sequencer.set_sequence(variables,value_lists,1,name="collection")'
print 'timing_sequencer.add_sequence(variables,value_lists,1,name="collection")'
print 'timing_sequencer.enabled'
print 'timing_sequencer.running'
print 'timing_sequencer.queue'
print 'timing_sequencer.clear_queue()'
print 'timing_sequencer.abort()'
print 'timing_system.xosct_enable.count = 0'
<file_sep>"""Temperature System Level (SL) Server
Capabilities:
- Time-based Temperature ramping
- EPICS IOC
Authors: <NAME>, <NAME>
Date created: 2019-05-08
Date last modified: 2019-05-21
"""
__version__ = "1.3" # lightwave_temperature_controller
from logging import debug,warn,info,error
from IOC import IOC
class Temperature_Server(IOC):
name = "temperature"
prefix = "NIH:TEMP."
property_names = [
"time_points",
"temp_points",
"VAL",
"RBV",
"set_point_update_period",
]
from persistent_property import persistent_property
time_points = persistent_property("time_points",[])
temp_points = persistent_property("temp_points",[])
set_point_update_period = persistent_property("set_point_update_period",0.5)
def run(self):
self.monitoring = True
self.running = True
from sleep import sleep
while self.running: sleep(0.25)
def get_monitoring(self):
from timing_system import timing_system
return self.on_acquire in timing_system.acquiring.monitors
def set_monitoring(self,value):
value = bool(value)
from timing_system import timing_system
if value != self.monitoring:
if value == True: timing_system.acquiring.monitor(self.on_acquire)
if value == False: timing_system.acquiring.monitor_clear(self.on_acquire)
monitoring = property(get_monitoring,set_monitoring)
def on_acquire(self):
self.ramping = self.acquiring
from thread_property_2 import thread_property
@thread_property
def ramping(self):
from time_string import date_time
info("Ramp start time: %s" % date_time(self.start_time))
from time import time,sleep
for (t,T) in zip(self.times,self.temperatures):
dt = self.start_time+t - time()
if dt > 0:
sleep(dt)
self.VAL = T
if self.ramping_cancelled: break
info("Ramp ended")
@property
def acquiring(self):
from timing_system import timing_system
return timing_system.acquiring.value
@property
def start_time(self):
from numpy import nan
start_time = nan
from timing_system import timing_system
if timing_system.acquiring.value == 1:
from CA import cainfo
start_time = cainfo(timing_system.acquiring.PV_name,"timestamp")
return start_time
@property
def times(self):
from numpy import arange,concatenate
min_dt = self.set_point_update_period
times = [[]]
for i in range(0,len(self.time_points)-1):
T0,T1 = self.time_points[i],self.time_points[i+1]
DT = T1-T0
N = max(int(DT/min_dt),1)
dt = DT/N
T = T0 + arange(0,N)*dt
times.append(T)
if len(self.time_points) > 0:
times.append([self.time_points[-1]])
times = concatenate(times)
return times
@property
def temperatures(self):
temperatures = []
time_points = self.time_points[0:self.N_points]
temp_points = self.temp_points[0:self.N_points]
if len(temp_points) > 1:
from scipy.interpolate import interp1d
f = interp1d(time_points,temp_points,kind='linear',bounds_error=False)
temperatures = f(self.times)
if len(temp_points) == 1:
from numpy import array
temperatures = array(temp_points)
return temperatures
@property
def N_points(self):
return min(len(self.time_points),len(self.temp_points))
def get_VAL(self): return self.temperature_controller.VAL
def set_VAL(self,value):
info("VAL = %r" % value)
self.temperature_controller.VAL = value
VAL = property(get_VAL,set_VAL)
def get_RBV(self): return self.temperature_controller.RBV
RBV = property(get_RBV,set_VAL)
@property
def temperature_controller(self):
from lightwave_temperature_controller import lightwave_temperature_controller
return lightwave_temperature_controller
temperature_server = Temperature_Server()
if __name__ == "__main__":
import logging
logging.basicConfig(level=logging.DEBUG,
format="%(asctime)s %(levelname)s %(module)s.%(funcName)s: %(message)s",
)
##from time import sleep
##sleep(0.5)
from collect import collect
print('collect.temperature_start()')
print('')
from temperature import temperature
from numpy import nan
##print('temperature.VAL = %r' % temperature.VAL)
##print('temperature.RBV = %r' % temperature.RBV)
print('temperature.time_points = %r' % temperature.time_points)
print('temperature.temp_points = %r' % temperature.temp_points)
##print('temperature.time_points = [nan]')
##print('temperature.temp_points = [nan]')
print('')
from timing_sequencer import timing_sequencer
print("timing_sequencer.queue_active = %r" % timing_sequencer.queue_active)
print("timing_sequencer.queue_active = False # cancel acquistion")
print("timing_sequencer.queue_repeat_count = 0 # restart acquistion")
print("timing_sequencer.queue_active = True # simulate acquistion")
print ('')
print ('temperature_server.monitoring = True')
print ('temperature_server.running = True')
self = temperature_server # for debugging
<file_sep>"""
Authors: <NAME>
Date created: 2019-05-20
Date last modified: 2019-05-20
"""
__version__ = "1.0"
from logging import error,warn,info,debug
class Serial_Device(object):
name = "serial_device"
timeout = 1.0
baudrate = 9600
# Make multithread safe
from thread import allocate_lock
__lock__ = allocate_lock()
port = None
id_query = ""
id_reply_length = 0
def id_reply_valid(self,reply):
valid = len(reply) == self.id_reply_length
debug("Reply %r valid? %r" % (reply,valid))
return valid
@property
def connected(self): return self.port is not None
@property
def online(self):
if self.port is None: self.init_communications()
online = self.port is not None
if online: debug("Device online")
else: warn("Device offline")
return online
@property
def port_name(self):
"""Serial port name"""
if self.port is None: value = ""
else: value = self.port.name
return value
COMM = port_name
def query(self,command,count=1):
"""Send a command to the controller and return the reply"""
with self.__lock__: # multithread safe
for i in range(0,2):
try: reply = self.__query__(command,count)
except Exception,msg:
warn("query: %r: attempt %s/2: %s" % (command,i+1,msg))
reply = ""
if reply: return reply
self.init_communications()
return reply
def __query__(self,command,count=1):
"""Send a command to the controller and return the reply"""
from time import time
from sleep import sleep
sleep(self.last_reply_time + self.wait_time - time())
self.write(command)
reply = self.read(count=count)
self.last_reply_time = time()
return reply
from persistent_property import persistent_property
wait_time = persistent_property("wait_time",1.0) # bewteen commands
last_reply_time = 0.0
def write(self,command):
"""Send a command to the controller"""
if self.port is not None:
self.port.write(command)
debug("%s: Sent %r" % (self.port.name,command))
def read(self,count=None,port=None):
"""Read a reply from the controller,
terminated with the given terminator string"""
##debug("read count=%r,port=%r" % (count,port))
if port is None: port = self.port
if port is not None:
#print("in wait:" + str(self.port.inWaiting()))
debug("Trying to read %r bytes from %s..." % (count,port.name))
port.timeout = self.timeout
reply = port.read(count)
debug("%s: Read %r" % (port.name,reply))
else: reply = ""
return reply
def init_communications(self):
"""To do before communncating with the controller"""
from os.path import exists
from serial import Serial
if self.port is not None:
try:
info("Checking whether device is still responsive...")
self.port.write(self.id_query)
debug("%s: Sent %r" % (self.port.name,self.id_query))
reply = self.read(count=self.id_reply_length)
if not self.id_reply_valid(reply):
debug("%s: %r: invalid reply %r" % (self.port.name,self.id_query,reply))
info("%s: lost connection" % self.port.name)
self.port = None
else: info("Device is still responsive.")
except Exception,msg:
debug("%s: %s" % (Exception,msg))
self.port = None
if self.port is None:
port_basenames = ["COM"] if not exists("/dev") \
else ["/dev/tty.usbserial","/dev/ttyUSB"]
for i in range(-1,50):
for port_basename in port_basenames:
port_name = port_basename+("%d" % i if i>=0 else "")
##debug("Trying port %s..." % port_name)
try:
port = Serial(port_name,baudrate=self.baudrate)
port.write(self.id_query)
debug("%s: Sent %r" % (port.name,self.id_query))
reply = self.read(count=self.id_reply_length,port=port)
if self.id_reply_valid(reply):
self.port = port
info("Discovered device at %s based on reply %r" % (self.port.name,reply))
break
except Exception,msg: debug("%s: %s" % (Exception,msg))
if self.port is not None: break
if __name__ == "__main__":
from pdb import pm
import logging
logging.basicConfig(level=logging.DEBUG,
format="%(asctime)s %(levelname)s: %(message)s")
class Oasis_Chiller_Device(Serial_Device):
id_query = "A"
id_reply_length = 3
def id_reply_valid(self,reply):
valid = reply.startswith("A") and len(reply) == 3
debug("Reply %r valid? %r" % (reply,valid))
return valid
self = Oasis_Chiller_Device()
print("self.init_communications()")
<file_sep>#!/usr/bin/env python
"""Control panel for SAXS-WAXS Experiments.
<NAME>, Jun 12, 2017 - Jun 25, 2017"""
__version__ = "1.2.2" # passing "globals()" environment to "Control", Mode
from logging import debug,info,warn,error
import wx
from SAXS_WAXS_control import SAXS_WAXS_control # passed on in "globals()"
class SAXS_WAXS_Control_Panel(wx.Frame):
"""Control panel for SAXS-WAXS Experiments"""
def __init__(self):
wx.Frame.__init__(self,parent=None,title="SAXS-WAXS Control")
# Icon
from Icon import SetIcon
SetIcon(self,"SAXS-WAXS Control")
# Controls
panel = wx.Panel(self)
from EditableControls import ComboBox,TextCtrl
from Controls import Control
self.Environment = Control(panel,type=ComboBox,
name="SAXS_WAXS_Control_Panel.Environment",globals=globals(),
size=(80,-1),choices=["0 (NIH)","1 (APS)","2 (LCLS)"])
self.Home = Control(panel,type=wx.ToggleButton,
name="SAXS_WAXS_Control_Panel.Home",globals=globals(),
size=(100,-1))
self.ProgramRunning = Control(panel,type=wx.ToggleButton,
name="SAXS_WAXS_Control_Panel.ProgramRunning",globals=globals(),
size=(100,-1))
self.GotoSaved = Control(panel,type=wx.Button,
name="SAXS_WAXS_Control_Panel.GotoSaved",globals=globals(),
label="Go To Saved Position",
size=(180,-1))
self.Save = Control(panel,type=wx.Button,
name="SAXS_WAXS_Control_Panel.Save",globals=globals(),
label="Save Current X,Y Positions",size=(180,-1))
self.Inserted = Control(panel,type=wx.ToggleButton,
name="SAXS_WAXS_Control_Panel.Inserted",globals=globals(),
size=(150,-1))
self.Mode = Control(panel,type=wx.ComboBox,
name="SAXS_WAXS_Control_Panel.Mode",globals=globals(),
size=(100,-1),choices=SAXS_WAXS_control.modes)
self.ShutterEnabled = Control(panel,type=wx.CheckBox,
name="SAXS_WAXS_Control_Panel.ShutterEnabled",globals=globals(),
size=(80,-1))
self.PumpEnabled = Control(panel,type=wx.CheckBox,
name="SAXS_WAXS_Control_Panel.PumpEnabled",globals=globals(),
size=(80,-1))
self.PumpStep = Control(panel,type=ComboBox,
name="SAXS_WAXS_Control_Panel.PumpStep",globals=globals(),
size=(80,-1),choices=SAXS_WAXS_control.pump_step_choices)
self.PumpPosition = Control(panel,type=TextCtrl,
name="SAXS_WAXS_Control_Panel.PumpPosition",globals=globals(),
size=(70,-1))
self.PumpHomed = Control(panel,type=wx.ToggleButton,
name="SAXS_WAXS_Control_Panel.PumpHomed",globals=globals(),
size=(140,-1))
choices = ["500","600","700","800","1000"]
self.LoadSampleStep = Control(panel,type=ComboBox,
name="SAXS_WAXS_Control_Panel.LoadSampleStep",globals=globals(),
size=(70,-1),choices=choices)
self.LoadSample = Control(panel,type=wx.ToggleButton,
name="SAXS_WAXS_Control_Panel.LoadSample",globals=globals(),
label="Load Sample",size=(140,-1))
choices = ["-500","-600","-700","-800","-1000"]
self.ExtractSampleStep = Control(panel,type=ComboBox,
name="SAXS_WAXS_Control_Panel.ExtractSampleStep",globals=globals(),
size=(70,-1),choices=choices)
self.ExtractSample = Control(panel,type=wx.ToggleButton,
name="SAXS_WAXS_Control_Panel.ExtractSample",globals=globals(),
label="Extract Sample",size=(140,-1))
choices = ["500","600","700","800","1000"]
self.CirculateSampleStep = Control(panel,type=ComboBox,
name="SAXS_WAXS_Control_Panel.CirculateSampleStep",globals=globals(),
size=(70,-1),choices=choices)
self.CirculateSample = Control(panel,type=wx.ToggleButton,
name="SAXS_WAXS_Control_Panel.CirculateSample",globals=globals(),
label="Circulate Sample",size=(140,-1))
self.PumpSpeed = Control(panel,type=TextCtrl,
name="SAXS_WAXS_Control_Panel.PumpSpeed",globals=globals(),
size=(70,-1))
# Layout
flag = wx.ALIGN_CENTRE_HORIZONTAL|wx.ALL
border = 5
layout = wx.BoxSizer(wx.HORIZONTAL)
left_panel = wx.BoxSizer(wx.VERTICAL)
group = wx.BoxSizer(wx.HORIZONTAL)
text = wx.StaticText(panel,label="Environment:")
group.Add (text,flag=flag,border=border)
group.Add (self.Environment,flag=flag,border=border)
left_panel.Add (group,flag=flag,border=border)
group = wx.BoxSizer(wx.VERTICAL)
text = wx.StaticText(panel,label="Ensemble Operation")
group.Add (text,flag=flag,border=border)
group.Add (self.Home,flag=flag,border=border)
group.Add (self.ProgramRunning,flag=flag,border=border)
left_panel.Add (group,flag=flag,border=border)
group = wx.BoxSizer(wx.VERTICAL)
text = wx.StaticText(panel,label="Capillary Position")
group.Add (text,flag=flag,border=border)
group.Add (self.GotoSaved,flag=flag,border=border)
group.Add (self.Save,flag=flag,border=border)
group.Add (self.Inserted,flag=flag,border=border)
left_panel.Add (group,flag=flag,border=border)
layout.Add (left_panel,flag=flag,border=border)
right_panel = wx.BoxSizer(wx.VERTICAL)
group = wx.GridBagSizer(4,2)
l = wx.ALIGN_LEFT; r = wx.ALIGN_RIGHT; cv = wx.ALIGN_CENTER_VERTICAL
a = wx.ALL
text = wx.StaticText(panel,label="Mode: ")
group.Add (text,(0,0),flag=r|cv)
group.Add (self.Mode,(0,1),flag=l|cv)
text = wx.StaticText(panel,label="X-ray ms shutter: ")
group.Add (text,(1,0),flag=r|cv)
group.Add (self.ShutterEnabled,(1,1),flag=l|cv)
text = wx.StaticText(panel,label="Pump: ")
group.Add (text,(2,0),flag=r|cv)
group.Add (self.PumpEnabled,(2,1),flag=l|cv)
text = wx.StaticText(panel,label="Pump Steps/Stroke: ")
group.Add (text,(3,0),flag=r|cv)
group.Add (self.PumpStep,(3,1),flag=l|cv)
right_panel.Add (group,flag=flag,border=border)
text = wx.StaticText(panel,label="Peristaltic Pump Operation [motor steps]")
right_panel.Add (text,flag=flag,border=border)
group = wx.GridBagSizer(1,1)
group.Add (self.PumpPosition,(0,0),flag=r|cv|a,border=border)
group.Add (self.PumpHomed,(0,1),flag=l|cv|a,border=border)
group.Add (self.LoadSampleStep,(1,0),flag=r|cv|a,border=border)
group.Add (self.LoadSample,(1,1),flag=l|cv|a,border=border)
group.Add (self.ExtractSampleStep,(2,0),flag=r|cv|a,border=border)
group.Add (self.ExtractSample,(2,1),flag=l|cv|a,border=border)
group.Add (self.CirculateSampleStep,(3,0),flag=r|cv|a,border=border)
group.Add (self.CirculateSample,(3,1),flag=l|cv|a,border=border)
group.Add (self.PumpSpeed,(4,0),flag=r|cv|a,border=border)
text = wx.StaticText(panel,label="Pump Speed [steps/s]",size=(140,-1))
group.Add (text,(4,1),flag=l|cv|a,border=border)
right_panel.Add (group,flag=flag,border=border)
layout.Add (right_panel,flag=flag,border=border)
panel.SetSizer(layout)
panel.Fit()
self.Fit()
# Settings
self.Environment.defaults = {"Value":"offline?","Enabled":False}
self.Environment.value = "SAXS_WAXS_control.environment"
self.Environment.properties = {
"Enabled": [
(True, "SAXS_WAXS_control.ensemble_online"),
],
}
self.Home.defaults = {"Label":"Home","Enabled":False}
self.Home.action = {
False: "SAXS_WAXS_control.ensemble_homing = True",
True: "SAXS_WAXS_control.ensemble_homing = True",
}
self.Home.properties = {
"Value": [
(False, "SAXS_WAXS_control.ensemble_homed == False"),
(True, "SAXS_WAXS_control.ensemble_homed == True"),
],
"Enabled": [
(False, "SAXS_WAXS_control.ensemble_program_running == True"),
(True, "SAXS_WAXS_control.ensemble_program_running == False"),
],
"Label": [
("Homing","SAXS_WAXS_control.ensemble_homing == True"),
("Home", "SAXS_WAXS_control.ensemble_homed == False"),
("Homed", "SAXS_WAXS_control.ensemble_homed == True"),
],
"BackgroundColour": [
("yellow", "SAXS_WAXS_control.ensemble_homing == True"),
("green", "SAXS_WAXS_control.ensemble_homed == True"),
("red", "SAXS_WAXS_control.ensemble_homed == False"),
],
}
self.ProgramRunning.defaults = {"Label":"Start [Stop]","Enabled":False}
self.ProgramRunning.action = {
False: "SAXS_WAXS_control.ensemble_program_running = False",
True: "SAXS_WAXS_control.ensemble_program_running = True",
}
self.ProgramRunning.properties = {
"Value": [
(False, "SAXS_WAXS_control.ensemble_program_running == False"),
(True, "SAXS_WAXS_control.ensemble_program_running == True"),
],
"Enabled": [
(False, "SAXS_WAXS_control.fault == True"),
(True, "SAXS_WAXS_control.fault == False"),
],
"Label": [
("Fault","SAXS_WAXS_control.fault == True"),
("Start","SAXS_WAXS_control.ensemble_program_running == False"),
("Stop" ,"SAXS_WAXS_control.ensemble_program_running == True"),
],
"BackgroundColour": [
("green", "SAXS_WAXS_control.ensemble_program_running == True"),
("red", "SAXS_WAXS_control.ensemble_program_running == False"),
],
}
self.GotoSaved.action = {
True: "SAXS_WAXS_control.inserted = True",
}
self.GotoSaved.defaults = {"Enabled":False}
self.GotoSaved.properties = {
"Enabled": [
(True,"1-SAXS_WAXS_control.inserted"),
],
"BackgroundColour": [
("red","SAXS_WAXS_control.XY_enabled == False"),
],
}
self.Save.action = {
True: "SAXS_WAXS_control.at_inserted_position = True",
}
self.Save.defaults = {"Enabled":False}
self.Save.properties = {
"Enabled": [
(True, "SAXS_WAXS_control.at_inserted_position == False"),
],
}
self.Inserted.action = {
True: "SAXS_WAXS_control.inserted = True",
False: "SAXS_WAXS_control.retracted = True",
}
self.Inserted.defaults = {"Enabled":False,"Label":"Inserted [Withdrawn]"}
self.Inserted.properties = {
"Value": [
(True, "SAXS_WAXS_control.inserted == True"),
(False,"SAXS_WAXS_control.retracted == True"),
],
"Enabled": [
(True, "SAXS_WAXS_control.XY_enabled"),
],
"Label": [
("Inserted", "SAXS_WAXS_control.inserted == True"),
("Retracted","SAXS_WAXS_control.retracted == True"),
("Insert","SAXS_WAXS_control.inserted == SAXS_WAXS_control.retracted"),
],
"BackgroundColour": [
("green", "SAXS_WAXS_control.inserted == True"),
("yellow","SAXS_WAXS_control.retracted == True"),
("red","SAXS_WAXS_control.inserted == SAXS_WAXS_control.retracted"),
],
}
self.Mode.defaults = {"Value":"offline","Enabled":False}
self.Mode.value = "SAXS_WAXS_control.mode"
self.Mode.properties = {
"Enabled": [
(True,"SAXS_WAXS_control.timing_system_running == True"),
],
}
self.ShutterEnabled.defaults = {"Enabled":False,"Label":"offline"}
self.ShutterEnabled.action = {
False: "SAXS_WAXS_control.ms_on = False",
True: "SAXS_WAXS_control.ms_on = True",
}
self.ShutterEnabled.properties = {
"Value": [
(False, "SAXS_WAXS_control.ms_on == False"),
(True, "SAXS_WAXS_control.ms_on == True"),
],
"Label": [
("", "SAXS_WAXS_control.timing_system_running == True"),
("stopped", "SAXS_WAXS_control.timing_system_running == False"),
],
"Enabled": [
(True, "SAXS_WAXS_control.timing_system_running == True"),
],
}
self.PumpEnabled.defaults = {"Enabled":False,"Label":"offline"}
self.PumpEnabled.action = {
False: "SAXS_WAXS_control.pump_on = False",
True: "SAXS_WAXS_control.pump_on = True",
}
self.PumpEnabled.properties = {
"Value": [
(False, "SAXS_WAXS_control.pump_on == False"),
(True, "SAXS_WAXS_control.pump_on == True"),
],
"Label": [
("", "SAXS_WAXS_control.timing_system_running == True"),
("stopped", "SAXS_WAXS_control.timing_system_running == False"),
],
"Enabled": [
(True, "SAXS_WAXS_control.timing_system_running == True"),
],
}
self.PumpStep.defaults = {"Value":"offline","Enabled":False}
self.PumpStep.value = "SAXS_WAXS_control.pump_step"
self.PumpStep.properties = {
"Enabled": [
(True,"SAXS_WAXS_control.ensemble_online"),
],
}
self.PumpPosition.defaults = {"Value":"offline","Enabled":False}
self.PumpPosition.value = "SAXS_WAXS_control.pump_position"
self.PumpPosition.format = "%.1f"
self.PumpPosition.properties = {
"Enabled": [
(True,"SAXS_WAXS_control.ensemble_online"),
],
}
self.PumpHomed.defaults = {"Label":"Home","Enabled":False}
self.PumpHomed.action = {
False: "SAXS_WAXS_control.pump_homed = True",
True: "SAXS_WAXS_control.pump_homed = True",
}
self.PumpHomed.properties = {
"Value": [
(True, "SAXS_WAXS_control.pump_homed == True"),
],
"Enabled": [
(True, "SAXS_WAXS_control.pump_movable"),
],
"Label": [
("Home", "SAXS_WAXS_control.pump_homed == False"),
("Homed", "SAXS_WAXS_control.pump_homed == True"),
],
"BackgroundColour": [
("green", "SAXS_WAXS_control.pump_homed == True"),
("red", "SAXS_WAXS_control.pump_homed == False"),
],
}
self.LoadSampleStep.value = "SAXS_WAXS_control.load_step"
self.ExtractSampleStep.value = "SAXS_WAXS_control.extract_step"
self.CirculateSampleStep.value = "SAXS_WAXS_control.circulate_step"
self.LoadSample.action = {
False: "SAXS_WAXS_control.sample_loading = False",
True: "SAXS_WAXS_control.sample_loading = True",
}
self.LoadSample.defaults = {"Enabled":False}
self.LoadSample.properties = {
"Value": [
(True,"SAXS_WAXS_control.sample_loading == True"),
],
"Enabled": [
(True, "SAXS_WAXS_control.pump_movable"),
],
"Label": [
("Load Sample","not SAXS_WAXS_control.sample_loading"),
("Cancel Load","SAXS_WAXS_control.sample_loading"),
],
"BackgroundColour": [
("yellow", "SAXS_WAXS_control.sample_loading"),
("red", "SAXS_WAXS_control.pump_enabled == False"),
],
}
self.ExtractSample.action = {
False: "SAXS_WAXS_control.sample_extracting = False",
True: "SAXS_WAXS_control.sample_extracting = True",
}
self.ExtractSample.defaults = {"Enabled":False}
self.ExtractSample.properties = {
"Value": [
(True,"SAXS_WAXS_control.sample_extracting == True"),
],
"Enabled": [
(True, "SAXS_WAXS_control.pump_movable"),
],
"Label": [
("Extract Sample","not SAXS_WAXS_control.sample_extracting"),
("Cancel Extract","SAXS_WAXS_control.sample_extracting"),
],
"BackgroundColour": [
("yellow", "SAXS_WAXS_control.sample_extracting == True"),
("red", "SAXS_WAXS_control.pump_enabled == False"),
],
}
self.CirculateSample.action = {
False: "SAXS_WAXS_control.sample_circulating = False",
True: "SAXS_WAXS_control.sample_circulating = True",
}
self.CirculateSample.defaults = {"Enabled":False}
self.CirculateSample.properties = {
"Value": [
(True,"SAXS_WAXS_control.sample_circulating == True"),
],
"Enabled": [
(True, "SAXS_WAXS_control.pump_movable"),
],
"Label": [
("Circulate Sample","not SAXS_WAXS_control.sample_circulating"),
("Cancel Circulate","SAXS_WAXS_control.sample_circulating"),
],
"BackgroundColour": [
("yellow", "SAXS_WAXS_control.sample_circulating"),
("red", "SAXS_WAXS_control.pump_enabled == False"),
],
}
self.PumpSpeed.defaults = {"Value":"offline","Enabled":False}
self.PumpSpeed.value = "SAXS_WAXS_control.pump_speed"
self.PumpSpeed.properties = {
"Enabled": [
(True,"SAXS_WAXS_control.ensemble_online"),
],
}
self.Show()
if __name__ == '__main__':
from pdb import pm
import logging; from tempfile import gettempdir
logfile = gettempdir()+"/SAXS_WAXS_Control_Panel.log"
logging.basicConfig(level=logging.INFO,
format="%(asctime)s %(levelname)s: %(message)s",filename=None)
# Needed to initialize WX library
if not hasattr(wx,"app"): wx.app = wx.App(redirect=False)
panel = SAXS_WAXS_Control_Panel()
wx.app.MainLoop()
<file_sep>#!/bin/env python
"""
Acquire a series of images using the XPP Rayonix detector with the
LCLS data acquisition system and a server running on a "mond" node.
This script listens to a shared memory server of the DAQ system and resends
images to a client program (Lauecollect) running on "xpp-daq" or "xpp-control".
Setup:
ssh daq-xpp-mon05
cd ~xppopr/experiments/xppj1216/software
./shmem.py
Author: <NAME>, Jan 22, 2016 - Jan 27, 2016
"""
import time
import zmq
from psana import *
import numpy as np
from thread import start_new_thread
def rebin(a, shape):
sh = shape[0],a.shape[0]//shape[0],shape[1],a.shape[1]//shape[1]
# can do either two means, or two sums here. have
# to watch out for overflows with integers
return a.reshape(sh).sum(-1).sum(1)
ds = DataSource('shmem=XPP.0:stop=no')
#src = Source('rayonix')
det = Detector('rayonix',ds.env())
from mpi4py import MPI
comm = MPI.COMM_WORLD
rank = comm.Get_rank()
size = comm.Get_size()
startport = 12300
binning = 1
context = zmq.Context()
socket = context.socket(zmq.PUB)
socket.bind("tcp://*:%d" % (startport+(rank%12)))
def update_binning():
global binning
cmd_socket = context.socket(zmq.SUB)
cmd_socket.connect('tcp://172.21.38.54:12399') # xpp-daq
cmd_socket.connect('tcp://172.21.38.71:12399') # xpp-control
cmd_socket.setsockopt(zmq.SUBSCRIBE, 'cmd')
while True:
try:
topic = cmd_socket.recv()
binning = cmd_socket.recv_pyobj()
print '*** New binning',binning
except:
pass
start_new_thread(update_binning,())
comm.Barrier()
start = time.time()
for nevent,evt in enumerate(ds.events()):
#print rank,evt.get(EventId).fiducials()
if nevent%100==0:
neventtot = comm.reduce(nevent)
if rank==0:
print '***',nevent,neventtot,neventtot/(time.time()-start),'Hz'
#raw = evt.get(Camera.FrameV1,src)
raw = det.raw(evt)
if raw is None: continue
#data = raw.data16()
socket.send('rayonix',zmq.SNDMORE)
fid = evt.get(EventId).fiducials()
socket.send_pyobj(fid,zmq.SNDMORE)
raw_int32 = raw.astype(np.int32) # to avoid overflows
if binning == 1:
binned_uint16 = raw
else:
binned = rebin(raw_int32,[raw_int32.shape[0]/binning,raw_int32.shape[1]/binning])
binned -= 10*(binning**2-1) # subtract off all but 1 of the 10ADU pedestals that the rayonix has
binned[binned>65535]=65535
binned[binned<0]=0
binned_uint16 = binned.astype(np.uint16)
print 'Sending array data:',binned_uint16.shape,fid
socket.send_pyobj(binned_uint16)
<file_sep>MEAN.filename = '//mx340hs/data/anfinrud_1906/Archive/NIH.OPTICAL_SCATTERING.MEAN.txt'
STDEV.filename = '//mx340hs/data/anfinrud_1906/Archive/NIH.OPTICAL_SCATTERING.STDEV.txt'<file_sep>"""
Python interface to EPICS-controlled motors.
Author: <NAME>
Date created: 2007-11-07
Date last modified: 2019-05-28
"""
from CA import Record,caget,caput
from time import time,sleep
from logging import debug,info,warn,error
__version__ = "3.1.6" # no debug messages
nan = 1e1000/1e1000 # generates Not A Number
def isnan(x): return x!=x # checks for Not A Number
class EPICS_motor(Record):
"""EPICS-controlled motor
Using the following process variables:
VAL - nominal position
RBV - read back value
DRBV - dial read back value
HLM - high limit
LLM - low limit
DESC - description
EGU - unit
DMOV - 0 if currently moving, 1 if done
STOP - set to 1 momentarily to stop ?
VELO - speed in mm/s
CNEN - enabled
DIR - user to dial sign
OFF - user to dial offset
HLS - at high limit switch
LLS = at low limit switch
"""
def __init__(self,prefix,name=None,command="VAL",readback="RBV",
readback_slop = 0.001,timeout=20.0,min_step=0):
"""prefix = EPICS motor record
If is assumed that command value process varialbe is named 'VAL'
and the readback process variable 'RBV', unless specified otherwise
by the optional 'command' and 'readback' keywords.
readback slop: A motion is considered finished when the difference
between the command value and the readback value is smaller than this
amount.
timeout: The motion is considered finished when the readback value has
not changed within the readback slop for this amount of time.
min_step: only if the new position deviates from the current position by
at least this ammount will a command to move to motor be sent to the
IOC.
"""
Record.__init__(self,prefix)
if name is not None: self.__db_name__ = name
self.__command__ = command
self.__readback__ = readback
self.__readback_slop__ = readback_slop
self.__timeout__ = timeout
self.__min_step__ = min_step
self.__last_command_value__ = nan
self.__new_command_value__ = nan
self.__motion_started__ = 0
self.__move_done__ = True
self.__last_moving__ = 0
def get_prefix(self):
from DB import dbget
dbname = getattr(self,"__db_name__","")
try: prefix = eval(dbget("EPICS_motor/"+dbname+".prefix"))
except: prefix = ""
if not prefix: prefix = getattr(self,"__my_prefix__","")
return prefix
def set_prefix(self,value):
##debug("EPICS_motor.prefix = %r" % value)
from DB import dbput
dbname = getattr(self,"__db_name__","")
if dbname:
##debug("EPICS_motor/"+dbname+".prefix: "+repr(value))
dbput("EPICS_motor/"+dbname+".prefix" , repr(value))
else:
##debug("EPCIS_motor.__my_prefix__ = %r" % value)
self.__my_prefix__ = value
prefix = property(get_prefix,set_prefix)
__prefix__ = prefix
def get_command_PV(self):
"""Process variable value for the motor target position.
Ususually the value of the VAL process variable, but may me overriden."""
if not ":" in self.__command__: return getattr(self,self.__command__)
else: return caget(self.__command__)
def set_command_PV(self,value):
if not ":" in self.__command__:
##debug("setattr(%r,%r)" % (self.__command__,value))
setattr(self,self.__command__,value)
else:
##debug("caput(%r,%r)" % (self.__command__,value))
caput(self.__command__,value)
command_PV = property(get_command_PV,set_command_PV)
def get_readback_PV(self):
"""Process variable value for the actual position as measured.
Ususually the value of the RBV process variable, but may me overriden."""
if not ":" in self.__readback__: return getattr(self,self.__readback__)
else: return caget(self.__readback__)
def set_readback_PV(self,value):
if not ":" in self.__readback__: setattr(self,self.__readback__,value)
else: caput(self.__readback__,value)
readback_PV = property(get_readback_PV,set_readback_PV)
def get_command_value(self):
# Found that the Aerotech "Ensemble" EPICS driver is slow updating
# the command value. Make that not an old command value is returned.
# Wait 0.05 s from the command value to update. - <NAME>, 7 Mar 2013
if time() - self.__motion_started__ < 0.05 \
and not isnan(self.__new_command_value__):
value = self.__new_command_value__
else: value = self.command_PV
return asfloat(value)
def set_command_value(self,value):
##debug("value = %r" % value)
try: value = float(value)
except: return
if isnan(value): return
if abs(value - self.value) < self.__min_step__: return
# Found that the Aerotech "Ensemble" EPICS driver is slow updating
# the command value.
# Cache the new command value for a short period.
self.__new_command_value__ = value
# Record the time the last motion was initiated.
self.__motion_started__ = time()
# Enable the motor (in case it was disabled)
#self.CNEN = 1
# Initiate the motion by setting a new commond value.
##debug("command_PV = %r" % value)
self.command_PV = value
self.__last_command_value__ = value
self.__move_done__ = False
command_value = property(get_command_value,set_command_value,
doc="""Position of motor (user value). If read, readback position;
if assigned, starts motion to new position (but does not wait for the
motion to complete)""")
def set_value(self,value): self.command_value = value
def get_value(self): return asfloat(self.readback_PV)
value = property(get_value,set_value,
doc="""Position of motor (user value). If read, readback position;
if assigned, starts motion to new position (but does not wait for the
motion to complete)""")
def get_command_dial(self):
"""Target position as unscaled dial value."""
return asfloat(self.DVAL)
def set_command_dial(self,value):
value = asfloat(value)
if isnan(value): return
# Record the time the last motion was initiated.
self.__motion_started__ = time()
self.DVAL = value
command_dial = property(get_command_dial,set_command_dial)
def get_dial(self):
return asfloat(self.DRBV)
dial = property(get_dial,set_command_dial,
doc="""Position of motor as reported by the encoder (dial value).
If read, readback position; if assigned, starts motion to new position""")
def get_min(self):
"""Low limit in user units"""
return asfloat(self.LLM)
def set_min(self,value): self.LLM = value
min = property(get_min,set_min)
low_limit = min
def get_max(self):
"""Positive and of travel in user units"""
return asfloat(self.HLM)
def set_max(self,value): self.HLM = value
max = property(get_max,set_max)
high_limit = max
def get_at_low_limit(self):
"""Is motor at end switch?"""
return asbool(self.LLS)
at_low_limit = property(get_at_low_limit)
def get_at_high_limit(self):
"""Is motor at end switch?"""
return asbool(self.HLS)
at_high_limit = property(get_at_high_limit)
def get_name(self):
"""Description"""
name = self.DESC
if name == None: name = ""
return name
def set_name(self,value): self.DESC = value
name = property(get_name,set_name)
def get_unit(self):
"""mm,deg or mrad"""
unit = self.EGU
if unit == None: unit = ""
unit = unit.strip("()") # Somtimes the unit is included in parenthses.
return unit
def set_unit(self,value): self.EGU = value
unit = property(get_unit,set_unit)
def get_moving(self):
"""True if currently moving, False if done. Stops motor is assigned the
value False"""
# EPICS provides the DMOV flag in the motor record to tell when
# the motion has finished. However I found this to be unreliable
# because there can be a variable delay between the time
# the VAL variable is written, and the DMOV flag goes from the value 1
# to 0. (0 if currently moving, 1 if done).
# Does DMOV flag indicate that motor is moving?
DMOV = self.DMOV
if DMOV == 0: self.__last_moving__ = time()
if DMOV == 0: return not DMOV
if self.__last_moving__ > self.__motion_started__: return not DMOV
# Is motor at target position?
if self.__move_done__: return False;
if isnan(self.__last_command_value__): return False
if abs(self.value - self.__last_command_value__) < self.__readback_slop__:
self.__move_done__ = True; return False
# If the DMOV flag indicates that the motor is not moving and the
# motor is still not at the target position, give up after the
# timeout (default: 20s) expires.
if time()-self.__motion_started__ > self.__timeout__:
self.log("move timed out after %g s "\
"(target: %g %s, readback value: %g %s, readback slop: %g %s)" %
(self.__timeout__,self.__last_command_value__,self.unit,self.value,self.unit,
self.__readback_slop__,self.unit))
self.__move_done__ = True; return False
else: return True
def set_moving(self,value):
"""Stops the motor if value == False"""
if not value: self.stop()
moving = property(get_moving,set_moving)
def get_speed(self):
"""Velocity in mm/s or deg/s"""
return asfloat(self.VELO)
def set_speed(self,value):
try: value = float(value)
except: return
self.VELO = value
speed = property(get_speed,set_speed)
def get_acceleration(self):
"""Accelation in mm/s^2 or deg/s^2"""
T = asfloat(self.ACCL) # acceleration time
acceleration = self.speed/T
return acceleration
def set_acceleration(self,acceleration):
try: value = float(value)
except: return
T = self.speed/acceleration
self.ACCL = T
acceleration = property(get_acceleration,set_acceleration)
def get_enabled(self):
value = self.CNEN
if value == None: value = nan
return value
def set_enabled(self,value):
self.CNEN = value
enabled = property(get_enabled,set_enabled)
def get_homing(self):
"""Current executing a home calibaion? If set execute the home
calibration."""
if self.HOMR: value = True
elif self.HOMF: value = True
else: value = False
return value
def set_homing(self,value):
self.HOMF = value
homing = property(get_homing,set_homing)
def get_homed(self):
"""Current executing a home calibaion? If set execute the home
calibration."""
status_bits = self.MSTA
if status_bits == None: homed = nan
else: homed = bool((status_bits>>15)&1)
return homed
def set_homed(self,value): pass
homed = property(get_homed,set_homed)
def get_sign(self):
"""Dial to user direction: +1 or -1"""
value = self.DIR
if value == 0: return 1
elif value == 1: return -1
else: return nan
def set_sign(self,sign):
self.DIR = 0 if sign>=0 else 1
sign = property(get_sign,set_sign)
def get_offset(self):
"""Dial to user direction: +1 or -1"""
return asfloat(self.OFF)
def set_offset(self,value):
self.OFF = value
offset = property(get_offset,set_offset)
def define_value(self,value):
"modifies the user to dial offset such that the new user value is 'value'"
self.offset = value - self.dial * self.sign
# user = dial*sign + offset; offset = user - dial*sign
def get_readback_slop(self):
"""Maxmimum allowed difference between readback value and command value
for the motion to be considered complete."""
return self.__readback_slop__
def set_readback_slop(self,value):
self.__readback_slop__ = value
readback_slop = property(get_readback_slop,set_readback_slop)
def wait(self):
"""If the motor is moving, returns control after current move move is
complete."""
while self.moving: sleep(0.01)
def stop(self):
self.STOP = 1
def __repr__(self):
return 'EPICS_motor("'+self.__prefix__+'")'
def log(self,message):
"""Append a message to the log file (/tmp/EPICS_motor.log)"""
from tempfile import gettempdir
from time import strftime
from sys import stderr
timestamp = strftime("%d-%b-%y %H:%M:%S")
if len(message) == 0 or message[-1] != "\n": message += "\n"
name = self.name
if not name: name = repr(self)
message = timestamp+" "+name+": "+message
stderr.write(message)
logfile = gettempdir()+"/EPICS_motor.log"
file(logfile,"a").write(message)
motor = EPICS_motor
def asfloat(x):
"""Convert x to a floating point number without rasing an exception.
Return nan instead if conversion fails"""
try: return float(x)
except: return nan
def asbool(x):
"""Convert x to a boolean without rasing an exception.
Return False instead if conversion fails"""
try: return bool(int(x))
except: return False
if __name__ == "__main__": # for testing
from pdb import pm # for debugging
import logging
logging.basicConfig(level=logging.DEBUG,format="%(asctime)s: %(message)s")
shg = motor("14IDB:m25",name="shg")
MirrorV = motor("14IDA:DAC1_4",readback="VAL",name="MirrorV")
print('shg.prefix = %r' % shg.prefix)
print('shg.command_value')
print('shg.value')
print('MirrorV.prefix = %r' % MirrorV.prefix)
print('MirrorV.command_value')
print('MirrorV.value')
<file_sep>#!/usr/bin/env python
"""General motor control panel.
<NAME>, 31 Oct 2013 - 7 Jul 2017"""
__version__ = "1.3" # multiple rows
import wx
from EditableControls import TextCtrl,ComboBox
from logging import debug,info,warn,error
class MotorWindow(wx.Frame):
"""Motors"""
def __init__(self,motors,title="Motors"):
"""motors: list of EPICS_motor objects
If a nested list, each sublist is packed into a row.
"""
# Make sure "motors" is a nested list.
if motors and not hasattr(motors[0],"__len__"): motors = [motors]
wx.Frame.__init__(self,parent=None,title=title)
sizer = wx.GridBagSizer(1,1)
for i,motor_group in enumerate(motors):
for j,motor in enumerate(motor_group):
panel = MotorPanel(self,motor)
sizer.Add (panel,(i,j),flag=wx.ALL,border=5)
self.SetSizer(sizer)
self.Fit()
self.Show()
class MotorPanel(wx.Panel):
"""Motor"""
name = "MotorPanel"
def __init__(self,parent,motor,refresh_period=1.0):
wx.Panel.__init__(self,parent)
self.motor = motor
self.refresh_period = refresh_period
# Controls
self.MotorName = wx.StaticText(self,size=(100,-1),style=wx.ALIGN_CENTRE)
self.background = self.MotorName.BackgroundColour
self.Unit = wx.StaticText(self,size=(100,-1),style=wx.ALIGN_CENTRE)
self.Value = wx.StaticText(self,size=(100,-1),style=wx.ALIGN_CENTRE)
self.CommandValue = TextCtrl(self,size=(100,-1),style=wx.TE_PROCESS_ENTER)
self.TweakValue = ComboBox(self,size=(50,-1),style=wx.TE_PROCESS_ENTER)
left = wx.ArtProvider.GetBitmap(wx.ART_GO_BACK)
right = wx.ArtProvider.GetBitmap(wx.ART_GO_FORWARD)
self.TweakDownButton = wx.BitmapButton(self,bitmap=left)
self.TweakUpButton = wx.BitmapButton(self,bitmap=right)
self.EnableButton = wx.ToggleButton(self,label="Enabled",size=(70,-1))
w,h = self.EnableButton.Size
self.HomeButton = wx.ToggleButton(self,label="Homed",size=(w,h))
self.Bind(wx.EVT_CONTEXT_MENU,self.OnConfigureMenu,self.MotorName)
self.Bind(wx.EVT_CONTEXT_MENU,self.OnConfigureMenu,self.Unit)
self.Bind(wx.EVT_CONTEXT_MENU,self.OnSetValueMenu,self.Value)
self.Bind(wx.EVT_TEXT_ENTER,self.OnEnterCommandValue,self.CommandValue)
self.Bind(wx.EVT_CONTEXT_MENU,self.OnSetValueMenu,self.CommandValue)
self.Bind(wx.EVT_COMBOBOX,self.OnEnterTweakValue,self.TweakValue)
self.Bind(wx.EVT_TEXT_ENTER,self.OnEnterTweakValue,self.TweakValue)
self.Bind(wx.EVT_CONTEXT_MENU,self.OnTweakMenu,self.TweakValue)
self.Bind(wx.EVT_BUTTON,self.OnTweakDown,self.TweakDownButton)
self.Bind(wx.EVT_BUTTON,self.OnTweakUp,self.TweakUpButton)
self.Bind(wx.EVT_TOGGLEBUTTON,self.OnEnable,self.EnableButton)
self.Bind(wx.EVT_TOGGLEBUTTON,self.OnHome,self.HomeButton)
# Layout
controls = wx.GridBagSizer(1,1)
a = wx.ALIGN_CENTRE_HORIZONTAL|wx.ALIGN_CENTRE_VERTICAL
e = wx.EXPAND
controls.Add(self.MotorName,(0,0),span=(1,3),flag=a|e)
controls.Add(self.Unit,(1,0),span=(1,3),flag=a|e)
controls.Add(self.Value,(2,0),span=(1,3),flag=a|e)
controls.Add(self.CommandValue,(3,0),span=(1,3),flag=a|e)
controls.Add(self.TweakDownButton,(4,0),flag=a|e)
controls.Add(self.TweakValue,(4,1),flag=a|e)
controls.Add(self.TweakUpButton,(4,2),flag=a|e)
controls.Add(self.EnableButton,(5,1),flag=a)
controls.Add(self.HomeButton,(6,1),flag=a)
# Leave a 10 pixel wide border.
box = wx.BoxSizer(wx.VERTICAL)
box.Add(controls,flag=wx.ALL,border=5)
self.SetSizer(box)
self.Fit()
# Initialization
self.CommandValue.Enabled = False
self.TweakDownButton.Enabled = False
self.TweakUpButton.Enabled = False
self.EnableButton.Enabled = False
self.HomeButton.Enabled = False
# Refresh
self.attributes = ["name","unit","value","command_value",
"moving","enabled","homed","homing"]
from numpy import nan
self.values = dict([(n,nan) for n in self.attributes])
self.values["name"] = ""
self.values["unit"] = ""
self.old_values = {}
from threading import Thread
self.refresh_thread = Thread(target=self.refresh_background,
name=self.name+".refresh")
self.refreshing = False
from wx.lib.newevent import NewEvent
self.EVT_THREAD = NewEvent()[1]
self.Bind(self.EVT_THREAD,self.OnUpdate)
self.thread = Thread(target=self.keep_updated,name=self.name)
self.thread.start()
def keep_updated(self):
"""Periodically refresh the displayed settings."""
from time import time,sleep
while True:
try:
t0 = time()
while time() < t0+self.refresh_period: sleep(0.1)
if self.Shown:
self.update_data()
if self.data_changed:
event = wx.PyCommandEvent(self.EVT_THREAD.typeId,self.Id)
# call OnUpdate in GUI thread
wx.PostEvent(self.EventHandler,event)
except wx.PyDeadObjectError: break
def refresh(self):
"""Force update"""
from threading import Thread
if not self.refreshing and self.Shown:
self.refresh_thread = Thread(target=self.refresh_background,
name=self.name+".refresh")
self.refreshing = True
self.refresh_thread.start()
def refresh_background(self):
"""Force update"""
self.update_data()
if self.data_changed:
event = wx.PyCommandEvent(self.EVT_THREAD.typeId,self.Id)
wx.PostEvent(self.EventHandler,event) # call OnUpdate in GUI thread
self.refreshing = False
def update_data(self):
"""Retreive status information"""
from numpy import nan
self.old_values = dict(self.values) # make a copy
for n in self.attributes: self.values[n] = self.getattr(self.motor,n,nan)
from numpy import nan
@staticmethod
def getattr(object,attribute,default_value=nan):
"""Get a propoerty of an object
attribute: e.g. 'value' or 'member.value'"""
try: return eval("object."+attribute)
except Exception,msg:
import traceback
error("%s.%s: %s" % (object,attribute,msg))
for line in traceback.format_exc().split("\n"): error(line)
return default_value
@property
def data_changed(self):
"""Did the last 'update_data' change the data to be plotted?"""
changed = (self.values != self.old_values)
return changed
def OnUpdate(self,event=None):
"""Periodically refresh the displayed settings."""
self.refresh_status()
def refresh_status(self,event=None):
"""Update the controls with current values"""
from numpy import nan,isnan
unit = self.values["unit"]
value = self.values["value"]
command_value = self.values["command_value"]
enabled = self.values["enabled"]
moving = self.values["moving"]
homed = self.values["homed"]
homing = self.values["homing"]
self.MotorName.Label = self.values["name"]
self.Unit.Label = "[%s]" % unit if unit else ""
self.Value.Label = "%.4f" % value if not isnan(value) else ""
self.Value.BackgroundColour = \
(128,128,255) if moving == True else self.background
##self.CommandValue.BackgroundColour = \
## (128,128,255) if moving else self.background
self.CommandValue.Value = "%.4f" % command_value \
if not isnan(command_value) else ""
self.CommandValue.Enabled = (enabled == True)
choices = ["%.4f" % x for x in self.tweak_values]
if self.TweakValue.Items != choices: self.TweakValue.Items = choices
self.TweakValue.Value = "%.4f" % self.tweak_value
self.TweakDownButton.Enabled = (enabled == True)
self.TweakUpButton.Enabled = (enabled == True)
self.EnableButton.Value = bool(enabled)
self.EnableButton.Label = \
"Stop" if moving == True else \
"Enable" if isnan(enabled) else \
"Enabled" if enabled == True else \
"Disabled"
self.EnableButton.BackgroundColour = \
(255,0,0) if moving == True else \
self.background if enabled == True else \
(255,0,0) if enabled == False else \
self.background
self.EnableButton.Enabled = \
True if moving == True else \
not isnan(enabled)
self.HomeButton.Value = bool(homing)
self.HomeButton.BackgroundColour = \
self.background if isnan(homed) or (enabled != True) else \
(255,255,0) if homing == True else \
(0,255,0) if homed == True else (255,0,0)
self.HomeButton.Label = \
"Home" if isnan(homed) else \
"Homing" if homing == True else \
"Homed" if homed == True else \
"Home"
self.HomeButton.Enabled = (enabled == True)
def OnEnterCommandValue(self,event):
"""Set the voltage to a specific value."""
text = self.CommandValue.Value
try: value = float(eval(text))
except Exception,details:
##debug("%s: %s" % (text,details))
self.refresh(); return
##debug("self.motor.command_value = %r" % value)
self.motor.command_value = value
self.refresh()
def OnSetValueMenu(self,event):
"""Bring up a menu to set the position without moving the motor"""
menu = wx.Menu()
menu.Append (1,"Set...","Set the position without moving the motor")
self.Bind (wx.EVT_MENU,self.OnSetValue,id=1)
# Display the menu. If an item is selected then its handler will
# be called before 'PopupMenu' returns.
self.PopupMenu(menu)
menu.Destroy()
def OnSetValue(self,event):
"""Set the position without moving the motor"""
dlg = wx.TextEntryDialog(self,"New position",
"Set the position without moving the motor","")
dlg.Value = "%.4f" % self.motor.command_value
OK = (dlg.ShowModal() == wx.ID_OK)
if not OK: return
text = dlg.Value
try: value = float(eval(text))
except Exception,details:
##debug("Set Value %s: %s" % (text,details))
self.refresh(); return
self.motor.offset = -self.motor.sign*self.motor.dial + value
self.refresh()
def OnEnterTweakValue(self,event):
"""Set the voltage to a specific value."""
text = self.TweakValue.Value
try: value = float(eval(text))
except: self.refresh(); return
self.tweak_value = value
self.refresh()
def OnTweakMenu(self,event):
"""Bring up a menu to set the position without moving the motor"""
menu = wx.Menu()
menu.Append (1,"Choices...","Edit the choices for tweak values")
self.Bind (wx.EVT_MENU,self.OnTweakValues,id=1)
# Display the menu. If an item is selected then its handler will
# be called before 'PopupMenu' returns.
self.PopupMenu(menu)
menu.Destroy()
def OnTweakValues(self,event):
"""Edit the choices for tweak values"""
dlg = wx.TextEntryDialog(self,"Tweak values",
"Choices for tweak values","")
dlg.Value = ",".join(["%.4f" % x for x in self.tweak_values])
OK = (dlg.ShowModal() == wx.ID_OK)
if not OK: return
text = dlg.Value
try: values = eval(text)
except Exception,details:
debug("Set Value %s: %s" % (text,details))
self.refresh(); return
try: values = [float(x) for x in values]
except Exception,details:
debug("Set Value %s: %s" % (text,details))
self.refresh(); return
self.tweak_values = values
self.refresh()
def OnTweakDown(self,event):
""""""
self.motor.command_value -= self.tweak_value
self.refresh()
def OnTweakUp(self,event):
""""""
self.motor.command_value += self.tweak_value
self.refresh()
def OnEnable(self,event):
"""Enable the motor if t hebutton is toggled on,
disable th emotor if the butto is toggled off."""
if self.EnableButton.Label == "Stop":
print "Stop"
print self.motor.moving
self.motor.moving = False
print self.motor.moving
else: self.motor.enabled = self.EnableButton.Value
self.refresh()
def OnHome(self,event):
"""Start a home run, if the button is toggled on.
Cancel a home run, if is is toggled off."""
self.motor.homing = self.HomeButton.Value
self.refresh()
def OnConfigureMenu(self,event):
"""Bring up a menu to set the position without moving the motor"""
menu = wx.Menu()
menu.Append (1,"More...","Configure motor parameters")
self.Bind (wx.EVT_MENU,self.OnConfigure,id=1)
# Display the menu. If an item is selected then its handler will
# be called before 'PopupMenu' returns.
self.PopupMenu(menu)
menu.Destroy()
def OnConfigure(self,event):
"""Configure motor parameters"""
dlg = ConfigurationPanel(self)
dlg.CenterOnParent()
dlg.Show()
def get_tweak_value(self):
from DB import dbget
value = dbget("motor_panel.%s.tweak_value" % self.motor.name)
try: value = float(value)
except ValueError: value = 1.0
return value
def set_tweak_value(self,value):
from DB import dbput
return dbput("motor_panel.%s.tweak_value" % self.motor.name,str(value))
tweak_value = property(get_tweak_value,set_tweak_value)
def get_tweak_values(self):
from DB import dbget
values = dbget("motor_panel.%s.tweak_values" % self.motor.name)
try: values = eval(values)
except: values = [1.0]
try: values = [float(x) for x in values]
except: pass
return values
def set_tweak_values(self,values):
from DB import dbput
return dbput("motor_panel.%s.tweak_values" % self.motor.name,str(values))
tweak_values = property(get_tweak_values,set_tweak_values)
class ConfigurationPanel(wx.Frame):
def __init__(self,parent=None):
wx.Frame.__init__(self,parent=parent,title="Configuration")
panel = wx.Panel(self)
# Controls
style = wx.TE_PROCESS_ENTER
self.UserValue = TextCtrl(self,size=(90,-1),style=style)
self.DialValue = TextCtrl(self,size=(90,-1),style=style)
self.HighLimit = TextCtrl(self,size=(90,-1),style=style)
self.LowLimit = TextCtrl(self,size=(90,-1),style=style)
self.Sign = ComboBox(self,size=(90,-1),style=style,
choices=["+1","-1"])
self.Offset = TextCtrl(self,size=(90,-1),style=style)
self.Speed = ComboBox (self,size=(90,-1),style=style,
choices=["1.8","15","90"])
self.Bind (wx.EVT_TEXT_ENTER,self.OnEnter)
self.Bind (wx.EVT_COMBOBOX,self.OnEnter)
self.Bind (wx.EVT_TEXT_ENTER,self.OnEnterUserValue,self.UserValue)
# Layout
layout = wx.BoxSizer()
grid = wx.FlexGridSizer (cols=2,hgap=5,vgap=5)
flag = wx.ALIGN_CENTER_VERTICAL
label = "User value:"
grid.Add (wx.StaticText(self,label=label),flag=flag)
grid.Add (self.UserValue,flag=flag)
label = "Dial value:"
grid.Add (wx.StaticText(self,label=label),flag=flag)
grid.Add (self.DialValue,flag=flag)
label = "High Limit:"
grid.Add (wx.StaticText(self,label=label),flag=flag)
grid.Add (self.HighLimit,flag=flag)
label = "Low Limit:"
grid.Add (wx.StaticText(self,label=label),flag=flag)
grid.Add (self.LowLimit,flag=flag)
label = "Sign:"
grid.Add (wx.StaticText(self,label=label),flag=flag)
grid.Add (self.Sign,flag=flag)
label = "Offset:"
grid.Add (wx.StaticText(self,label=label),flag=flag)
grid.Add (self.Offset,flag=flag)
label = "Speed:"
grid.Add (wx.StaticText(self,label=label),flag=flag)
grid.Add (self.Speed,flag=flag)
# Leave a 10-pixel wide space around the panel.
layout.Add (grid,flag=wx.EXPAND|wx.ALL,border=10)
self.SetSizer(layout)
self.Fit()
self.update()
def update(self,Event=0):
motor = self.Parent.motor
if hasattr(motor,"name"): self.Title = motor.name
if hasattr(motor,"command_value"):
self.UserValue.Value = "%.4f" % motor.command_value
else: self.UserValue.Value = ""
if hasattr(motor,"command_dial"):
self.DialValue.Value = "%.4f" % motor.command_dial
else: self.DialValue.Value = ""
if hasattr(motor,"low_limit"):
self.LowLimit.Value = "%.4f" % motor.low_limit
else: self.LowLimit.Value = ""
if hasattr(motor,"high_limit"):
self.HighLimit.Value = "%.4f" % motor.high_limit
else: self.HighLimit.Value = ""
if hasattr(motor,"sign"):
self.Sign.Value = "%+g" % motor.sign
else: self.Sign.Value = ""
if hasattr(motor,"offset"):
self.Offset.Value = "%.4f" % motor.offset
else: self.Offset.Value = ""
if hasattr(motor,"speed"):
self.Speed.Value = "%g" % motor.speed
else: self.Speed.Value = ""
# Relaunch yourself.
self.update_timer = wx.Timer(self)
self.Bind (wx.EVT_TIMER,self.update,self.update_timer)
self.update_timer.Start(2000,oneShot=True)
def OnEnter(self,event):
"""Read back updated parameters from the configuration panel"""
from numpy import nan,inf
motor = self.Parent.motor
if hasattr(motor,"command_dial"):
try: motor.command_dial = float(eval(self.DialValue.Value))
except: pass
if hasattr(motor,"low_limit"):
try: motor.low_limit = float(eval(self.LowLimit.Value))
except: pass
if hasattr(motor,"high_limit"):
try: motor.high_limit = float(eval(self.HighLimit.Value))
except: pass
if hasattr(motor,"offset"):
try: motor.offset = float(eval(self.Offset.Value))
except: pass
if hasattr(motor,"sign"):
try: motor.sign = float(eval(self.Sign.Value))
except: pass
if hasattr(motor,"speed"):
try: motor.speed = float(eval(self.Speed.Value))
except: pass
self.update()
def OnEnterUserValue(self,event):
"""Change the user value without moving the motor"""
motor = self.Parent.motor
try: value = float(eval(self.UserValue.Value))
except: self.update(); return
if hasattr(motor,"offset") and hasattr(motor,"sign") and \
hasattr(motor,"dial"):
motor.offset = -motor.sign*motor.dial + value
self.update()
def tofloat(x):
from numpy import nan
try: return float(x)
except: return nan
if __name__ == '__main__':
import logging
logging.basicConfig(level=logging.DEBUG,format="%(asctime)s: %(message)s")
# Needed to initialize WX library
if not "app" in globals(): app = wx.App(redirect=False)
from cavro_centris_syringe_pump_IOC import volume,port
motors = [port,volume]
window = MotorWindow(motors,title="Cavro Centris Syringe Pumps")
app.MainLoop()
<file_sep>"""
Scripts to verify the linearity of the MAR CCD detector
scan: data aqusistion
analyze_scan: image processing
<NAME>, APS, 5 Feb 2009
"""
from id14 import * # Beamline instrumentation
from os import makedirs
from os.path import exists,dirname,basename
from numpy import array,where,isnan,amax,zeros,rint,isinf,nansum,nanmax,sum,average
from textfile import read,save
scan_dir = "/data/anfinrud_0902/Data/MARCCD_linearity/scan3"
npasses = 32
# Stacked aluminum foil attenuator, step size 0.5 mm
motor = DetY
start = 2.1-0.7 # [mm] no foil: 2.1, lead tape 2.1-0.7
step = 0.7 # [mm] relative vertical offset of foils
end = start + 10*0.7 # [mm] maximum number of foils
# Record X-ray beam intensity
# C1 = I0 PIN diode reverse-biased, 50 Ohm, C4 = trigger
xray_pulse = id14b_wavesurfer.measurement(1)
I0_offset = 4.97e-9 # [Vs] measured in auto trigger mode
boxsize = 5 # [pixels] box size around peak to integrate
def scan():
"""Acquires a series of image with different vertical offsets
in order to to find the edge of the crystal"""
# Make sure directory exists
if not exists (scan_dir): makedirs (scan_dir)
# Clean up directory.
for i in range(0,100):
filename = "%s/%03d.mccd" % (scan_dir,i+1)
if exists(filename): remove(filename)
pson.value = 0 # Disable ps laser.
lxd.value = 0 # Make sure the X-ray pulse is not delayed.
npoints = int(round(abs((end-start)/step)))+1
logfile = "%s/scan.log" % scan_dir
if not exists(logfile):
log = file(logfile,"a")
log.write("# source: U23 at %.2f mm, U27 at %.2f mm\n" %
(caget("ID14ds:Gap.VAL"),caget("ID14us:Gap.VAL")))
log.write("#filename\t%s[%s]\tI0[Vs]\tbunchcurrent[mA]\n" %
(motor.name.replace(" ",""),motor.unit))
log = file(logfile,"a")
for j in range(0,npasses):
for i in range(0,npoints):
filename = "%s/%03d_%03d.mccd" % (scan_dir,i+1,j+1)
if not exists(filename):
pos = (start + i*step)
print "%s\t%g" % (basename(filename),pos)
motor.value = pos
while motor.moving: sleep (0.1)
acquire_single_shot(filename)
log.write("%s\t%g\t%g\t%g\n" %
(basename(filename),pos,xray_pulse.average,bunch_current()))
log.flush()
motor.value = start # return the sample to starting point
def acquire_single_shot(filename):
"Acquires a single image of an alignment scan"
waitt.value = 0.1 # no need for long waiting time
# Postpone the acquisition of the image, if a top-up is scheduled.
if time_to_next_refill() < 1.0: print "Waiting for refill..."
while time_to_next_refill() < 1.0: sleep (0.1)
xray_pulse.start() # for diangostics
ccd.start()
pulses.value = 1 # This riggers the ms shutter once.
while pulses.value > 0: sleep (0.1)
# After pulses drops to zero, the Xr-ay pulse is sent within 0.1 s
sleep (0.1)
ccd.readout(filename)
def time_to_next_refill():
"""This tells the number of seconds to the next top-up.
This is needed to decide whether it is necessary to postpone the next image
until after the next top-up, to avoid collecting data during a top-up. """
return caget("Mt:TopUpTime2Inject")
def bunch_current():
"Reads current of of bunch '#1' in mA from the machine info"
try: return float(caget("BNCHI:BunchCurrentAI.VAL"))
except: return nan
def analyze_scan():
""" Processes the dataset in directory 'scan_dir'
"""
global filenames,pos,I0,curr,sum_image,ave_image,peakI,x,y,r,image,I # for debugging
logfile = "%s/scan.log" % scan_dir
filenames,pos,I0,curr = read(logfile,labels=
"filename,DetY[mm],I0[Vs],bunchcurrent[mA]")
nimages = len(filenames)
# Find the peak position. This first image might be an empty image.
# Thus use an averaged image to determine the peak position.
print "Finding peak",
w,h = imagesize(scan_dir+"/"+filenames[0])
sum_image = zeros((w,h))
count = 0
for i in range(0,nimages):
image = numimage(scan_dir+"/"+filenames[i])
if isinf(nanmax(image)): print "!",; continue # skip saturated images
print ".",
sum_image += image
count += 1
if count>=5: break
ave_image = sum_image/count
peakI = nanmax(ave_image)
peakpos = where(ave_image == peakI)
x,y = peakpos[0][0],peakpos[1][0]
print x,y
r = int(rint(boxsize/2))
I = array([nan]*nimages)
for i in range(0,nimages):
image = numimage(scan_dir+"/"+filenames[i])
I[i] = average(image[x-r:x+r+1,y-r:y+r+1])
print "%g\t%g" % (pos[i],I[i])
outfile = "%s/scan.txt" % scan_dir
save([pos,I,I0,curr],outfile,labels=
"DetY[mm],I[counts],I0[Vs],bunchcurrent[mA]")
def imagesize(filename):
"""Get width and height in pixels as (w,h) pair"""
from PIL import Image
image = Image.open(filename)
return image.size
def numimage(filename):
"""Load an image as numpy array"""
from PIL import Image
from numpy import array,where,nan,inf
image = Image.open(filename)
image = array(image.convert("I"),float).T
image[where(image == 0)] = nan
image[where(image == 65535)] = inf
image -= 10 # undo MAR CCD image software offset
return image
if __name__ == "__main__":
"for testing"
analyze_scan()
<file_sep>"""Display a live image during data collection
<NAME>, Jun 28, 2017 - Jun 29, 2017
"""
__version__ = "1.0"
from ImageViewer import show_images
from ADXV_live_image import show_image
if __name__ == "__main__":
from rayonix_detector_continuous import ccd
print('show_image(ccd.temp_image_filename)')
<file_sep>#!/bin/env python
""" This is a python script that will analyse images triggered by the FPGA
It will be a standalone unit that can be called from either "Optical Sample Freeze Detector" or
LAUE Crystalography image analyser.
Core functions:
- get background array
- get current array
- get difference array
- save array as image
Author: <NAME>
Date created: 2018-03-08
Date last modified: 2018-03-28
This used to be optical_image_analyser_rgb
but I need to have a generalized code to use it for both LAUE and SAXS|WAXS
The images are saved in correct orientation. This was achieved by rotating the array camera.RGB_array provides.
The arrays dimensionality is (vertical, horizontal, depth) or (y,x, depth) where depth is RGB or RGBK depending on dimensionality.
"""
__version__ = "1.1" # <NAME>: WideFieldCamera (with uppercase F)
import matplotlib.pyplot as plt
from numpy import mean, transpose, std,array,hypot , abs, zeros, savetxt, loadtxt,save ,load ,uint8, uint16, reshape, asarray
from numpy.ma import masked_array
#import numpy.ma as ma
#plt.ion()
from time import sleep, time
from PIL import Image
from persistent_property import persistent_property
from datetime import datetime
from scipy import ndimage, misc
import os
from logging import debug,info,warn,error
from thread import start_new_thread
from CA import caget
class Camera_image_analyser(object):
camera_name = persistent_property('camera name', '')
cameraSettingGain = persistent_property('camera Setting Gain', 6)
cameraSettingExposureTime = persistent_property('camera Setting exposure time', 0.072)
pixels_to_use_h = persistent_property('pixels_to_use_h', (300,700))
pixels_to_use_v = persistent_property('pixels_to_use_v', (300,700))
def __init__(self, name = 'camera_image_analyser', camera_name = 'MicroscopeCamera'):
self.name = name
self.camera_name = camera_name #WideFieldCamera #MicroscopeCamera
self.frame_count = camera.frame_count
self.image_timeout = 10
#self.pixels_to_use_v = (509,515)
#self.pixels_to_use_h = (0,1360)
self.difference_array = zeros((self.pixels_to_use_v[1]-self.pixels_to_use_v[0],self.pixels_to_use_h[1]-self.pixels_to_use_h[0]))
self.background_image_flag = False
self.logFolder = os.getcwd() + '/' + self.name +'/'
self.save_every_image = False
if os.path.exists(os.path.dirname(self.logFolder)):
pass
else:
os.makedirs(os.path.dirname(self.logFolder))
if os.path.exists(os.path.dirname(self.logFolder+ 'Laue/Archive/') ):
pass
else:
os.makedirs(os.path.dirname(self.logFolder+ 'Laue/Archive/'))
if os.path.exists(os.path.dirname(self.logFolder+ 'Laue/Images/') ):
pass
else:
os.makedirs(os.path.dirname(self.logFolder+ 'Laue/Images/'))
try:
self.background_array_filename = 'background_default'
self.background_array = load(self.logFolder + self.background_array_filename + '.npy')
self.background_image_flag = True
debug('got bckg image from the drive')
except:
debug('couldn"t load bckg image')
self.background_image_flag = False
self.logfile = self.logFolder + self.name + '.log'
if os.path.isfile(self.logfile):
pass
else:
f = open(self.logfile,'w')
timeRecord = time()
f.write('####This experiment started at: %r and other information %r \r\n' %(timeRecord,'Other Garbage'))
f.write('time,\r\n')
f.close()
def get_image(self):
from numpy import rot90, float16, flipud
if self.is_new_image():
self.current_image = flipud(rot90(camera.RGB_array, k = 1, axes = (0,2)))
self.frame_count = camera.frame_count
if self.save_every_image:
start_new_thread(self.save_array_as_image,(self.current_image,))
res = True
else:
res = False
return res
def mask_current_image(self):
debug('mask_current_image function')
self.current_array = self.mask_array(self.current_image)
def mask_array(self,arr):
from numpy import zeros, float16
arr_res = zeros((self.pixels_to_use_v[1]-self.pixels_to_use_v[0],self.pixels_to_use_h[1]-self.pixels_to_use_h[0],arr.shape[2]+1))
arr_R = arr_res[:,:,0] = arr[self.pixels_to_use_v[0]:self.pixels_to_use_v[1],self.pixels_to_use_h[0]:self.pixels_to_use_h[1],0] #R
arr_G = arr_res[:,:,1] = arr[self.pixels_to_use_v[0]:self.pixels_to_use_v[1],self.pixels_to_use_h[0]:self.pixels_to_use_h[1],1] #G
arr_B = arr_res[:,:,2] = arr[self.pixels_to_use_v[0]:self.pixels_to_use_v[1],self.pixels_to_use_h[0]:self.pixels_to_use_h[1],2] #B
arr_res[:,:,3] = arr_R + arr_G +arr_B #K
return arr_res
def is_new_image(self):
from time import time
if self.frame_count > camera.frame_count: #this is for wrapping arround
self.frame_count = 0
t0 = time()
while self.frame_count >= camera.frame_count and time() - t0 < self.image_timeout:
sleep(0.2)
if self.frame_count < camera.frame_count:
res = True
else:
res = False
return res
def get_background_array(self):
debug('getting bacgkround array')
self.get_current_array()
self.background_array = self.current_array
self.background_image_flag = True
self.save_to_pickle_file(filename = self.background_array_filename, data = self.background_array)
def run_get_background_array(self):
self.background_image_flag = False
start_new_thread(self.get_background_array,())
def get_difference_array(self):
#wait for new image
if self.background_image_flag:
self.get_current_array()
self.difference_array = self.current_array - self.background_array
res = True
else:
res = False
return res
def get_current_array(self):
#wait for new image
debug('getting bacgkround array')
self.get_image()
self.mask_current_image()
def save_array_as_image(self,arr, filename = ''):
import PIL
from numpy import uint8, rot90
from time import time
image = PIL.Image.fromarray(arr, 'RGB')
if len(filename) == 0:
filename = str(time()) + '.tiff'
image.save(self.logFolder+'Images/'+ filename)
def save_to_pickle_file(self,data, filename = "current_array"):
import numpy
numpy.save(self.logFolder + filename, data, allow_pickle = True)
"""plotting functions"""
def plot_array(self, arr):
from numpy import float32
if arr.min()<0: #for difference image to be plotted properly
plt.imshow(arr[:,:,0:3]-arr.min())
else:
plt.imshow(arr[:,:,0:3])
plt.colorbar()
plt.show()
from GigE_camera_client import Camera
camera = Camera("MicroscopeCamera")
laue_image_analyser = Camera_image_analyser(name = 'LAUE_image_analyser', camera_name = 'MicroscopeCamera') #for LAUE crystalography
if __name__ == "__main__":
import logging
from tempfile import gettempdir
import logging
logfile = gettempdir() + "/logging/camera_image_analyser.log"
logger = logging.getLogger('camera_image_analyser')
hdlr = logging.FileHandler(logfile)
formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s')
hdlr.setFormatter(formatter)
logger.addHandler(hdlr)
logger.setLevel(logging.DEBUG)
self = camera_image_analyser #for testing
info('Time Start: %r' % str(datetime.now()))
<file_sep>#!/usr/bin/env python
"""
Archive EPICS process variable via Channel Access
Author: <NAME>
Date created: 10/4/2017
Date last modified: 10/5/2017
"""
__version__ = "1.0"
import wx
from Panel import BasePanel
from TimeChart import TimeChart
class ArchiveViewer(BasePanel):
name = "ArchiveViewer"
title = "Archive Viewer"
standard_view = ["Data"]
def __init__(self,PV,parent=None):
from channel_archiver import channel_archiver
log = channel_archiver.logfile(PV)
parameters = [
[[TimeChart,"Data",log,"date time","value"],{"refresh_period":2}],
]
BasePanel.__init__(self,
name=self.name,
title=self.title,
icon="Archiver",
parent=parent,
parameters=parameters,
standard_view=self.standard_view,
refresh=False,
live=False,
)
if __name__ == "__main__":
from pdb import pm # for debugging
import autoreload
import logging # for debugging
from tempfile import gettempdir
logfile = gettempdir()+"/ArchiveViewer.log"
logging.basicConfig(level=logging.DEBUG,
format="%(asctime)s %(levelname)s: %(message)s",
filename=logfile,
)
from sys import argv
if len(argv) > 1: PV = argv[1]
else: PV = "NIH:TEMP.RBV"
app = wx.App(redirect=False)
panel = ArchiveViewer(PV)
app.MainLoop()
<file_sep>"""
Dynamically refresh Python code
Author: <NAME>
Date created: 07/08/2017
Date last modified: 12/07/2017
"""
__version__ = "1.2.2" # daemon thread
from logging import debug,info,warn,error
#-----------------------------------------------------------------------------
# This code is from the IPython extension "autoreload" by <NAME>,
# based on the autoreload code by <NAME>.
# Copyright (C) 2000 <NAME>
#-----------------------------------------------------------------------------
import os
import sys
import traceback
import types
import weakref
PY3 = sys.version_info[0] == 3
if PY3:
func_attrs = ['__code__', '__defaults__', '__doc__',
'__closure__', '__globals__', '__dict__']
else:
func_attrs = ['func_code', 'func_defaults', 'func_doc',
'func_closure', 'func_globals', 'func_dict']
def update_function(old, new):
"""Upgrade the code object of a function"""
for name in func_attrs:
try:
setattr(old, name, getattr(new, name))
except (AttributeError, TypeError):
pass
def update_class(old, new):
"""Replace stuff in the __dict__ of a class, and upgrade
method code objects"""
for key in list(old.__dict__.keys()):
old_obj = getattr(old, key)
try:
new_obj = getattr(new, key)
except AttributeError:
# obsolete attribute: remove it
try:
delattr(old, key)
except (AttributeError, TypeError):
pass
continue
if update_generic(old_obj, new_obj): continue
try:
setattr(old, key, getattr(new, key))
except (AttributeError, TypeError):
pass # skip non-writable attributes
def update_property(old, new):
"""Replace get/set/del functions of a property"""
update_generic(old.fdel, new.fdel)
update_generic(old.fget, new.fget)
update_generic(old.fset, new.fset)
def isinstance2(a, b, typ):
return isinstance(a, typ) and isinstance(b, typ)
UPDATE_RULES = [
(lambda a, b: isinstance2(a, b, type),
update_class),
(lambda a, b: isinstance2(a, b, types.FunctionType),
update_function),
(lambda a, b: isinstance2(a, b, property),
update_property),
]
if PY3:
UPDATE_RULES.extend([(lambda a, b: isinstance2(a, b, types.MethodType),
lambda a, b: update_function(a.__func__, b.__func__)),
])
else:
UPDATE_RULES.extend([(lambda a, b: isinstance2(a, b, types.ClassType),
update_class),
(lambda a, b: isinstance2(a, b, types.MethodType),
lambda a, b: update_function(a.__func__, b.__func__)),
])
def update_generic(a, b):
for type_check, update in UPDATE_RULES:
if type_check(a, b):
update(a, b)
return True
return False
class StrongRef(object):
def __init__(self, obj):
self.obj = obj
def __call__(self):
return self.obj
def superreload(module, reload=reload, old_objects={}):
"""Enhanced version of the builtin reload function.
superreload remembers objects previously in the module, and
- upgrades the class dictionary of every old class in the module
- upgrades the code object of every old function and method
- clears the module's namespace before reloading
"""
# collect old objects in the module
for name, obj in list(module.__dict__.items()):
if not hasattr(obj, '__module__') or obj.__module__ != module.__name__:
continue
key = (module.__name__, name)
try:
old_objects.setdefault(key, []).append(weakref.ref(obj))
except TypeError:
# weakref doesn't work for all types;
# create strong references for 'important' cases
if not PY3 and isinstance(obj, types.ClassType):
old_objects.setdefault(key, []).append(StrongRef(obj))
# reload module
try:
# clear namespace first from old cruft
old_dict = module.__dict__.copy()
old_name = module.__name__
module.__dict__.clear()
module.__dict__['__name__'] = old_name
module.__dict__['__loader__'] = old_dict['__loader__']
except (TypeError, AttributeError, KeyError):
pass
try:
module = reload(module)
except:
# restore module dictionary on failed reload
module.__dict__.update(old_dict)
raise
# iterate over all objects and update functions & classes
for name, new_obj in list(module.__dict__.items()):
key = (module.__name__, name)
if key not in old_objects: continue
new_refs = []
for old_ref in old_objects[key]:
old_obj = old_ref()
if old_obj is None: continue
new_refs.append(old_ref)
update_generic(old_obj, new_obj)
if new_refs:
old_objects[key] = new_refs
else:
del old_objects[key]
return module
def keep_user_modules_updated():
global task
if not task or not task.isAlive():
import threading
task = threading.Thread(target=keep_user_modules_updated_task,
name="keep_user_modules_updated_task")
task.daemon = True
task.start()
task = None
def keep_user_modules_updated_task():
from time import sleep
while True:
try: update_user_modules()
except Exception,msg: error("%s\n%s" % (msg,traceback.format_exc()))
sleep(1)
def update_user_modules():
import sys
from os.path import getmtime,basename
from time import time
import traceback
modules = user_modules()
for module in modules:
filename = module.__file__.replace(".pyc",".py")
if not filename in module_file_timestamps:
module_file_timestamps[filename] = getmtime(filename)
if module_file_timestamps[filename] != getmtime(filename):
module_file_timestamps[filename] = getmtime(filename)
name = module.__name__
if name == "__main__":
module_name = basename(filename).replace(".py","")
debug("module %r is %r" % (name,module_name))
module = __import__(module_name)
module_load_timestamps[filename] = t0 = time()
try: superreload(module)
except Exception,msg: error("%s\n%s" % (msg,traceback.format_exc()))
t = time() - t0
info("reloaded module %r (%.3f s)" % (name,t))
module_file_timestamps = {}
module_load_timestamps = {}
def user_modules():
"""List of non-builtin modules"""
import sys
path = sys.path[1:] # exclude current directory
modules = []
system_modules = {}; system_modules.update(sys.modules)
for name in system_modules:
module = system_modules[name]
module_file = module.__file__ if hasattr(module,"__file__") else ""
if module_file and not any([module_file.startswith(d) for d in path]):
modules.append(module)
return modules
keep_user_modules_updated()
if __name__ == "__main__":
from pdb import pm
import logging
logging.basicConfig(level=logging.DEBUG,
format="%(asctime)s %(levelname)s: %(message)s")
##from timing_system_simulator import timing_system_simulator
##object = timing_system_simulator # for debugging
##import lauecollect
##print('outdated(getmodule(object))')
##print('object = update(object,always=True)')
##print('object = update(object)')
##print('user_modules()')
print('update_user_modules()')
print('keep_user_modules_updated()')
<file_sep>"""Temperature controller server
The server communicates with Lightwave( previously known as temperature controller IOC) and Oasis IOC to synchronize the temperature changes.
Authors: <NAME>, <NAME>
Date created: 2019-05-08
Date last modified: 2019-05-14
"""
__version__ = "0.1" # <NAME>: bug fixes
from logging import debug,warn,info,error
import os
from IOC import IOC
import traceback
from time import time,sleep
from numpy import empty, mean, std, zeros, abs, where, nan , isnan
import numpy.polynomial.polynomial as poly
from scipy.interpolate import interp1d
from CA import caget, caput
from CAServer import casput,casget,casdel
class Temperature_Server_IOC(object):
name = "temperature_server_IOC"
from persistent_property import persistent_property
prefix = persistent_property("prefix","NIH:TEMP")
SCAN = persistent_property("SCAN",0.5)
P_default = persistent_property("P_default",1.000)
I_default = persistent_property("I_default",0.316)
D_default = persistent_property("D_default",0.562)
oasis_slave = persistent_property("oasis_slave",1)
temperature_oasis_switch = persistent_property("T_threshold",83.0)
idle_temperature_oasis = persistent_property("idle_temperature_oasis",8.0)
temperature_oasis_limit_high = persistent_property("temperature_oasis_limit_high",45.0)
oasis_headstart_time = persistent_property("oasis_headstart_time",15.0)
lightwave_prefix = persistent_property("lightwave_prefix",'NIH:LIGHTWAVE')
oasis_prefix = persistent_property("oasis_prefix",'NIH:CHILLER')
set_point_update_period = persistent_property("set_point_update_period",0.5)
running = False
last_valid_reply = 0
was_online = False
ramping_cancelled = False
idle_temperature = 22.0
time_points = []
temp_points = []
def get_EPICS_enabled(self):
return self.running
def set_EPICS_enabled(self,value):
from thread import start_new_thread
if value:
if not self.running: start_new_thread(self.run,())
else: self.running = False
EPICS_enabled = property(get_EPICS_enabled,set_EPICS_enabled)
def startup(self):
from CAServer import casput,casmonitor
from CA import caput,camonitor
from numpy import nan
#self.P_default , self.I_default , self.D_default = 1.0,0.316,0.562
#print('startup with prefix = %r' %self.prefix)
casput(self.prefix+".SCAN",self.SCAN)
casput(self.prefix+".DESC",value = "Temperature server IOC: a System Layer server that orchestrates setting on Lightwave IOC and Oasis IOC.", update = False)
casput(self.prefix+".EGU",value = "C")
# Set defaults
casput(self.prefix+".VAL",value = nan)
casput(self.prefix+".VAL_ADV",value = nan)
casput(self.prefix+".RBV",value = nan)
casput(self.prefix+".P",value = nan)
casput(self.prefix+".I",value = nan)
casput(self.prefix+".TIME_POINTS",self.time_points)
casput(self.prefix+".TEMP_POINTS",self.temp_points)
casput(self.prefix+".FAULTS"," ")
casput(self.prefix+".DMOV",value = nan)
casput(self.prefix+".KILL",value = 'write password to kill the process')
casput(self.prefix+".P_default",value = self.P_default)
casput(self.prefix+".I_default",value = self.I_default)
casput(self.prefix+".D_default",value = self.D_default)
casput(self.prefix+".oasis_slave",value = self.oasis_slave)
casput(self.prefix+".temperature_oasis_switch",value = self.temperature_oasis_switch)
casput(self.prefix+".idle_temperature_oasis",value = self.idle_temperature_oasis)
casput(self.prefix+".temperature_oasis_limit_high",value = self.temperature_oasis_limit_high)
casput(self.prefix+".oasis_headstart_time",value = self.oasis_headstart_time)
casput(self.prefix+".lightwave_prefix",value = self.lightwave_prefix)
casput(self.prefix+".oasis_prefix",value = self.oasis_prefix)
casput(self.prefix+".set_point_update_period",value = self.set_point_update_period)
casput(self.prefix+".oasis_RBV",value = nan)
casput(self.prefix+".oasis_VAL",value = nan)
#PV with a list of all process variable registered at the current Channel Access Server
casput(self.prefix+".LIST_ALL_PVS",value = self.get_pv_list())
# Monitor client-writable PVs.
casmonitor(self.prefix+".VAL",callback=self.monitor)
casmonitor(self.prefix+".VAL_ADV",callback=self.monitor)
casmonitor(self.prefix+".TIME_POINTS",callback=self.monitor)
casmonitor(self.prefix+".TEMP_POINTS",callback=self.monitor)
casmonitor(self.prefix+".KILL",callback=self.monitor)
casmonitor(self.prefix+".P_default",callback=self.monitor)
casmonitor(self.prefix+".I_default",callback=self.monitor)
casmonitor(self.prefix+".D_default",callback=self.monitor)
casmonitor(self.prefix+".oasis_slave",callback=self.monitor)
casmonitor(self.prefix+".temperature_oasis_switch",callback=self.monitor)
casmonitor(self.prefix+".idle_temperature_oasis",callback=self.monitor)
casmonitor(self.prefix+".temperature_oasis_limit_high",callback=self.monitor)
casmonitor(self.prefix+".oasis_headstart_time",callback=self.monitor)
casmonitor(self.prefix+".lightwave_prefix",callback=self.monitor)
casmonitor(self.prefix+".oasis_prefix",callback=self.monitor)
casmonitor(self.prefix+".set_point_update_period",callback=self.monitor)
#############################################################################
## Monitor server-writable PVs that come other servers
## Monitor Timing system IOC
from timing_system import timing_system
camonitor(timing_system.acquiring.PV_name,callback=self.on_acquire)
## Lightwave Temperature controller server
prefix = self.lightwave_prefix
camonitor(prefix+".VAL",callback=self.lightwave_monitor)
camonitor(prefix+".RBV",callback=self.lightwave_monitor)
camonitor(prefix+".P",callback=self.lightwave_monitor)
camonitor(prefix+".I",callback=self.lightwave_monitor)
camonitor(prefix+".DMOV",callback=self.lightwave_monitor)
## Oasis chiller server
prefix = self.oasis_prefix
camonitor(prefix+".VAL",callback=self.oasis_monitor)
camonitor(prefix+".RBV",callback=self.oasis_monitor)
## Create local circular buffers
from circular_buffer_LL import Server
self.buffers = {}
self.buffers['oasis_RBV'] = Server(size = (2,1*3600*2) , var_type = 'float64')
self.buffers['oasis_VAL'] = Server(size = (2,1*3600*2) , var_type = 'float64')
self.buffers['oasis_FAULTS'] = Server(size = (2,1*3600*2) , var_type = 'float64')
self.buffers['lightwave_RBV'] = Server(size = (2,1*3600*2) , var_type = 'float64')
self.buffers['lightwave_P'] = Server(size = (2,1*3600*2) , var_type = 'float64')
self.buffers['lightwave_I'] = Server(size = (2,1*3600*2) , var_type = 'float64')
self.buffers['lightwave_VAL'] = Server(size = (2,1*3600*2) , var_type = 'float64')
def update_once(self):
from CAServer import casput
from numpy import isfinite,isnan,nan
from time import time
from sleep import sleep
pass
def run(self):
"""Run EPICS IOC"""
self.startup()
self.running = True
while self.running:
sleep(0.1)
self.running = False
def start(self):
"""Run EPCIS IOC in background"""
from threading import Thread
task = Thread(target=self.run,name="temperature_server_IOC.run")
task.daemon = True
task.start()
def shutdown(self):
from CAServer import casdel
print('SHUTDOWN command received')
self.running = False
casdel(self.prefix)
del self
def get_pv_list(self):
from CAServer import PVs
lst = list(PVs.keys())
#lst_new = []
#for item in lst:
# lst_new.append(item.replace(self.prefix,'').replace('.',''))
return lst#lst_new
def monitor(self,PV_name,value,char_value):
"""Process PV change requests"""
from CAServer import casput
from CA import caput
print("monitor: %s = %r" % (PV_name,value))
if PV_name == self.prefix+".VAL_ADV":
if self.get_set_lightwaveT() != value or self.get_set_oasisT() != self.temp_to_oasis(value):
self.set_T(value)
if PV_name == self.prefix+".VAL":
if self.get_set_lightwaveT() != value or self.get_set_oasisT() != self.temp_to_oasis(value):
self.set_adv_T(value)
if PV_name == self.prefix + ".oasis_VAL":
if self.get_set_oasisT() != value:
self.set_set_oasisT(value)
if PV_name == self.prefix + ".TIME_POINTS":
self.time_points = value
if PV_name == self.prefix + ".TEMP_POINTS":
self.temp_points = value
if PV_name == self.prefix + ".KILL":
if value == 'shutdown':
self.shutdown()
if PV_name == self.prefix + ".P_default":
self.P_default = value
self.set_PIDCOF((self.P_default,self.I_default,self.D_default))
if PV_name == self.prefix + ".I_default":
self.I_default = value
self.set_PIDCOF((self.P_default,self.I_default,self.D_default))
if PV_name == self.prefix + ".D_default":
self.D_default = value
self.set_PIDCOF((self.P_default,self.I_default,self.D_default))
if PV_name == self.prefix + ".oasis_slave":
self.oasis_slave = value
if PV_name == self.prefix + ".temperature_oasis_switch":
self.temperature_oasis_switch = value
if PV_name == self.prefix + ".idle_temperature_oasis":
self.idle_temperature_oasis = value
if PV_name == self.prefix + ".temperature_oasis_limit_high":
self.temperature_oasis_limit_high = value
if PV_name == self.prefix + ".oasis_headstart_time":
self.oasis_headstart_time = value
if PV_name == self.prefix + ".lightwave_prefix":
self.lightwave_prefix = value
if PV_name == self.prefix + ".oasis_prefix":
self.oasis_prefix = value
if PV_name == self.prefix + ".set_point_update_period":
self.set_point_update_period = value
def lightwave_monitor(self,PV_name,value,char_value):
#print('time: %r, PV_name = %r,value= %r,char_value = %r' %(time(),PV_name,value,char_value) )
from CA import cainfo
from CAServer import casput
prefix = self.lightwave_prefix
if PV_name == prefix+".VAL":
arr = empty((2,1))
arr[0] = cainfo(prefix+".VAL","timestamp")
arr[1] = float(value)
self.buffers['lightwave_VAL'].append(arr)
casput(self.prefix +'.VAL',value = float(value))
if PV_name == prefix+".RBV":
arr = empty((2,1))
arr[0] = cainfo(prefix+".RBV","timestamp")
arr[1] = float(value)
self.buffers['lightwave_RBV'].append(arr)
casput(self.prefix +'.RBV',value = float(value))
if PV_name == prefix+".P":
arr = empty((2,1))
arr[0] = cainfo(prefix+".P","timestamp")
arr[1] = float(value)
self.buffers['lightwave_P'].append(arr)
casput(self.prefix +'.P',value = float(value))
if PV_name == prefix+".I":
arr = empty((2,1))
arr[0] = cainfo(prefix+".I","timestamp")
arr[1] = float(value)
self.buffers['lightwave_I'].append(arr)
casput(self.prefix +'.I',value = float(value))
#Done Move PV
if PV_name == prefix+".DMOV":
casput(self.prefix +'.DMOV',value = float(value))
def oasis_monitor(self,PV_name,value,char_value):
#print('oasis_monitor: time: %r, PV_name = %r,value= %r,char_value = %r' %(time(),PV_name,value,char_value) )
from CA import cainfo
prefix = self.oasis_prefix
if PV_name == prefix+".VAL":
arr = empty((2,1))
arr[0] = cainfo(prefix+".VAL","timestamp")
arr[1] = float(value)
self.buffers['oasis_VAL'].append(arr)
casput(self.prefix +'.oasis_VAL',value = float(value))
if PV_name == prefix+".RBV":
arr = empty((2,1))
arr[0] = cainfo(prefix+".RBV","timestamp")
arr[1] = float(value)
self.buffers['oasis_RBV'].append(arr)
casput(self.prefix +'.oasis_RBV',value = float(value))
## Temperature trajectory
def on_acquire(self):
"""
starts T-Ramp.
Usually called from monitor()
"""
print('on acquire')
self.ramping = self.acquiring
self.start_ramping()
def start_ramping(self):
"""
starts T-Ramp run_ramping_once method in a separate thread
"""
from thread import start_new_thread
start_new_thread(self.run_ramping_once,())
def run_ramping_once(self):
"""
runs ramping trajectory defined by self.time_points and self.temperatures
"""
from time_string import date_time
info("Ramp start time: %s" % date_time(self.start_time))
from time import time,sleep
from numpy import where, asarray
if len(self.temperatures) != 0:
max_set_T = max(self.temperatures)
min_set_T = min(self.temperatures)
else:
min_set_T = nan
max_set_T = nan
for (t,T, grad_T) in zip(self.times,self.temperatures,self.grad_temperatures):
dt = self.start_time + t - time()
if dt > 0:
sleep(dt)
current_setT = self.get_setT()
debug('t = %r, T = %r,dt = %r' %(t,T,dt))
if len(self.temp_points)>0:
self.set_ramp_T(T)
else:
info("The TEMP_POINTS list is empty. No temperature to set in the temperature trajectory.")
# if T == max_set_T or T == min_set_T:
# self.set_PIDCOF((self.P_default,self.I_default,self.D_default))
# else:
# (self.P_default,0.0,0.0)
# if grad_T > 0:
# self.set_PIDCOF((self.proportional_vs_sample_temperature(T,'up'),0.0,0.0))
# elif grad_T < 0:
# self.set_PIDCOF((self.proportional_vs_sample_temperature(T,'down'),0.0,0.0))
# else:
# self.set_PIDCOF((self.P_default,0.0,0.0))
try:
indices = where(self.times >= t+self.oasis_headstart_time)[0][0:1]
debug('current index in the trajectory = %r' %indices)
if len(indices) > 0:
idx = indices[0]
self.set_set_oasisT(self.oasis_temperatures[idx])
debug('time = %r, oasis T = %r' %(t,self.temp_to_oasis(self.temperatures[idx])))
except:
error(traceback.format_exc())
if self.ramping_cancelled: break
info("Ramp ended")
self.set_PIDCOF((self.P_default,self.I_default,self.D_default))
self.ramping_cancelled = False
self.ramping = False
@property
def acquiring(self):
from timing_system import timing_system
return timing_system.acquiring.value
@property
def start_time(self):
from numpy import nan
start_time = nan
from timing_system import timing_system
if timing_system.acquiring.value == 1:
from CA import cainfo
start_time = cainfo(timing_system.acquiring.PV_name,"timestamp")
return start_time
@property
def times(self):
"""
converts self.time_points to an array of values with specified spacing (readT_time_spacing0
"""
from numpy import arange,concatenate
min_dt = self.set_point_update_period
times = [[]]
for i in range(0,len(self.time_points)-1):
T0,T1 = self.time_points[i],self.time_points[i+1]
DT = T1-T0
N = max(int(DT/min_dt),1)
dt = DT/N
T = T0 + arange(0,N)*dt
times.append(T)
if len(self.time_points) > 0:
times.append([self.time_points[-1]])
times = concatenate(times)
return times
@property
def temperatures(self):
temperatures = []
time_points = self.time_points[0:self.N_points]
temp_points = self.temp_points[0:self.N_points]
if len(temp_points) > 1:
from scipy.interpolate import interp1d
f = interp1d(time_points,temp_points, kind='linear',bounds_error=False)
temperatures = f(self.times)
if len(temp_points) == 1:
from numpy import array
temperatures = array(temp_points)
return temperatures
@property
def grad_temperatures(self):
from numpy import gradient,array
temp_points = self.temp_points[0:self.N_points]
if len(temp_points) > 1:
grad = gradient(self.temperatures)
else:
grad = array([0])
return grad
@property
def oasis_temperatures(self):
from numpy import max
if len(self.temperatures) == 0:
t_oasis = []
else:
temp_points = self.temperatures
first_temp = self.temperatures[0]
max_temp = max(temp_points)
t_oasis = []
idx = 0
for temp in temp_points:
oasis_temp = self.temp_to_oasis(temp)
if max_temp >=self.temperature_oasis_switch:
if idx <=1:
t_oasis.append(oasis_temp)
elif idx > 1:
if temp > temp_points[idx-1] and temp_points[idx-1] > temp_points[idx-2]:
t_oasis.append(self.temperature_oasis_limit_high)
elif temp < temp_points[idx-1] and temp_points[idx-1] < temp_points[idx-2]:
t_oasis.append(self.idle_temperature_oasis)
else:
t_oasis.append(t_oasis[idx-2])
else:
t_oasis.append(oasis_temp)
idx +=1
return t_oasis
@property
def oasis_times(self):
time_points = self.times
time_oasis = []
for time in time_points:
time_oasis.append(time - self.oasis_dl.headstart_time)
return time_oasis
@property
def N_points(self):
return min(len(self.time_points),len(self.temp_points))
def get_setT(self):
value = self.buffers['lightwave_VAL'].get_last_N(N = 1)[1,0]
return value
def set_setT(self,value):
debug("set_point = %r" % value)
value = float(value)
if self.get_setT() != value:
self.lightwave_dl.set_cmdT(value)
self.oasis_dl.set_cmdT(self.temp_to_oasis(value))
setT = property(get_setT,set_setT)
def get_lightwaveT(self):
value = self.buffers['lightwave_RBV'].get_last_N(N = 1)[1,0]
return value
lightwaveT = property(get_lightwaveT)
def get_set_lightwaveT(self):
value = self.buffers['lightwave_VAL'].get_last_N(N = 1)[1,0]
return value
def set_set_lightwaveT(self,value):
from CA import caput, cawait
from numpy import isnan
if value is not isnan:
caput(self.lightwave_prefix + '.VAL', value = float(value))
cawait(self.lightwave_prefix + '.VAL')
set_lightwaveT = property(get_set_lightwaveT,set_set_lightwaveT)
def get_oasisT(self):
value = self.buffers['oasis_RBV'].get_last_N(N = 1)[1,0]
return value
oasisT = property(get_oasisT)
def get_set_oasisT(self):
value = self.buffers['oasis_VAL'].get_last_N(N = 1)[1,0]
return value
def set_set_oasisT(self,value):
from CA import caput
from numpy import isnan
if self.get_set_oasisT() != float(value):
if value is not isnan:
caput(self.oasis_prefix+'.VAL', value = float(value))
set_oasisT = property(get_set_oasisT,set_set_oasisT)
def set_T(self,value):
value = float(value)
if value != self.get_set_lightwaveT() or self.temp_to_oasis(value) != self.get_set_oasisT():
if self.oasis_slave:
self.set_set_oasisT(self.temp_to_oasis(value))
self.set_set_lightwaveT(value)
def set_ramp_T(self,value):
value = float(value)
if value != self.get_lightwaveT():
self.set_set_lightwaveT(value)
def set_adv_T(self,value):
value = float(value)
if value != self.get_lightwaveT() or self.temp_to_oasis(value) != self.get_set_oasisT() :
self.set_set_oasisT(self.temp_to_oasis(value))
self.set_PIDCOF((self.P_default,0.0,self.D_default))
self.set_set_lightwaveT(value)
info('set_set_lightwaveT %r at %r' %(value , time()))
info(abs(self.get_lightwaveT() - self.get_set_lightwaveT()))
if value >= self.temperature_oasis_switch:
t_diff = 3.0
else:
t_diff = 3.0
timeout = abs(self.get_lightwaveT() - self.get_set_lightwaveT())*1.5
t1 = time()
while abs(self.get_lightwaveT() - self.get_set_lightwaveT()) > t_diff:
sleep(0.05)
if time() - t1 > timeout:
break
self.set_PIDCOF((self.P_default,self.I_default,self.D_default))
def set_PCOF(self,value):
from CA import caput, cawait
if self.get_PCOF() != value:
caput(self.lightwave_prefix + '.PCOF',value)
cawait(self.lightwave_prefix + '.PCOF')
def get_PCOF(self):
from CA import caget
value = caget(self.lightwave_prefix + '.PCOF')
return value
def set_ICOF(self,value):
from CA import caput, cawait
if self.get_ICOF() != value:
caput(self.lightwave_prefix + '.ICOF',value)
cawait(self.lightwave_prefix + '.ICOF')
def get_ICOF(self):
from CA import caget
value = caget(self.lightwave_prefix + '.ICOF')
return value
def set_DCOF(self,value):
from CA import caput,cawait
if self.get_DCOF() != value:
caput(self.lightwave_prefix + '.DCOF',value)
cawait(self.lightwave_prefix + '.DCOF')
def get_DCOF(self):
from CA import caget
value = caget(self.lightwave_prefix + '.DCOF')
return value
def set_PIDCOF(self,value):
from CA import caput,cawait
if self.get_PIDCOF() != value:
print('setting PIDCOF: %r -> %r' %(self.get_PIDCOF(),value))
caput(self.lightwave_prefix + '.PIDCOF',value)
cawait(self.lightwave_prefix + '.PIDCOF')
def get_PIDCOF(self):
from CA import caget
value = caget(self.lightwave_prefix + '.PIDCOF')
return value
def temp_to_oasis(self,T, mode = 'bistable'):
if mode == 'bistable':
if T >= self.temperature_oasis_switch:
t = self.temperature_oasis_limit_high
else:
t = self.idle_temperature_oasis
else:
oasis_min = t_min= self.idle_temperature_oasis
oasis_max = t_max = self.temperature_oasis_limit_high
T_max= 120.0
T_min= -16
if T <=T_max or T >=T_min:
t = ((T-T_min)/(T_max-T_min))*(t_max-t_min) + t_min
elif T>T_max:
t = self.temperature_oasis_limit_high
elif T<T_min:
t = self.idle_temperature_oasis
if self.oasis_slave:
return round(t,1)
else:
return self.idle_temperature_oasis
def proportional_vs_sample_temperature(self, temperature = 0.0, direction = ''):
T = temperature
if direction == 'down':
P = 4e-8*T**4 - 1e-5*T**3 + 0.0012*T**2 - 0.0723*T + 3.3001
elif direction == 'up':
P = 7e-9*T**4 - 3e-6*T**3 + 0.0004*T**2 - 0.0003*T + 1.6942
else:
P = self.P_default
return round(P,3)
temperature_server_IOC = Temperature_Server_IOC()
if __name__ == "__main__":
import logging
logging.basicConfig(level=logging.INFO,
format="%(asctime)s %(levelname)s %(module)s.%(funcName)s: %(message)s",
)
from timing_sequencer import timing_sequencer
print("timing_sequencer.queue_active = %r" % timing_sequencer.queue_active)
print("timing_sequencer.queue_active = False # cancel acquistion")
print("timing_sequencer.queue_active = True # simulate acquistion")
print("timing_sequencer.queue_repeat_count = 0 # restart acquistion")
print("timing_sequencer.queue_active = True # simulate acquistion")
print("self.start_time = time(); self.start_ramping()")
self = temperature_server_IOC
##from matplotlib import pyplot as plt
self.time_points = [0.0,30.0,302.0,332.0,634.0,30.0+634.0,302.0+634.0,332.0+634.0,634.0+634.0]
self.temp_points = [-16,-16,120,120,-16,-16,120,120,-16]
##print("self.lightwave_dl.driver.feedback_loop.PID = (1.0, 0.300000012, 0.561999977)")
##print('plt.plot(self.times,self.temperatures); plt.plot(self.oasis_times,self.oasis_temperatures); plt.show()')
##plt.plot(self.times,self.temperatures); plt.plot(self.oasis_times,self.oasis_temperatures); plt.show()
<file_sep>"""
General diffractometer module
<NAME>, 27 Feb 2013 - 31 Jan 2016
"""
__version__ = "1.1"
from DB import dbget,dbput
class Diffractometer(object):
"""General diffractometer with hardware intedendent degrees of freedom
x: horizontal translation in X-ray beam direction
y: vertical translation orthogonal to X-ray beam direction
z: horizonal translation orthogonal to X-ray beam direction
phi: rotation around z axis
"""
def __init__(self):
self.cache = {}
# Horizontal translation in X-ray beam direction
self.X = self.Motor(self,"x")
# Vertical translation orthogonal to X-ray beam direction
self.Y = self.Motor(self,"y")
# Horizonal translation orthogonal to X-ray beam direction
self.Z = self.Motor(self,"z")
# Rotation around z axis
self.Phi = self.Motor(self,"phi")
# Object-specific offset from the rotation axis
self.ClickCenterX = self.Motor(self,"click_center_x")
# Object-specific offset from the rotation axis
self.ClickCenterY = self.Motor(self,"click_center_y")
self.ClickCenterZ = self.Motor(self,"click_center_z")
def get_x_motor_name(self):
try: return eval(dbget("sample.x_motor_name"))
except: return "GonX"
def set_x_motor_name(self,name): dbput("sample.x_motor_name",repr(name))
x_motor_name = property(get_x_motor_name,set_x_motor_name)
def get_y_motor_name(self):
try: return eval(dbget("sample.y_motor_name"))
except: return "GonY"
def set_y_motor_name(self,name): dbput("sample.y_motor_name",repr(name))
y_motor_name = property(get_y_motor_name,set_y_motor_name)
def get_z_motor_name(self):
try: return eval(dbget("sample.z_motor_name"))
except: return "GonZ"
def set_z_motor_name(self,name): dbput("sample.z_motor_name",repr(name))
z_motor_name = property(get_z_motor_name,set_z_motor_name)
def get_phi_motor_name(self):
try: return eval(dbget("sample.phi_motor_name"))
except: return "Phi"
def set_phi_motor_name(self,name):
dbput("sample.phi_motor_name",repr(name))
phi_motor_name = property(get_phi_motor_name,set_phi_motor_name)
def motor(self,name):
if not name in self.cache: self.cache[name] = motor(name)
return self.cache[name]
@property
def x_hardware_motor(self):
"""Translation hardware motor"""
return self.motor(self.x_motor_name)
@property
def y_hardware_motor(self):
"""Translation hardware motor"""
return self.motor(self.y_motor_name)
@property
def z_hardware_motor(self):
"""Translation hardware motor"""
return self.motor(self.z_motor_name)
@property
def phi_hardware_motor(self):
"""Translation hardware motor"""
return self.motor(self.phi_motor_name)
@property
def hardware_motors(self):
"""List of Motor objects"""
return [self.x_hardware_motor,self.y_hardware_motor,
self.z_hardware_motor,self.phi_hardware_motor]
def get_xy_rotating(self):
"""Do the hardware X and Y motors rotate with the PHI rotation stage?"""
return dbget("sample.xy_rotating") == "True"
def set_xy_rotating(self,value):
dbput("sample.xy_rotating",repr(value))
xy_rotating = property(get_xy_rotating,set_xy_rotating)
def get_x_scale(self):
"""Scale factor to apply to the hardware X translation motor"""
try: return float(dbget("sample.x_scale"))
except ValueError: return 1.0
def set_x_scale(self,value): dbput("sample.x_scale",repr(float(value)))
x_scale = property(get_x_scale,set_x_scale)
def get_y_scale(self):
"""Scale factor to apply to the hardware Y translation motor"""
try: return float(dbget("sample.y_scale"))
except ValueError: return 1.0
def set_y_scale(self,value): dbput("sample.y_scale",repr(float(value)))
y_scale = property(get_y_scale,set_y_scale)
def get_z_scale(self):
"""Scale factor to apply to the hardware Z translation motor"""
try: return float(dbget("sample.z_scale"))
except ValueError: return 1.0
def set_z_scale(self,value): dbput("sample.z_scale",repr(float(value)))
z_scale = property(get_z_scale,set_z_scale)
def get_phi_scale(self):
"""Scale factor to apply to the hardware Phi rotation motor"""
try: return float(dbget("sample.phi_scale"))
except ValueError: return 1.0
def set_phi_scale(self,value): dbput("sample.phi_scale",repr(float(value)))
phi_scale = property(get_phi_scale,set_phi_scale)
def get_rotation_center_x(self):
"""To which position do you have to drive the X motor for the rotation
axis to be in the crosshair of both cameras?"""
try: x,y = eval(dbget("sample.rotation_center"))
except: return 0.0
return x
def set_rotation_center_x(self,value):
x,y = self.rotation_center_x,self.rotation_center_y
x = value
dbput("sample.rotation_center",repr((x,y)))
rotation_center_x = property(get_rotation_center_x,set_rotation_center_x)
def get_rotation_center_y(self):
"""To which position do you have to drive the Y motor for the rotation
axis to be in the crosshair of both cameras?"""
try: x,y = eval(dbget("sample.rotation_center"))
except: return 0.0
return y
def set_rotation_center_y(self,value):
x,y = self.rotation_center_x,self.rotation_center_y
y = value
dbput("sample.rotation_center",repr((x,y)))
rotation_center_y = property(get_rotation_center_y,set_rotation_center_y)
def get_click_center_x(self):
try: return float(dbget("sample.click_center_x"))
except: return 0.0
def set_click_center_x(self,value):
dbput("sample.click_center_x",repr(float(value)))
click_center_x = property(get_click_center_x,set_click_center_x)
def get_click_center_y(self):
try: return float(dbget("sample.click_center_y"))
except: return 0.0
def set_click_center_y(self,value):
dbput("sample.click_center_y",repr(float(value)))
click_center_y = property(get_click_center_y,set_click_center_y)
def get_click_center_z(self):
try: return float(dbget("sample.click_center_z"))
except: return 0.0
def set_click_center_z(self,value):
dbput("sample.click_center_z",repr(float(value)))
click_center_z = property(get_click_center_z,set_click_center_z)
def get_calibration_z(self):
try: return float(dbget("sample.calibration_z"))
except: return 0.0
def set_calibration_z(self,value):
dbput("sample.calibration_z",repr(float(value)))
calibration_z = property(get_calibration_z,set_calibration_z)
def diffractometer_xy(self,x,y,phi):
"""Transform from hardware motor positions to diffractometer coordinates.
x,y,phi: hardware motor positions
Return value: (x,y)"""
from numpy import sin,cos,radians
rx,ry = self.rotation_center_x,self.rotation_center_y
cx,cy = self.click_center_x,self.click_center_y
sx,sy = self.x_scale,self.y_scale
phip = self.diffractometer_phi(phi)
phir = phip if self.xy_rotating else 0
xp = sx*(x-rx)*cos(radians(phir)) - sy*(y-ry)*sin(radians(phir))
yp = sx*(x-rx)*sin(radians(phir)) + sy*(y-ry)*cos(radians(phir))
# Offset of the sample with respect to the rotation axis.
dx = cx*cos(radians(phip)) + cy*sin(radians(phip))
dy = -cx*sin(radians(phip)) + cy*cos(radians(phip))
xp -= dx
yp -= dy
return xp,yp
def hardware_xy(self,xp,yp,phip):
"""Transform from diffractometer coordinates to hardware motor positions.
xp,yp: hardware-independent diffractometer coordinates
phip: hardware-independent diffractometer phi
Return value: (x,y)"""
from numpy import sin,cos,radians
rx,ry = self.rotation_center_x,self.rotation_center_y
cx,cy = self.click_center_x,self.click_center_y
sx,sy = self.x_scale,self.y_scale
# Offset of the sample with respect to the rotation axis.
dx = cx*cos(radians(phip)) + cy*sin(radians(phip))
dy = -cx*sin(radians(phip)) + cy*cos(radians(phip))
phir = phip if self.xy_rotating else 0
x = ( (xp+dx)*cos(radians(phir)) + (yp+dy)*sin(radians(phir))) / sx + rx
y = (-(xp+dx)*sin(radians(phir)) + (yp+dy)*cos(radians(phir))) / sy + ry
return x,y
def sample_center_xyz(self,phi):
"""Where does the sample need to be translated such that the current
center is on the crosshair?
Return value: SampleX.value,SampleY.value"""
from numpy import degrees,arctan2,sqrt,sin,cos,radians
x0,y0 = self.click_center_x,self.click_center_y
r = sqrt(x0**2+y0**2)
phi0 = degrees(arctan2(-y0,x0)) % 360
phi1 = (phi0 + phi) % 360
dx = r*cos(radians(phi1))
dy = -r*sin(radians(phi1))
cx,cy = self.rotation_center_x,self.rotation_center_y
x,y = cx+dx,cy+dy
z = self.click_center_z + self.calibration_z
return x,y,z
def xyz_of_sample(self,(sample_x,sample_y,sample_z),phi):
"""Where does the sample need to be translated such that the current
center is on the crosshair?
sample_x,sample_y,sample_z: sample coordinates with respect the
rotation axis of the phi motor
Return value: SampleX.value,SampleY.value,SampleZ.value"""
from numpy import degrees,arctan2,sqrt,sin,cos,radians
x0,y0 = sample_x,sample_y
r = sqrt(x0**2+y0**2)
phi0 = degrees(arctan2(-y0,x0)) % 360
phi1 = (phi0 + phi) % 360
dx = r*cos(radians(phi1))
dy = -r*sin(radians(phi1))
cx,cy = self.rotation_center_x,self.rotation_center_y
x,y = cx+dx,cy+dy
z = sample_z + self.calibration_z
return x,y,z
def z_of_sample(self,sample_z):
"""Where does the sample need to be translated such that the current
center is on the crosshair?
sample_z:
Return value: SampleZ.value"""
z = sample_z + self.calibration_z
return z
def diffractometer_z(self,z):
"""Transform from hardware motor positions to diffractometer."""
return z*self.z_scale
def hardware_z(self,z):
"""Transform from diffractometer to hardware motor positions."""
return z/self.z_scale
def diffractometer_phi(self,phi):
"""Transform from hardware motor positions to diffractometer."""
return phi*self.phi_scale
def hardware_phi(self,phi):
"""Transform from diffractometer to hardware motor positions."""
return phi/self.phi_scale
def get_xy(self):
"""Horizontal translation in X-ray beam direction and vertical
translation"""
x = self.x_hardware_motor.value
y = self.y_hardware_motor.value
phi = self.phi_hardware_motor.value
xp,yp = self.diffractometer_xy(x,y,phi)
return xp,yp
def set_xy(self,(xp,yp)):
phi = self.phi_hardware_motor.command_value
phip = self.diffractometer_phi(phi)
x,y = self.hardware_xy(xp,yp,phip)
self.x_hardware_motor.command_value = x
self.y_hardware_motor.command_value = y
xy = property(get_xy,set_xy)
def get_xyc(self):
"""Target (command) value of horizontal translation in X-ray beam
direction."""
x = self.x_hardware_motor.command_value
y = self.y_hardware_motor.command_value
phi = self.phi_hardware_motor.command_value
xp,yp = self.diffractometer_xy(x,y,phi)
return xp,yp
xyc = property(get_xyc,set_xy)
def get_x(self):
"""Horizontal translation in X-ray beam direction."""
x = self.x_hardware_motor.value
y = self.y_hardware_motor.value
phi = self.phi_hardware_motor.value
xp,yp = self.diffractometer_xy(x,y,phi)
return xp
def set_x(self,value):
x = self.x_hardware_motor.command_value
y = self.y_hardware_motor.command_value
phi = self.phi_hardware_motor.command_value
xp,yp = self.diffractometer_xy(x,y,phi)
xp = value
phip = self.diffractometer_phi(phi)
x,y = self.hardware_xy(xp,yp,phip)
self.x_hardware_motor.command_value = x
self.y_hardware_motor.command_value = y
x = property(get_x,set_x)
def get_xc(self):
"""Target (command) value of horizontal translation in X-ray beam
direction."""
x = self.x_hardware_motor.command_value
y = self.y_hardware_motor.command_value
phi = self.phi_hardware_motor.command_value
xp,yp = self.diffractometer_xy(x,y,phi)
return xp
xc = property(get_xc,set_x)
def get_y(self):
"""Vertical translation orthogonal to the X-ray beam direction."""
x = self.x_hardware_motor.value
y = self.y_hardware_motor.value
phi = self.phi_hardware_motor.value
xp,yp = self.diffractometer_xy(x,y,phi)
return yp
def set_y(self,value):
x = self.x_hardware_motor.command_value
y = self.y_hardware_motor.command_value
phi = self.phi_hardware_motor.command_value
xp,yp = self.diffractometer_xy(x,y,phi)
yp = value
phip = self.diffractometer_phi(phi)
x,y = self.hardware_xy(xp,yp,phip)
self.x_hardware_motor.command_value = x
self.y_hardware_motor.command_value = y
y = property(get_y,set_y)
def get_yc(self):
"""Target (command) value of vertical translation orthogonal to the
X-ray beam direction."""
x = self.x_hardware_motor.command_value
y = self.y_hardware_motor.command_value
phi = self.phi_hardware_motor.command_value
xp,yp = self.diffractometer_xy(x,y,phi)
return yp
yc = property(get_yc,set_y)
def get_z(self):
"""Horizontal translation orthogonal to the X-ray beam direction."""
return self.diffractometer_z(self.z_hardware_motor.value)
def set_z(self,value):
self.z_hardware_motor.command_value = self.hardware_z(value)
z = property(get_z,set_z)
def get_zc(self):
"""Target (command) value of horizontal translation orthogonal to the
X-ray beam direction."""
return self.diffractometer_z(self.z_hardware_motor.command_value)
zc = property(get_zc,set_z)
def get_phi(self):
"""Horizontal translation orthogonal to the X-ray beam direction."""
return self.diffractometer_phi(self.phi_hardware_motor.value)
def set_phi(self,value):
self.phi_hardware_motor.command_value = self.hardware_phi(value)
phi = property(get_phi,set_phi)
def get_phic(self):
"""Target (command) value of horizontal translation orthogonal to the
X-ray beam direction."""
return self.diffractometer_phi(self.phi_hardware_motor.command_value)
phic = property(get_phic,set_phi)
def get_phi_moving(self):
"""Is the motor moving?"""
return self.phi_hardware_motor.moving
def set_phi_moving(self,value):
"""value: False = stop motors"""
self.phi_hardware_motor.moving = value
phi_moving = property(get_phi_moving,set_phi_moving)
def get_z_moving(self):
"""Is the motor moving?"""
return self.z_hardware_motor.moving
def set_z_moving(self,value):
"""value: False = stop motors"""
self.z_hardware_motor.moving = value
z_moving = property(get_z_moving,set_z_moving)
def get_x_moving(self):
"""Is the motor moving?"""
return self.x_hardware_motor.moving or self.y_hardware_motor.moving
def set_x_moving(self,value):
"""value: False = stop motors"""
self.x_hardware_motor.moving = value
self.y_hardware_motor.moving = value
x_moving = property(get_x_moving,set_x_moving)
def get_y_moving(self):
"""Is the motor moving?"""
return self.x_hardware_motor.moving or self.y_hardware_motor.moving
def set_y_moving(self,value):
"""value: False = stop motors"""
self.x_hardware_motor.moving = value
self.y_hardware_motor.moving = value
y_moving = property(get_y_moving,set_y_moving)
def get_moving(self):
"""Is any of the hardware motors moving?"""
for m in self.hardware_motors:
if m.moving: return True
return False
def set_moving(self,value):
"""value: False = stop motors"""
for m in self.hardware_motors: m.moving = value
moving = property(get_moving,set_moving)
def stop(self):
"""Abort all active motion of the hardware motors"""
self.moving = False
class Motor(object):
def __init__(self,diffractometer,name):
self.diffractometer = diffractometer
self.name = name
def get_value(self): return getattr(self.diffractometer,self.name)
def get_command_value(self):
if hasattr(self.diffractometer,self.name+"c"):
return getattr(self.diffractometer,self.name+"c")
else: return self.value
def set_value(self,value): setattr(self.diffractometer,self.name,value)
value = property(get_value,set_value)
command_value = property(get_value,set_value)
def get_moving(self):
if hasattr(self.diffractometer,self.name+"_moving"):
return getattr(self.diffractometer,self.name+"_moving")
else: return False
def set_moving(self,value):
if hasattr(self.diffractometer,self.name+"_moving"):
setattr(self.diffractometer,self.name+"_moving",value)
moving = property(get_moving,set_moving)
def stop(self): self.moving = False
def get_unit(self):
if "phi" in self.name.lower(): return "deg"
else: return "mm"
unit = property(get_unit)
speed = 1.0
def __repr__(self): return "diffractometer.Motor(\""+self.name+"\")"
def motor(name):
"""name: EPICS PV or Python motor defined in 'id14.py'"""
if not ":" in name:
exec("from id14 import *")
try: return eval(name)
except: pass
from EPICS_motor import motor
return motor(name)
diffractometer = Diffractometer()
if __name__ == "__main__": # for testing
self = diffractometer # for debugging
print 'diffractometer.sample_center_xyz(diffractometer.phi)'
<file_sep>values[4].filename = '//mx340hs/data/anfinrud_1906/Archive/NIH.ENSEMBLE.values[4].txt'<file_sep>__version__ = "1.0"
if __name__ == "__main__":
from pdb import pm # for debugging
from timing_system import *
from Ensemble_SAXS import Ensemble_SAXS
from numpy import arange,vectorize
from time import time # for timing
from numpy import *
import logging
logging.basicConfig(level=logging.DEBUG,format="%(asctime)s: %(message)s")
##import timing_system; timing_system.DEBUG = True
@vectorize
def round(x,n): return float(("%."+str(n)+"g") % x)
timepoints = round(10**arange(-9,-3+1e-6,0.25),3)
laser_modes = [0,1]
delays = array([x for x in timepoints for l in laser_modes])
laser_on = laser_modes*len(timepoints)
xray_on = [1]*2*len(timepoints)
modes = [Ensemble_SAXS.delay_mode(d) for d in delays]
waitts = [Ensemble_SAXS.delay_waitt(d) for d in delays]
pst_delay_count = rint(delays/(0.5/bcf))
N = len(delays)
n = 1000
xray_on_2 = zeros((N*n),int); xray_on_2[0:-1:n] = xray_on
laser_on_2 = zeros((N*n),int); laser_on_2[0:-1:n] = laser_on
pst_delay_count_2 = zeros((N*n),int); pst_delay_count_2[0:-1:n] = pst_delay_count
variables,value_lists = [],[]
variables += [timing_system.xosct_enable]; value_lists += [xray_on_2]
variables += [timing_system.pst_enable]; value_lists += [laser_on_2]
variables += [timing_system.pst_delay]; value_lists += [pst_delay_count_2]
for l in value_lists: l += [0] # After last image, turn everything off.
data = sequencer_stream(variables,value_lists)
print 'timing_system.ip_address = %r' % timing_system.ip_address
print 'timing_sequencer.set_sequence(variables,value_lists,1)'
print 'timing_sequencer.add_sequence(variables,value_lists,1)'
print 'timing_sequencer.enabled'
print 'timing_sequencer.running'
print 'timing_sequencer.queue'
print 'timing_sequencer.clear_queue()'
print 'timing_sequencer.abort()'
print 'timing_system.xosct_enable.count = 0'
<file_sep>"""Platform-indepedent way to generate sound.
<NAME>, 2 Jul 2010
Need to install the package PyAudio from people.csail.mit.edu/hubert/pyaudio
"""
def play_sound(filename):
# based on people.csail.mit.edu/hubert/pyaudio/#examples
try: import pyaudio
except ImportError:
print "pyaudio module not found. Sound not played."; return
import wave
from os.path import exists
if not exists(filename):
print "%s: file not found. Sound not played" % filename; return
wf = wave.open(filename,"rb")
p = pyaudio.PyAudio()
# open stream
stream = p.open(format = p.get_format_from_width(wf.getsampwidth()),
channels = wf.getnchannels(),rate = wf.getframerate(),output = True)
# read data
chunk = 1024
data = wf.readframes(chunk)
# play stream
while data != '':
stream.write(data)
data = wf.readframes(chunk)
stream.close()
p.terminate()
def module_dir():
"directory in which the .py file of current module is located"
from sys import path
from os import getcwd
from os.path import exists
from inspect import getmodulename,getfile
modulename = getmodulename(getfile(lambda x: None))
##print "module name: %r" % modulename
dirs = [dir for dir in [getcwd()]+path if exists(dir+"/"+modulename+".py")]
dir = dirs[0] if len(dirs) > 0 else "."
return dir
if __name__ == "__main__":
play_sound(module_dir()+"/sounds/ding.wav")
<file_sep>"""
Interface to visual sample alignment using the camera image.
<NAME>, 6 Oct 2010 - 31 Jan 2016
"""
from diffractometer import diffractometer
__version__ = "1.7"
class Sample(object):
"""Subsystem for sample alignment"""
def __init__(self):
# settings
self.settings = Settings()
@property
def spot_zs(self):
"""Diffracometer Z positions at which support points were entered"""
Zs = []
for s in self.samples:
Zs += [diffractometer.z_of_sample(s["start"][2])]
Zs += [diffractometer.z_of_sample(s["end"][2])]
return Zs
zs = spot_zs
@property
def mark_zs(self):
"""Diffracometer Z positions at which support points where entered"""
from numpy import array,unique,isnan
if len(self.support_points) == 0: # MarKk sample start and end
Z = []
sx1,sy1,sz1 = self.sample_start
sx2,sy2,sz2 = self.sample_end
z1,z2 = self.calibration_z + sz1,self.calibration_z + sz2
if not isnan(z1): Z += [z1]
if not isnan(z2): Z += [z2]
else: # Define edge
PHI,X,Y,Z,OFFSET = array(self.support_points).T
Z = unique(Z)
return Z
def get_spot_phis(self):
"""Diffracometer Z positions at which support points where entered"""
from numpy import array,unique
support_points = self.support_points
if len(support_points) == 0:
return array([0.0])
else:
PHI,X,Y,Z,OFFSET = array(support_points).T
return unique(PHI)
spot_phis = property(get_spot_phis)
def visual_center_offset(self,phi,z):
"""The returned offset is with respect to the center of the sample
as defined by visual click centering."""
offset1 = self.visual_edge_offset(phi,z)
offset2 = self.visual_edge_offset(phi+180,z)
return (offset1-offset2)/2
def xray_scan_start_offset(self,phi,z):
"""The X-ray alignment scan starts outside the sample, in sufficient
distance not to hit the sample.
The returned offset is with respect to the center of the sample
as defined by visual click centering."""
return self.visual_edge_offset(phi,z)+self.xray_scan_clearance
def visual_edge_offset(self,phi,z):
"""Interpolated offset as function of phi and z, using measured
support points.
The returned offset is with respect to the center of the sample
as defined by visual click centering."""
from numpy import nan,array,concatenate
if len(self.support_points) == 0: # Mark Sample
sx1,sy1,sz1 = self.sample_start
sx2,sy2,sz2 = self.sample_end
z1,z2 = self.calibration_z + sz1,self.calibration_z + sz2
cx,cy = self.click_center_x,self.click_center_y
sdx1,sdy1 = sx1-cx,sy1-cy
sdx2,sdy2 = sx2-cx,sy2-cy
dx1,dy1 = self.diffractometer_dxdy(sdx1,sdy1,phi)
dx2,dy2 = self.diffractometer_dxdy(sdx2,sdy2,phi)
dy = interpolate([[z1,dy1],[z2,dy2]],z)
offset = dy + self.sample_r
return -offset
else: # Define Edge
PHI,X,Y,Z,OFFSET = array(self.support_points).T
PHI = concatenate((PHI-360,PHI,PHI+360))
Z = concatenate((Z,Z,Z))
OFFSET = concatenate((OFFSET,OFFSET,OFFSET))
phi = phi % 360
offset = interpolate_2D(PHI,Z,OFFSET,phi,z)
return -offset
def diffractometer_dxdy(self,sx,sy,phi):
"""Sample position with respect to the intersection of laser and X-ray
beam.
sx,sy: point on sample the with respect to the rotation axis at phi=0
phi: spidle angle
Return value: (dx,dy,dz)
dx: horizontal along x-ray beam
dy: vertical
"""
from numpy import sin,cos,radians,degrees,arctan2,sqrt
r = sqrt(sx**2+sy**2)
phi0 = degrees(arctan2(-sy,sx)) % 360
phi1 = phi0 + phi
dx = -r*cos(radians(phi1))
dy = r*sin(radians(phi1))
return dx,dy
def get_support_points(self):
"""List if (phi,x,y,z,offset) tuples"""
self.settings.read()
return self.settings.support_points
def set_support_points(self,value):
self.settings.support_points = value
self.settings.save()
support_points = property(get_support_points,set_support_points)
def get_samples(self):
"""Starting and ending points of the center lines for each sample
marked on the camera image"""
self.settings.read()
return self.settings.samples
def set_samples(self,value):
self.settings.samples = value
self.settings.save()
samples = property(get_samples,set_samples)
def get_sample_r(self):
"""Sample radius as marked on the camera"""
self.settings.read()
return self.settings.sample_r
def set_sample_r(self,value):
self.settings.sample_r = value
self.settings.save()
sample_r = property(get_sample_r,set_sample_r)
def get_sample_start(self):
"""Start of crystal center line, defined by mouse click.
(x,y,z) relative coordonates
x,y relative to rotation center at phi=0
z relatize to "calibraion_z"
"""
self.settings.read()
return self.settings.sample_start
def set_sample_start(self,value):
self.settings.sample_start = value
self.settings.save()
sample_start = property(get_sample_start,set_sample_start)
def get_sample_end(self):
"""End of crystal center line, defined by mouse click.
(x,y,z) relative coordonates in mm
x,y relative to rotation center at phi=0
z relatize to "calibraion_z"
"""
self.settings.read()
return self.settings.sample_end
def set_sample_end(self,value):
self.settings.sample_end = value
self.settings.save()
sample_end = property(get_sample_end,set_sample_end)
def get_sample_r(self):
"""Radius for the outline of the sample defined by mouse click,
in mm"""
self.settings.read()
return self.settings.sample_r
def set_sample_r(self,value):
self.settings.sample_r = value
self.settings.save()
sample_r = property(get_sample_r,set_sample_r)
def get_calibration_z(self):
"""List of (phi,x,y,z,offset) tuples"""
self.settings.read()
return self.settings.calibration_z
def set_calibration_z(self,value):
self.settings.calibration_z = value
self.settings.save()
calibration_z = property(get_calibration_z,set_calibration_z)
def get_center(self):
"""Click centering X,Y,Z"""
self.settings.read()
x,y,z = 0,0,self.settings.click_center_z
return x,y,z
def set_center(self,(x,y,z)):
self.settings.click_center_z = z
self.settings.save()
center = property(get_center,set_center)
def get_click_center_x(self):
"""Offset of the sample (as marked by a mouse click) from the
rotation axis in x direction at phi = 0."""
self.settings.read()
value = self.settings.click_center_x
return value
def set_click_center_x(self,value):
self.settings.click_center_x = value
self.settings.save()
click_center_x = property(get_click_center_x,set_click_center_x)
def get_click_center_y(self):
"""Offset of the sample (as marked by a mouse click) from the
rotation axis in y direction at phi = 0."""
self.settings.read()
value = self.settings.click_center_y
return value
def set_click_center_y(self,value):
self.settings.click_center_y = value
self.settings.save()
click_center_y = property(get_click_center_y,set_click_center_y)
def get_click_center_z(self):
"""Offset of the sample (as marked by a mouse click) from the
rotation axis in y direction at phi = 0."""
self.settings.read()
value = self.settings.click_center_z
return value
def set_click_center_z(self,value):
self.settings.click_center_z = value
self.settings.save()
click_center_z = property(get_click_center_z,set_click_center_z)
def get_grid_spacing(self):
"""Horizontal spacing on Diffracometer Z direction used on camera image, in mm"""
self.settings.read()
return self.settings.GridSpacing
def set_grid_spacing(self,value):
self.settings.GridSpacing = value
self.settings.save()
grid_spacing = property(get_grid_spacing,set_grid_spacing)
def get_xray_scan_clearance(self):
"""Horizontal spacing on Diffracometer Z direction used on camera image, in mm"""
self.settings.read()
return self.settings.xray_scan_clearance
def set_xray_scan_clearance(self,value):
self.settings.xray_scan_clearance = value
self.settings.save()
xray_scan_clearance = property(get_xray_scan_clearance,set_xray_scan_clearance)
def get_zmin(self):
"""Diffracometer Z translation range for data collection.
Defined as range over which support points have been entered"""
if len(self.mark_zs) == 0: return diffractometer.Z.command_value
return min(self.mark_zs)
zmin = property(get_zmin)
def get_zmax(self):
"""Diffracometer Z translation range for data collection.
Defined as range over which support points have been entered"""
if len(self.mark_zs) == 0: return diffractometer.Z.command_value
return max(self.mark_zs)
zmax = property(get_zmax)
z_step = grid_spacing
def closest_support_points(self,phi,z):
"""Phi values and z values of the four closest click point
to (phi,z) which have been defined visually,
as numpy array"""
from numpy import concatenate,argmin,nan,isnan,array,any
phi = phi % 360
PHI,Z = self.spot_phis,self.mark_zs
PHI = concatenate((PHI-360,PHI,PHI+360))
PHI1,PHI2 = PHI[PHI<=phi],PHI[PHI>=phi]
PHI1,PHI2 = PHI[PHI<=phi],PHI[PHI>=phi]
phi1 = PHI1[argmin(abs(PHI1-phi))] if len(PHI1)>0 else nan
phi2 = PHI2[argmin(abs(PHI2-phi))] if len(PHI2)>0 else nan
phi1 = phi1 % 360
phi2 = phi2 % 360
if phi1 == phi2: phi2 = nan
Z1,Z2 = Z[Z<=z],Z[Z>=z]
z1 = Z1[argmin(abs(Z1-z))] if len(Z1)>0 else nan
z2 = Z2[argmin(abs(Z2-z))] if len(Z2)>0 else nan
if z1 == z2: z2 = nan
points = array([[phi1,z1],[phi1,z2],[phi2,z1],[phi2,z2]])
points = points[~any(isnan(points),axis=1)]
return points.T
def closest_support_phis(self,phi):
"""Phi values of the two closest click point
to 'phi' which have been defined visually,
as numpy array"""
from numpy import concatenate,argmin,nan,isnan,array,any
phi = phi % 360
PHI = self.spot_phis
PHI = concatenate((PHI-360,PHI,PHI+360))
PHI1,PHI2 = PHI[PHI<=phi],PHI[PHI>=phi]
PHI1,PHI2 = PHI[PHI<=phi],PHI[PHI>=phi]
phi1 = PHI1[argmin(abs(PHI1-phi))] if len(PHI1)>0 else nan
phi2 = PHI2[argmin(abs(PHI2-phi))] if len(PHI2)>0 else nan
phi1 = phi1 % 360
phi2 = phi2 % 360
if phi1 == phi2: phi2 = nan
phis = array([phi1,phi2])
phis = phis[~any(isnan(phis))]
if not hasattr(phis,"len"): phis = array([phis])
return phis
def closest_support_zs(self,z):
"""z values of the two closest click point
to 'z' which have been defined visually,
as numpy array"""
from numpy import argmin,nan,isnan,array,any
Z = self.mark_zs
Z1,Z2 = Z[Z<=z],Z[Z>=z]
z1 = Z1[argmin(abs(Z1-z))] if len(Z1)>0 else nan
z2 = Z2[argmin(abs(Z2-z))] if len(Z2)>0 else nan
if z1 == z2: z2 = nan
zs = array([z1,z2])
zs = zs[~any(isnan(zs))]
if not hasattr(zs,"len"): zs = array([zs])
return zs
class Settings(object):
"""Aligment info stored in settings file"""
attributes = ["support_points","GridOffset","GridSpacing","click_center_z"]
def __init__(self):
self.timestamp = 0
# Default values
self.support_points = []
self.GridOffset = 0.0
self.GridSpacing = 0.100
self.click_center_z = 0.0
self.xray_scan_clearance = -0.15 # mm
self.read()
def read(self):
"Monitor the settings file and reloads it if it is updated."
from os.path import exists
settings_file = settings_dir()+"/sample_settings.py"
if exists(settings_file) and getmtime(settings_file) != self.timestamp:
# (Re)load settings file.
self.state = file(settings_file).read()
self.saved_sample_state = self.state
self.timestamp = getmtime(settings_file)
def save(self):
"Monitor the settings file and reloads it if it is updated."
from os import makedirs,remove,rename
from os.path import exists
settings_file = settings_dir()+"/sample_settings.py"
if not hasattr(self,"saved_state") or self.state != self.saved_state \
or not exists(settings_file):
# Update settings file.
if not exists(settings_dir()): makedirs(settings_dir())
try:
file(settings_file+".tmp","wb").write(self.state)
if exists(settings_file): remove(settings_file)
rename(settings_file+".tmp",settings_file)
self.saved_state = self.state
self.timestamp = getmtime(settings_file)
except IOError:
print("Failed to update %r" % settings_file)
def get_state(self):
state = ""
for attr in self.attributes:
line = attr+" = "+repr(eval("self."+attr))
state += line+"\n"
return state
def set_state(self,state):
from numpy import nan
for line in state.split("\n"):
line = line.strip(" \n\r")
if line != "":
try: exec("self."+line)
except Exception,msg: print("ignoring line %r: %s" % (line,msg))
state = property(get_state,set_state)
def camera_position(Z,offset):
"""Transform from Z, offset to camera viewing plane 2D
coordinates, using the current settigs of the diffractomter Z,Y,Z,Phi."""
x = (diffractometer.Z.value - Z)
y = offset
return x,y
def interpolate_2D(X,Y,Z,x,y):
"""
Z is a scalar function of the variables x and y.
X,Y: vector of length N, support points
Z: vector of length N, function values at support points
x,y: where to evaluate the function Z
"""
from numpy import array,unique
X,Y,Z = array(X),array(Y),array(Z)
UY = unique(Y)
UZ = [interpolate(zip(X[Y==uy],Z[Y==uy]),x) for uy in UY]
return interpolate(zip(UY,UZ),y)
def interpolate(xy_data,xval):
"Linear interpolation"
from numpy import array,argsort
x = array(xvals(xy_data)); y = array(yvals(xy_data)); n = len(xy_data)
if n == 0: return nan
if n == 1: return y[0]
order = argsort(x)
x = x[order]; y= y[order]
for i in range (1,n):
if x[i]>xval: break
if x[i-1]==x[i]: return (y[i-1]+y[i])/2.
yval = y[i-1]+(y[i]-y[i-1])*(xval-x[i-1])/(x[i]-x[i-1])
return yval
def xvals(xy_data):
"xy_data = list of (x,y)-tuples. Teturns list of x values only."
xvals = []
for i in range (0,len(xy_data)): xvals.append(xy_data[i][0])
return xvals
def yvals(xy_data):
"xy_data = list of (x,y)-tuples. Returns list of y values only."
yvals = []
for i in range (0,len(xy_data)): yvals.append(xy_data[i][1])
return yvals
def getmtime(filename):
"""Modification timestamp of a file"""
from os.path import getmtime
try: return getmtime(filename)
except: return 0
def settings_dir():
"""pathname of the file used to store persistent parameters"""
from os.path import dirname
path = module_dir()+"/settings"
return path
def module_dir():
"""directory of the current module"""
from os.path import dirname
module_dir = dirname(module_path())
if module_dir == "": module_dir = "."
return module_dir
def module_path():
"full pathname of the current module"
from sys import path
from os import getcwd
from os.path import basename,exists
from inspect import getmodulename,getfile
# 'getfile' retreives the source file name name compiled into the .pyc file.
pathname = getfile(lambda x: None)
##print "module_path: pathname: %r" % pathname
if exists(pathname): return pathname
# The module might have been compiled on a different machine or in a
# different directory.
pathname = pathname.replace("\\","/")
filename = basename(pathname)
##print "module_path: filename: %r" % filename
dirs = [dir for dir in [getcwd()]+path if exists(dir+"/"+filename)]
if len(dirs) == 0: print "pathname of file %r not found" % filename
dir = dirs[0] if len(dirs) > 0 else "."
pathname = dir+"/"+filename
##print "module_path: pathname: %r" % pathname
return pathname
sample = Sample()
def test():
from numpy import array
print "z range %.3f to %.3f, step %.3f mm" % (sample.zmin,sample.zmax,sample.z_step)
# Outline the crystal shape.
Z = arange(sample.zmin,sample.zmax+1e-6,sample.z_step)
phi = Phi.value
OFFSET = array([sample.visual_edge_offset(phi,z) for z in Z])
for z,o in zip(Z,OFFSET): print "%.3f\t%.3f" % (z,o)
if __name__ == "__main__": # for testing
self = sample # for debugging
phi,z = diffractometer.phic,diffractometer.zc
print("sample.zs")
print("sample.spot_zs")
print("sample.closest_support_points(phi,z)")
print("sample.visual_edge_offset(phi,z)")
print("sample.z_step")
print("sample.center")
<file_sep>#!/usr/bin/env python
import logging
logging.basicConfig(level=logging.DEBUG,format="%(asctime)s: %(message)s")
from Ensemble_registers import ensemble
x = ensemble.integer_registers
x[-1] += -1; ensemble.integer_registers = x
y = ensemble.floating_point_registers
y[-1] += 0.1; ensemble.floating_point_registers = y
<file_sep># This is a replacement for the Python serial module based on EPICS
# <NAME>, NIH 4 Oct 2008 - 8 Feb 2011
# Serial record fields:
# TMOD: Transfor mode: 0 = write/read, 1 = write, 2 = read, 3 = flush
# AOUT: Output buffer. Data is send as soon as AOUT is changed. Limited to
# 40 characters.
# TMOT: Timeout in seconds (floating point value)
# OEOS: Output terminator
# IFMT: Input format: 0 = ASCII, 1 = hybrid, 2 = binary
# IEOS: Input terminator
# BINP: Binary Input: This variable contains the received data.
# TINP: Translated input: This variable contains the received data, with control
# characters replaced by escape codes, e.g. ASCII 13 -> "\r".
# Limited to 40 bytes.
# TINP retains its old value if no data is received and a timeout occurs.
# If NORD=0, TINP is not valid.
# NRRD: Number of requested read bytes.
# NORD: Number of read bytes.
# EOMR: End of Media? Reason: 0 = none (timeout), 1 = count, 2 = EOS
# SCAN: 0 = passive: changing AOUT triggers sending.
# 1 = event (meaning?)
# 2 = I/O Intr: PROC=1 triggers sending, received data updates TINP
# 3-9: periodic scan rates. Automatically resend AOUT at intervals of 10s,
# 5s,2s,1s,0.5s,0.2s,0.1s
# PROC: If set to 1: If TMOD = 1, send data in AOUT. If TMOD = 2, receive data
# until either an input terminator is received or NRRD bytes are
# received, or a timeout occurs.
# BAUD: Baud rate: 0 = unkonwn, 1 = 300, 2 = 600, 3 = 1200, 4 = 2400, 5 = 4800,
# 6 = 9600, 7 = 19200, 8 = 38400, 9 = 57600, 10 = 115200, 11 = 230400
# DBIT: Data bits: 0 = unknown, 1 = 5, 2 = 6, 3 = 7, 4 = 8
# SBIT: Stop bits: 0 = unknown, 1 = 1, 2 = 2
# PRTY: Parity: 0 = unknown, 1 = none, 2 = even, 3 = odd
# FCTL: Flow control: 0 = unknown, 1 = none, 2 = hardware
# based on aps.anl.gov/epics/modules/soft/asyn/R3-1/asynRecord.html
# EpicsCA is a EPICS to Python interface by <NAME>, U Chigago,
# Downloaded from cars9.uchicago.edu/~newville/Epics/Python, 10 Sep 2007
# Needed to patch file PV.py, line 614:
# self._val = stmp[:slen].strip -> self._val = stmp[:slen]
from epics import caput,caget
from time import sleep,time
__version__ = "1.7"
# For compatibility for "serial" module.
PARITY_NONE = "N"
PARITY_EVEN = "E"
PARITY_ODD = "O"
SEVENBITS = 7
EIGHTBITS = 8
STOPBITS_ONE = 1
STOPBITS_TWO = 2
class Serial(object):
"EPICS controlled RS-323 port"
def __init__(self,port):
"port: EPICS record name, e.g. ID14B:serial16"
self.port = port
def write(self,string):
"Send data"
caput(self.port+".TMOD",1,wait=True) # 1 = write
caput(self.port+".OEOS","\0") # no output terminator
caput(self.port+".SCAN",0) # 0 = passive
# If case string contains binary data, EpicsCA would strip away trailing
# null characters. Seding non-ASCII chacters as except codes
# makes sure that null characters are sent, too.
encoded_string = repr(string)[1:-1]
caput(self.port+".AOUT",encoded_string)
def read(self,nchar=1):
"""Receive data, until either nchar bytes have received or a timeout has
occurred"""
caput(self.port+".TMOD",2) # 2 = read
caput(self.port+".IEOS","\0",wait=True) # no input terminator
caput(self.port+".NRRD",nchar,wait=True)
# For unknown reason, following fails at the first try, but succeed at
# the second try.
try: caput(self.port+".PROC","1",wait=True) # this will cause it to wait for data
except: caput(self.port+".PROC","1",wait=True)
try: return caget(self.port+".TINP")
except: return caget(self.port+".TINP")
def query(self,string,terminator="",count=0):
"""Receive data, until either the terminator character was received,
the number of bytes given by 'count' have have received or
a timeout has occurred."""
# The first 'caget' after python statup always fails. As a work-around, use a
# dummy caget just in case.
caget(self.port+".TMOD")
caput(self.port+".TMOD",0) # 0 = write/read
caput(self.port+".OEOS","\0") # not output terminator
if terminator: caput(self.port+".IEOS",terminator) # input terminator
else: caput(self.port+".IEOS","\0") # input terminator "\0" = none
caput(self.port+".IFMT",1) # 1 = hybrid
caput(self.port+".NRRD",count) # number of chars (0 = unlimited)
caput(self.port+".SCAN",0) # 0 = passive
# If case string contains binary data, EpicsCA would strip away trailing
# null characters. Seding non-ASCII chacters as except codes
# makes sure that null characters are sent, too.
encoded_string = repr(string)[1:-1]
caput(self.port+".AOUT",encoded_string,wait=True)
n = caget(self.port+".NORD")
if n == None: n = 0
if n == 0: return "" # nothing read
# With EpicsCA it is (as of June 2009) not possible to reliably retreive
# special characters from the BINP (binary input) variable, because
# EpicsCA strips off trailing carraigle return and null characters
# before passing back a string. Thus, I read the AINP (ASCII input)
# variable instead.
reply = caget(self.port+".TINP")
if not reply: reply = ""
# Special characters in the TINP field are encoded as octal
# escape sequences. Decode them.
##print "reply",repr(reply)
reply = eval("'"+reply+"'")
if caget(self.port+".EOMR") == 2: # 2 = EOS
return reply+terminator # terminator was stripped off, add it back
return reply
def get_timeout(self): return caget(self.port+".TMOT")
def set_timeout(self,value): caput(self.port+".TMOT",value)
timeout = property(get_timeout,set_timeout,
doc="maxmimum read time in seconds")
baudrates = ["unknown",300,600,1200,2400,4800,9600,19200,38400,57600,115200,
230400]
def get_baudrate(self): return self.baudrates[caget(self.port+".BAUD")]
def set_baudrate(self,value):
caput(self.port+".BAUD",self.baudrates.index(value))
baudrate = property(get_baudrate,set_baudrate,
doc="speed of serial line")
bytesizes = ["unknown",5,6,7,8]
def get_bytesize(self): return self.bytesizes[caget(self.port+".DBIT")]
def set_bytesize(self,value):
caput(self.port+".DBIT",self.bytesizes.index(value))
bytesize = property(get_bytesize,set_bytesize,
doc="number of data bits (7 or 8)")
parities = ["unknown","N","E","O"]
def get_parity(self): return self.parities[caget(self.port+".PRTY")]
def set_parity(self,value):
caput(self.port+".PRTY",self.parities.index(value))
parity = property(get_parity,set_parity,
doc="checkum bit: N = none, E = even, O = odd")
def get_stopbits(self): return caget(self.port+".SBIT")
def set_stopbits(self,value): caput(self.port+".SBIT",value)
stopbits = property(get_stopbits,set_stopbits,
doc="checkum bit: N = none, E = even, O = odd")
use_rtscts = ["unknown",False,True]
def get_rtscts(self): return self.use_rtscts[caget(self.port+".FCTL")]
def set_rtscts(self,value):
caput(self.port+".FCTL",self.use_rtscts.index(value))
rtscts = property(get_rtscts,set_rtscts,
doc="Hardware handshake: use 'Ready To Send' / 'Clear To Send' lines")
# Software flow control is not supported by EPICS
xonxoff = property(lambda self: False,lambda self,v: None)
# Modem handshake is not supported by EPICS
dsrdtr = property(lambda self: False,lambda self,v: None)
def wait_for_change(pvname):
"This return only when the named prcess variable changes."
global changed
pv = PV(pvname,callback=on_change)
pend_event (0.05)
changed = False
while not changed: pend_event (0.05)
def on_change(pv):
global changed
changed = True
print pv.pvname,"changed to",pv.value
if __name__ == "__main__": # for testing - remove when done.
port = Serial("14IDB:serial16")
<file_sep>"""
A propery object to be used inside a class
Author: <NAME>
Date created: 2018-11-01
"""
from logging import debug,warn,info,error
__version__ = "1.0"
def thread_property(procedure_name):
"""A propery object to be used inside a class"""
def get(self):
thread = getattr(self,procedure_name+"_thread",None)
return thread is not None and thread.isAlive()
def set(self,value):
if value != get(self):
if value:
procedure = getattr(self,procedure_name)
from threading import Thread
thread = Thread(target=procedure)
setattr(self,procedure_name+"_thread",thread)
thread.daemon = True
self.cancelled = False
thread.start()
else: self.cancelled = True
return property(get,set)
if __name__ == "__main__":
from pdb import pm
class Test(object):
cancelled = False
def procedure(self):
from time import time,sleep
t0 = time()
while time()-t0 < 10 and not self.cancelled: sleep(0.1)
procedure_running = thread_property("procedure")
test = Test()
print("test.procedure_running = True")
print("test.procedure_running")
print("test.cancelled = True")
<file_sep>"""EPICS Channel Access Protocol"""
from CA import PV,Record,caput,caget
SAMPLET = Record("14IDB-NIH:SAMPLET")
if __name__ == "__main__":
print "SAMPLET.port_name.value"
print "SAMPLET.T.unit"
print "SAMPLET.T.value"
print "SAMPLET.T.moving"
<file_sep>Environment.defaults = {'Enabled': False, 'Value': 'offline?'}
Environment.properties = {'Enabled': [(True, 'control.ensemble_online')]}
Environment.value = 'control.environment'
XRayDetector.properties = {
'Enabled': 'True',
'Label': '"X-Ray Detector %g mm" % control.DetZ.value',
}
XRayDetectorInserted.action = {
False: 'control.det_retracted = True',
True: 'control.det_inserted = True'
}
XRayDetectorInserted.defaults = {
'Enabled': False,
'Label': 'offline',
}
XRayDetectorInserted.properties = {
'BackgroundColour': [
('green', 'control.det_inserted == True'),
('yellow', 'control.det_retracted == True'),
('red', 'control.det_inserted == control.det_retracted'),
],
'Enabled': [(True, 'control.det_inserted in [True,False]')],
'Value': [
(True, 'control.det_inserted == True'),
(False, 'control.det_retracted == True'),
],
'Label': [
('Cancel', 'control.det_moving == True'),
('Retract', 'control.det_inserted == True'),
('Insert', 'control.det_inserted == False'),
],
}
ProgramRunning.action = {
False: 'control.ensemble_program_running = False',
True: 'control.ensemble_program_running = True',
}
ProgramRunning.defaults = {'Enabled': False, 'Label': 'offline'}
ProgramRunning.properties = {
'BackgroundColour': [
('green', 'control.ensemble_program_running == True'),
('red', 'control.ensemble_program_running == False')],
'Enabled': [(False, 'control.fault == True'),
(True, 'control.fault == False')],
'Value': [(False, 'control.ensemble_program_running == False'),
(True, 'control.ensemble_program_running == True')],
'Label': [
('Fault', 'control.fault == True'),
('Start', 'control.ensemble_program_running == False'),
('Stop', 'control.ensemble_program_running == True')]
}
GotoSaved.action = {True: 'control.inserted = True'}
GotoSaved.defaults = {'Enabled': False}
GotoSaved.properties = {
'BackgroundColour': [('red', 'control.XY_enabled == False')],
'Enabled': [(True, '1-control.inserted')]}
Home.action = {
False: 'control.ensemble_homing = True',
True: 'control.ensemble_homing = True'}
Home.defaults = {'Enabled': False, 'Label': 'Home'}
Home.properties = {
'BackgroundColour': [
('yellow', 'control.ensemble_homing == True'),
('green', 'control.ensemble_homed == True'),
('red', 'control.ensemble_homed == False')],
'Enabled': [
(False, "control.ensemble_homing_prohibited != ''"),
(True, "control.ensemble_homing_prohibited == ''")],
'Value': [
(False, 'control.ensemble_homed == False'),
(True, 'control.ensemble_homed == True')],
'Label': [
('Cancel', 'control.ensemble_homing == True'),
('Home', 'control.ensemble_homed == False'),
('Home', 'control.ensemble_homed == True')]
}
Inserted.action = {
False: 'control.retracted = True',
True: 'control.inserted = True',
}
Inserted.defaults = {
'Enabled': True,
'Label': 'Inserted [Withdrawn]'
}
Inserted.properties = {
'BackgroundColour': [
('grey80', 'control.moving_sample == True'),
('green', 'control.inserted == True'),
('yellow', 'control.retracted == True'),
('red', 'control.inserted == control.retracted'),
],
'Enabled': [
(True, 'control.XY_enabled and not control.moving_sample'),
(False, 'not control.ensemble_online'),
],
'Value': [
(True, 'control.inserted == True'),
(False, 'control.retracted == True'),
],
'Label': [
('Cancel', 'control.inserting_sample == True'),
('Cancel', 'control.retracting_sample == True'),
('Retract', 'control.inserted == True'),
('Insert', 'control.inserted == False'),
],
}
Temperature_Setpoint.defaults = {'Enabled': False, 'Value': 'offline'}
Temperature_Setpoint.type = 'float'
Temperature_Setpoint.format = '%.1f'
Temperature_Setpoint.unit = 'C'
Temperature_Setpoint.properties = {'Enabled': [(True, 'control.temperature_online')]}
Temperature_Setpoint.value = 'control.temperature_setpoint'
Temperature.defaults = {'Enabled': False, 'Value': 'offline'}
Temperature.type = 'float'
Temperature.format = '%.3f'
Temperature.unit = 'C'
Temperature.properties = {'Enabled': [(True, 'control.temperature_online')]}
Temperature.value = 'control.temperature'
XRayShutter.defaults = {'Enabled': False, 'Label': 'offline'}
XRayShutter.properties = {
'Enabled': 'control.xray_safety_shutters_enabled == True',
'Value': 'control.xray_safety_shutters_open == True',
'Label': [
('Disabled', 'control.xray_safety_shutters_enabled == False'),
('Close','control.xray_safety_shutters_open == True'),
('Open', 'control.xray_safety_shutters_open == False'),
],
'BackgroundColour': [
('green', 'control.xray_safety_shutters_open'),
('red', 'not control.xray_safety_shutters_open and control.xray_safety_shutters_enabled'),
],
}
XRayShutter.action = {
False: 'control.xray_safety_shutters_open = False',
True: 'control.xray_safety_shutters_open = True',
}
XRayShutterAutoOpen.defaults = {'Enabled': False}
XRayShutterAutoOpen.properties = {
'Enabled': 'control.xray_safety_shutters_auto_open in [True,False]',
'Value': 'control.xray_safety_shutters_auto_open == True',
}
XRayShutterAutoOpen.action = {
False: 'control.xray_safety_shutters_auto_open = False',
True: 'control.xray_safety_shutters_auto_open = True',
}
LaserShutter.defaults = {'Enabled': False, 'Label': 'offline'}
LaserShutter.properties = {
'Enabled': 'control.laser_safety_shutter_open in [True,False]',
'Value': 'control.laser_safety_shutter_open == True',
'Label': [
('Close','control.laser_safety_shutter_open == True'),
('Open', 'control.laser_safety_shutter_open == False'),
],
'BackgroundColour': [
('green', 'control.laser_safety_shutter_open == True'),
('red', 'control.laser_safety_shutter_open == False'),
],
}
LaserShutter.action = {
False: 'control.laser_safety_shutter_open = False',
True: 'control.laser_safety_shutter_open = True',
}
LaserShutterAutoOpen.defaults = {'Enabled': False}
LaserShutterAutoOpen.properties = {
'Enabled': 'control.laser_safety_shutter_auto_open in [True,False]',
'Value': 'control.laser_safety_shutter_auto_open == True',
}
LaserShutterAutoOpen.action = {
False: 'control.laser_safety_shutter_auto_open = False',
True: 'control.laser_safety_shutter_auto_open = True',
}
Mode.defaults = {'Enabled': False, 'Value': 'offline'}
Mode.properties = {'Enabled': [(True, 'control.timing_system_online == True')]}
Mode.value = 'control.mode'
PumpEnabled.action = {
False: 'control.pump_on_command = False',
True: 'control.pump_on_command = True'
}
PumpEnabled.defaults = {'Enabled': False, 'Label': 'offline'}
PumpEnabled.properties = {
'Enabled': [(True, 'control.timing_system_running == True')],
'Value': [
(False, 'control.pump_on_command == False'),
(True, 'control.pump_on_command == True')],
'Label': [
('running', 'control.pump_on == True'),
('stopped', 'control.pump_on == False'),
('offline', 'control.pump_on not in [True,False]'),
]
}
LoadSample.action = {
False: 'control.sample_loading = False',
True: 'control.sample_loading = True'
}
LoadSample.defaults = {'Enabled': False}
LoadSample.properties = {
'BackgroundColour': [
('yellow', 'control.sample_loading'),
('red', 'control.pump_enabled == False')],
'Enabled': [
(True, 'control.pump_movable or control.sample_loading')],
'Value': [(True, 'control.sample_loading == True')],
'Label': [('Load Sample', 'not control.sample_loading'),
('Cancel Load', 'control.sample_loading')]
}
LoadSampleStep.value = 'control.load_step'
LoadSampleStep.properties = {'Enabled': 'True'}
ExtractSample.action = {
False: 'control.sample_extracting = False',
True: 'control.sample_extracting = True',
}
ExtractSample.defaults = {'Enabled': False}
ExtractSample.properties = {
'BackgroundColour': [
('yellow', 'control.sample_extracting == True'),
('red', 'control.pump_enabled == False')
],
'Enabled': [(True, 'control.pump_movable or control.sample_extracting')],
'Value': [(True, 'control.sample_extracting == True')],
'Label': [
('Extract Sample', 'not control.sample_extracting'),
('Cancel Extract', 'control.sample_extracting')
]
}
ExtractSampleStep.value = 'control.extract_step'
ExtractSampleStep.properties = {'Enabled': 'True'}
CirculateSample.action = {
False: 'control.sample_circulating = False',
True: 'control.sample_circulating = True'
}
CirculateSample.defaults = {'Enabled': False}
CirculateSample.properties = {
'BackgroundColour': [
('yellow', 'control.sample_circulating'),
('red', 'control.pump_enabled == False')
],
'Enabled': [(True, 'control.pump_movable or control.sample_circulating')],
'Value': [(True, 'control.sample_circulating == True')],
'Label': [
('Circulate Sample', 'not control.sample_circulating'),
('Cancel Circulate', 'control.sample_circulating')
],
}
CirculateSampleStep.value = 'control.circulate_step'
CirculateSampleStep.properties = {'Enabled': 'True'}
PumpHomed.action = {
False: 'control.pump_homed = True',
True: 'control.pump_homed = True',
}
PumpHomed.defaults = {'Enabled': False, 'Label': 'offline', 'Value': True}
PumpHomed.properties = {
'Enabled': [
(True, 'control.pump_movable == True')
],
'Label': [
('Home', 'control.ensemble_online'),
]
}
PumpPosition.defaults = {'Enabled': False, 'Value': 'offline'}
PumpPosition.format = '%.1f'
PumpPosition.properties = {'Enabled': [(True, 'control.ensemble_online')]}
PumpPosition.value = 'control.pump_position'
PumpSpeed.defaults = {'Enabled': False, 'Value': 'offline'}
PumpSpeed.properties = {'Enabled': [(True, 'control.ensemble_online')]}
PumpSpeed.value = 'control.pump_speed'
PumpStep.defaults = {'Enabled': False, 'Value': 'offline'}
PumpStep.properties = {'Enabled': [(True, 'control.ensemble_online')]}
PumpStep.value = 'control.pump_step'
Save.action = {True: 'control.at_inserted_position = True'}
Save.defaults = {'Enabled': False}
Save.properties = {
'Enabled': [(True, 'control.at_inserted_position == False')]
}
<file_sep>prefix = '14IDB:m153'
description = 'Alio Y'
target = 0.48996875
EPICS_enabled = True<file_sep>"""Data Collection for Wang Group
Author: <NAME>
Date created: 2018-05-24
Date last modified: 2018-05-24
"""
__version__ = "1.0" #
from pdb import pm # for debugging
import logging
logging.basicConfig(level=logging.INFO,format="%(asctime)s: %(levelname)s %(message)s")
from instrumentation import ccd,timing_sequencer,timing_system
from numpy import *
timepoints = [1]
nlaser = 1
directory = "/net/mx340hs/data/wang_1805/pyp2/"
file_basename = "pyp8"
filenames = ["%s/%s_%gs.mccd" % (directory,file_basename,t) for t in timepoints]
dt = timing_system.hsct*48
it0 = max(nlaser,2)+1 # number seqeunces before t=0
N = it0 + int(rint(max(timepoints)/dt))+1+50
# Laser pulse burst is centered at t=0.
laser_on = array([0]*N)
nlaser1 = nlaser; nlaser2 = nlaser-nlaser1
laser_on[it0-nlaser1:it0+nlaser2] = 1
xray_on = array([0]*N)
for t in timepoints: xray_on[it0 + int(rint(t/dt))] = 1
ms_on = xray_on
# Trigger X-ray detector after X-ray ms shutter pulse
xdet_on = roll(ms_on,1)
# Additional detector triggers to clear zingers (must be >100 ms ealier)
xdet_on += roll(ms_on,-2)
image_numbers = cumsum(xdet_on)
save_filenames = [""]*max(image_numbers)
j = 0
for i in range(0,N):
if image_numbers[i] > 0 and xray_on[i-1]:
save_filenames[image_numbers[i]-1] = filenames[j]
j += 1
save_image_numbers = range(1,max(image_numbers)+1)
waitt = array([dt]*N)
npulses = array([1]*N)
def setup():
timing_sequencer.acquire(laser_on=laser_on,
npulses=npulses,waitt=waitt,burst_waitt=waitt,
image_numbers=image_numbers,
ms_on=ms_on,xdet_on=xdet_on,
xosct_on=xray_on,losct_on=laser_on)
timing_system.image_number.count = 0
ccd.acquire_images(save_image_numbers,save_filenames)
def start(): timing_sequencer.acquisition_start()
def finish():
from time import sleep
while timing_sequencer.image_number < max(save_image_numbers): sleep(dt)
timing_sequencer.acquisition_cancel()
def cancel(): timing_sequencer.acquisition_cancel()
def collect():
setup()
start()
finish()
##print("timing_system.ip_address = %r" % timing_system.ip_address)
##print("")
##print("setup()")
##print("start()")
##print("finish()")
##print("collect()")
collect()
<file_sep>"""
Remote control of thermoelectric chiller by Solid State Cooling Systems,
www.sscooling.com, via RS-323 interface
Model: Oasis 160
See: Oasis Thermoelectric Chiller Manual, Section 7 "Oasis RS-232
communication", p. 15-16
Settings: 9600 baud, 8 bits, parity none, stop bits 1, flow control none
DB09 connector pin 2 = TxD, 3 = RxD, 5 = Ground
The controller accepts binary commands and generates binary replies.
Commands are have the length of one to three bytes.
Replies have a length of either one or two bytes, depending on the command.
Command byte: bit 7: remote control active (1 = remote control,0 = local control)
bit 6 remote on/off (1 = Oasis running, 0 = Oasis in standby mode)
bit 5: communication direction (1 = write,0 = read)
bits 4-0: 00001: [1] Set-point temperature (followed by 2 bytes: temperature in C * 10)
00110: [6] Temperature low limit (followed by 2 bytes: temperature in C * 10)
00111: [7] Temperature high limit(followed by 2 bytes: temperature in C * 10)
01000: [8] Faults (followed by 1 byte)
01001: [9] Actual temperature (followed by 2 bytes: temperature in C * 10)
The 2-byte value is a 16-bit binary number enoding the temperature in units
of 0.1 degrees Celsius (range 0-400 for 0-40.0 C)
The fault byte is a bit map (0 = OK, 1 = Fault):
bit 0: Tank Level Low
bit 2: Temperature above alarm range
bit 4: RTD Fault
bit 5: Pump Fault
bit 7: Temperature below alarm range
Undocumented commands:
C6: Receive the lower limit. (should receive back C6 14 00)
E6 14 00: Set set point low limit to 2C
C7: Receive the upper limit. (should receive back C7 C2 01)
E7 C2 01: Set set point high limit to 45C
E-mail by <NAME> <<EMAIL>>, May 31, 2016,
"RE: Issue with Oasis 160 (S/N 8005853)"
Cabling:
"NIH-Instrumentation" MacBook Pro -> 3-port USB hub ->
"ICUSB232 SM3" UBS-Serial cable -> Oasis chiller
Setup to run IOC:
Windows 7 > Control Panel > Windows Firewall > Advanced Settings > Inbound Rules
> New Rule... > Port > TCP > Specific local ports > 5064-5070
> Allow the connection > When does the rule apply? Domain, Private, Public
> Name: EPICS CA IOC
Inbound Rules > python > General > Allow the connection
Inbound Rules > pythonw > General > Allow the connection
Authors: <NAME>, <NAME>, <NAME>
Date created: 2009-05-28
Date last modified: 2019-05-26
"""
from struct import pack,unpack
from numpy import nan,rint,isnan
from logging import error,warn,info,debug
import os
import platform
computer_name = platform.node()
__version__ = "2.4" # added PID parameters to monitor; changed parameter numbers for PID parameter objects 208-213 VS
class OasisChillerDriver(object):
"""Oasis thermoelectric chiller by Solid State Cooling Systems"""
name = "oasis_chiller"
timeout = 1.0
baudrate = 9600
id_query = "A"
id_reply_length = 3
from persistent_property import persistent_property
wait_time = persistent_property("wait_time",1.0) # bewteen commands
last_reply_time = 0.0
def id_reply_valid(self,reply):
valid = reply.startswith("A") and len(reply) == 3
debug("Reply %r valid? %r" % (reply,valid))
return valid
# Make multithread safe
from thread import allocate_lock
__lock__ = allocate_lock()
port = None
def parameter_property(parameter_number,scale_factor=1):
"""A 16-bit parameter"""
def get(self): return self.get_value(parameter_number)/scale_factor
def set(self,value): self.set_value(parameter_number,value*scale_factor)
return property(get,set)
nominal_temperature = parameter_property(1,scale_factor=10.0)
actual_temperature = parameter_property(9,scale_factor=10.0)
low_limit = parameter_property(6,scale_factor=10.0)
high_limit = parameter_property(7,scale_factor=10.0)
VAL = nominal_temperature
RBV = actual_temperature
LLM = low_limit
HLM = high_limit
P1 = parameter_property(208)
I1 = parameter_property(209)
D1 = parameter_property(210)
P2 = parameter_property(211)
I2 = parameter_property(212)
D2 = parameter_property(213)
def set_factory_PID(self):
"""Reset PID parameters to factory settings"""
self.P1 = 90
self.I1 = 32
self.D1 = 2
self.P2 = 50
self.I2 = 35
self.D2 = 3
@property
def port_name(self):
"""Serial port name"""
if self.port is None: value = ""
else: value = self.port.name
return value
COMM = port_name
@property
def connected(self): return self.port is not None
@property
def online(self):
if self.port is None: self.init_communications()
online = self.port is not None
if online: debug("Device online")
else: warn("Device offline")
return online
@property
def fault_code(self):
"""Report faults as number
0: no fault
1: Tank Level Low
2: Temp above alarm range
5: RTD Fault
6: Pump Fault
8: Temp below alarm range
"""
fault_code = self.faults_byte
if fault_code == 2.0**7:
fault_code = 8
elif fault_code == 2.0**6:
fault_code = 7
elif fault_code == 2.0**5:
fault_code = 6
elif fault_code == 2.0**4:
fault_code = 5
elif fault_code == 2.0**3:
fault_code = 4
elif fault_code == 2.0**2:
fault_code = 3
elif fault_code == 2.0**1:
fault_code = 2
elif fault_code == 2.0**0:
fault_code = 1
elif fault_code == 0:
fault_code = 0
else:
fault_code = -1
debug("Fault code %s" % fault_code)
return fault_code
@property
def faults(self):
"""Report list of faults as string"""
faults = ""
bits = self.faults_byte
if not isnan(bits):
for i in range(0,8):
if (bits >> i) & 1:
if i in self.fault_names: faults += self.fault_names[i]+", "
else: faults += str(i)+", "
faults = faults.strip(", ")
if faults == "": faults = "none"
if faults == "": faults = " "
debug("Faults %s" % faults)
return faults
fault_names = {
0:"Tank Level Low",
2:"Temp above alarm range",
4:"RTD Fault",
5:"Pump Fault",
7:"Temp below alarm range",
}
@property
def faults_byte(self):
return self.get_byte(8)
def get_byte(self,parameter_number):
"""Read an 8-bit value
parameter_number: 0-255
8 = fault
"""
code = int("01000000",2) | parameter_number
command = pack('B',code)
reply = self.query(command,count=2)
# The reply is 0xC8 followed by a faults status byte.
count = nan
if len(reply) != 2:
if len(reply)>0:
warn("%r: expecting 2-byte reply, got %r" % (command,reply))
elif self.connected:
warn("%r: expecting 2-byte reply, got no reply" % command)
else:
reply_code,count = unpack('<BB',reply)
if reply_code != code:
warn("reply %r: expecting 0x%X(%s), got 0x%X(%s)" %
(reply,code,bin(code),reply_code,bin(reply_code)))
count = nan
return count
def get_value(self,parameter_number):
"""Read a 16-bit value
parameter_number: 0-255
1=set point, 6=low limit, 7=high limit, 9=coolant temp.
208-213=PID parameter P1,I1,D1,P2,I2,D2
"""
from struct import pack
code = int("01000000",2) | parameter_number
command = pack('B',code)
reply = self.query(command,count=3)
# The reply is 0xC1 followed by 1 16-bit binary count on little-endian byte
# order. The count is the temperature in degrees Celsius, times 10.
if len(reply) != 3:
if len(reply)>0:
warn("%r: expecting 3-byte reply, got %r" % (command,reply))
elif self.connected:
warn("%r: expecting 3-byte reply, got no reply" % command)
return nan
reply_code,count = unpack('<BH',reply)
if reply_code != code:
warn("reply %r: expecting 0x%X(%s), got 0x%X(%s)" %
(reply,code,bin(code),reply_code,bin(reply_code)))
return nan
return count
def set_value(self,parameter_number,value):
"""Set a 16-bit value"""
from numpy import rint
from struct import pack
code = int("01100000",2) | parameter_number
command = pack('<BH',code,int(rint(value)))
reply = self.query(command,count=1)
if len(reply) != 1:
warn("expecting 1, got %d bytes" % len(reply)); return
reply_code, = unpack('B',reply)
if reply_code != code: warn("expecting 0x%X, got 0x%X" % (code,reply_code))
def query(self,command,count=1):
"""Send a command to the controller and return the reply"""
with self.__lock__: # multithread safe
for i in range(0,2):
try: reply = self.__query__(command,count)
except Exception,msg:
warn("query: %r: attempt %s/2: %s" % (command,i+1,msg))
reply = ""
if reply: return reply
self.init_communications()
return reply
def __query__(self,command,count=1):
"""Send a command to the controller and return the reply"""
from time import time
from sleep import sleep
sleep(self.last_reply_time + self.wait_time - time())
self.write(command)
reply = self.read(count=count)
self.last_reply_time = time()
return reply
def write(self,command):
"""Send a command to the controller"""
if self.port is not None:
self.port.write(command)
debug("%s: Sent %r" % (self.port.name,command))
def read(self,count=None,port=None):
"""Read a reply from the controller,
terminated with the given terminator string"""
##debug("read count=%r,port=%r" % (count,port))
if port is None: port = self.port
if port is not None:
#print("in wait:" + str(self.port.inWaiting()))
debug("Trying to read %r bytes from %s..." % (count,port.name))
port.timeout = self.timeout
reply = port.read(count)
debug("%s: Read %r" % (port.name,reply))
else: reply = ""
return reply
def init_communications(self):
"""To do before communncating with the controller"""
from os.path import exists
from serial import Serial
if self.port is not None:
try:
info("Checking whether device is still responsive...")
self.port.write(self.id_query)
debug("%s: Sent %r" % (self.port.name,self.id_query))
reply = self.read(count=self.id_reply_length)
if not self.id_reply_valid(reply):
debug("%s: %r: invalid reply %r" % (self.port.name,self.id_query,reply))
info("%s: lost connection" % self.port.name)
self.port = None
else: info("Device is still responsive.")
except Exception,msg:
debug("%s: %s" % (Exception,msg))
self.port = None
if self.port is None:
port_basenames = ["COM"] if not exists("/dev") \
else ["/dev/tty.usbserial","/dev/ttyUSB"]
for i in range(-1,50):
for port_basename in port_basenames:
port_name = port_basename+("%d" % i if i>=0 else "")
##debug("Trying port %s..." % port_name)
try:
port = Serial(port_name,baudrate=self.baudrate)
port.write(self.id_query)
debug("%s: Sent %r" % (port.name,self.id_query))
reply = self.read(count=self.id_reply_length,port=port)
if self.id_reply_valid(reply):
self.port = port
info("Discovered device at %s based on reply %r" % (self.port.name,reply))
break
except Exception,msg: debug("%s: %s" % (Exception,msg))
if self.port is not None: break
oasis_chiller_driver = OasisChillerDriver()
class OasisChiller_IOC(object):
name = "oasis_chiller_IOC"
from persistent_property import persistent_property
prefix = persistent_property("prefix","NIH:CHILLER")
running = False
was_online = False
def run(self):
"""Run EPICS IOC"""
self.startup()
self.running = True
while self.running: self.update_once()
self.shutdown()
def start(self):
"""Run EPCIS IOC in background"""
from threading import Thread
task = Thread(target=self.run,name="oasis_chiller_IOC.run")
task.daemon = True
task.start()
def shutdown(self):
from CAServer import casdel
casdel(self.prefix)
def get_EPICS_enabled(self):
return self.running
def set_EPICS_enabled(self,value):
from thread import start_new_thread
if value:
if not self.running: start_new_thread(self.run,())
else: self.running = False
EPICS_enabled = property(get_EPICS_enabled,set_EPICS_enabled)
def startup(self):
from CAServer import casput,casmonitor
from numpy import nan
casput(self.prefix+".SCAN",oasis_chiller_driver.wait_time)
casput(self.prefix+".DESC","Temp")
casput(self.prefix+".EGU","C")
# Set defaults
casput(self.prefix+".VAL",nan)
casput(self.prefix+".RBV",nan)
casput(self.prefix+".LLM",nan)
casput(self.prefix+".HLM",nan)
casput(self.prefix+".P1",nan)
casput(self.prefix+".I1",nan)
casput(self.prefix+".D1",nan)
casput(self.prefix+".P2",nan)
casput(self.prefix+".I2",nan)
casput(self.prefix+".D2",nan)
casput(self.prefix+".faults"," ")
casput(self.prefix+".fault_code",0)
casput(self.prefix+".COMM"," ")
casput(self.prefix+".SCANT",nan)
# Monitor client-writable PVs.
casmonitor(self.prefix+".SCAN",callback=self.monitor)
casmonitor(self.prefix+".VAL",callback=self.monitor)
casmonitor(self.prefix+".LLM",callback=self.monitor)
casmonitor(self.prefix+".HLM",callback=self.monitor)
casmonitor(self.prefix+".P1",callback=self.monitor)
casmonitor(self.prefix+".I1",callback=self.monitor)
casmonitor(self.prefix+".D1",callback=self.monitor)
casmonitor(self.prefix+".P2",callback=self.monitor)
casmonitor(self.prefix+".I2",callback=self.monitor)
casmonitor(self.prefix+".D2",callback=self.monitor)
def update_once(self):
from CAServer import casput
from numpy import isfinite,isnan,nan
from time import time
from sleep import sleep
t = time()
online = oasis_chiller_driver.online
if online:
if online and not self.was_online:
info("Reading configuration...")
casput(self.prefix+".COMM",oasis_chiller_driver.COMM)
casput(self.prefix+".VAL",oasis_chiller_driver.VAL)
casput(self.prefix+".RBV",oasis_chiller_driver.RBV)
casput(self.prefix+".fault_code",oasis_chiller_driver.fault_code)
casput(self.prefix+".faults",oasis_chiller_driver.faults)
casput(self.prefix+".LLM",oasis_chiller_driver.LLM)
casput(self.prefix+".HLM",oasis_chiller_driver.HLM)
casput(self.prefix+".P1",oasis_chiller_driver.P1)
casput(self.prefix+".I1",oasis_chiller_driver.I1)
casput(self.prefix+".D1",oasis_chiller_driver.D1)
casput(self.prefix+".P2",oasis_chiller_driver.P2)
casput(self.prefix+".I2",oasis_chiller_driver.I2)
casput(self.prefix+".D2",oasis_chiller_driver.D2)
casput(self.prefix+".SCANT",nan)
casput(self.prefix+".processID",value = os.getpid(), update = False)
casput(self.prefix+".computer_name", value = computer_name, update = False)
if len(self.command_queue) > 0:
attr,value = self.command_queue.popleft()
setattr(oasis_chiller_driver,attr,value)
value = getattr(oasis_chiller_driver,attr)
else:
attr = self.next_poll_property
value = getattr(oasis_chiller_driver,attr)
casput(self.prefix+"."+attr,value)
casput(self.prefix+".SCANT",time()-t) # post actual scan time for diagnostics
else:
sleep(1)
self.was_online = online
from collections import deque
command_queue = deque()
@property
def next_poll_property(self):
name = self.poll_properties[self.poll_count % len(self.poll_properties)]
self.poll_count += 1
return name
poll_properties = ["RBV","VAL","fault_code","faults"]
poll_count = 0
def monitor(self,PV_name,value,char_value):
"""Process PV change requests"""
from CAServer import casput
info("%s = %r" % (PV_name,value))
if PV_name == self.prefix+".SCAN":
oasis_chiller_driver.wait_time = float(value)
casput(self.prefix+".SCAN",oasis_chiller_driver.wait_time)
else:
attr = PV_name.replace(self.prefix+".","")
self.command_queue.append([attr,float(value)])
oasis_chiller_IOC = OasisChiller_IOC()
def run_IOC():
"""Serve the Ensemble IPAQ up on the network as EPICS IOC"""
import logging
from tempfile import gettempdir
logfile = gettempdir()+"/oasis_chiller.log"
logging.basicConfig(level=logging.DEBUG,
format="%(asctime)s %(levelname)s: %(message)s",
filename=logfile,
)
oasis_chiller_IOC.run()
def alias(name):
"""Make property given by name be known under a different name"""
def get(self): return getattr(self,name)
def set(self,value): setattr(self,name,value)
return property(get,set)
from EPICS_motor import EPICS_motor
class OasisChiller(EPICS_motor):
"""Thermoelectric water cooler"""
command_value = alias("VAL") # EPICS_motor.command_value not changable
port_name = alias("COMM")
prefix = alias("__prefix__") # EPICS_motor.prefix not changable
nominal_temperature = alias("VAL") # for backward compatbility
actual_temperature = alias("RBV") # for backward compatbility
oasis_chiller = OasisChiller(prefix="NIH:CHILLER",name="oasis_chiller")
chiller = oasis_chiller # for backward compatbility
def binstr(n):
"""binary number representation of n"""
s = ""
for i in range(31,-1,-1):
if (n >> i) & 1: s += "1"
elif s != "": s += "0"
return s
if __name__ == "__main__": # for testing
from sys import argv
if "run_IOC" in argv: run_IOC()
from pdb import pm
import logging
from numpy import nan
import CAServer
from CAServer import casput,casmonitor,PVs,PV_info
##CAServer.DEBUG = True
logging.basicConfig(level=logging.INFO,
format="%(asctime)s %(levelname)s: %(message)s")
self = oasis_chiller_IOC # for debugging
PV_name = "NIH:CHILLER.VAL"
##print('oasis_chiller_driver.init_communications()')
##print("oasis_chiller_driver.port_name")
print("oasis_chiller_driver.nominal_temperature = 40")
print("oasis_chiller_driver.nominal_temperature = 5")
##print("oasis_chiller_driver.actual_temperature")
##print("oasis_chiller_driver.low_limit")
##print("oasis_chiller_driver.high_limit")
print("oasis_chiller_driver.fault_code")
print("oasis_chiller_driver.faults")
##print('CAServer.DEBUG = %r' % CAServer.DEBUG)
print('oasis_chiller_IOC.run()')
print('oasis_chiller_IOC.start()')
print("oasis_chiller.fault_code")
print("oasis_chiller.faults")
##print('oasis_chiller_IOC.startup()')
##print('oasis_chiller_IOC.update_once()')
##print('casput(self.prefix+".VAL",nan)')
##print('casmonitor(self.prefix+".VAL",callback=self.monitor)')
##print('CAServer.start_server()')
##rint('CAServer.PVs[PV_name] = CAServer.PV_info()')
##print('CAServer.PVs')
##print("run_IOC()")
<file_sep>"""
Run a Python command as in an independent sub-process
Author: <NAME>
Date created: 2018-12-05
Date last modified: 2019-01-30
"""
__version__ = "1.1" # using "redirect" to log error messages, including tracebacks
def start(module,command):
"""
module: e.g. "SavedPositionsPanel_2"
command: e.g. "ConfigurationsPanel()"
SavedPositionsPanel(name="methods",globals=globals(),locals=locals())
ConfigurationPanel(name="methods",globals=globals(),locals=locals())
ConfigurationsPanel()
"""
from module_dir import module_dir
directory = module_dir(start)
from os import chdir
try: chdir(directory)
except Exception,msg: warn("%s: %s" % (directory,msg))
from subprocess import Popen
Popen(command_line(module,command),stdin=None,stdout=None,stderr=None,
close_fds=True)
def command_line(module,command):
"""
module: e.g. "SavedPositionsPanel_2"
command: e.g. "ConfigurationsPanel()"
"""
from sys import executable as python
command = ("from start import run; run(%r,%r)" % (module,command))
command_line = [python,"-c",command]
return command_line
def run(module,command):
"""
module: e.g. "SavedPositionsPanel_2"
command: e.g. "ConfigurationsPanel()"
"""
from redirect import redirect
redirect(module)
import autoreload
import wx
if not hasattr(wx,"app"): wx.app = wx.App(redirect=False)
exec("from instrumentation import *") # -> locals()
exec("from %s import *" % module)
exec(command)
wx.app.MainLoop()
def modulename(object):
from inspect import getmodulename,getfile
return getmodulename(getfile(object))
if __name__ == '__main__':
from pdb import pm # for debugging
import logging
logging.basicConfig(
level=logging.DEBUG,
format="%(asctime)s %(levelname)s %(module)s.%(funcName)s: %(message)s",
)
name = "detector_configuration"
print('start("SavedPositionsPanel_2","ConfigurationsPanel()")')
print('''start("SavedPositionsPanel_2","SavedPositionsPanel(name=%r,globals=globals(),locals=locals())")''' % name)
print('''start("SavedPositionsPanel_2","ConfigurationPanel(name=%r,globals=globals(),locals=locals())")''' % name)
print('''run("SavedPositionsPanel_2","SavedPositionsPanel(name=%r,globals=globals(),locals=locals())")''' % name)
<file_sep>"""Read LeCroy binary waveform file.
For offline analysis of wavform files, not for waveform data acqisition.
<NAME>, 30 Jan 2012 - 14 Apr 2017
Found documentation about the LeCroy binary waveform format in form of Matlab
code:
File ReadLeCroyBinaryWaveform.m by <NAME>, LeCroy, 2006
Extended by <NAME>, 13 Jan 2010, to read multisegment waveforms.
http://www.mathworks.com/matlabcentral/fileexchange/26375
Structure of a LeCroy binary waveform file:
Magic number "#9001120146", length: 11 bytes
Binary wave descriptor, starting with WAVEDESC", length: 346 bytes
Optional comment section, usully length 0 bytes
Trigger time/trigger offset array, length: 16 bytes times number of segments
pairs of 64-bit floating point numbers
Waveform data, length: number of samples per trigger, plus two,
times number of segments
signed 8-bit integers
"""
__version__ = "1.4" # sub sampling rate ajustments to time scales
from logging import debug,info,warn,error
def read_waveform(filename):
"""Filename: path of .trc file.
Return value: tuple of two arrays, time, voltage"""
content = file(filename,"rb").read()
wavedesc_offset = content.find("WAVEDESC")
wavedesc = content[wavedesc_offset:wavedesc_offset+346]
from struct import unpack
comm_type, = unpack("<H",wavedesc[32:34]) # 0 = 8-bit, 1=16-bit
comm_order, = unpack("<H",wavedesc[34:36]) # 0=big endian, 1=little endian
# Check if format is indeed little-endian.
assert(comm_order != 0)
wave_descriptor_length, = unpack("<i",wavedesc[36:40])
user_text_length, = unpack("<i",wavedesc[40:44])
trig_time_array_size, = unpack("<i",wavedesc[48:52])
wave_array_1, = unpack("<i",wavedesc[60:64])
wave_array_count, = unpack("<i",wavedesc[116:120])
subarray_count, = unpack("<i",wavedesc[144:148]) # number of trigger events
vertical_gain, = unpack("<f",wavedesc[156:160])
vertical_offset, = unpack("<f",wavedesc[160:164])
horiz_interval, = unpack("<f",wavedesc[176:180])
horiz_offset, = unpack("<d",wavedesc[180:188])
data_offset = wavedesc_offset + wave_descriptor_length + user_text_length + \
trig_time_array_size
from numpy import frombuffer,int8,int16,float64,concatenate,zeros,nan
dtype = int8 if comm_type == 0 else int16
data = frombuffer(content[data_offset:],dtype).astype(float)
Nsamples = wave_array_count/subarray_count
expected_size = subarray_count*Nsamples
if len(data) < expected_size:
warn("%s: expecting %d*%d=%d samples, file truncated at %d samples." %
(filename,subarray_count,Nsamples,expected_size,len(data)))
data = concatenate((data,nan*zeros(expected_size-len(data))))
data = data.reshape((subarray_count,Nsamples))
# Convert counts to voltage.
U = data*vertical_gain - vertical_offset
# Reconstruct time scales.
trigger_time_array_offset = wavedesc_offset + wave_descriptor_length + user_text_length
trigger_time_array = content[trigger_time_array_offset:trigger_time_array_offset+trig_time_array_size]
data = frombuffer(trigger_time_array,float64)
data = data.reshape((subarray_count,2))
relative_trigger_times,trigger_offsets = data.T
from numpy import arange,row_stack,array
t = array([arange(0,Nsamples)*horiz_interval+t0 for t0 in trigger_offsets])
##t = array([arange(0,Nsamples)*horiz_interval for t0 in trigger_offsets])+trigger_offsets[0]
return t,U
def trigger_times(filename):
"""Filename: path of .trc file.
Return value: tuple of two arrays, time, voltage"""
content = file(filename,"rb").read()
wavedesc_offset = content.find("WAVEDESC")
wavedesc = content[wavedesc_offset:wavedesc_offset+346]
from struct import unpack
second, = unpack("<d",wavedesc[296+0:296+8])
minute, = unpack("B" ,wavedesc[296+8:296+9])
hour, = unpack("B" ,wavedesc[296+9:296+10])
day, = unpack("B" ,wavedesc[296+10:296+11])
month, = unpack("B" ,wavedesc[296+11:296+12])
year, = unpack("H" ,wavedesc[296+12:296+14])
from time import mktime
from numpy import floor,rint
trigger_time = mktime((year,month,day,hour,minute,int(floor(second)),-1,-1,-1))\
+(second-floor(second))
from struct import unpack
comm_type, = unpack("<H",wavedesc[32:34]) # 0 = 8-bit, 1=16-bit
comm_order, = unpack("<H",wavedesc[34:36]) # 0=big endian, 1=little endian
# Check if format is indeed little-endian.
assert(comm_order != 0)
wave_descriptor_length, = unpack("<i",wavedesc[36:40])
user_text_length, = unpack("<i",wavedesc[40:44])
trig_time_array_size, = unpack("<i",wavedesc[48:52])
subarray_count, = unpack("<i",wavedesc[144:148]) # number of trigger events
trigger_time_array_offset = wavedesc_offset + wave_descriptor_length + user_text_length
trigger_time_array = content[trigger_time_array_offset:trigger_time_array_offset+trig_time_array_size]
from numpy import frombuffer,int8,float64
data = frombuffer(trigger_time_array,float64)
data = data.reshape((subarray_count,2))
relative_trigger_times,trigger_offsets = data.T
trigger_times = trigger_time+relative_trigger_times
return trigger_times
def trigger_time(filename):
"""Filename: path of .trc file.
Return value: time in seconds since 1 jan 1970 0:00 UTC"""
content = file(filename,"rb").read()
wavedesc_offset = content.find("WAVEDESC")
wavedesc = content[wavedesc_offset:wavedesc_offset+346]
from struct import unpack
second, = unpack("<d",wavedesc[296+0:296+8])
minute, = unpack("B" ,wavedesc[296+8:296+9])
hour, = unpack("B" ,wavedesc[296+9:296+10])
day, = unpack("B" ,wavedesc[296+10:296+11])
month, = unpack("B" ,wavedesc[296+11:296+12])
year, = unpack("H" ,wavedesc[296+12:296+14])
from time import mktime
from numpy import floor,rint
trigger_time = mktime((year,month,day,hour,minute,int(floor(second)),-1,-1,-1))\
+(second-floor(second))
return trigger_time
def show_waveform(filename,first=0,N=2):
"""for testing"""
t,U = read_waveform(filename)
if first > len(U): first = len(U)-1
if first+N > len(U): N = len(U)-first
from pylab import plot,grid,xlabel,ylabel,ylim,show
plot(t[first:first+N].T/1e-9,U[first:first+N].T,linestyle="-",marker="o",
ms=3,mew=0)
grid()
xlabel("t [ns]")
ylabel("U [V]")
##ylim(-4,4)
show()
def time_string(seconds):
from datetime import datetime
from time import gmtime,localtime,strftime
t = datetime.fromtimestamp(seconds).strftime("%d %b %Y %H:%M:%S.%f")
return t
if __name__ == "__main__": # for testing
from glob import glob
from numpy import array,diff,sort,concatenate
filename = "//femto-data/C/Data/2017.03/WAXS/RNA-VA1-WT/RNA-VA1-WT-1/"\
"laser_traces/RNA-VA1-WT-1_1_31C_1_-10.1us_02_laser.trc"
filenames = glob("//femto-data/C/Data/2017.03/WAXS/RNA-VA1-WT/RNA-VA1-WT-1/"\
"laser_traces/RNA-VA1-WT-1_1_31C_1_*_laser.trc")
from os.path import getmtime
from numpy import diff,where
print("show_waveform(filename,first=0,N=41)")
##print("time_string(getmtime(filename))")
print("t = sort(concatenate([trigger_times(f) for f in filenames]))")
print("dt = diff(sort(concatenate([trigger_times(f) for f in filenames])))")
##print("where(diff(trigger_times(filename))>0.025)")
##print("[time_string(t) for t in trigger_times(filename)]")
<file_sep>MEAN.filename = '/net/mx340hs/data/anfinrud_1906/Archive/NIH.SCATTERING_OPTICAL.MEAN.txt'
STDEV.filename = '//mx340hs/data/anfinrud_1906/Archive/NIH.SCATTERING_OPTICAL.STDEV.txt'<file_sep>EPICS_enabled = True
description = 'High-speed chopper X'
prefix = '14IDB:m1'
target = 37.18<file_sep>[.ShellClassInfo]
IconFile=I:\NIH\Software\icons\BioCARS.ico
IconIndex=0
<file_sep>#!/usr/bin/env python
"""
Driver for Prosilica GigE CCD cameras.
Author: <NAME>
Date created: 2010-10-16
Date last modified: 2018-10-30
"""
# Copied libPvAPI-1.22-OSX-x86.dylib from AVT GigE SDK 1.22 for Mac OS X,
# bin-pc/x86/libPvAPI.dylib
# AVT PvAPI Programmer's Reference Manual, Version 1.22, March 10, 2010
# https://www.alliedvision.com/fileadmin/content/documents/products/software/software/PvAPI/docu/PvAPI_SDK_Manual.pdf
# Lauecollect/doc/PvAPI-1.22.pdf
# AVT PvAPI Programmer's Reference Manual, V1.28 20 March 2015
# https://www.alliedvision.com/fileadmin/content/documents/products/software/software/PvAPI/docu/PvAPI_SDK_Manual.pdf
# Lauecollect/doc/PvAPI-1.28.pdf
# AVT GigE Camera and Driver Attributes Firmware 1.38, April 7, 2010
# Lauecollect/doc/PvAPI_Attributes-1.38.pdf
# AVT GigE Camera and Driver Attributes, Prosilica Firmware version 01.54,
# V1.4.1 2017-June-19
# https://www.alliedvision.com/fileadmin/content/documents/products/cameras/various/features/Camera_and_Driver_Attributes.pdf
# Lauecollect/doc/PvAPI_Attributes-1.54.pdf
# ctypes Tutorial
# http://python.net/crew/theller/ctypes/tutorial.html
import ctypes
__version__ = "2.4" # Frame, queued_time
class GigE_camera(object):
default_width = 1360
default_height = 1024
reception_timeout = 10.0
def __init__(self,IP_addr="",use_multicast=True,auto_resume=True):
"""If IP_addr is omitted the first detected GigE camera in the local
network is used.
If use_multicast is True the other viewer can watch the same video stream
simulataneously.
If False on this connection can receive live video.
Under Linux, python must by run with 'sudo' for Multicast to work.
"""
from ctypes import c_void_p
from numpy import nan
self.IP_addr = IP_addr
self.use_multicast = use_multicast
self.auto_resume = auto_resume
self.handle = c_void_p()
self.last_error = ""
self.mode = "not connected"
self.acquisition_started = False
self.capturing_images = True
self.Frames = [self.Frame() for i in range(0,2)]
# Mark all frames as been not "valid" (Status = 0).
for i in range(0,len(self.Frames)): self.Frames[i].frame.Status = 99
self.framerate = nan
class Frame(object):
def __init__(self):
self.frame = tPvFrame()
self.buffer = ""
self.queued_time = 0
@property
def reception_pending_time(self):
from time import time
from numpy import nan
if self.reception_pending:
value = time() - self.reception_started_time
else: value = nan
return value
@property
def reception_pending(self):
value = self.reception_started and not self.reception_finished
return value
@property
def reception_started(self):
ImageBuffer = self.frame.ImageBuffer
value = ImageBuffer and len(ImageBuffer)>=2 and \
ImageBuffer[0:2] != "\xFE\xFE"
return value
@property
def reception_finished(self):
ImageBuffer = self.frame.ImageBuffer
value = ImageBuffer and len(ImageBuffer)>=2 and \
ImageBuffer[-2:] != "\xFE\xFE"
return value
def get_reception_started_time(self):
from numpy import nan,isnan
value = getattr(self,"__reception_started_time__",nan)
if isnan(value) and self.reception_started:
from time import time
value = time()
self.set_reception_started_time(value)
return value
def set_reception_started_time(self,value):
setattr(self,"__reception_started_time__",value)
reception_started_time = property(get_reception_started_time,set_reception_started_time)
def init(self,mode="control"):
from socket import gethostbyname,inet_aton
from struct import unpack
from ctypes import c_void_p,byref
# Is the current handle valid and is the current mode the right mode?
if handle_valid(self.handle):
if self.mode == mode: return # nothing to do
if self.mode == "control": return # control is good for read-only too
# Even for handles no longer valid 'PvCameraClose' should be called.
if self.handle: PvAPI.PvCameraClose (self.handle)
self.handle.value = None
self.mode = "not connected"
self.last_error = ""
self.mode = mode
dot_addr = gethostbyname(self.IP_addr)
int_addr, = unpack("I",inet_aton(dot_addr))
access = 4 if mode == "control" else 2
status = PvAPI.PvCameraOpenByAddr (int_addr,access,byref(self.handle))
# If failed to connect as 'master', try as 'monitor'.
##print "init, first attempt: mode %r, status %r" % (mode,status)
if mode == "control" and status == 7: # 7:cannot be opened in the specified mode
self.mode = "read-only"
status = PvAPI.PvCameraOpenByAddr (int_addr,2,byref(self.handle))
if status != 0:
self.mode = "not connected"
self.last_error = "not connected: "+error(status)
def start(self):
"""Starts video streaming."""
from ctypes import byref,c_char,c_char_p,addressof
if self.capturing: return # already started
self.init("control")
if self.handle.value == None: return # camera unusable
# Enable multicast mode so the connection can be shared by other viewers.
# It is the responibility of the first view conntecting to request
# multicast. If the first viewer connects without it, no other viewer
# can access the video stream while the first one is connected.
if self.use_multicast and self.mode == "control":
self.set_attr("MulticastEnable","On")
# Allocate two frame buffers.
frame_size = self.get_attr("TotalBytesPerFrame")
for i in range(0,len(self.Frames)):
self.Frames[i].buffer = (c_char*frame_size)()
self.Frames[i].frame.ImageBuffer = c_char_p(addressof(self.Frames[i].buffer))
self.Frames[i].frame.ImageBufferSize = frame_size
# Initialize the image capture stream.
status = PvAPI.PvCaptureStart(self.handle)
if status != 0:
self.last_error = "not capturing: "+error(status)
return
else: self.last_error = ""
# Set the camera in acquisition mode.
if self.mode == "control":
# Make sure that the ethernet packet size is OK for a network
# that does not support Jumbo frames. (Factory setting is 8228
# bytes.)
if self.get_attr("PacketSize") > 1500:
self.set_attr("PacketSize",1500)
# Set the bandwidth appropriately for 2 cameras sharing
# one 100-Mb connection.
#self.set_attr("StreamBytesPerSecond",5000000)
status = PvAPI.PvCommandRun(self.handle,"AcquisitionStart")
if status != 0:
self.acquisition_started = False
self.last_error = "not started: "+error(status)
raise RuntimeError("AcquisitionStart: "+error(status))
else: self.acquisition_started = True; self.last_error = ""
# Start the capturing of the life video network packets sent by the
# camera to be reassembled as images in local memory.
# This is done in a background thread in the PvAPI library, started by
# calling PvCaptureQueueFrame.
for i in range(0,len(self.Frames)):
# Mark frame buffer as "not containg a valid image".
self.Frames[i].frame.FrameCount = 0
self.Frames[i].frame.TimestampHi = 0
self.Frames[i].frame.TimestampLo = 0
self.Frames[i].frame.Status = 99 # 0 Status indicates "frame complete".
self.Frames[i].buffer[0:2] = "\xFE\xFE" # marker for testing
self.Frames[i].buffer[-2:] = "\xFE\xFE" # marker for testing
from time import time
self.Frames[i].queued_time = time()
from numpy import nan
self.Frames[i].reception_started_time = nan
status = PvAPI.PvCaptureQueueFrame(self.handle,
byref(self.Frames[i].frame),None)
if status != 0:
raise RuntimeError("PvCaptureQueueFrame: "+error(status))
# "PvCaptureQueueFrame" acquires only a single image.
# After this need to periodcally call "resume" to put back the
# image buffers into the capture queue.
self.capturing_images = True
@property
def reception_timed_out(self):
return self.reception_pending_time > self.reception_timeout
@property
def reception_pending_time(self):
return nanmax([Frame.reception_pending_time for Frame in self.Frames])
def resume(self):
"""To be called periodically when captuting images"""
if self.reception_timed_out: self.stop(); self.start()
# Image stream stops at image #65535
if self.current_frame_count >= 65000: self.stop(); self.start()
self.calculate_framerate()
from ctypes import byref
if not self.capturing_images: return
# Find buffers with images that were completed, except the current
# frame, and put them back into the queue of capture buffers.
current_frame_count = self.current_frame_count
for i in range(0,len(self.Frames)):
# Do not overwrite the last acquired image.
if self.Frames[i].frame.FrameCount == current_frame_count: continue
# Do not re-enqueue a buffer already in the queue.
if self.Frames[i].frame.FrameCount == 0: continue
if self.Frames[i].frame.Status == 99: continue
# Mark frame buffer as "not containg a valid image".
self.Frames[i].frame.FrameCount = 0
self.Frames[i].frame.TimestampHi = 0
self.Frames[i].frame.TimestampLo = 0
self.Frames[i].frame.Status = 99 # 0 Status 0 indicates "frame complete".
self.Frames[i].buffer[0:2] = "\xFE\xFE" # marker for testing
self.Frames[i].buffer[-2:] = "\xFE\xFE" # marker for testing
from time import time
self.Frames[i].queued_time = time()
from numpy import nan
self.Frames[i].reception_started_time = nan
status = PvAPI.PvCaptureQueueFrame(self.handle,
byref(self.Frames[i].frame),None)
if status != 0:
raise RuntimeError("PvCaptureQueueFrame: "+error(status))
def stop(self):
"""This is to disconnect for the camera and leave the Prosilica
Video Libary in an orderly state"""
self.capturing_images = False
self.acquisition_started = False
if self.handle.value != None:
PvAPI.PvCommandRun (self.handle,"AcquisitionStop")
PvAPI.PvCaptureEnd (self.handle)
PvAPI.PvCaptureQueueClear (self.handle)
PvAPI.PvCameraClose (self.handle)
self.handle.value = None
def get_capturing(self):
"""Has the image capture stream been started?
That is, has PvCaptureStart been called successfully?"""
from ctypes import c_uint32,byref
if self.handle == None: return False
is_started = c_uint32()
status = PvAPI.PvCaptureQuery (self.handle,byref(is_started))
if status != 0: return False
return (is_started.value != 0)
capturing = property(get_capturing)
def get_state(self):
if self.auto_resume: self.resume()
if not handle_valid(self.handle): state = "not connected"
else:
state = self.mode
if self.get_attr("MulticastEnable") == "On": state += ", multicast"
capturing = self.capturing
if capturing:
state += ", capturing"
if self.external_trigger: state += " (ext. trig.)"
if self.reception_pending_time > 0:
state += ", pending %.1f s" % self.reception_pending_time
elif self.acquisition_started: state += ", started"
if capturing and self.current_frame_count > 0:
state += (", %.3g fps" % self.framerate)
state += (", #%d" % self.current_frame_count)
state += ", "+self.pixel_format
if not self.pixel_format in ["Bayer8","Rgb24"]:
state += ", unsupported format"
error_codes = []
for Frame in self.Frames:
if Frame.frame.Status not in [0,99]:
if Frame.frame.Status not in error_codes:
error_codes+=[Frame.frame.Status]
for error_code in error_codes: state += ", "+error(error_code)
if self.last_error: state += ", "+self.last_error
return state
state = property (fget=get_state,doc="connection info")
def get_rgb_array(self):
"""Last read image as 3D nmupy array. Dimensions: 3xWxH
datatype: uint8
Usage R,G,B = camera.rgb_array"""
from numpy import frombuffer,uint8
w,h = self.width,self.height
return frombuffer(self.rgb_data,uint8).reshape(h,w,3).T
rgb_array = RGB_array = property(get_rgb_array)
def get_rgb_data(self):
"""All this pixels of the last read image as one single chunk
of contiguous data.
The format is one byte per pixel, in the order R,G,B, by scan line,
top left to bottom right.
'PixelFormat' attribute of the camera needs to be set to 'Bayer8'
or 'Rgb24'.
"""
if self.auto_resume: self.resume()
if not self.has_image: return self.default_rgb_data()
if self.image_pixel_format == "Rgb24": return self.get_image_data()
elif self.image_pixel_format == "Bayer8": return self.rgb_from_bayer8()
else: return ""
rgb_data = property(get_rgb_data)
def default_rgb_data(self):
""" This is used in case RGB data is requested but no image is
available yet. Returns a black image of appropriate size
(CCD chip size with binning and ROI applied)."""
rgb_size = self.width*self.height*3
return "\0"*rgb_size
def get_image_data(self):
"""Returns all this pixels of the last read image as one single chunk
of contiguous data."""
from ctypes import string_at
frame = self.Frames[self.current_buffer()].frame
buffer = self.Frames[self.current_buffer()].buffer
if frame.ImageBufferSize == 0: return ""
return string_at(buffer,frame.ImageBufferSize)
def rgb_from_bayer8 (self):
"Assuming BayerPattern = 0: first line RGRG, second line GBGB..."
from ctypes import addressof,byref,c_char,c_char_p,string_at
frame = self.Frames[self.current_buffer()].frame
RGB_size = frame.ImageBufferSize*3
RGB = (c_char*RGB_size)()
addr = addressof(RGB)
R,G,B = c_char_p(addr),c_char_p(addr+1),c_char_p(addr+2)
PvAPI.PvUtilityColorInterpolate(byref(frame),R,G,B,2,0)
return string_at(RGB,RGB_size)
# PvUtilityColorInterpolate converts 8-bit Bayer mosaic images into
# RGB24 images. The first parameter is the input frame data structure,
# the following three parameter are the strating addresses for the
# output R,G and B value respectively. The number 2 is the number of
# bytes to skip between subsequent of R values (same for G and B),
# and the last parameter is the number of bytes the skip and the end
# is a scan line as padding.
# Although RGB data is continguous in memory, Prosilica requires to
# pass three pointers for the same chunck of memory.
# This gives the function the flexibility to also generate BRG images.
# The number of bytes between R values is also a parameter so the
# function can generate also RGB32 or RGBA output (skipping 3 bytes)
# or separate color planes (skpping 0 bytes).
def save_image(self,filename):
"""Acquire a single image from the camera and save it as a file.
filename: the exension determines the image format, may be '.jpg',
'.png' or '.tif' or any other extensino supported by the Python Image
Library (PIL)"""
from PIL import Image
image = Image.new('RGB',(self.width,self.height))
image.fromstring(self.rgb_data)
image.save(filename)
def get_width(self):
frame = self.Frames[self.current_buffer()].frame
if frame.FrameCount > 0: width = frame.Width
else: width = self.get_attr("Width")
if width == 0 or width == None: width = self.default_width
return width
def set_width(self,value): self.set_attr("Width",value)
width = property(get_width,set_width,doc="""number of columns in the image.
If smaller that the chip width and bin factor = 1, a region of interest
if read""")
def get_height(self):
frame = self.Frames[self.current_buffer()].frame
if frame.FrameCount > 0: height = frame.Height
else: height = self.get_attr("Height")
if height == 0 or height == None: height = self.default_height
return height
def set_height(self,value): self.set_attr("Height",value)
height = property(get_height,set_height,doc="""number of rows in the image.
If smaller that the chip height and bin factor = 1, a region of interest
if read""")
def get_bin_factor(self):
return max(self.get_attr("BinningX"),self.get_attr("BinningY"))
def set_bin_factor(self,value):
previous_bin_factor = self.bin_factor
previous_width = self.width
previous_height = self.height
self.set_attr("BinningX",value)
self.set_attr("BinningY",value)
# Adjust width and height, so the portion of the image read is
# independent of bin factor.
# (This happens atomatically when increasing the bin factor, bot does
# not when decreasing the bin factor.)
if self.bin_factor < previous_bin_factor:
scale = float(previous_bin_factor) / self.bin_factor
self.width = previous_width * scale
self.height = previous_height * scale
bin_factor = property(get_bin_factor,set_bin_factor,
doc="common CCD row and column binning factor")
def get_pixel_format(self):
"""Format (RGB,mono,YUV,Bayer) and number of bits per pixel as
set up in the camera. Last buffered image in local memory might be
different. See 'image_pixel_format'"""
return str(self.get_attr("PixelFormat"))
def set_pixel_format(self,value): self.set_attr("PixelFormat",value)
pixel_format = property(get_pixel_format,set_pixel_format)
def get_image_pixel_format(self):
"""Format (RGB,mono,YUV,Bayer) and number of bits per pixel for
last acquired image stored in local memory.
Camera might be currently setup to send images in a different format.
See 'pixel_format'.
Returns '' if no image was acquired so far"""
frame = self.Frames[self.current_buffer()].frame
if frame.FrameCount > 0: return self.pixel_format_name(frame.Format)
else: return ""
image_pixel_format = property(get_image_pixel_format)
def pixel_format_name(self,pixel_format):
"Translates GigE Vision image format numbers to a readable form"
formats = {
0: "Mono8",
1: "Mono16",
2: "Bayer8",
3: "Bayer16",
4: "Rgb24",
5: "Rgb48",
6: "Yuv411",
7: "Yuv422",
8: "Yuv444",
9: "Bgr24",
10: "Rgba32",
11: "Bgra32"
}
try: return formats[pixel_format]
except: return "unknown pixel type (%d)" % format
pixel_formats = ["Mono8","Bayer8","Bayer16","Rgb24","Rgb48","Yuv411",
"Yuv422","Yuv444","Bgr24","Rgba32","Bgra32"]
def frame_timestamp(self,i):
"""i =0,1. Returns a camera generated time stamp of an image
in units of s"""
lo = self.Frames[i].frame.TimestampLo
hi = self.Frames[i].frame.TimestampHi
count = (hi<<32)+lo
# Timestamp frequency: 36,858,974 Hz for firmware 1.36.0
# Starting from firmware 1.50.1 the timestamp in units of nanoseconds.
# Is there a resource to read to get the timestamp clock frequency?
dt = 1/36858974. if self.firmware_version < 1.50 else 1e-9
t = count*dt
return t
@property
def firmware_version(self):
"""As floating point number in the format ii.jj,
where ii is the major and jj is the minor version number"""
from numpy import nan
if not hasattr(self,"__firmware_version__"):
i = self.get_attr("FirmwareVerMajor")
if i is None: return nan
j = self.get_attr("FirmwareVerMinor")
self.__firmware_version__ = i+j*0.01
return self.__firmware_version__
def get_timestamp(self):
if not self.has_image: return 0.0
return self.frame_timestamp(self.current_buffer())
timestamp = property(get_timestamp,doc="""camera-generated
time stamp of current image in seconds""")
def calculate_framerate(self):
"""Calculate the image acquisition frequency in Hz and store it
in the member variable 'framerate'"""
# The "StatFrameRate" attribute always reads 0.0.
# Called preiodically from "resume".
from numpy import argsort,array as a,nan
if len(self.Frames) < 2: return nan
# Find the last two image based on their frame count.
counts = a([self.Frames[i].frame.FrameCount for i in range(0,len(self.Frames))])
times = a([self.frame_timestamp(i) for i in range(0,len(self.Frames))])
order = argsort(counts)
count1,count2 = counts[order][-2:]
time1,time2 = times[order][-2:]
if count1 == 0 or count2 == 0: return nan # not enough valid images.
# Calculate the frame rate based on the last two images.
if time2 == time1: return nan
self.framerate = (count2-count1)/(time2-time1)
def get_frame_count(self):
"""Camera-generated serial number the last acquired image in local
memory which is transferred completely
The first image aquired has a frame count of one.
A return value of zero indicates that no images have been acquired
so far."""
if self.auto_resume: self.resume()
return self.current_frame_count
frame_count = property(get_frame_count)
def get_internal_frame_count(self):
# frame count for internal usage
counts = []
for i in range(0,len(self.Frames)):
if self.Frames[i].frame.Status == 0: counts += [self.Frames[i].frame.FrameCount]
if len(counts) == 0: return 0
return max(counts)
current_frame_count = property(get_internal_frame_count)
def get_exposure_time (self):
"Current electronic shutter time (in both manual and automatic mode)"
# The attribute ExposureValue is in units of microseconds.
try: return self.get_attr("ExposureValue")*1e-6
except TypeError: return 0.0
def set_exposure_time (self,value):
"Sets 'ExposureMode' to 'Manual' and changes electronic shutter time ."
# Also, make sure 'ExposureMode' is set to 'Manual', otherwise
# the attribute 'ExposureValue' would not be changable.
self.set_attr("ExposureMode","Manual")
# The attribute ExposureValue is in units of microseconds.
self.set_attr("ExposureValue",round(value*1e6))
exposure_time = property(get_exposure_time,set_exposure_time,
doc="""Electronic shutter time (in both manual and automatic mode).
If set, the exposure mode is set to 'Manual'.
The minimum value is 10 us, the maximum 60 s.""")
def get_auto_exposure(self):
if self.get_attr("ExposureMode") == "Auto": return True
else: return False
def set_auto_exposure(self,value):
if value == True: self.set_attr("ExposureMode","Auto")
else: self.set_attr("ExposureMode","Manual")
auto_exposure = property(get_auto_exposure,set_auto_exposure,
doc="If True the camera dynamically adjusts its integration time")
def current_buffer(self):
"""The index of the buffer that contains the last aquired complete image
"""
# In order for an to be completely transfered its "Status" field must
# be zero.
current_frame_count = self.current_frame_count
if current_frame_count == 0: return 0
for i in range(0,len(self.Frames)):
if self.Frames[i].frame.FrameCount != current_frame_count: continue
if self.Frames[i].frame.Status != 0: continue
return i
return 0
def get_has_image(self):
# In order for one image to be complete the frame count in both
# buffers must be > 1.
if self.auto_resume: self.resume()
if self.current_frame_count == 0: return False
if not self.image_pixel_format in ["Bayer8","Rgb24"]: return False
return True
has_image = property(get_has_image,doc="Is there currently a valid image?")
def get_center(self):
"""For displaying a crosshair on the image.
In order for the crosshair to be shared among viewers running on
different machines, its coordinates are stored inside the camera
itself. There is are no unused or general purpose variables that
could be used for this purpose. However, the upper limits for the 'DSP
Subregion' (2^32-1 pixels) are much larger that the actual chip size
(1360x1024). Thus any value written to the variables larger than 1359
will no change the effective subregion used for automatic exposure and
automatic white balance.
"""
if self.auto_resume: self.resume()
val1 = self.get_attr("DSPSubregionRight")
val2 = self.get_attr("DSPSubregionBottom")
if val1 == None or val1 == None: return None
maxval = 2**32-1
x = int(maxval - val1)
y = int(maxval - val2)
if x == 0 and y == 0: return None
return x,y
def set_center(self,center):
"""For displaying a crosshair on the image. 'Center' is an (x,y) tuple.
"""
if center == None: return
x = center[0]; y = center[1]
maxval = 2**32-1
self.set_attr("DSPSubregionRight",maxval-x)
self.set_attr("DSPSubregionBottom",maxval-y)
self.save_parameters()
center = property (get_center,set_center,doc=
"Crosshair position saved in non-volatile memory of camera")
def get_stream_bytes_per_second (self):
return self.get_attr("StreamBytesPerSecond")
def set_stream_bytes_per_second (self,value):
self.set_attr("StreamBytesPerSecond",value)
stream_bytes_per_second = property(get_stream_bytes_per_second,
set_stream_bytes_per_second,
doc="Maximum transmission rate in Bytes/s")
def get_trigger_mode(self):
"""Possible values: "Freerun", "SyncIn1", "SyncIn2", "FixedRate",
"Software" """
return self.get_attr("FrameStartTriggerMode")
def set_trigger_mode(self,value): self.set_attr("FrameStartTriggerMode",value)
trigger_mode = property(get_trigger_mode,set_trigger_mode)
def get_external_trigger(self):
"Is external trigger enabled?"
mode = self.trigger_mode
if mode == None: return False
return ("SyncIn" in mode)
def set_external_trigger(self,value):
if value: self.trigger_mode = "SyncIn2"
else: self.trigger_mode = "Freerun"
external_trigger = property(get_external_trigger,set_external_trigger)
def get_gain(self):
"Defines the dynamic range, 0 = max. range, 22 = min. range"
return self.get_attr("GainValue")
def set_gain(self,value): self.set_attr("GainValue",value)
gain = property(get_gain,set_gain)
def get_attr(self,name):
"""Queries a camera attribute.
Attributes are named variables inside the GigE camera, used to control
and monitor it.
The return value can be of type int,float or string.
The return value is None is the attribute is not readable"""
from ctypes import byref,c_uint32,c_float
self.init("read-only")
if self.handle.value == None: return None
info = tPvAttributeInfo()
status = PvAPI.PvAttrInfo (self.handle,name,byref(info))
if status != 0: return None
if info.Datatype == ePvDatatypeUint32:
value = c_uint32()
status = PvAPI.PvAttrUint32Get (self.handle,name,byref(value))
if status != 0: return None
return value.value
if info.Datatype == ePvDatatypeFloat32:
value = c_float()
status = PvAPI.PvAttrFloat32Get (self.handle,name,byref(value))
if status != 0: return None
return value.value
if info.Datatype == ePvDatatypeEnum:
value = '\0'*81
status = PvAPI.PvAttrEnumGet (self.handle,name,value,80,None)
if status != 0: return None
return value.strip('\0')
if info.Datatype == ePvDatatypeString:
value = '\0'*81
status = PvAPI.PvAttrStringGet (self.handle,name,value,80,None)
if status != 0: return None
return value.strip('\0')
def set_attr (self,name,value):
"""Modifies a camera attribute.
value can be of type int,float or string."""
from ctypes import byref,c_uint32,c_float
self.init("control")
if self.handle.value == None: return
if self.mode != "control": return
info = tPvAttributeInfo()
status = PvAPI.PvAttrInfo (self.handle,name,byref(info))
if status != 0:
self.last_error = name+": "+error(status)
print self.last_error
if info.Datatype == ePvDatatypeUint32:
value = int(round(float(value)))
vmin = c_uint32(); vmax = c_uint32()
status = PvAPI.PvAttrRangeUint32 (self.handle,name,byref(vmin),
byref(vmax))
if status == 0:
if value < vmin.value: value = vmin.value
if value > vmax.value: value = vmax.value
status = PvAPI.PvAttrUint32Set (self.handle,name,value)
elif info.Datatype == ePvDatatypeFloat32:
value = float(value)
vmin = c_float(); vmax = c_float()
status = PvAttrRangeFloat32 (self.handle,name,byref(vmin),
byref(vmax))
if status == 0:
if value < vmin.value: value = vmin.value
if value > vmax.value: value = vmax.value
status = PvAPI.PvAttrFloat32Set (self.handle,name,value)
elif info.Datatype == ePvDatatypeEnum:
status = PvAPI.PvAttrEnumSet (self.handle,name,str(value))
elif info.Datatype == ePvDatatypeString:
status = PvAPI.PvAttrStringSet (self.handle,name,str(value))
else: return
if status != 0:
self.last_error = name+": "+error(status)
##print self.last_error
else: self.last_error = ""
def command (self,name):
"Executes a named command inside the camera"
self.init("control")
if self.handle.value == None: return
if self.mode != "control": return
status = PvAPI.PvCommandRun (self.handle,name)
if status != 0:
self.last_error = "Run Command %r: %s" % (name,error(status))
##print self.last_error
def save_parameters(self):
"""Writes current settings to non-volatile memory as default
configuration to be loaded at power up."""
self.set_attr("ConfigFileIndex",1)
self.set_attr("ConfigFilePowerUp",1)
self.command("ConfigFileSave")
def get_buffer_status(self):
"""[for debugging] list which image buffers are in use and what their
their frame number s and timestamps are"""
status = ""
for i in range(0,len(self.Frames)):
status += "[%d] " % i
if self.Frames[i].frame.FrameCount:
status += "#%02d " % self.Frames[i].frame.FrameCount
else: status += " - "
if self.Frames[i].frame.Status == 99: status += " - "
elif self.Frames[i].frame.Status == 0: status += "OK "
else: status += "%2.2d " % self.Frames[i].frame.Status
if self.frame_timestamp(i):
status += "%11.3fs " % self.frame_timestamp(i)
else: status += " - "
return status[:-1]
buffer_status = property(get_buffer_status)
def initialize():
load_library()
if hasattr(PvAPI,"initialized"): return
status = PvAPI.PvInitialize()
if status != 0: raise RuntimeError("PvInitialize: "+error(status))
PvAPI.initialized = True
def load_library():
global PvAPI
import os,ctypes
if os.name == 'nt': LoadLibrary = ctypes.windll.LoadLibrary
else: LoadLibrary = ctypes.cdll.LoadLibrary
# Try to load any of the libraries found, until sucessful.
library_loaded = ""
for filename in library_pathnames():
try: PvAPI = LoadLibrary(filename)
except: continue
library_loaded = filename
break
##print "PvAPI library loaded: %r" % library_loaded
if not library_loaded:
# Report which files was tried, but were not usable and why.
message = "None of the following PvAPI was usable:\n"
for filename in library_pathnames():
try: LoadLibrary(filename); exception = "OK"
except Exception,exception: pass
message += "%s: %s\n" % (filename,exception)
message.rstrip("\n")
raise RuntimeError(message)
def library_pathnames():
"""location of the dynamic library as lsit of pathnames"""
from sys import path
from os.path import exists
from platform import system,machine
from glob import glob
if not "." in path: path += ["."]
pathnames = []
for directory in path:
if system() == "Darwin": filename = "libPvAPI*.dylib"
elif system() == "Linux": filename = "libPvAPI*.so"
elif system() == "Windows": filename = "PvAPI*.dll"
else: filename = "libPvAPI*.so"
for pathname in glob(directory+"/"+filename):
if not pathname in pathnames: pathnames += [pathname]
if pathnames == []:
raise RuntimeError("Library %r not found in %r" % (filename,path))
return pathnames
def handle_valid(handle):
"Does this handle refer to a connection that is alive?"
from ctypes import c_int32,byref
if handle.value == None: return False
is_started = c_int32()
status = PvAPI.PvCaptureQuery (handle,byref(is_started))
if status == 0: return True
else: return False
def error (status):
"Readable error message from PvAPI call return status"
msg = {
0: "no error",
1: "unexpected camera fault",
2: "unexpected fault in PvApi or driver",
3: "camera handle is invalid",
4: "bad parameter to API call",
5: "sequence of API calls is incorrect",
6: "camera or attribute not found",
7: "camera cannot be opened in the specified mode",
8: "camera was unplugged",
9: "setup is invalid (an attribute is invalid)",
10: "system/network resources or memory not available",
11: "1394 bandwidth not available",
12: "too many frames on queue",
13: "frame buffer is too small",
14: "frame cancelled by user",
15: "the data for the frame was lost",
16: "some data in the frame is missing",
17: "timeout during wait",
18: "attribute value is out of the expected range",
19: "attribute is not this type (wrong access function)",
20: "attribute write forbidden at this time",
21: "attribute is not available at this time",
22: "a firewall is blocking the traffic"
}
try: return msg[status]
except: return "unknown error (%d)" % status
# Attribute data types
ePvDatatypeUnknown = 0
ePvDatatypeCommand = 1
ePvDatatypeRaw = 2
ePvDatatypeString = 3
ePvDatatypeEnum = 4
ePvDatatypeUint32 = 5
ePvDatatypeFloat32 = 6
from ctypes import Structure
class tPvAttributeInfo(Structure):
from ctypes import c_int32,c_char_p
_fields_ = [
("Datatype", c_int32),
("Flags", c_int32),
("Category", c_char_p),
("Impact", c_char_p),
("_reserved", c_int32*4)
]
class tPvFrame(Structure):
from ctypes import c_ulong,c_void_p,c_char_p
_fields_ = [
("ImageBuffer",c_char_p), # Your image buffer (was: c_void_p)
("ImageBufferSize",c_ulong), # Size of your image buffer in bytes
("AncillaryBuffer",c_void_p), # Your buffer to capture associated
# header & trailer data for this image.
("AncillaryBufferSize",c_ulong), # Size of your ancillary buffer in bytes
# (can be 0 for no buffer).
("Context",c_void_p*4), # For your use (valuable for your
# frame-done callback).
("_reserved1",c_ulong*8),
("Status",c_ulong), # Status of this frame
("ImageSize",c_ulong), # Image size, in bytes
("AncillarySize",c_ulong), # Ancillary data size, in bytes
("Width",c_ulong), # Image width
("Height",c_ulong), # Image height
("RegionX",c_ulong), # Start of readout region (left)
("RegionY",c_ulong), # Start of readout region (top)
("Format",c_ulong), # Image format
("BitDepth",c_ulong), # Number of significant bits
("BayerPattern",c_ulong), # Bayer pattern, if bayer format
("FrameCount",c_ulong), # Rolling frame counter
("TimestampLo",c_ulong), # Time stamp, lower 32-bits
("TimestampHi",c_ulong), # Time stamp, upper 32-bits
("_reserved2",c_ulong*32),
]
def sleep(seconds):
"""Return after for the specified number of seconds"""
# After load and initializing the PvAPI Python's built-in 'sleep' function
# stops working (returns too early). The is a replacement.
from time import sleep,time
t = t0 = time()
while t < t0+seconds: sleep(t0+seconds - t); t = time()
def nanmax(a):
from numpy import max,nan,isnan,any,asarray
a = asarray(a)
try:
valid = ~isnan(a)
return max(a[valid]) if any(valid) else nan
except: return nan
initialize()
def test():
global camera,self,i
camera = GigE_camera("id14b-prosilica4.cars.aps.anl.gov",
use_multicast=False)
self = camera # for debugging
i = 0 # for debugging
camera.start()
sleep(1)
print camera.state
def test_buffering():
global camera,self,i
camera = GigE_camera("id14b-prosilica4.cars.aps.anl.gov",
use_multicast=False)
self = camera # for debugging
camera.start()
for i in range(0,20):
print "%s" % (camera.buffer_status)
camera.resume()
sleep(0.1)
print camera.state
i = 0 # for debugging
def test_buffering_and_intensity():
from numpy import average,sum
global camera,self,i
camera = GigE_camera("id14b-prosilica4.cars.aps.anl.gov",
use_multicast=False)
self = camera # for debugging
camera.start()
for i in range(0,20):
image = camera.rgb_array
I = float(sum(image))/image.size
print "%d %s %8.2f" % (camera.has_image,camera.buffer_status,I)
sleep(0.2)
print camera.state
i = 0 # for debugging
def test_GUI():
from CameraViewer import CameraViewer
import wx
app = wx.PySimpleApp(redirect=False) # Needed to initialize WX library
camera = GigE_camera("id14b-prosilica4.cars.aps.anl.gov")
camera.use_multicast = True
viewer = CameraViewer (camera,title="Microscope Test",name="Camera_Test",
pixelsize=0.00465)
app.MainLoop()
def test_framerate():
camera = GigE_camera("id14b-prosilica4.cars.aps.anl.gov",
use_multicast=False)
self = camera # for debugging
camera.start()
sleep(2)
print camera.state
sleep(2)
print camera.state
print "StatFrameRate",camera.get_attr("StatFrameRate")
def test_single_image():
from time import time
from numpy import average,sum
global camera,image,I
camera = GigE_camera("id14b-prosilica4.cars.aps.anl.gov",
use_multicast=False)
camera.start()
t = time()
while not camera.has_image:
if time()-t > 2.0 and not "started" in camera.state:
print ("Prosilica image unreadable (%s)" % camera.state)
break
if time()-t > 5.0:
print ("image acquistion timed out (%s)" % camera.state)
break
sleep(0.1)
print "Status", camera.frames[0].Status,camera.frames[1].Status
print "acquisition time %.3fs" % (time()-t)
image = camera.rgb_array
I = float(sum(image))/image.size
print "average: %g counts/pixel" % I
print "fraction of pixels >0: %g" % average(image != 0)
if __name__ == "__main__": ## for tseting
camera = GigE_camera("pico3.niddk.nih.gov",use_multicast=False)
self = camera
print "camera.start()"
print "camera.state"
<file_sep>#!/usr/bin/env python
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
"""
EPICS Channel Access Protocol
https://github.io/python_ca
Author: <NAME> and <NAME>
Date created: 4/26/2009
Date last modified: 5/30/2017
Python Version: 2.7 and 3.7
The upgrade of the module to python 3.7 was done by <NAME>
functions tested: caget, caput,camonitor, cainfo
Based on: 'Channel Access Protocol Specification', version 4.11
http://epics.cosylab.com/cosyjava/JCA-Common/Documentation/CAproto.html
version 3.0.0
- was tested with server running on Python 2.7 code,
- however, CAServer3 running on Python 3.7 machine seems to fail to post PVs
"""
__authors__ = ["<NAME>"]
__credits__ = []
__license__ = "GPLv3+"
__version__ = "3.0.0" # monitor_always = True
__status__ = "Prototype"
import socket
from logging import debug,info,warn,error
import sys
timeout = 1.0 # s
DEBUG = False # Generate diagnostics messages?
monitor_always = True # run server communication alsways in background
class PV_info:
"""State information for each process variable"""
def __init__(self):
from time import time
t = time()
self.connection_requested = t # first time a PV was asked for
self.last_connection_requested = t # last time a PV was asked for
self.connection_initiated = 0 # time a CA connection for PV was initiated
self.servers_queried = [] # for address resolution
self.addr = None # IP address and port number of IOC
self.channel_ID = None # client-provided reference number for PV
self.channel_SID = None # server-provided reference number for PV
self.data_type = None # DOUBLE,INT,STRING,...
self.data_count = None # 1 if a scalar, >1 if an array
self.access_bits = None # premissions bit map (bit 0: read, 1: write)
self.IOID = 0 # last used read/write transaction reference number
self.subscription_ID = None # locally assiged reference number for server updates
self.response_time = 0 # timestamp of last reply from server
self.data = None # value in CA representation (big-edian binary data)
self.last_updated = 0 # timestamp of data, time update event received
self.write_data = None # if put in progres, new value in CA representation
self.write_requested = 0 # time WRITE_NOTIFY command sent
self.write_sent = 0 # time WRITE_NOTIFY command sent
self.write_confirmed = 0 # time WRITE_NOTIFY reply received
self.callbacks = [] # for "camonitor"
self.writers = [] # for "camonitor"
def reset(self):
"""Use if connection to IOC was lost"""
self.connection_initiated = 0
self.servers_queried = []
self.addr = None
self.channel_ID = None
self.channel_SID = None
self.data_type = None
self.data_count = None
self.access_bits = None
self.IOID = 0
self.subscription_ID = None
self.response_time = 0
self.data = None
self.last_updated = 0
self.write_data = None
self.write_requested = 0
self.write_sent = 0
self.write_confirmed = 0
def __str__(self):
s = "PV_info:"
for attr in dir(self):
if not "__" in attr:
s += "\n %s = %r" % (attr,getattr(self,attr))
return s
PVs = {} # Unique list of active process variables
class connection_info:
"Per CA server (IOC) state information"
socket = None
access_bits = None
connections = {} # list of known CA servers (IOCs)
# Used for IOC disocvery broadcasts
UDP_socket = None
# Protocol version 4.11:
major_version = 4
minor_version = 11
# CA server port = 5056 + major version * 2
# CA repeater port = 5056 + major version * 2 + 1
port = 5056 + major_version * 2
# CA Message command codes:
VERSION = 0
EVENT_ADD = 1
EVENT_CANCEL = 2
WRITE = 4
SEARCH = 6
NOT_FOUND = 14
READ_NOTIFY = 15
WRITE_NOTIFY = 19
CLIENT_NAME = 20
HOST_NAME = 21
CREATE_CHAN = 18
ACCESS_RIGHTS = 22
commands = {
"VERSION": 0,
"EVENT_ADD": 1,
"EVENT_CANCEL": 2,
"WRITE": 4,
"SEARCH": 6,
"NOT_FOUND": 14,
"READ_NOTIFY": 15,
"WRITE_NOTIFY": 19,
"CLIENT_NAME": 20,
"HOST_NAME": 21,
"CREATE_CHAN": 18,
"ACCESS_RIGHTS": 22,
}
# CA Message data type codes:
STRING = 0
INT = 1
SHORT = 1
FLOAT = 2
ENUM = 3
CHAR = 4
LONG = 5
DOUBLE = 6
NO_ACCESS = 7
types = {
"STRING": 0,
"INT": 1,
"SHORT": 1,
"FLOAT": 2,
"ENUM": 3,
"CHAR": 4,
"LONG": 5,
"DOUBLE": 6,
"NO_ACCESS": 7,
}
# CA Message monitor mask bits
VALUE = 0x01 # Value change events are reported.
LOG = 0x02 # Log events are reported (different dead band than VALUE)
ALARM = 0x04 # Alarm events are reported
class PV (object):
"""EPICS Process Variable or
a collections of process variable with common prefix"""
def __init__(self,name):
"""name: PREFIX:Record.Field or PREFIX:Record or RPEFIX:"""
self.name = name
def get_value(self): return caget(self.name)
def set_value(self,value): caput(self.name,value)
value = property(get_value,set_value)
def get_info(self): return cainfo(self.name,printit=False)
info = property(get_info)
def __getattr__(self,name):
"""If this PV object is a record of process variables, retreive
a process vairable within this record."""
# Called for attributes other than "value" or "info".
# E.g. temperature_controller = PV("NIH:TEMP")
# print temperature_controller.feedback_loop.P.value
if self.name.endswith(":"): pv = PV(self.name+name)
else: pv = PV(self.name+"."+name)
object.__setattr__(self,name,pv)
return pv
def __repr__(self): return "PV(%r)" % self.name
def add_callback(self,callback):
"""Have the routine 'callback' be called every the time value
of the PV changes.
callback: function that takes three parameters:
PV_name, value, char_value"""
camonitor(self.name,callback=callback)
def clear_callbacks(self,callback):
"""Undo 'add_callback'."""
camonitor_clear(self.name)
class Record(object):
"""A collections of process variables with common prefix"""
__prefix__ = ""
def __init__(self,prefix=""):
"""prefix: common beginning for all process variables within the record.
e.g. 'NIH:TEMP'"""
self.__prefix__ = prefix
def __getattr__(self,name):
"""Called when 'x.name' is evaluated."""
## __getattr__ is only invoked if the attribute wasn't found the usual ways.
##debug("Record.__getattribute__(%r)" % name)
# __members__ is used for auto completion, browsing and "dir".
if name == "__members__": return self.__PV_names__()
if name == "name" or name == "__name__": return self.__prefix__
if (name.startswith("__") and name.endswith("__")):
return object.__getattribute__(self,name)
full_name = self.__prefix__+"."+name
value = caget(full_name)
##debug("Record: caget(%r) = %r" % (full_name,value))
# The value being "<record>" indicates that this
# is a record of PVs, not a PV.
if isinstance(value,str) and value.startswith("<record"):
return Record(full_name)
return value
def __setattr__(self,name,value):
"""Called when 'x.name = value' is evaluated."""
##debug("Record.__setattribute__(%r,%r)" % (name,value))
if (name.startswith("__") and name.endswith("__")):
object.__setattr__(self,name,value)
return
if name in self.__dict__ or name in self.__class__.__dict__:
object.__setattr__(self,name,value)
return
##debug("Record: caput(%r,%r)" % (self.__prefix__+"."+name,value))
caput(self.__prefix__+"."+name,value)
def __PV_names__(self):
"""A list of PV names in the record."""
value = caget(self.__prefix__)
if isinstance(value,str) and value.startswith("<record"):
return value[9:-1].split(", ")
return []
def __repr__(self): return "Record(%r)" % self.__prefix__
def caget(PV_name,timeout=None,wait=None):
"""Retreive the current value of a process variable
timeout: time in seconds, overrides default timeout of 1.0 s
wait:
True: always wait for a timeout to pass before giving up
False: return None if the value is not readily availabe.
Default: Wait for a timeout to pass before giving up only the first time
"""
from time import time
if timeout is None: timeout = globals()["timeout"]
if wait == False: timeout = 0
camonitor_background()
if not PV_name in PVs: PVs[PV_name] = PV_info(); process_replies(update=True)
process_replies()
pv = PVs[PV_name]
while pv.data is None and time() - pv.connection_requested < timeout:
process_replies()
v = value(pv.data_type,pv.data_count,pv.data) if pv.data else None
return v
def caput(PV_name,value,wait=False,timeout=60):
"""Modify the value of a process variable
If wait=True the call returns only after the server has confirmed
that is has finished processing the write request or the timeout
has expired."""
from time import time
if timeout is None: timeout = globals()["timeout"]
if not PV_name in PVs: PVs[PV_name] = PV_info()
pv = PVs[PV_name]
pv.write_data = value
pv.write_requested = write_requested = time()
pv.write_confirmed = 0
write_sent = pv.write_sent
process_replies(update=True)
while pv.write_sent == write_sent and time() - write_requested < timeout:
process_replies()
if wait:
while not pv.write_confirmed and time() - write_requested < timeout:
process_replies()
camonitor_background()
def cawait(PV_name,timeout=None):
"""Wait for the server to send an update event for the PV."""
if timeout == None: timeout = globals()["timeout"]
from time import time
t0 = time()
if not PV_name in PVs: PVs[PV_name] = PV_info(); process_replies(update=True)
pv = PVs[PV_name]
# If the PV has changed in the past 70 ms, let it count as 'changed now'.
##debug("pv.last_updated - t0 = %r" % (pv.last_updated - t0))
if pv.last_updated - t0 > -0.070: return
process_replies()
last_updated = pv.last_updated
while pv.last_updated == last_updated and time()-t0 < timeout:
process_replies()
def camonitor(PV_name,writer=None,callback=None,new_thread=True):
"""Call a function every time a PV changes value.
writer: function that will be passed a formatted string:
"<PB_name> <date> <time> <value>"
new_thread: start callback in new thread?
E.g. "14IDB:SAMPLEZ.RBV 2013-11-02 18:25:13.555540 4.3290"
f=file("PV.log","w"); camonitor("14IDB:SAMPLEZ.RBV",f.write)
callback: function that will be passed three arguments:
the PV name, its new value, and its new value as string.
E.g. def callback(PV_name,value,char_value):
def callback(pvname,value,char_value): print pvname,value,char_value
"""
if not PV_name in PVs: PVs[PV_name] = PV_info(); process_replies(update=True)
pv = PVs[PV_name]
if callback is None and writer is None:
# By default, if not argument are given, just print update messages.
import sys
writer = sys.stdout.write
if callback is not None:
if not has_callback(PV_name,callback):
if new_thread:
# Run the callback function in a separate thread to avoid
# deadlock in case the function calls "caput" or "caget".
callback = new_thread_function(callback)
pv.callbacks += [callback]
elif DEBUG: warn("camonitor: %r already has %r as callback." %
(PV_name,object_name(callback)))
if writer is not None:
if not writer in pv.writers: pv.writers += [writer]
camonitor_background()
def has_callback(PV_name,callback):
if not PV_name in PVs: PVs[PV_name] = PV_info(); process_replies(update=True)
pv = PVs[PV_name]
for f in pv.callbacks:
if f == callback: return True
if hasattr(f,"function") and f.function == callback: return True
return False
def new_thread_function(function):
"""A function that runs the lorginal function in a new thread"""
if sys.version_info[0] ==3:
from _thread import start_new_thread
else:
from thread import start_new_thread
import traceback
def function_error_logged(*args):
try: function(*args)
except Exception as msg:
error("%s: %s\n%s" %
(object_name(function),msg,traceback.format_exc()))
def new_thread_function(*args): start_new_thread(function_error_logged,args)
new_thread_function.function = function
return new_thread_function
def camonitor_clear(PV_name,writer=None,callback=None):
"""Undo "camonitor" """
if PV_name in PVs:
pv = PVs[PV_name]
if writer is None: pv.writers = []
elif writer in pv.writers: pv.writers.remove(writer)
if callback is None: pv.callbacks = []
elif callback in pv.callbacks: pv.callbacks.remove(callback)
camonitor_thread_ID = None
def camonitor_background():
"""Handle IOC communication in background"""
global camonitor_thread_ID
if camonitor_thread_ID is None:
if sys.version_info[0] ==3:
from _thread import start_new_thread
else:
from thread import start_new_thread
camonitor_thread_ID = start_new_thread (camonitor_thread,())
def camonitor_thread():
"""Perform montitoring to triggger call of registered callback
routines."""
while (camonitors() or (monitor_always and PVs)) and process_replies:
process_replies(1.0)
global camonitor_thread_ID
camonitor_thread_ID = None
def camonitors():
"""List of active callback routines"""
camonitors = []
for PV_name in PVs.keys():
pv = PVs[PV_name]
camonitors += pv.callbacks+pv.writers
return camonitors
def socketpair(family=socket.AF_INET,type=socket.SOCK_STREAM,proto=0):
"""Create a pair of connected socket objects using TCP/IP protocol.
This is a replacement for the socket library's 'socketpair' function,
which is not portalbe to Windows.
"""
from socket import socket,error
global listen_socket
listen_socket = socket(family,type,proto)
port = 1024
while port < 16535:
try: listen_socket.bind(("127.0.0.1",port)); break
except error: port += 1
listen_socket.listen(1)
s1 = socket(family,type,proto)
s1.connect(("127.0.0.1",port))
s2,addr = listen_socket.accept()
return s1,s2
# Used to wake up the CA background (server) thread
request_sockets = socketpair()
def PV_server_discover(PV_name):
"""Send UDP broadcast to find the server hosting a PV
PV_name: string"""
from time import time
if not PV_name in PVs: PVs[PV_name] = PV_info()
pv = PVs[PV_name]
global UDP_socket
if UDP_socket == None:
from socket import socket,SOCK_DGRAM,SOL_SOCKET,SO_BROADCAST
UDP_socket = socket(type=SOCK_DGRAM)
UDP_socket.setsockopt(SOL_SOCKET,SO_BROADCAST,1)
if pv.addr is None:
pv.connection_initiated = time()
reply_flag = 5 # Do not reply
if pv.channel_ID == None: pv.channel_ID = new_channel_ID()
request = message(SEARCH,0,reply_flag,minor_version,pv.channel_ID,
pv.channel_ID,PV_name+"\0")
for addr in broadcast_addresses():
sendto(UDP_socket,(addr,port),request)
pv.servers_queried += [addr]
# updates PV.addr, then calls "PV_connect"
def PV_connect(PV_name):
"""Translate PV name from string to server-specific channel ID.
PV_name: string"""
PV_server_connect(PV_name) # make sure ocnnection to server is established.
if PV_name in PVs:
pv = PVs[PV_name]
if pv.addr and pv.addr in connections and pv.channel_SID is None:
# Directly connect to the server hosting the PV.
s = connections[pv.addr].socket
if pv.channel_ID == None: pv.channel_ID = new_channel_ID()
send(s,message(CREATE_CHAN,0,0,0,pv.channel_ID,minor_version,
PV_name+"\0"))
# updates pv.channel_SID, then calls "PV_subscribe"
def PV_server_connect(PV_name):
"""Establish a TCP connection to the server hosting a PV.
PV_name: string"""
from socket import socket,gethostname,error,timeout as socket_timeout
from getpass import getuser
if PV_name in PVs:
pv = PVs[PV_name]
if pv.addr is not None and pv.addr not in connections:
addr,cport = pv.addr
s = socket()
s.settimeout(timeout)
try: s.connect((addr,cport))
except error as msg:
if DEBUG: debug("%s:%r: %r" % (addr,cport,msg))
return
except socket_timeout:
if DEBUG: debug("%s: timeout" % (addr))
return
connections[addr,cport] = connection_info()
connections[addr,cport].socket = s
send(s,message(VERSION,0,10,minor_version,0,0)) # 10 = priority
send(s,message(CLIENT_NAME,0,0,0,0,0,getuser()+"\0"))
send(s,message(HOST_NAME,0,0,0,0,0,gethostname()+"\0"))
def PV_subscribe(PV_name):
"""Ask the server to be notified about when the value of a PV changes.
PV_name: string"""
from struct import pack
if PV_name in PVs:
pv = PVs[PV_name]
if pv.subscription_ID is None and pv.channel_SID is not None \
and pv.addr in connections:
s = connections[pv.addr].socket
pv.subscription_ID = new_subscription_ID()
send(s,message(EVENT_ADD,16,pv.data_type,pv.data_count,pv.channel_SID,
pv.subscription_ID,pack(">fffHxx",0.0,0.0,0.0,VALUE|LOG|ALARM)))
if sys.version_info[0] ==3:
from _thread import allocate_lock
else:
from thread import allocate_lock
lock = allocate_lock()
def process_replies(timeout = 0.001,update=False):
"""Interpret any packets comming from the IOC waiting in the system's
receive queue.
If timeout > 0 wait for more packets to arrive for the specified number
of seconds.
update: make sure pending connection and write processes are
handled
"""
if lock.acquire(False):
import socket
from select import select,error as select_error
from struct import unpack
process_pending_connection_requests()
process_pending_write_requests()
while True:
# Use 'select' to check which sockets have data pending in the input
# queue.
sockets = []
if request_sockets[1]: sockets += [request_sockets[1]]
if UDP_socket: sockets += [UDP_socket]
for connection in connections.values(): sockets += [connection.socket]
try: ready_to_read,x,in_error = select(sockets,[],sockets,timeout)
except select_error: continue # 'Interrupted system call'
if request_sockets[1] in ready_to_read:
# This indicates that a wakeup from "select" had been triggred.
request_sockets[1].recv(2048)
if DEBUG: debug("Wake up call")
global wake_up_in_progress
wake_up_in_progress = False
process_pending_connection_requests()
process_pending_write_requests()
if UDP_socket in ready_to_read:
try: messages,addr = UDP_socket.recvfrom(2048)
except socket.error: messages = ""
# Several replies may be concantenated. Break them up.
while len(messages) > 0:
# The minimum message size is 16 bytes. If the 'payload size'
# field has value > 0, the total size if 16+'payload size'.
payload_size, = unpack(">H",messages[2:4])
message = messages[0:16+payload_size]
messages = messages[16+payload_size:]
if DEBUG: debug("Recv upd:%s:%s %s" % (addr[0],addr[1],message_info
(message)))
process_message(addr,message)
if UDP_socket in in_error:
if DEBUG: debug("UDP error")
for addr in connections.keys():
connection = connections[addr]
s = connection.socket
if s in in_error:
if DEBUG: debug("Lost connection to server %s:%s" % addr)
reset_PVs(addr)
del connections[addr]
continue
if s in ready_to_read:
# Several replies may be concatenated. Read one at a time.
# The minimum message size is 16 bytes.
try: message = s.recv(16)
except socket.error:
if DEBUG: debug("Recv: lost connection to server %s:%s" % addr)
reset_PVs(addr)
del connections[addr]
continue
if len(message) == 0:
if DEBUG: debug("Server %s:%s closed connection" % addr)
reset_PVs(addr)
del connections[addr]
break
# If the 'payload size' field has value > 0, 'payload size'
# more bytes are part of the message.
payload_size, = unpack(">H",message[2:4])
if payload_size > 0:
try: message += s.recv(payload_size)
except socket.timeout:
if DEBUG: debug("Recv timed out")
if DEBUG: debug("Recv %s:%s %s" % (addr[0],addr[1],
message_info(message)))
process_message(addr,message)
process_pending_connection_requests()
process_pending_write_requests()
if len(ready_to_read) == 0 and len(in_error) == 0: break # select timed out
lock.release()
else: # already in progress
if update: wake_up()
from time import sleep
sleep(timeout)
wake_up_in_progress = False
wake_up_lock = allocate_lock()
def wake_up():
"""Make sure 'process_replies' handles pending connection and write requests"""
with wake_up_lock:
global wake_up_in_progress
if not wake_up_in_progress:
wake_up_in_progress = True
request_sockets[0].send(b".")
def process_pending_connection_requests():
"""Check list of PVs unconnected PVs and conntect them."""
from time import time
for name in PVs.keys():
pv = PVs[name]
# Does PV need to be connected?
##if time() - pv.last_connection_requested > timeout: continue
# Is PV already connected?
if pv.subscription_ID != None: continue
# Is connection already in progress?
if time() - pv.connection_initiated < timeout: continue
# To Do: retry after timeout
if DEBUG: debug("Processing connection request for PV %r" % name)
PV_server_discover(name)
def process_pending_write_requests():
"""Check list of PVs for pending write requests and execute them when possible."""
from time import time
for name in PVs.keys():
pv = PVs[name]
if pv.write_data == None: continue # nothing to do
if pv.addr == None: continue # need to postpone
if pv.channel_SID == None: continue # need to postpone
if pv.data_type == None: continue # need to postpone
if DEBUG: debug("Processing write request for PV %r" % name)
s = connections[pv.addr].socket
pv.IOID = pv.IOID + 1
pv.write_confirmed = 0
data = network_data(pv.write_data,pv.data_type)
count = data_count(pv.write_data,pv.data_type)
send(s,message(WRITE_NOTIFY,0,pv.data_type,count,
pv.channel_SID,pv.IOID,data))
pv.write_sent = time()
pv.write_data = None
def process_message(addr,message):
"""Interpret a CA protocol datagram"""
from struct import unpack
from time import time
import traceback
header = message[0:16]
payload = message[16:]
if len(header) < 16:
if DEBUG: debug("process_message: invalid header %r" % header)
return
command,payload_size,data_type,data_count,parameter1,parameter2 = \
unpack(">HHHHII",header)
if command == SEARCH: # Reply to a SEARCH request.
port_number = data_type
channel_SID = parameter1 # 'temporary server ID': 0xFFFFFFFF
channel_ID = parameter2
if DEBUG: debug("SEARCH port_number=%r, channel_ID=%r, channel_SID=%r" %
(port_number,channel_ID,channel_SID))
for name in PVs.keys():
if PVs[name].channel_ID == channel_ID:
# Ignore duplicate replies.
if PVs[name].addr != None:
if DEBUG: debug("Ignoring duplicate SEARCH reply for %r from "
"%r:%r" % (name,addr[0],addr[1]))
continue
PVs[name].addr = (addr[0],port_number)
if DEBUG: debug("PVs[%r].addr = %r" % (name,addr))
PVs[name].response_time = time()
PV_connect(name)
elif command == CREATE_CHAN: # Reply to a 'Create Channel' request.
channel_ID = parameter1
channel_SID = parameter2
if DEBUG: debug("CREATE_CHAN channel_ID=%r, channel_SID=%r" %
(channel_ID,channel_SID))
for name in PVs.keys():
if PVs[name].channel_ID == channel_ID:
if PVs[name].channel_SID != None:
if DEBUG: debug("Ignoring duplicate CREATE_CHAN reply for %r from "
"%r:%r" % (name,addr[0],addr[1]))
continue
PVs[name].addr = addr
if DEBUG: debug("PVs[%r].addr = %r" % (name,addr))
PVs[name].channel_SID = channel_SID
if DEBUG: debug("PVs[%r].channel_SID = %r" % (name,channel_SID))
PVs[name].data_type = data_type
if DEBUG: debug("PVs[%r].data_type = %r" % (name,data_type))
PVs[name].data_count = data_count
if DEBUG: debug("PVs[%r].data_count = %r" % (name,data_count))
PVs[name].response_time = time()
PV_subscribe(name)
elif command == ACCESS_RIGHTS:
# Reply to the CLIENT_NAME/HOST_NAME greeting.
channel_ID = parameter1
access_bits = parameter2
if DEBUG: debug("ACCESS_RIGHTS channel_ID %r, %s" % (channel_ID,access_bits))
for name in PVs.keys():
if PVs[name].channel_ID == channel_ID:
PVs[name].access_bits = access_bits
if DEBUG: debug("PVs[%r].access_bits = %r" % (name,access_bits))
PVs[name].response_time = time()
elif command == READ_NOTIFY:
# Reply to a synchronous read request (never used).
# Channel Access Protocol Specification, section 6.15.2, says:
# parameter 1: channel_SID, parameter 2: IOID
# However, I always get: parameter 1 = 1, parameter 2 = 1.
channel_SID = parameter1
IOID = parameter2
val = value(data_type,data_count,payload)
if DEBUG: debug("READ_NOTIFY channel_SID=%r, IOID=%r, value=%r" %
(channel_SID,IOID,val))
for name in PVs.keys():
if PVs[name].channel_SID == channel_SID:
if DEBUG: debug("PVs[%r].data = %r" % (name,payload))
PVs[name].data = payload
PVs[name].data_type = data_type
PVs[name].data_count = data_count
PVs[name].response_time = time()
elif command == EVENT_ADD: # Asynchronous notification that PV changed.
status_code = parameter1
subscription_ID = parameter2
val = value(data_type,data_count,payload)
if DEBUG: debug("EVENT_ADD status_code=%r, subscription_ID=%r, value=%r" % (status_code,
subscription_ID,val))
for name in PVs.keys():
if PVs[name].subscription_ID == subscription_ID and \
PVs[name].addr == addr:
update = True if PVs[name].data is not None else False
PVs[name].data_type = data_type
PVs[name].data_count = data_count
if DEBUG: debug("PVs[%r].data = %r" % (name,payload))
t = time()
if PVs[name].data != None: PVs[name].last_updated = t
PVs[name].data = payload
PVs[name].response_time = t
# Call any callback routines for this PV.
pv = PVs[name]
if len(pv.callbacks) > 0 or len(pv.writers) > 0:
if DEBUG: debug("%s has callbacks" % name)
new_value = value(pv.data_type,pv.data_count,pv.data)
char_value = "%r" % new_value
if DEBUG: debug("%s = %s" % (name,char_value))
for function in pv.callbacks:
if DEBUG: debug("%s: calling %s" % (name,object_name(function)))
try: function(name,new_value,char_value)
except Exception as msg: error("%s: calling %s: %s\n%s" %
(name,object_name(function),msg,traceback.format_exc()))
from datetime import datetime
message = "%s %s %s\n" % (name,datetime.fromtimestamp(t),
char_value)
for function in pv.writers:
if DEBUG: debug("%s: calling %s" % (name,object_name(function)))
try: function(message)
except Exception as msg: error("%s: calling %s: %s\n%s" %
(name,object_name(function),msg,traceback.format_exc()))
elif command == EVENT_CANCEL: # Asynchronous notification that PV not longer exists.
channel_SID = parameter1
subscription_ID = parameter2
if DEBUG: debug("EVENT_CANCEL channel_SID=%r, subscription_ID=%r" %
(channel_SID,subscription_ID))
for name in PVs.keys():
if PVs[name].subscription_ID == subscription_ID and \
PVs[name].addr == addr:
del PVs[name]
elif command == WRITE_NOTIFY: # Confirmation of a sucessful write.
status = parameter1
IOID = parameter2
if DEBUG: debug("WRITE_NOTIFY status_code=%r, IOID=%r" % (status,IOID))
for name in PVs.keys():
if PVs[name].IOID == IOID and \
PVs[name].addr == addr:
t = time()
if DEBUG: debug("PVs[%r].write_confirmed = %r" % (name,t))
PVs[name].write_confirmed = t
PVs[name].response_time = t
elif command == NOT_FOUND:
channel_ID = parameter1
PV_name = "unknown"
for name in PVs.keys():
if PVs[name].channel_ID == channel_ID: PV_name = name
if DEBUG: debug("NOT_FOUND: %r" % PV_name)
else:
if DEBUG: debug("%r: unknown command code" % command)
def object_name(object):
"""Convert Python object to string"""
if hasattr(object,"__name__"): return object.__name__
else: return repr(object)
def new_channel_ID():
"""Return a unique integer to be used as 'Channel ID' for a PV.
A Channel ID is a client-provided integer number, which the CA server (IOC)
includes as reference when replying to 'create channel' requests."""
IDs = [pv.channel_ID for pv in PVs.values()]
ID = 1
while ID in IDs: ID += 1
return ID
def new_subscription_ID():
"""Return a unique integer to be used as 'Subscription ID' for a PV.
A subscription ID is a client-provided integer number, which the CA server
(IOC) includes as reference number when sending update events."""
IDs = [pv.subscription_ID for pv in PVs.values()]
ID = 1
while ID in IDs: ID += 1
return ID
def reset_PVs(addr):
"""If the connection to the server 'addr' is lost, clear outdate PV state
info."""
# TO DO: preserve callbacks
for name in PVs.keys(): PVs[name].reset()
def message(command=0,payload_size=0,data_type=0,data_count=0,
parameter1=0,parameter2=0,payload=""):
"""Assemble a Channel Access message datagram for network transmission"""
assert data_type is not None
assert data_count is not None
assert parameter1 is not None
assert parameter2 is not None
from math import ceil
from struct import pack
if isinstance(payload,str):
payload = str.encode(payload)
if payload_size == 0 and len(payload) > 0:
# Pad to multiple of 8.
payload_size = int(ceil(len(payload)/8.)*8)
while len(payload) < payload_size: payload += b"\0"
# 16-byte header consisting of four 16-bit integers
# and two 32-bit integers in big-edian byte order.
header = pack(">HHHHII",command,payload_size,data_type,data_count,
parameter1,parameter2)
if isinstance(payload,str):
payload = str.encode(payload)
message = header + payload
return message
def message_info(message):
"""Text representation of the CA message datagram"""
from struct import unpack
header = message[0:16]
payload = message[16:]
if len(header) < 16: return "invalid message %r" % header
command,payload_size,data_type,data_count,parameter1,parameter2 = \
unpack(">HHHHII",header)
s = str(command)
if command in commands.values():
s += "("+commands.keys()[commands.values().index(command)]+")"
s += ","+str(payload_size)
s += ","+str(data_type)
if data_type in types.values():
s += "("+types.keys()[types.values().index(data_type)]+")"
s += ","+str(data_count)
s += ", %r, %r" % (parameter1,parameter2)
if payload:
s += ", %r" % payload
if command in (EVENT_ADD,WRITE,READ_NOTIFY,WRITE_NOTIFY):
s += "(%r)" % (value(data_type,data_count,payload),)
return s
def send(socket,message):
"""Transmit a Channel Access message to an IOC via TCP"""
from socket import error as socket_error
addr,port = socket.getpeername()
if DEBUG: debug("Send %s:%s %s" % (addr,port,message_info(message)))
try: socket.sendall(message)
except socket_error as error:
if DEBUG: debug("Send failed: %r" % error)
def sendto(socket,addr,message):
"""Transmit a Channel Access message to an IOC via UDP"""
from socket import error as socket_error
if DEBUG: debug("Send UDP %s:%s %s" % (addr[0],addr[1],message_info(message)))
try: socket.sendto(message,addr)
except socket_error as error:
if DEBUG: debug("Sendto %r failed: %r" % (addr,error))
def value(data_type,data_count,payload):
"""Convert received network binary data to a Python data type"""
if payload == None: return None
from struct import unpack
if data_type == STRING:
# Null-terminated string.
# data_count is the number of null-terminated strings (characters)
value = payload.split(b"\0")[0:data_count]
if len(value) == 1: value = value[0]
elif data_type == SHORT:
payload = payload.ljust(2*data_count,b"\0")
value = list(unpack(">%dh"%data_count,payload[0:2*data_count]))
if len(value) == 1: value = value[0]
elif data_type == FLOAT:
payload = payload.ljust(4*data_count,b"\0")
value = list(unpack(">%df"%data_count,payload[0:4*data_count]))
if len(value) == 1: value = value[0]
elif data_type == ENUM:
payload = payload.ljust(2*data_count,b"\0")
value = list(unpack(">%dh"%data_count,payload[0:2*data_count]))
if len(value) == 1: value = value[0]
elif data_type == CHAR:
payload = payload.ljust(data_count,b"\0")
value = list(unpack("%db"%data_count,payload[0:data_count]))
if len(value) == 1: value = value[0]
elif data_type == LONG:
payload = payload.ljust(4*data_count,b"\0")
value = list(unpack(">%di"%data_count,payload[0:4*data_count]))
if len(value) == 1: value = value[0]
elif data_type == DOUBLE:
payload = payload.ljust(8*data_count,b"\0")
value = list(unpack(">%dd"%data_count,payload[0:8*data_count]))
if len(value) == 1: value = value[0]
elif data_type == None: value = payload
else:
if DEBUG: debug("unsupported data type %r" % data_type)
value = payload
return value
def data_count(value,data_type):
"""If value is an array return the number of elements, else return 1.
In CA, a string counts as a single element."""
# If the data type is STRING the data count is the number of NULL-
# terminated strings, if the data type if CHAR the data count is the
# number is characters in the string, including any NULL characters
# inside and at the end.
try:
basestring
except NameError:
basestring = str
if issubclass(type(value),basestring): return 1
if hasattr(value,"__len__"): return len(value)
return 1
def network_data(value,data_type):
"Convert a Python data type to binary data for network transmission"
from struct import pack
from numpy import int8,int16,int32,float32,float64
payload = ""
if isinstance(payload,str):
payload = str.encode(payload)
if data_type == STRING:
payload = str(value)
if isinstance(payload,str):
payload = str.encode(payload)
# EPICS requires that strings are NULL-terminated.
if not payload.endswith(b"\0"): payload += b"\0"
elif data_type == SHORT:
if hasattr(value,"__len__"):
for v in value: payload += pack(">h",to(v,int16))
else: payload = pack(">h",to(value,int16))
elif data_type == FLOAT:
if hasattr(value,"__len__"):
for v in value: payload += pack(">f",to(v,float32))
else: payload = pack(">f",to(value,float32))
elif data_type == ENUM:
if hasattr(value,"__len__"):
for v in value: payload += pack(">h",to(v,int16))
else: payload = pack(">h",to(value,int16))
elif data_type == CHAR:
if hasattr(value,"__len__"):
for v in value: payload += pack(">b",to(v,int8))
else: payload = pack(">b",to(value,int8))
elif data_type == LONG:
if hasattr(value,"__len__"):
for v in value: payload += pack(">i",to(v,int32))
else: payload = pack(">i",to(value,int32))
elif data_type == DOUBLE:
if hasattr(value,"__len__"):
for v in value: payload += pack(">d",to(v,float64))
else: payload = pack(">d",to(value,float64))
else:
if DEBUG: debug("network_data: unsupported data type %r" % data_type)
payload = str(value)
return payload
def to(value,dtype):
"""Force conversion to int data type. If failed return 0:
dtype: int8, int32, int64"""
isfloat = "float" in str(dtype)
try: return dtype(value)
except: return 0 if not isfloat else 0.0
def broadcast_addresses():
"""A list if IP adresses to use for name resolution broadcasts"""
from os import environ
if "EPICS_CA_AUTO_ADDR_LIST" in environ and \
environ["EPICS_CA_AUTO_ADDR_LIST"] == "NO": return []
# You can override the automatic selection of broadcast
# addresses by setting the variable 'broadcast_address'.
if "broadcast_address" in globals() and broadcast_address:
return [broadcast_address]
from socket import inet_aton,inet_ntoa,error
from struct import pack,unpack
addresses = []
for address in network_interfaces():
try: num_address = inet_aton(address)
except: continue # E.g. IPv6 address
if not address in addresses: addresses += [address]
ipaddr, = unpack(">I",num_address)
ipaddr |= 0x000000FF
address = inet_ntoa(pack(">I",ipaddr))
if not address in addresses: addresses += [address]
# This is a hack (was in an hurry).
addresses += ["172.21.46.255"] # LCLS XPP ICS subnet
return addresses
def network_interfaces():
"""A list of IP adresses of the local network interfaces,
as strings in numerical dot notation"""
from socket import getaddrinfo,gethostname
addresses = [local_ip_address()]
addrinfos = getaddrinfo(None,0)
try: addrinfos += getaddrinfo(gethostname(),0)
except: pass
for addrinfo in addrinfos:
address = addrinfo[4][0]
if not address in addresses: addresses += [address]
return addresses
def local_ip_address():
"""IP address of the local network interface as string in dot notation"""
# Unfortunately, Python has no platform-indepdent function to find
# the IP address of the local machine.
# As a work-around let us pretend we want to send a UDP datagram to a
# non existing external IP address.
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
try: s.connect(("172.16.31.10",1024))
except socket.error: return "127.0.0.1" # Network is unreachable
# This code does not geneate any network traffic, because UDP is not
# a connection-orientation protocol.
# Now, Python can tell us what would be thet "source address" of the packets
# if we would sent a packet (but we won't actally sent a packet).
address,port = s.getsockname()
return address
def cainfo(PV_name="all",printit=True,update=True):
"Print status info string"
from socket import gethostbyaddr,herror
from datetime import datetime
from time import time
if PV_name == "all":
for name in PVs: cainfo(name,update=False)
else:
if update: caget(PV_name)
s = PV_name+"\n"
if PV_name in PVs: pv = PVs[PV_name]
else: pv = PV_info()
fmt = " %-14s %.60s\n"
if pv.channel_SID: val = "connected"
else: val = "not connected"
if pv.subscription_ID: val += ", receiving notifications"
if pv.connection_requested and not pv.subscription_ID:
val += ", pending for %.0f s" % (time() - pv.connection_requested)
s += fmt % ("State:",val)
if pv.addr:
val = pv.addr[0]
# Try to translate numeric IP address to host name.
try: val = gethostbyaddr(val)[0]
except herror: pass
val += ":%s" % pv.addr[1]
else: val = "N/A"
s += fmt % ("Host:",val)
if pv.access_bits != None:
val = ""
if pv.access_bits & 1: val += "read/"
if pv.access_bits & 2: val += "write/"
val = val.strip("/")
if val == "": val = "none"
else: val = "N/A"
s += fmt % ("Access:",val)
if pv.data_type != None:
val = repr(pv.data_type)
for t in types:
if types[t] == pv.data_type: val = t
else: val = "N/A"
s += fmt % ("Data type:",val)
if pv.data_count != None: val = str(pv.data_count)
else: val = "N/A"
s += fmt % ("Element count:",val)
if pv.data != None: val = repr(value(pv.data_type,pv.data_count,pv.data))
else: val = "N/A"
s += fmt % ("Value:",val)
if pv.last_updated != 0:
t = pv.last_updated
val = "%s (%s)" % (t,datetime.fromtimestamp(t))
s += fmt % ("Last changed:",val)
if pv.response_time != 0:
t = pv.response_time
val = "%s (%s)" % (t,datetime.fromtimestamp(t))
s += fmt % ("Time stamp:",val)
if printit: print(s)
else: return s
def PV_status():
"""print status info"""
for name in PVs:
s = "%s: " % name
pv = PVs[name]
for attr in dir(pv):
if not "__" in attr: s += "%s = %r, " % (attr,getattr(pv,attr))
s = s.strip(", ")
print(s)
if __name__ == "__main__": # for testing
from pdb import pm
from time import time
import logging
from tempfile import gettempdir
logfile = gettempdir()+"/CA.log"
logging.basicConfig(level=logging.INFO,
format="%(asctime)s %(levelname)s: %(message)s",
##filename=logfile,
)
DEBUG = False
PV_name = 'NIH:TEMP.RBV'
def writer(msg): info(msg)
def callback(PV,val,strval): info("%s=%r" % (PV,val))
print('DEBUG = %r' % DEBUG)
print('monitor_always = %r' % monitor_always)
print('caget(%r)' % PV_name)
print('caput(%r,4.8372)' % PV_name)
print('camonitor(%r,writer=writer)' % PV_name)
print('camonitor(%r,callback=callback,new_thread=False)' % PV_name)
print('camonitor_clear(%r)' % PV_name)
<file_sep>Size = (425, 340)
Position = (242, 66)
ScaleFactor = 1.0
ZoomLevel = 1.0
Orientation = 0
filename = ''
ImageWindow.Center = None
ImageWindow.ViewportCenter = (5.3893499999999994, 4.2222)
ImageWindow.crosshair_color = (255, 0, 255)
ImageWindow.boxsize = (0.10000000000000001, 0.059999999999999998)
ImageWindow.box_color = (128, 128, 255)
ImageWindow.show_box = False
ImageWindow.Scale = [(-0.10000000000000001, -0.10000000000000001), (-0.10000000000000001, 0.10000000000000001)]
ImageWindow.show_scale = False
ImageWindow.scale_color = (128, 128, 255)
ImageWindow.crosshair_size = (0.050000000000000003, 0.050000000000000003)
ImageWindow.show_crosshair = True
ImageWindow.show_profile = False
ImageWindow.show_FWHM = False
ImageWindow.show_center = False
ImageWindow.calculate_section = False
ImageWindow.profile_color = (255, 0, 255)
ImageWindow.FWHM_color = (0, 0, 255)
ImageWindow.center_color = (0, 0, 255)
ImageWindow.ROI = [[-0.20000000000000001, -0.20000000000000001], [0.20000000000000001, 0.20000000000000001]]
ImageWindow.ROI_color = (255, 255, 0)
ImageWindow.show_saturated_pixels = False
ImageWindow.mask_bad_pixels = False
ImageWindow.saturation_threshold = 233
ImageWindow.saturated_color = (255, 0, 0)
ImageWindow.linearity_correction = False
ImageWindow.bad_pixel_threshold = 233
ImageWindow.bad_pixel_color = (30, 30, 30)
ImageWindow.show_grid = False
ImageWindow.grid_type = 'xy'
ImageWindow.grid_color = (0, 0, 255)
ImageWindow.grid_x_spacing = 1.0
ImageWindow.grid_x_offset = 0.0
ImageWindow.grid_y_spacing = 1.0
ImageWindow.grid_y_offset = 0.0
<file_sep>#!/usr/bin/env python
"""
Prosilica GigE CCD cameras.
Author: <NAME>
Date created: 04/13/2017
Date last modified: 02/07/2018
"""
__version__ = "1.5" # camera_ip_address
from logging import debug,info,warn,error
class Camera(object):
from persistent_property import persistent_property
ip_address = persistent_property("GigE_camera.{name}.ip_address",
"pico20.niddk.nih.gov:2000")
orientation = persistent_property("GigE_camera.{name}.orientation",0)
mirror = persistent_property("GigE_camera.{name}.mirror",False)
def __init__(self,name):
self.name = name
def attr(name,default_value=0):
def get(self):
dtype = type(default_value)
try: return dtype(eval(self.query(name)))
except: return default_value
def set(self,value):
self.query(name+"=%r" % value,count=0)
propery_object = property(get,set)
return propery_object
camera_ip_address = attr("camera.IP_addr","")
rgb_data_size = attr("len(camera.images[-1])",0)
acquiring = attr("camera.acquiring",False)
state = attr("camera.state","Server offline")
width = attr("camera.width",1360)
height = attr("camera.height",1024)
frame_count = attr("camera.frame_count",0)
frame_counts = attr("camera.frame_counts",0)
timestamp = attr("camera.timestamp",0.0)
has_image = attr("len(camera.images)>0",False)
exposure_time = attr("camera.exposure_time",0.0)
auto_exposure = attr("camera.auto_exposure",False)
use_multicast = attr("camera.use_multicast",False)
external_trigger = attr("camera.external_trigger",False)
pixel_formats = attr("camera.pixel_formats",[])
pixel_format = attr("camera.pixel_format","")
gain = attr("camera.gain",0)
bin_factor = attr("camera.bin_factor",1)
stream_bytes_per_second = attr("camera.stream_bytes_per_second",0.0)
@property
def rgb_data(self):
return self.query("camera.rgb_data",count=self.rgb_data_size)
@property
def RGB_array(self):
"""Last read image as 3D nmupy array. Dimensions: 3xWxH
datatype: uint8
Usage R,G,B = camera.rgb_array"""
from numpy import frombuffer,uint8,zeros
w,h = self.width,self.height
rgb_data = self.rgb_data
size = 3*w*h
if len(rgb_data) < size:
warn("RGB_array %dx%d: padding from %d to %d bytes" % (w,h,len(rgb_data),size))
rgb_data += "\0"*(size-len(rgb_data))
if len(rgb_data) > size:
warn("RGB_array %dx%d: truncating from %d to %d bytes" % (w,h,len(rgb_data),size))
rgb_data = rgb_data[0:size]
array = frombuffer(rgb_data,uint8).reshape(h,w,3).T
return array
@property
def wxImage(self):
"""image in wx.Bitmap format"""
import wx
image = self.RGB_array
d,w,h = image.shape
wximage = wx.EmptyImage(w,h)
data = image.T.tostring()
wximage.Data = data
return wximage
@property
def wxBitmap(self):
"""image in wx.Bitmap format"""
import wx
image = self.RGB_array
d,w,h = image.shape
wximage = wx.EmptyImage(w,h)
data = image.T.tostring()
wximage.Data = data
bitmap = wx.BitmapFromImage(wximage)
return bitmap
def acquire_sequence(self,frame_counts=None,filenames=[]):
"""filenames: list of pathnames"""
if frame_counts is None:
start = self.frame_count+2
frame_counts = range(start,start+len(filenames))
self.query("camera.acquire_sequence(%r,%r)" % (frame_counts,filenames),count=0)
def query(self,command,terminator="\n",count=None):
"""Evaluate a command in the camera server and return the result.
"""
from tcp_client import query
reply = query(self.ip_address,command,terminator,count)
return reply
def save_image(self,filename):
RGB_array = self.transform_image(self.RGB_array,self.orientation,self.mirror)
from PIL import Image
image = Image.new('RGB',(self.width,self.height))
image.frombytes(RGB_array.T.tostring())
##image.frombytes(self.rgb_data)
##image = self.rotated_image(image)
from os import makedirs; from os.path import dirname,exists
if not exists(dirname(filename)): makedirs(dirname(filename))
info("Saving %r" % filename)
image.save(filename)
def transform_image(self,image,angle,mirror):
"""Transform from raw to displayed to displayed image.
image: 3D numpy array with dimensions 3 x width x height
angle: in units of deg, positive = counterclockwise, must be a multiple
of 90 deg
Return value: rotated version of the input image"""
from numpy import rint
angle = rint((angle % 360)/90.)*90
if mirror: image = image[:,::-1,:] # flip horizonally
if angle == 90: image = image.transpose(0,2,1)[:,:,::-1]
if angle == 180: image = image[:,::-1,::-1]
if angle == 270: image = image.transpose(0,2,1)[:,::-1,:]
return image
def rotated_image(self,image):
"""image: PIL image object"""
return image.rotate(self.orientation)
if __name__ == "__main__":
camera = Camera("MicroscopeCamera")
self = camera # for debugging
##camera.frame_count
command = "frame_count"; terminator="\n";count=None
from tcp_client import query
##reply = query(self.ip_address,command,terminator,count)
import logging
logging.basicConfig(level=logging.DEBUG,format="%(asctime)s: %(message)s")
from time import time
from tempfile import gettempdir
dir = "//femto-data//C/Data/2017.04/Test/Test1/camera_images/"
frame_counts = range(0,20)
filenames = [dir+"/Test_%03d.jpg" % (i+1) for i in frame_counts]
print('camera = Camera("WidefieldCamera")')
print('camera = Camera("MicroscopeCamera")')
print('camera.ip_address')
print('camera.state')
print('camera.camera_ip_address')
print('camera.acquiring = True')
debug('?')
<file_sep>"""
Optimize the X-ray pulse intensity at the sample
The X-ray beam is steered through an aperture upstream the I0 PIN detector
while recorded the transmitted pulse energy through with the X-ray oscillope
by gated integration of the X-ray pulse.
A three-point scan is performed and the optimum determined by parabolic fit.
Author: <NAME>
Date created : 2016-06-25
Date last modified: 2018-10-31
"""
__version__ = "1.2" # Don't switch oscilloscope from "Sequence" to "RealTime" mode
from instrumentation import xray_pulse,timing_system
from Ensemble_SAXS_pp import Ensemble_SAXS
from timing_sequencer import timing_sequencer
from CA import caget,caput,PV
from persistent_property import persistent_property
from numpy import nan,sqrt,arange
from thread import start_new_thread
from time import sleep,time
from instrumentation import MirrorH,MirrorV,s1hg,shg,svg
from logfile import LogFile
class Xray_Beam_Check(object):
name = "xray_beam_check"
class Settings(object):
name = "xray_beam_check.settings"
# X-Ray beam steering controls.
# Horizontal deflection mirror jacks
def get_x1_motor(self): return MirrorH.m1.prefix
def set_x1_motor(self,value): MirrorH.m1.prefix = value
x1_motor = property(get_x1_motor,set_x1_motor)
def get_x2_motor(self): return MirrorH.m2.prefix
def set_x2_motor(self,value): MirrorH.m2.prefix = value
x2_motor = property(get_x2_motor,set_x2_motor)
def get_y_motor(self): return MirrorV.prefix
def set_y_motor(self,value): MirrorV.prefix = value
y_motor = property(get_y_motor,set_y_motor)
dx_scan = persistent_property("dx_scan",6*0.000416*2/1.045) # stepsize: 0.000416*2/1.045 = 0.000796 mrad
dy_scan = persistent_property("dy_scan",0.150) # in V
x_resolution = persistent_property("x_resolution",0.000416*2/1.045) # stepsize: 0.000416*2/1.045 = 0.000796 mrad
y_resolution = persistent_property("y_resolution",0.001) # in V
beamline_mode = persistent_property("beamline_mode","SAXS/WAXS")
beamline_modes = ["SAXS/WAXS","Laue"]
@property
def x_aperture_control(self):
"""Which motor to use to narrow down the horizontal arperture"""
return s1hg if self.beamline_mode == "Laue" else shg
@property
def y_aperture_control(self):
"""Which motor to use to narrow down the horizontal arperture"""
return svg
# To narrow down aperture upstream of the detector for higher senitivity
def get_x_aperture_motor(self): return self.x_aperture_control.prefix
def set_x_aperture_motor(self,value):
self.x_aperture_control.prefix = value
x_aperture_motor = property(get_x_aperture_motor,set_x_aperture_motor)
def get_y_aperture_motor(self): return self.y_aperture_control.prefix
def set_y_aperture_motor(self,value): self.y_aperture_control.prefix = value
y_aperture_motor = property(get_y_aperture_motor,set_y_aperture_motor)
x_aperture_norm = persistent_property("x_aperture_norm",0.150)
y_aperture_norm = persistent_property("y_aperture_norm",0.050)
x_aperture_scan = persistent_property("x_aperture_scan",0.050)
y_aperture_scan = persistent_property("y_aperture_scan",0.020)
def get_x_aperture(self): return self.x_aperture_control.command_value
def set_x_aperture(self,value):
self.x_aperture_control.command_value = value
x_aperture = property(get_x_aperture,set_x_aperture)
def get_y_aperture(self): return self.y_aperture_control.command_value
def set_y_aperture(self,value):
self.y_aperture_control.command_value = value
y_aperture = property(get_y_aperture,set_y_aperture)
@property
def x_aperture_moving(self): return self.x_aperture_control.moving
@property
def y_aperture_moving(self): return self.y_aperture_control.moving
def get_timing_system_ip_address(self): return timing_system.ip_address
def set_timing_system_ip_address(self,value): timing_system.ip_address = value
timing_system_ip_address = property(get_timing_system_ip_address,set_timing_system_ip_address)
def get_scope_ip_address(self): return xray_pulse.scope.ip_address
def set_scope_ip_address(self,value): xray_pulse.scope.ip_address = value
scope_ip_address = property(get_scope_ip_address,set_scope_ip_address)
ms_on_norm = persistent_property("ms_on_norm",True)
xosct_on_norm = persistent_property("xosct_on_norm",True)
scan_timeout = 30 # seconds
timing_mode = persistent_property("timining_mode","SAXS/WAXS")
timing_modes = ["SAXS/WAXS","Laue"]
@property
def timing_sequencer(self):
return timing_sequencer if self.timing_mode == "Laue" \
else Ensemble_SAXS
settings = Settings()
log = LogFile(name+".log",["date time","x_control","y_control"])
if log.filename == "":
log.filename = "//mx340hs/data/anfinrud_1703/Logfiles/xray_beam_check.log"
x_scan_x = persistent_property("x_scan_x", [])
x_scan_I = persistent_property("x_scan_I", [])
x_scan_sigI = persistent_property("x_scan_sigI",[])
y_scan_y = persistent_property("y_scan_y", [])
y_scan_I = persistent_property("y_scan_I", [])
y_scan_sigI = persistent_property("y_scan_sigI",[])
cancelled = persistent_property("cancelled",False)
x_scan_started = persistent_property("x_scan_started",0.0)
y_scan_started = persistent_property("y_scan_started",0.0)
def get_x_control(self): return MirrorH.command_value
def set_x_control(self,value): MirrorH.command_value = value
x_control = property(get_x_control,set_x_control)
def x_next(self,x):
"""The next value that is an intergal motor step"""
offset = MirrorH.offset
dx = self.settings.x_resolution
return round_next(x-offset,dx)+offset
def y_next(self,y):
"""The next value that is an integral motor step"""
offset = 0 ##MirrorV.offset
dy = self.settings.y_resolution
return round_next(y-offset,dy)+offset
def get_y_control(self): return MirrorV.command_value
def set_y_control(self,value): MirrorV.command_value = value
y_control = property(get_y_control,set_y_control)
def x_pre_scan_setup(self):
self.settings.x_aperture_norm = self.settings.x_aperture
self.settings.x_aperture = self.settings.x_aperture_scan
while self.settings.x_aperture_moving and not self.cancelled: sleep(0.1)
##xray_pulse.scope.sampling_mode = "RealTime" # Lauecollect uses "Sequence"
xray_pulse.enabled = True
def x_post_scan_setup(self):
self.settings.x_aperture = self.settings.x_aperture_norm
xray_pulse.enabled = False
def y_pre_scan_setup(self):
self.settings.y_aperture_norm = self.settings.y_aperture
self.settings.y_aperture = self.settings.y_aperture_scan
while self.settings.y_aperture_moving and not self.cancelled: sleep(0.1)
##xray_pulse.scope.sampling_mode = "RealTime" # Lauecollect uses "Sequence"
xray_pulse.enabled = True
def y_post_scan_setup(self):
self.settings.y_aperture = self.settings.y_aperture_norm
xray_pulse.enabled = False
def timing_system_pre_scan_setup(self):
# Save current settings
self.settings.xosct_on_norm = self.settings.timing_sequencer.xosct_on
self.settings.ms_on_norm = self.settings.timing_sequencer.ms_on
if not self.settings.timing_sequencer.xosct_on:
self.settings.timing_sequencer.xosct_on = True
if not self.settings.timing_sequencer.ms_on:
self.settings.timing_sequencer.ms_on = True
while not (self.settings.timing_sequencer.xosct_on
and self.settings.timing_sequencer.ms_on) and not self.cancelled:
sleep(0.1)
def timing_system_post_scan_setup(self):
# Restore settings
self.settings.timing_sequencer.xosct_on = self.settings.xosct_on_norm
self.settings.timing_sequencer.ms_on = self.settings.ms_on_norm
def get_x_scan_running(self):
return self.x_scan_started > time()-self.settings.scan_timeout
def set_x_scan_running(self,value):
if value:
if not self.x_scan_running: self.start_x_scan()
else: self.cancelled = True
x_scan_running = property(get_x_scan_running,set_x_scan_running)
def get_y_scan_running(self):
return self.y_scan_started > time()-self.settings.scan_timeout
def set_y_scan_running(self,value):
if value:
if not self.y_scan_running: self.start_y_scan()
else: self.cancelled = True
y_scan_running = property(get_y_scan_running,set_y_scan_running)
def start_x_scan(self):
self.cancelled = False
start_new_thread(self.perform_x_scan,())
def start_y_scan(self):
self.cancelled = False
start_new_thread(self.perform_y_scan,())
def perform_x_scan(self):
self.x_scan_started = time()
self.x_pre_scan_setup()
self.timing_system_pre_scan_setup()
self.x_scan_x = []; self.x_scan_I = []; self.x_scan_sigI = []
x0 = self.x_control
# Start scanning in positive direction.
dx = self.settings.dx_scan
x = x0
self.x_control = x; I,sigI = self.I_sigI
self.x_scan_x += [x]; self.x_scan_I += [I]; self.x_scan_sigI += [sigI]
x += dx
self.x_control = x; I,sigI = self.I_sigI
self.x_scan_x += [x]; self.x_scan_I += [I]; self.x_scan_sigI += [sigI]
# If the intensity goes down, reverse direction.
if self.x_scan_I[1] < self.x_scan_I[0]:
dx = -dx; x = x0
self.x_scan_x = self.x_scan_x[::-1]
self.x_scan_I = self.x_scan_I[::-1]
self.x_scan_sigI = self.x_scan_sigI[::-1]
x += dx
self.x_control = x; I,sigI = self.I_sigI
self.x_scan_x += [x]; self.x_scan_I += [I]; self.x_scan_sigI += [sigI]
# Continue scanning until a maximum is reached.
while self.x_scan_I[-1] > self.x_scan_I[-2] and not self.cancelled:
x += dx
self.x_control = x; I,sigI = self.I_sigI
self.x_scan_x += [x]; self.x_scan_I += [I]; self.x_scan_sigI += [sigI]
# Return to the starting point.
self.x_control = x0
self.x_post_scan_setup()
self.timing_system_post_scan_setup()
self.x_scan_started = 0
def perform_y_scan(self):
self.y_scan_started = time()
self.y_pre_scan_setup()
self.timing_system_pre_scan_setup()
self.y_scan_y = []; self.y_scan_I = []; self.y_scan_sigI = []
y0 = self.y_control
# Start scanning in positive direction.
dy = self.settings.dy_scan
y = y0
self.y_control = y; I,sigI = self.I_sigI
self.y_scan_y += [y]; self.y_scan_I += [I]; self.y_scan_sigI += [sigI]
y += dy
self.y_control = y; I,sigI = self.I_sigI
self.y_scan_y += [y]; self.y_scan_I += [I]; self.y_scan_sigI += [sigI]
# If the intensity goes down, reverse direction.
if self.y_scan_I[1] < self.y_scan_I[0]:
dy = -dy; y = y0
self.y_scan_y = self.y_scan_y[::-1]
self.y_scan_I = self.y_scan_I[::-1]
self.y_scan_sigI = self.y_scan_sigI[::-1]
y += dy
self.y_control = y; I,sigI = self.I_sigI
self.y_scan_y += [y]; self.y_scan_I += [I]; self.y_scan_sigI += [sigI]
# Continue scanning until a mayimum is reached.
while self.y_scan_I[-1] > self.y_scan_I[-2] and not self.cancelled:
y += dy
self.y_control = y; I,sigI = self.I_sigI
self.y_scan_y += [y]; self.y_scan_I += [I]; self.y_scan_sigI += [sigI]
# Return to the starting point.
self.y_control = y0
self.y_post_scan_setup()
self.timing_system_post_scan_setup()
self.y_scan_started = 0
@property
def x_control_corrected(self):
if len(self.x_scan_x) < 3 or len(self.x_scan_I) < 3: return nan
x = parabola_vertex(self.x_scan_x[-3:],self.x_scan_I[-3:])[0]
x = self.x_next(x)
return x
@property
def y_control_corrected(self):
if len(self.y_scan_y) < 3 or len(self.y_scan_I) < 3: return nan
y = parabola_vertex(self.y_scan_y[-3:],self.y_scan_I[-3:])[0]
##y = self.y_next(y)
return y
@property
def x_scan_x_fit(self): return parabolic_fit(self.x_scan_x,self.x_scan_I)[0]
@property
def x_scan_I_fit(self): return parabolic_fit(self.x_scan_x,self.x_scan_I)[1]
@property
def y_scan_y_fit(self): return parabolic_fit(self.y_scan_y,self.y_scan_I)[0]
@property
def y_scan_I_fit(self): return parabolic_fit(self.y_scan_y,self.y_scan_I)[1]
def apply_x_correction(self):
self.x_control = self.x_control_corrected
self.update_log()
def apply_y_correction(self):
self.y_control = self.y_control_corrected
self.update_log()
def update_log(self):
"""Create a log file entry every time a correction is applied"""
self.log.log(self.x_control,self.y_control)
@property
def I_sigI(self):
"""X-ray beam intensity"""
xray_pulse.reset_average()
sleep(4)
I = xray_pulse.average
sI = xray_pulse.stdev
N = xray_pulse.count
sigI = I/sqrt(N-1) if N>1 else nan
return I,sigI
xray_beam_check = Xray_Beam_Check()
def parabola_vertex((x1,x2,x3),(y1,y2,y3)):
"""Vertex of a parabola given three points
x: list of three value
Y: list 3 values"""
# http://stackoverflow.com/questions/717762/how-to-calculate-the-vertex-of-a-parabola-given-three-points
# y = A * x**2 + B * x + C
try:
denom = (x1 - x2) * (x1 - x3) * (x2 - x3)
A = (x3 * (y2 - y1) + x2 * (y1 - y3) + x1 * (y3 - y2)) / denom
B = (x3**2 * (y1 - y2) + x2**2 * (y3 - y1) + x1**2 * (y2 - y3)) / denom
C = (x2 * x3 * (x2 - x3) * y1 + x3 * x1 * (x3 - x1) * y2 + x1 * x2 * (x1 - x2) * y3) / denom
xv = -B / (2*A)
yv = C - B*B / (4*A)
except ZeroDivisionError: xv,yv = nan,nan
return xv,yv
def parabolic_fit((x1,x2,x3),(y1,y2,y3)):
# http://stackoverflow.com/questions/717762/how-to-calculate-the-vertex-of-a-parabola-given-three-points
# y = A * x^2 + B * x + C
try:
denom = (x1 - x2) * (x1 - x3) * (x2 - x3)
A = (x3 * (y2 - y1) + x2 * (y1 - y3) + x1 * (y3 - y2)) / denom
B = (x3**2 * (y1 - y2) + x2**2 * (y3 - y1) + x1**2 * (y2 - y3)) / denom
C = (x2 * x3 * (x2 - x3) * y1 + x3 * x1 * (x3 - x1) * y2 + x1 * x2 * (x1 - x2) * y3) / denom
except ZeroDivisionError: A,B,C = nan,nan,nan
def f(x): return A * x**2 + B * x + C
xa,xb = min(x1,x2,x3),max(x1,x2,x3)
eps = 1e-10
x = arange(xa,xb+eps,(xb-xa)/10)
return x,f(x)
def tofloat(x):
"""Convert to floating point number without throwing exception"""
from numpy import nan
try: return float(x)
except: return nan
def round_next(x,step):
"""Rounds x up or down to the next multiple of step."""
if step == 0: return x
return round(x/step)*step
if __name__ == "__main__":
from pdb import pm
from CA import cainfo
from instrumentation import mir2X1,mir2X2,mir2Th
self = xray_beam_check # for debugging
print('xray_beam_check.settings.timing_system_ip_address = %r' % xray_beam_check.settings.timing_system_ip_address)
print('xray_beam_check.settings.scope_ip_address = %r' % xray_beam_check.settings.scope_ip_address)
print('xray_beam_check.settings.timing_mode = %r' % xray_beam_check.settings.timing_mode)
print('xray_beam_check.settings.beamline_mode = %r' % xray_beam_check.settings.beamline_mode)
print('')
print('xray_beam_check.perform_x_scan()')
print('xray_beam_check.perform_y_scan()')
##print('xray_beam_check.settings.x1_motor = %r' % xray_beam_check.settings.x1_motor)
##print('xray_beam_check.settings.x2_motor = %r' % xray_beam_check.settings.x2_motor)
##print('xray_beam_check.settings.y_motor = %r' % xray_beam_check.settings.y_motor)
##print('xray_beam_check.settings.x_aperture_motor=%r' % xray_beam_check.settings.x_aperture_motor)
##print('xray_beam_check.settings.y_aperture_motor=%r' % xray_beam_check.settings.y_aperture_motor)
##print('xray_beam_check.x_control = %.4f' % xray_beam_check.x_control)
##print('xray_beam_check.y_control = %.4f' % xray_beam_check.y_control)
##print('xray_beam_check.settings.dx_scan = %.4f' % xray_beam_check.settings.dx_scan)
##print('xray_beam_check.settings.dy_scan = %.4f' % xray_beam_check.settings.dy_scan)
<file_sep> #!/usr/bin/env python
"""Support module for SAXS/WAXS control panel.
Author: <NAME>, <NAME>
Date created: 2017-06-12
Date last modified: 2019-05-29
"""
__version__ = "1.8.2" # added temperature control
from logging import debug,info,warn,error
from instrumentation import *
from Ensemble_client import ensemble as ensemble_tcp
from temperature import temperature
class SAXS_WAXS_Control(object):
name = "SAXS_WAXS_control"
from persistent_property import persistent_property
from action_property import action_property
from instrumentation import DetZ
cancelled = persistent_property("cancelled",False)
environment_choices = ['0 (NIH)','1 (APS)','2 (LCLS)']
def get_environment(self):
"""'0 (NIH)','1 (APS)','2 (LCLS)'"""
from numpy import isnan
i = self.environment_index
if 0 <= i < len(self.environment_choices):
value = self.environment_choices[i]
elif isnan(i): value = 'offline'
else: value = str(i)
return value
def set_environment(self,value):
if value in self.environment_choices:
i = self.environment_choices.index(value)
else: i = 0
self.environment_index = i
environment = property(get_environment,set_environment)
def get_environment_index(self):
"""0=NIH, 1=APS, 2=LCLS"""
return ensemble.UserInteger0
def set_environment_index(self,value):
ensemble.UserInteger0 = value
environment_index = property(get_environment_index,set_environment_index)
det_inserted_pos = 185.8
det_retracted_pos = 485.8
def get_det_inserted(self):
from numpy import isnan,nan
value = abs(DetZ.value-self.det_inserted_pos) < 0.001\
if not isnan(DetZ.value) else nan
return value
def set_det_inserted(self,value):
if DetZ.moving: DetZ.moving = False
else:
if value: DetZ.command_value = self.det_inserted_pos
det_inserted = property(get_det_inserted,set_det_inserted)
def get_det_retracted(self):
from numpy import isnan,nan
value = abs(DetZ.value-self.det_retracted_pos) < 0.001\
if not isnan(DetZ.value) else nan
return value
def set_det_retracted(self,value):
if DetZ.moving: DetZ.moving = False
else:
if value: DetZ.command_value = self.det_retracted_pos
det_retracted = property(get_det_retracted,set_det_retracted)
def get_det_moving(self): return DetZ.moving
def set_det_moving(self,value): DetZ.moving = value
det_moving = property(get_det_moving,set_det_moving)
def get_ensemble_homed(self):
from numpy import product
homed = product(ensemble.homed[[0,1,2,4,5]])
return homed
def set_ensemble_homed(self,value):
if value: self.ensemble_homing = True
ensemble_homed = property(get_ensemble_homed,set_ensemble_homed)
home_program_filename = "Home (safe).ab"
def get_ensemble_homing(self):
return ensemble.program_filename == self.home_program_filename
def set_ensemble_homing(self,value):
if value:
self.action = "homing"
# The entrace window of the helium code need to be at least
# 10 mm away from the stages position at Z=0.
detz = DetZ.command_value
DetZ.command_value = detz + 10
from time import sleep
while DetZ.moving: sleep(0.10)
ensemble.program_filename = self.home_program_filename
while ensemble.program_filename == "": sleep(0.01)
while ensemble.program_filename == self.home_program_filename:
sleep(0.01)
DetZ.command_value = detz
while DetZ.moving: sleep(0.10)
self.action = ""
if not value:
if ensemble.program_filename == self.home_program_filename:
ensemble.program_running = False
ensemble_homing = property(get_ensemble_homing,set_ensemble_homing)
@property
def ensemble_homing_prohibited(self):
if self.ensemble_program_running: reason = "Program running"
elif not self.ensemble_online: reason = "Offline"
else: reason = ""
return reason
program_filename = "NIH-diffractometer_PP.ab"
def get_ensemble_program_running(self):
return ensemble.program_filename == self.program_filename
def set_ensemble_program_running(self,value):
if value: ensemble.program_filename = self.program_filename
else: ensemble_tcp.integer_registers[0] = 0
ensemble_program_running = property(get_ensemble_program_running,set_ensemble_program_running)
def get_timing_system_running(self):
return Ensemble_SAXS.running
def set_timing_system_running(self,value):
Ensemble_SAXS.running = value
timing_system_running = property(get_timing_system_running,
set_timing_system_running)
@property
def timing_system_online(self):
return timing_system.online
x = persistent_property("x",0.0) #sample saved inserted position
y = persistent_property("y",0.0) #sample saved inserted position
@property
def yr(self): return self.y + 11.0 # retract position
@property
def xr(self): return self.x + 3.0 # retract position
def get_at_inserted_position(self):
return self.inserted
def set_at_inserted_position(self,value):
"""Define current position as 'inserted'"""
if value: self.x,self.y = SampleX.command_value,SampleY.command_value
at_inserted_position = property(get_at_inserted_position,
set_at_inserted_position)
def get_inserted(self):
from numpy import isnan,nan,allclose
x,y = SampleX.value,SampleY.value
value = allclose((x,y),(self.x,self.y),atol=0.005)
if any(isnan([x,y])): value = nan
return value
def set_inserted(self,value):
if value: self.inserting_sample = True
else: self.retracting_sample = True
inserted = property(get_inserted,set_inserted)
def get_retracted(self):
from numpy import isnan,nan,allclose
x,y = SampleX.value,SampleY.value
value = allclose((x,y),(self.xr,self.yr),atol=0.005)
if any(isnan([x,y])): value = nan
return value
def set_retracted(self,value):
if value: self.retracting_sample = True
else: self.inserting_sample = True
retracted = property(get_retracted,set_retracted)
inserting_sample = action_property("self.insert_sample()",
stop="self.stop_sample()")
retracting_sample = action_property("self.retract_sample()",
stop="self.stop_sample()")
def insert_sample(self):
x,y = self.x,self.y # destination
self.cancelled = False
self.timeout = 10
debug("retract sample: x -> %r" % x);
SampleX.command_value = x
debug("insert sample: x=%r" % SampleX.value);
while not abs(SampleX.value - x) < 0.005:
from time import sleep
sleep(0.1)
if self.cancelled: warn("insert sample: x cancelled"); return
if self.timed_out: warn("insert sample: x timed out"); return
debug("insert sample: x=%r" % SampleX.value);
debug("insert sample: x=%r" % SampleX.value);
debug("insert sample: y -> %r" % y);
SampleY.command_value = y
debug("insert sample: y=%r" % SampleY.value);
def retract_sample(self):
x,y = self.xr,self.yr # destination
self.cancelled = False
self.timeout = 10
debug("retract sample: y -> %r" % y);
SampleY.command_value = y
debug("retract sample: y=%r" % SampleY.value);
while not abs(SampleY.value - y) < 0.005:
from time import sleep
sleep(0.1)
if self.cancelled: warn("retract sample: y cancelled"); return
if self.timed_out: warn("retract sample: y timed out"); return
debug("retract sample: y=%r" % SampleY.value);
debug("retract sample: y=%r" % SampleY.value);
debug("retract sample: x -> %r" % x);
SampleX.command_value = x
debug("retract sample: x=%r" % SampleX.value);
timeout_start = persistent_property("timeout_start",0.0)
timeout_period = persistent_property("timeout_period",0.0)
def get_timeout(self):
return self.timeout_period
def set_timeout(self,value):
self.timeout_period = value
from time import time
self.timeout_start = time()
timeout = property(get_timeout,set_timeout)
@property
def timed_out(self):
from time import time
return time()-self.timeout_start > self.timeout
def stop_sample(self):
SampleX.moving,SampleY.moving = False,False
def get_moving_sample(self):
return self.inserting_sample or self.retracting_sample
def set_moving_sample(self,value):
if not value:
self.inserting_sample = False
self.retracting_sample = False
moving_sample = property(get_moving_sample,set_moving_sample)
def get_fault(self): return ensemble.fault
def set_fault(self,value): ensemble.fault = value
fault = property(get_fault,set_fault)
@property
def ensemble_online(self):
from numpy import isnan
return not isnan(SampleX.command_value)
def get_XY_enabled(self): return SampleX.enabled * SampleY.enabled
def set_XY_enabled(self,value): SampleX.enabled,SampleY.enabled = True,True
XY_enabled = property(get_XY_enabled,set_XY_enabled)
def get_xray_safety_shutters_open(self):
return xray_safety_shutters_open.value
def set_xray_safety_shutters_open(self,value):
xray_safety_shutters_open.value = value
xray_safety_shutters_open = property(get_xray_safety_shutters_open,
set_xray_safety_shutters_open)
def get_xray_safety_shutters_enabled(self):
return xray_safety_shutters_enabled.value
def set_xray_safety_shutters_enabled(self,value):
xray_safety_shutters_enabled.value = value
xray_safety_shutters_enabled = property(get_xray_safety_shutters_enabled,
set_xray_safety_shutters_enabled)
def get_xray_safety_shutters_auto_open(self):
return xray_safety_shutters_auto_open.value
def set_xray_safety_shutters_auto_open(self,value):
xray_safety_shutters_auto_open.value = value
xray_safety_shutters_auto_open = property(get_xray_safety_shutters_auto_open,
set_xray_safety_shutters_auto_open)
def get_laser_safety_shutter_open(self):
return laser_safety_shutter_open.value
def set_laser_safety_shutter_open(self,value):
laser_safety_shutter_open.value = value
laser_safety_shutter_open = property(get_laser_safety_shutter_open,
set_laser_safety_shutter_open)
def get_laser_safety_shutter_auto_open(self):
return laser_safety_shutter_auto_open.value
def set_laser_safety_shutter_auto_open(self,value):
laser_safety_shutter_auto_open.value = value
laser_safety_shutter_auto_open = property(get_laser_safety_shutter_auto_open,
set_laser_safety_shutter_auto_open)
def get_mode(self): return Ensemble_SAXS.mode
def set_mode(self,value): Ensemble_SAXS.mode = value
mode = property(get_mode,set_mode)
@property
def modes(self): return Ensemble_SAXS.modes
def get_ms_on(self): return Ensemble_SAXS.ms_on
def set_ms_on(self,value): Ensemble_SAXS.ms_on = value
ms_on = property(get_ms_on,set_ms_on)
def get_pump_on(self): return Ensemble_SAXS.pump_on
def set_pump_on(self,value): Ensemble_SAXS.pump_on = value
pump_on = property(get_pump_on,set_pump_on)
def get_pump_on_command(self): return Ensemble_SAXS.get_default("pump_on")
def set_pump_on_command(self,value): Ensemble_SAXS.pump_on = value
pump_on_command = property(get_pump_on_command,set_pump_on_command)
pump_step_choices = ["1(linear)","0.1","0.2","0.5","1","2.5","5","10","25","50"]
def get_pump_step(self):
"""'1(linear)','0.1','0.2','0.5','1','2.5','5','10','25','50'"""
i = self.pump_step_index
if 0 <= i < len(self.pump_step_choices): step = self.pump_step_choices[int(i)]
else: step = ''
return step
def set_pump_step(self,value):
if value in self.pump_step_choices:
i = self.pump_step_choices.index(value)
else: i = 0
self.pump_step_index = i
pump_step = property(get_pump_step,set_pump_step)
def get_pump_step_index(self):
"""0-9 = 1(linear),0.1,0.2,0.5,1,2.5,5,10,25,50"""
from numpy import nan
try: i = ensemble.integer_registers[2]
except: i = nan
return i
def set_pump_step_index(self,value):
ensemble_tcp.integer_registers[2] = value
pump_step_index = property(get_pump_step_index,set_pump_step_index)
def get_pump_position(self): return PumpA.value
def set_pump_position(self,value):
self.action = "move pump"
PumpA.command_value = value
pump_position = property(get_pump_position,set_pump_position)
def get_pump_speed(self): return PumpA.speed
def set_pump_speed(self,value): PumpA.speed = value
pump_speed = property(get_pump_speed,set_pump_speed)
def get_pump_homed(self): return PumpA.homed
def set_pump_homed(self,value):
self.action = "home pump"
PumpA.homing = value
pump_homed = property(get_pump_homed,set_pump_homed)
@property
def pump_movable(self):
pump_movable = True
if SAXS_WAXS_control.pump_on and self.ensemble_program_running:
pump_movable = False
if PumpA.moving: pump_movable = False
return pump_movable
def get_pump_enabled(self): return PumpA.enabled
def set_pump_enabled(self,value): PumpA.enabled = value
pump_enabled = property(get_pump_enabled,set_pump_enabled)
load_step = persistent_property("load_step",700)
extract_step = persistent_property("extract_step",-700)
circulate_step = persistent_property("circulate_step",700)
action = persistent_property("action","")
def get_sample_loading(self):
return PumpA.moving and self.action == "load sample"
def set_sample_loading(self,value):
if value:
self.action = "load sample"
PumpA.command_value += self.load_step
else:
self.action = ""
PumpA.moving = False
sample_loading = property(get_sample_loading,set_sample_loading)
def get_sample_extracting(self):
return PumpA.moving and self.action == "extract sample"
def set_sample_extracting(self,value):
if value:
self.action = "extract sample"
PumpA.command_value += self.extract_step
else:
self.action = ""
PumpA.moving = False
sample_extracting = property(get_sample_extracting,set_sample_extracting)
def get_sample_circulating(self):
return PumpA.moving and self.action == "circulate sample"
def set_sample_circulating(self,value):
if value:
self.action = "circulate sample"
PumpA.command_value += self.circulate_step
else:
self.action = ""
PumpA.moving = False
sample_circulating = property(get_sample_circulating,set_sample_circulating)
@property
def temperature_online(self):
""""""
from instrumentation import temperature
from numpy import isnan
return not isnan(temperature.value)
def get_temperature_setpoint(self):
"""sample temperature"""
from instrumentation import temperature
return temperature.command_value
def set_temperature_setpoint(self,value):
from instrumentation import temperature
temperature.command_value = value
temperature_setpoint = property(get_temperature_setpoint,set_temperature_setpoint)
def get_temperature(self):
"""sample temperature"""
from instrumentation import temperature
return temperature.value
def set_temperature(self,value):
from instrumentation import temperature
temperature.value = value
temperature = property(get_temperature,set_temperature)
SAXS_WAXS_control = control = SAXS_WAXS_Control()
if __name__ == "__main__": # for debugging
from pdb import pm
import logging
logging.basicConfig(level=logging.INFO,
format="%(asctime)s %(levelname)s: %(message)s")
self = SAXS_WAXS_control
print("control.det_inserted = True")
print("control.det_retracted = True")
print("control.det_moving = False")
print("control.det_moving")
<file_sep>#!/usr/bin/env python
"""Control panel for data dollection.
Author: <NAME>
Date created: 2018-10-17
Date last modified: 2019-05-21
"""
__version__ = "1.1.2" # changed pperiodic update timer from 5000 to 10000 ms Valentyn
from logging import debug,info,warn,error
import wx
from instrumentation import * # passed on in "globals()"
class Collect_Panel(wx.Frame):
"""Control panel for data dollection"""
name = "Collect_Panel"
title = "PP Acquire"
icon = "Tool"
def __init__(self,parent=None):
wx.Frame.__init__(self,parent=parent)
self.update()
self.Show()
# Refresh
self.timer = wx.Timer(self)
self.Bind (wx.EVT_TIMER,self.OnTimer,self.timer)
self.timer.Start(10000,oneShot=True)
def update(self):
self.Title = self.title
from Icon import SetIcon
SetIcon(self,self.icon)
panel = self.ControlPanel
if hasattr(self,"panel"): self.panel.Destroy()
self.panel = panel
self.Fit()
def OnTimer(self,event):
"""Perform periodic updates"""
try: self.update_controls()
except Exception,msg:
error("%s" % msg)
import traceback
traceback.print_exc()
self.timer.Start(10000,oneShot=True)
def update_controls(self):
if self.code_outdated:
self.update_code()
self.update()
@property
def code_outdated(self):
outdated = False
try:
from inspect import getfile
from os.path import getmtime,basename
filename = getfile(self.__class__).replace(".pyc",".py")
##debug("module: %s" % basename(filename))
if self.timestamp == 0: self.timestamp = getmtime(filename)
outdated = getmtime(filename) != self.timestamp
except Exception,msg: pass ##debug("code_outdated: %s" % msg)
return outdated
def update_code(self):
from inspect import getfile
from os.path import getmtime,basename
filename = getfile(self.__class__).replace(".pyc",".py")
##debug("module: %s" % basename(filename))
module_name = basename(filename).replace(".pyc",".py").replace(".py","")
module = __import__(module_name)
reload(module)
debug("Reloaded module %r" % module.__name__)
debug("Updating class of %r instance" % self.__class__.__name__)
self.__class__ = getattr(module,self.__class__.__name__)
timestamp = 0
@property
def ControlPanel(self):
# Controls and Layout
panel = wx.Panel(self)
from EditableControls import ComboBox,TextCtrl,Choice
from Controls import Control
from DirectoryControl import DirectoryControl
flag = wx.ALIGN_CENTRE_HORIZONTAL|wx.ALL
border = 2
l = wx.ALIGN_LEFT; r = wx.ALIGN_RIGHT; cv = wx.ALIGN_CENTER_VERTICAL
a = wx.ALL; e = wx.EXPAND
frame = wx.BoxSizer()
panel.SetSizer(frame)
layout = wx.BoxSizer(wx.VERTICAL)
frame.Add(layout,flag=wx.EXPAND|wx.ALL,border=10,proportion=1)
layout_flag = wx.EXPAND
group = wx.FlexGridSizer(cols=2)
layout.Add(group,flag=layout_flag,border=border,proportion=1)
label = wx.StaticText(panel,label="Method:")
group.Add(label,flag=cv,border=0,proportion=1)
subgroup = wx.BoxSizer(wx.HORIZONTAL)
control = Control(panel,type=ComboBox,
globals=globals(),
locals=locals(),
name="Collect_Panel.Method",
size=(395,-1),
)
subgroup.Add(control,flag=l|cv|a,border=0,proportion=1)
control = Control(panel,type=wx.Button,
globals=globals(),
locals=locals(),
name="Collect_Panel.Show_Methods",
label="Methods...",
)
subgroup.Add(control,flag=l|cv|a,border=0)
group.Add(subgroup,flag=l|cv|a,border=border)
label = wx.StaticText(panel,label="Time to Finish [s]:")
group.Add(label,flag=cv,border=0,proportion=1)
control = Control(panel,type=TextCtrl,
globals=globals(),
locals=locals(),
name="Collect_Panel.Time_to_Finish",
size=(350,-1),
)
group.Add(control,flag=l|cv|a|e,border=border,proportion=1)
group.AddSpacer(20)
group.AddSpacer(20)
label = wx.StaticText(panel,label="File:")
group.Add(label,flag=cv,border=0,proportion=1)
subgroup = wx.BoxSizer(wx.HORIZONTAL)
control = Control(panel,type=TextCtrl,
globals=globals(),
locals=locals(),
name="Collect_Panel.File",
size=(200,-1),
)
subgroup.Add(control,flag=l|cv|a,border=0)
label = wx.StaticText(panel,label="Extension:")
subgroup.Add(label,flag=cv,border=0)
control = Control(panel,type=wx.TextCtrl,
globals=globals(),
locals=locals(),
name="Collect_Panel.Extension",
size=(60,-1),
)
subgroup.Add(control,flag=l|cv|a,border=0)
group.Add(subgroup,flag=l|cv|a,border=border)
label = wx.StaticText(panel,label="Description:")
group.Add(label,flag=cv,border=0,proportion=1)
control = Control(panel,type=TextCtrl,
globals=globals(),
locals=locals(),
name="Collect_Panel.Description",
size=(480,-1),
)
group.Add(control,flag=l|cv|a,border=border)
label = wx.StaticText(panel,label="Logfile:")
group.Add(label,flag=cv,border=0,proportion=1)
control = Control(panel,type=TextCtrl,
globals=globals(),
locals=locals(),
name="Collect_Panel.Logfile",
size=(200,-1),
)
group.Add(control,flag=l|cv|a,border=border)
label = wx.StaticText(panel,label="Path:")
group.Add(label,flag=cv,border=0,proportion=1)
control = DirectoryControl(panel,
globals=globals(),
locals=locals(),
name="Collect_Panel.Path",
size=(390,-1),
)
group.Add(control,flag=l|cv|a,border=border)
indicator = Control(panel,type=wx.StaticText,
globals=globals(),
locals=locals(),
name="Collect_Panel.Info",
size=(600,-1),
label="-"*100,
)
layout.Add(indicator,flag=layout_flag,border=border,proportion=0)
indicator = Control(panel,type=wx.StaticText,
globals=globals(),
locals=locals(),
name="Collect_Panel.Status",
size=(600,-1),
label="-"*100,
)
layout.Add(indicator,flag=layout_flag,border=border,proportion=0)
indicator = Control(panel,type=wx.StaticText,
globals=globals(),
locals=locals(),
name="Collect_Panel.Actual",
size=(600,-1),
label="-"*100,
)
layout.Add(indicator,flag=layout_flag,border=border,proportion=0)
group = wx.BoxSizer(wx.HORIZONTAL)
layout.Add(group,flag=layout_flag,border=border)
width,height = 115,27
flag = wx.EXPAND
control = Control(panel,type=wx.ToggleButton,
globals=globals(),
locals=locals(),
name="Collect_Panel.Generate_Packets",
label="Generate Packets",
size=(width,height),
)
group.Add(control,flag=flag,border=border,proportion=1)
control = Control(panel,type=wx.ToggleButton,
globals=globals(),
locals=locals(),
name="Collect_Panel.Collect_Dataset",
label="Collect Dataset",
size=(width,height),
)
group.Add(control,flag=flag,border=border,proportion=1)
control = Control(panel,type=wx.ToggleButton,
globals=globals(),
locals=locals(),
name="Collect_Panel.Erase_Dataset",
label="Erase Dataset",
size=(width,height),
)
group.Add(control,flag=flag,border=border,proportion=1)
control = Control(panel,type=wx.ToggleButton,
globals=globals(),
locals=locals(),
name="Collect_Panel.Finish_Series",
label="Finish Series",
size=(width,height),
)
group.Add(control,flag=flag,border=border,proportion=1)
control = Control(panel,type=Choice,
globals=globals(),
locals=locals(),
name="Collect_Panel.Finish_Series_Variable",
size=(width,height),
)
group.Add(control,flag=flag,border=border,proportion=1)
panel.Fit()
return panel
@staticmethod
def show_methods():
from SavedPositionsPanel_2 import show_panel
show_panel("method")
@staticmethod
def play_sound():
from sound import play_sound
play_sound("ding")
if __name__ == '__main__':
from pdb import pm
from redirect import redirect
redirect("Collect_Panel")
##import autoreload
# Needed to initialize WX library
if not hasattr(wx,"app"): wx.app = wx.App(redirect=False)
panel = Collect_Panel()
wx.app.MainLoop()
<file_sep>"""
Automatically load samples for Lauec crystallography data collection
Author: <NAME>
Date created: Oct 28, 2017
Date last modified: Oct 28, 2017
"""
__version__ = "1.0"
from Laue_crystallography import Laue_crystallography
template = "/net/mx340hs/data/anfinrud_1711/Data/Laue/Lyz/Lyz-%d/alignment"
i = 8
def collect():
Laue_crystallography.image_scan.directory = template % i
Laue_crystallography.inject()
Laue_crystallography.scan()
i += 1
<file_sep>"""
ILX Lightwave LDT-5948 Precision Temperature Controller
EPICS client
Author: <NAME>
Date created: 14 Dec 2009
Date last modified: 2019-02-21
"""
__version__ = "4.5" # id
from pdb import pm # stabilization number of samples: stabilization_nsamples
import logging
##logging.basicConfig(level=logging.DEBUG,format="%(asctime)s: %(message)s")
def alias(name):
"""Make property given by name be known under a different name"""
def get(self): return getattr(self,name)
def set(self,value): setattr(self,name,value)
return property(get,set)
from EPICS_motor import EPICS_motor
class Lightwave_Temperature_Controller(EPICS_motor):
"""ILX Lightwave LDT-5948 Precision Temperature Controller"""
port_name = alias("COMM")
stabilization_threshold = alias("RDBD")
stabilization_nsamples = alias("NSAM")
current_low_limit = alias("ILLM")
current_high_limit = alias("IHLM")
trigger_enabled = alias("TENA")
trigger_start = alias("P1SP")
trigger_stop = alias("P1EP")
trigger_stepsize = alias("P1SI")
id = alias("ID")
setT = alias("command_value") # for backward compatbility with lauecollect
readT = alias("value") # for backward compatbility with lauecollect
lightwave_temperature_controller = Lightwave_Temperature_Controller(prefix="NIH:LIGHTWAVE",
name="lightwave_temperature_controller")
if __name__ == "__main__":
print('lightwave_temperature_controller.prefix = %r' % lightwave_temperature_controller.prefix)
print('lightwave_temperature_controller.port_name = %r' % lightwave_temperature_controller.port_name)
print('lightwave_temperature_controller.command_value = %r' % lightwave_temperature_controller.command_value)
<file_sep>Size = (1489, 413)
Position = (428, 0)
ScaleFactor = 1.0
ZoomLevel = 1.0
Orientation = 0
Mirror = 0
NominalPixelSize = 0.00465
filename = ''
ImageWindow.Center = None
ImageWindow.ViewportCenter = (3.162, 4.0501499999999995)
ImageWindow.crosshair_color = (255, 0, 255)
ImageWindow.boxsize = (0.1, 0.06)
ImageWindow.box_color = (128, 128, 255)
ImageWindow.show_box = False
ImageWindow.Scale = [[-0.12555, -1.6786499999999998], [-0.2976, -1.8227999999999998]]
ImageWindow.show_scale = True
ImageWindow.scale_color = (0, 0, 0, 255)
ImageWindow.crosshair_size = (0.05, 0.05)
ImageWindow.show_crosshair = True
ImageWindow.show_profile = False
ImageWindow.show_FWHM = False
ImageWindow.show_center = False
ImageWindow.calculate_section = False
ImageWindow.profile_color = (255, 0, 255)
ImageWindow.FWHM_color = (0, 0, 255)
ImageWindow.center_color = (0, 0, 255)
ImageWindow.ROI = [[-0.2, -0.2], [0.2, 0.2]]
ImageWindow.ROI_color = (255, 255, 0)
ImageWindow.show_saturated_pixels = False
ImageWindow.mask_bad_pixels = False
ImageWindow.saturation_threshold = 233
ImageWindow.saturated_color = (255, 0, 0)
ImageWindow.linearity_correction = False
ImageWindow.bad_pixel_threshold = 233
ImageWindow.bad_pixel_color = (30, 30, 30)
ImageWindow.show_grid = False
ImageWindow.grid_type = 'xy'
ImageWindow.grid_color = (0, 0, 255)
ImageWindow.grid_x_spacing = 1.0
ImageWindow.grid_x_offset = 0.0
ImageWindow.grid_y_spacing = 1.0
ImageWindow.grid_y_offset = 0.0
<file_sep>#!/usr/bin/env python
"""Control panel system level (SL) temperature control
Author: <NAME>
Date created: 2009-10-14
Date last modified: 2019-05-21
"""
import wx,wx3_compatibility
from temperature import temperature
from oasis_chiller import oasis_chiller as oasis
from EditableControls import ComboBox,TextCtrl
from logging import debug
from Panel import BasePanel,PropertyPanel,TogglePanel,TweakPanel
__version__ = "4.6" # title
class Temperature_Panel (wx.Frame):
def __init__(self):
wx.Frame.__init__(self,parent=None,title="Temperature SL")
# Icon
from Icon import SetIcon
SetIcon(self,"temperature")
# Controls
panel = wx.Panel(self)
style = wx.TE_PROCESS_ENTER
self.SetPoint = ComboBox(panel,style=style)
style = wx.TE_READONLY
self.ActualTemperature = wx.TextCtrl(panel,style=style)
self.OasisActualTemperature = wx.TextCtrl(panel,style=style)
self.CurrentPower = wx.TextCtrl(panel,style=style)
self.LiveCheckBox = wx.CheckBox (panel,label="Live")
self.RefreshButton = wx.Button (panel,label="Refresh",size=(65,-1))
self.MoreButton = wx.Button (panel,label="More...",size=(60,-1))
self.SettingsButton = wx.Button (panel,label="Settings...",size=(60,-1))
w,h = self.MoreButton.Size
self.AboutButton = wx.Button (panel,label="?",size=(h*1.25,h*0.75))
# Callbacks
self.Bind (wx.EVT_TEXT_ENTER,self.OnEnterSetPoint,self.SetPoint)
self.Bind (wx.EVT_COMBOBOX,self.OnEnterSetPoint,self.SetPoint)
self.Bind (wx.EVT_CHECKBOX,self.OnLive,self.LiveCheckBox)
self.Bind (wx.EVT_BUTTON,self.OnRefresh,self.RefreshButton)
self.Bind (wx.EVT_BUTTON,self.OnMore,self.MoreButton)
self.Bind (wx.EVT_BUTTON,self.OnAbout,self.AboutButton)
self.Bind (wx.EVT_BUTTON,self.OnTemperature,self.SettingsButton)
# Layout
layout = wx.GridBagSizer(1,1)
a = wx.ALIGN_CENTRE_VERTICAL
e = wx.EXPAND
# Under Linux, if the version of wxWidget is 2.6 or older,
# the label size needs to be specified to prevent line wrapping.
# (This bug has been corrected in version 2.8).
layout.Add (wx.StaticText(panel,label="Set Point:"),(0,0),flag=a)
layout.Add (self.SetPoint,(0,1),flag=a|e)
t = wx.StaticText(panel,label="Actual Temperature:")
layout.Add (t,(1,0),flag=a)
layout.Add (self.ActualTemperature,(1,1),flag=a|e)
t = wx.StaticText(panel,label="Oasis Temperature:")
layout.Add (t,(1,2),flag=a)
layout.Add (self.OasisActualTemperature,(1,3),flag=a|e)
t = wx.StaticText(panel,label="Current / Power:")
layout.Add (t,(2,0),flag=a)
layout.Add (self.CurrentPower,(2,1),flag=a|e)
buttons = wx.BoxSizer(wx.HORIZONTAL)
buttons.Add (self.LiveCheckBox,flag=wx.ALIGN_CENTER_VERTICAL)
buttons.AddSpacer(5)
buttons.Add (self.RefreshButton,flag=wx.ALIGN_CENTER_VERTICAL)
buttons.AddSpacer(5)
buttons.Add (self.MoreButton,flag=wx.ALIGN_CENTER_VERTICAL)
buttons.AddSpacer(5)
buttons.Add (self.SettingsButton,flag=wx.ALIGN_CENTER_VERTICAL)
buttons.AddSpacer(5)
buttons.Add (self.AboutButton,flag=wx.ALIGN_CENTER_VERTICAL)
# Leave a 5 pixel wide border.
box = wx.BoxSizer(wx.VERTICAL)
box.Add (layout,flag=wx.ALL,border=5)
box.Add (buttons,flag=wx.ALL|wx.ALIGN_CENTER_HORIZONTAL,border=5)
panel.SetSizer(box)
panel.Fit()
self.Fit()
self.Show()
# Restore saved history.
config_dir = wx.StandardPaths.Get().GetUserDataDir()
config_file = config_dir+"/TemperatureController.py"
self.config = wx.FileConfig (localFilename=config_file)
value = self.config.Read('History')
if value: self.history = eval(value)
else: self.history = []
self.update_history()
# Initialization
self.timer = wx.Timer(self)
self.Bind (wx.EVT_TIMER,self.refresh,self.timer)
self.timer.Start(1000,oneShot=True)
def update_history(self):
"""Update the pull down menu for the set point."""
self.SetPoint.Clear() # clears menu
choices = []
for T in sorted(set(self.history)): choices += [str(T)]
self.SetPoint.AppendItems(choices)
def OnEnterSetPoint(self,event):
"""Called when typing Enter in the position field.
or selecting a choice from the combo box drop down menu"""
text = self.SetPoint.Value
try: T = float(eval(text.replace("C","")))
except: self.refresh(); return
temperature.command_value = T
self.history = self.history[-20:]+[T]
self.update_history()
self.refresh()
# Make sure the history gets saved.
config_dir = wx.StandardPaths.Get().GetUserDataDir()
from os.path import exists
from os import makedirs
if not exists(config_dir): makedirs(config_dir)
self.config.Write ('history',repr(self.history))
self.config.Flush()
def OnLive(self,event):
"""Called when the 'Live' checkbox is either checked or unchecked."""
self.RefreshButton.Enabled = not self.LiveCheckBox.Value
if self.LiveCheckBox.Value == True: self.keep_alive()
def keep_alive(self,event=None):
"""Periodically refresh te displayed settings (every second)."""
if self.LiveCheckBox.Value == False: return
self.refresh()
self.timer = wx.Timer(self)
self.Bind (wx.EVT_TIMER,self.keep_alive,self.timer)
self.timer.Start(250,oneShot=True)
def OnRefresh(self,event):
"""Called when refrsh button is pressed"""
self.refresh()
def refresh(self,event=None):
"""Update displayed values"""
value = tofloat(temperature.command_value)
self.SetPoint.Value = "%.3f C" % value if not isnan(value) else ""
value = temperature.value
self.ActualTemperature.Value = "%.3f C"%value if not isnan(value) else ""
value = oasis.value
self.OasisActualTemperature.Value = "%.3f C"%value if not isnan(value) else ""
moving = temperature.moving
self.ActualTemperature.ForegroundColour = (255,0,0) if moving else (0,0,0)
moving = oasis.moving
self.OasisActualTemperature.ForegroundColour = (255,0,0) if moving else (0,0,0)
##self.ActualTemperature.BackgroundColour = (255,235,235) if moving else (255,255,255)
current = temperature.I
current = "%.3f A" % current if not isnan(current) else ""
power = temperature.P
power = "%.3f W" % power if not isnan(power) else ""
self.CurrentPower.Value = "%s / %s" % (current,power)
def OnMore(self,event):
"""Display panel with additional parameters."""
self.parameter_panel = ParameterPanel(self)
def OnTemperature(self,event):
"""Show panel with temperature ramp parameters"""
self.temperature_ramp_panel = Temperature(self)
def OnAbout(self,event):
"Called from the Help/About"
from os.path import basename
from inspect import getfile
filename = getfile(lambda x: None)
info = basename(filename)+" "+__version__+"\n"+__doc__
dlg = wx.MessageDialog(self,info,"About",wx.OK|wx.ICON_INFORMATION)
dlg.CenterOnParent()
dlg.ShowModal()
dlg.Destroy()
class ParameterPanel(BasePanel):
name = "parameters"
title = "Parameters"
standard_view = [
"EPICS Record",
]
parameters = [
[[PropertyPanel,"EPICS Record",temperature,"prefix"],{"choices":["NIH:TEMP","NIH:LIGHTWAVE"],"refresh_period":1.0}],
]
def __init__(self,parent=None):
BasePanel.__init__(self,
parent=parent,
name=self.name,
title=self.title,
parameters=self.parameters,
standard_view=self.standard_view,
subname=True,
refresh=True,
live=True,
label_width=90,
)
class Temperature(BasePanel):
name = "temperature"
title = "Temperature"
standard_view = [
"Temp Points",
"Time Points",
"P default",
"I default",
"D default",
"Lightwave prefix",
"Oasis slave (on/off)",
"Oasis threshold T",
"Oasis idle temperature (low limit) (C)",
"Oasis temperature limit high (C)",
"Oasis headstart time (s)",
"Oasis prefix",
"set point update period (s)",
]
parameters = [
[[PropertyPanel,"Temp Points",temperature,"temp_points" ],{}],
[[PropertyPanel,"Time Points",temperature,"time_points" ],{}],
[[PropertyPanel,"P default",temperature,"P_default" ],{}],
[[PropertyPanel,"I default",temperature,"I_default" ],{}],
[[PropertyPanel,"D default",temperature,"D_default" ],{}],
[[PropertyPanel,"Lightwave prefix",temperature,"lightwave_prefix"],{}],
[[PropertyPanel,"Oasis slave (on/off)",temperature,"oasis_slave" ],{}],
[[PropertyPanel,"Oasis threshold T",temperature,"T_threshold" ],{}],
[[PropertyPanel,"Oasis idle temperature (low limit) (C)",temperature,"idle_temperature_oasis" ],{}],
[[PropertyPanel,"Oasis temperature limit high (C)",temperature,"temperature_oasis_limit_high" ],{}],
[[PropertyPanel,"Oasis headstart time (s)",temperature,"oasis_headstart_time" ],{}],
[[PropertyPanel,"Oasis prefix",temperature,"oasis_prefix" ],{}],
]
def __init__(self,parent=None):
BasePanel.__init__(self,
parent=parent,
name=self.name,
title=self.title,
parameters=self.parameters,
standard_view=self.standard_view,
subname=True,
refresh=True,
live=True,
label_width=90,
)
def isnan(x):
"""Is x 'not a number' or 'None'"""
from numpy import isnan
try: return isnan(float(x))
except: return True
def tostr(x):
"""Convert x to string."""
if x is None: return ""
return str(x)
def tofloat(x):
"""Convert x to float if possible, else return nan"""
from numpy import nan
try: x = float(x)
except: x = nan
return x
def toint(x):
"""Convert x to int if possible, else return nan"""
from numpy import nan
try: x = int(x)
except: x = nan
return x
if __name__ == '__main__':
from pdb import pm
import logging; from tempfile import gettempdir
logfile = gettempdir()+"/Temperature_Panel.log"
logging.basicConfig(level=logging.DEBUG,format="%(asctime)s: %(message)s",
filename=logfile)
logging.debug("Temperature Panel started")
# Needed to initialize WX library
if not "app" in globals(): app = wx.App(redirect=False)
panel = Temperature_Panel()
app.MainLoop()
<file_sep>title = 'Wide-Field camera [advanced] (60 deg)'<file_sep>#!/usr/bin/env python
"""High-speed X-ray Chopper
Control panel to save and restore motor positions.
Author: <NAME>
Date created: 2017-10-16
Date last modified: 2018-09-13
"""
__version__ = "1.0"
from SavedPositionsPanel_2 import SavedPositionsPanel
if __name__ == '__main__':
from pdb import pm # for debugging
import logging # for debugging
from tempfile import gettempdir
logfile = gettempdir()+"/Julich_Chopper_Modes_Panel.log"
logging.basicConfig(level=logging.INFO,filename=logfile,
format="%(asctime)s %(levelname)s: %(message)s")
import autoreload
import wx
app = wx.App(redirect=False)
from instrumentation import * # -> globals()
panel = SavedPositionsPanel(name="Julich_chopper_modes",globals=globals())
app.MainLoop()
<file_sep>#!/usr/bin/env python
"""Control panel for ILX Lighwave Precision Temperature Controller.
Author: <NAME>
Date created: 2009-10-14
Date last modified: 2019-05-21
"""
import wx,wx3_compatibility
from lightwave_temperature_controller import lightwave_temperature_controller
from EditableControls import ComboBox,TextCtrl
from logging import debug
from Panel import BasePanel,PropertyPanel,TogglePanel,TweakPanel
__version__ = "4.6" # title, renamed: lightwave_temperature_controller
class Lightwave_Temperature_Controller_Panel (wx.Frame):
"""Control panel for ILX Lighwave Precision Temperature Controller"""
def __init__(self):
wx.Frame.__init__(self,parent=None)
self.Title = "Lightwave Temperature Controller DL"
# Icon
from Icon import SetIcon
SetIcon(self,"Temperature Controller")
# Controls
panel = wx.Panel(self)
style = wx.TE_PROCESS_ENTER
self.SetPoint = ComboBox(panel,style=style)
style = wx.TE_READONLY
self.ActualTemperature = wx.TextCtrl(panel,style=style)
self.CurrentPower = wx.TextCtrl(panel,style=style)
self.Status = ComboBox(panel,style=style,choices=["On","Off",""])
self.LiveCheckBox = wx.CheckBox (panel,label="Live")
self.RefreshButton = wx.Button (panel,label="Refresh",size=(65,-1))
self.MoreButton = wx.Button (panel,label="More...",size=(60,-1))
self.RampButton = wx.Button (panel,label="Ramp...",size=(60,-1))
w,h = self.MoreButton.Size
self.AboutButton = wx.Button (panel,label="?",size=(h*1.25,h*0.75))
# Callbacks
self.Bind (wx.EVT_TEXT_ENTER,self.OnEnterSetPoint,self.SetPoint)
self.Bind (wx.EVT_COMBOBOX,self.OnEnterSetPoint,self.SetPoint)
self.Bind (wx.EVT_TEXT_ENTER,self.OnChangeStatus,self.Status)
self.Bind (wx.EVT_COMBOBOX,self.OnChangeStatus,self.Status)
self.Bind (wx.EVT_CHECKBOX,self.OnLive,self.LiveCheckBox)
self.Bind (wx.EVT_BUTTON,self.OnRefresh,self.RefreshButton)
self.Bind (wx.EVT_BUTTON,self.OnMore,self.MoreButton)
self.Bind (wx.EVT_BUTTON,self.OnAbout,self.AboutButton)
self.Bind (wx.EVT_BUTTON,self.OnTemperatureRamp,self.RampButton)
# Layout
layout = wx.GridBagSizer(1,1)
a = wx.ALIGN_CENTRE_VERTICAL
e = wx.EXPAND
# Under Linux, if the version of wxWidget is 2.6 or older,
# the label size needs to be specified to prevent line wrapping.
# (This bug has been corrected in version 2.8).
layout.Add (wx.StaticText(panel,label="Set Point:"),(0,0),flag=a)
layout.Add (self.SetPoint,(0,1),flag=a|e)
t = wx.StaticText(panel,label="Actual Temperature:")
layout.Add (t,(1,0),flag=a)
layout.Add (self.ActualTemperature,(1,1),flag=a|e)
t = wx.StaticText(panel,label="Current / Power:")
layout.Add (t,(2,0),flag=a)
layout.Add (self.CurrentPower,(2,1),flag=a|e)
t = wx.StaticText(panel,label="Status:")
layout.Add (t,(3,0),flag=a)
layout.Add (self.Status,(3,1),flag=a|e)
buttons = wx.BoxSizer(wx.HORIZONTAL)
buttons.Add (self.LiveCheckBox,flag=wx.ALIGN_CENTER_VERTICAL)
buttons.AddSpacer(5)
buttons.Add (self.RefreshButton,flag=wx.ALIGN_CENTER_VERTICAL)
buttons.AddSpacer(5)
buttons.Add (self.MoreButton,flag=wx.ALIGN_CENTER_VERTICAL)
buttons.AddSpacer(5)
buttons.Add (self.RampButton,flag=wx.ALIGN_CENTER_VERTICAL)
buttons.AddSpacer(5)
buttons.Add (self.AboutButton,flag=wx.ALIGN_CENTER_VERTICAL)
# Leave a 5 pixel wide border.
box = wx.BoxSizer(wx.VERTICAL)
box.Add (layout,flag=wx.ALL,border=5)
box.Add (buttons,flag=wx.ALL|wx.ALIGN_CENTER_HORIZONTAL,border=5)
panel.SetSizer(box)
panel.Fit()
self.Fit()
self.Show()
# Restore saved history.
config_dir = wx.StandardPaths.Get().GetUserDataDir()
config_file = config_dir+"/TemperatureController.py"
self.config = wx.FileConfig (localFilename=config_file)
value = self.config.Read('History')
if value: self.history = eval(value)
else: self.history = []
self.update_history()
# Initialization
self.timer = wx.Timer(self)
self.Bind (wx.EVT_TIMER,self.refresh,self.timer)
self.timer.Start(1000,oneShot=True)
def update_history(self):
"""Update the pull down menu for the set point."""
self.SetPoint.Clear() # clears menu
choices = []
for T in sorted(set(self.history)): choices += [str(T)]
self.SetPoint.AppendItems(choices)
def OnEnterSetPoint(self,event):
"""Called when typing Enter in the position field.
or selecting a choice from the combo box drop down menu"""
text = self.SetPoint.Value
try: T = float(eval(text.replace("C","")))
except: self.refresh(); return
lightwave_temperature_controller.command_value = T
self.history = self.history[-20:]+[T]
self.update_history()
self.refresh()
# Make sure the history gets saved.
config_dir = wx.StandardPaths.Get().GetUserDataDir()
from os.path import exists
from os import makedirs
if not exists(config_dir): makedirs(config_dir)
self.config.Write ('history',repr(self.history))
self.config.Flush()
def OnChangeStatus(self,event):
"""Called when typing Enter in the position field.
or selecting a choice from the combo box drop down menu"""
text = self.Status.Value
if text == "On": lightwave_temperature_controller.enabled = True
if text == "Off": lightwave_temperature_controller.enabled = False
self.refresh()
def OnLive(self,event):
"""Called when the 'Live' checkbox is either checked or unchecked."""
self.RefreshButton.Enabled = not self.LiveCheckBox.Value
if self.LiveCheckBox.Value == True: self.keep_alive()
def keep_alive(self,event=None):
"""Periodically refresh te displayed settings (every second)."""
if self.LiveCheckBox.Value == False: return
self.refresh()
self.timer = wx.Timer(self)
self.Bind (wx.EVT_TIMER,self.keep_alive,self.timer)
self.timer.Start(250,oneShot=True)
def OnRefresh(self,event):
"""Called when refrsh button is pressed"""
self.refresh()
def refresh(self,event=None):
"""Update displayed values"""
value = tofloat(lightwave_temperature_controller.command_value)
self.SetPoint.Value = "%.3f C" % value if not isnan(value) else ""
value = lightwave_temperature_controller.value
self.ActualTemperature.Value = "%.3f C"%value if not isnan(value) else ""
moving = lightwave_temperature_controller.moving
self.ActualTemperature.ForegroundColour = (255,0,0) if moving else (0,0,0)
##self.ActualTemperature.BackgroundColour = (255,235,235) if moving else (255,255,255)
current = lightwave_temperature_controller.I
current = "%.3f A" % current if not isnan(current) else ""
power = lightwave_temperature_controller.P
power = "%.3f W" % power if not isnan(power) else ""
self.CurrentPower.Value = "%s / %s" % (current,power)
value = toint(lightwave_temperature_controller.enabled)
if value == 0: text = "Off"
elif value == 1: text = "On"
else: text = ""
self.Status.Value = text
def OnMore(self,event):
"""Display panel with additional parameters."""
self.parameter_panel = ParameterPanel(self)
def OnTemperatureRamp(self,event):
"""Show panel with temperature ramp parameters"""
self.temperature_ramp_panel = TemperatureRamp(self)
def OnAbout(self,event):
"Called from the Help/About"
from os.path import basename
from inspect import getfile
filename = getfile(lambda x: None)
info = basename(filename)+" "+__version__+"\n"+__doc__
dlg = wx.MessageDialog(self,info,"About",wx.OK|wx.ICON_INFORMATION)
dlg.CenterOnParent()
dlg.ShowModal()
dlg.Destroy()
class ParameterPanel(BasePanel):
name = "parameters"
title = "Parameters"
standard_view = [
"EPICS Record",
"Baud Rate",
"Serial Port",
"ID String",
"Act. Update Period",
"Nom. Update Period",
"Proportional Gain (P)",
"Integral Gain (I)",
"Differential Gain (D)",
"Stabilization Threshold",
"Stabilization N Samples",
"Current Low Limit",
"Current High Limit",
]
parameters = [
[[PropertyPanel,"EPICS Record",lightwave_temperature_controller,"prefix"],{"choices":["NIH:TEMP","NIH:LIGHTWAVE"],"refresh_period":1.0}],
[[PropertyPanel,"Baud Rate",lightwave_temperature_controller,"BAUD"],{"choices":[9600,14400,19200,38400,56700]}],
[[PropertyPanel,"Serial Port",lightwave_temperature_controller,"port_name"],{"read_only":True}],
[[PropertyPanel,"ID String",lightwave_temperature_controller,"id"],{"read_only":True}],
[[PropertyPanel,"Nom. Update Period",lightwave_temperature_controller,"SCAN"],{"choices":[0,0.2,0.5,1.0,2.0],"unit":"s","format":"%g"}],
[[PropertyPanel,"Act. Update Period",lightwave_temperature_controller,"SCANT"],{"read_only":True,"unit":"s","format":"%g"}],
[[PropertyPanel,"Proportional Gain (P)",lightwave_temperature_controller,"PCOF"],{"choices":[0.75]}],
[[PropertyPanel,"Integral Gain (I)" ,lightwave_temperature_controller,"ICOF"],{"choices":[0.3],"format":"%g"}],
[[PropertyPanel,"Differential Gain (D)",lightwave_temperature_controller,"DCOF"],{"choices":[0.3],"format":"%g"}],
[[PropertyPanel,"Stabilization Threshold",lightwave_temperature_controller,"stabilization_threshold"],{"digits":3,"unit":"C","choices":[0.01,0.008]}],
[[PropertyPanel,"Stabilization N Samples",lightwave_temperature_controller,"stabilization_nsamples"],{"choices":[3]}],
[[PropertyPanel,"Current Low Limit",lightwave_temperature_controller,"current_low_limit"],{"digits":3,"unit":"A","choices":[3.5,4,5]}],
[[PropertyPanel,"Current High Limit",lightwave_temperature_controller,"current_high_limit"],{"digits":3,"unit":"A","choices":[-3.5,-4,-5]}],
]
def __init__(self,parent=None):
BasePanel.__init__(self,
parent=parent,
name=self.name,
title=self.title,
parameters=self.parameters,
standard_view=self.standard_view,
subname=True,
refresh=True,
live=True,
label_width=90,
)
class TemperatureRamp(BasePanel):
name = "temperature_ramp"
title = "Temperature Ramp"
standard_view = [
"Trigger Enabled",
"Start",
"Stepsize",
"Stop",
]
parameters = [
[[TogglePanel,"Trigger Enabled",lightwave_temperature_controller,"trigger_enabled" ],{"type":"Off/On"}],
[[TweakPanel,"Start" ,lightwave_temperature_controller,"trigger_start" ],{"digits":3,"unit":"C"}],
[[TweakPanel,"Stop" ,lightwave_temperature_controller,"trigger_stop" ],{"digits":3,"unit":"C"}],
[[TweakPanel,"Stepsize",lightwave_temperature_controller,"trigger_stepsize"],{"digits":3,"unit":"C"}],
]
def __init__(self,parent=None):
BasePanel.__init__(self,
parent=parent,
name=self.name,
title=self.title,
parameters=self.parameters,
standard_view=self.standard_view,
subname=True,
refresh=True,
live=True,
label_width=90,
)
def isnan(x):
"""Is x 'not a number' or 'None'"""
from numpy import isnan
try: return isnan(float(x))
except: return True
def tostr(x):
"""Convert x to string."""
if x is None: return ""
return str(x)
def tofloat(x):
"""Convert x to float if possible, else return nan"""
from numpy import nan
try: x = float(x)
except: x = nan
return x
def toint(x):
"""Convert x to int if possible, else return nan"""
from numpy import nan
try: x = int(x)
except: x = nan
return x
if __name__ == '__main__':
from pdb import pm
import logging; from tempfile import gettempdir
logfile = gettempdir()+"/Lightwave_Temperature_Controller_Panel.log"
logging.basicConfig(level=logging.DEBUG,format="%(asctime)s: %(message)s",
filename=logfile)
logging.debug("Lightwave Temperature Controller Panel started")
# Needed to initialize WX library
if not "app" in globals(): app = wx.App(redirect=False)
panel = Lightwave_Temperature_Controller_Panel()
app.MainLoop()
<file_sep>VAL.filename = '//mx340hs/data/anfinrud_1906/Archive/14IDA.DAC1_4.VAL.txt'<file_sep>Size = (538, 542)
Position = (933, 171)
ScaleFactor = 0.33
ZoomLevel = 1.0
Orientation = 0
Mirror = True
NominalPixelSize = 0.000526
filename = '/root/Desktop/hekstra_screenshots/E65_a_precollect..jpg'
ImageWindow.Center = (680.0, 512.0)
ImageWindow.ViewportCenter = (0.35768, 0.2685150303030303)
ImageWindow.crosshair_color = (255, 255, 0)
ImageWindow.boxsize = (0.04, 0.34)
ImageWindow.box_color = (0, 0, 255)
ImageWindow.show_box = True
ImageWindow.Scale = [(-0.252044, -0.016726799999999997), (-0.002044000000000004, -0.016726799999999997)]
ImageWindow.show_scale = False
ImageWindow.scale_color = (255, 0, 0)
ImageWindow.crosshair_size = (0.025, 0.025)
ImageWindow.show_crosshair = True
ImageWindow.show_profile = False
ImageWindow.show_FWHM = False
ImageWindow.show_center = False
ImageWindow.calculate_section = False
ImageWindow.profile_color = wx.Colour(255, 0, 255, 255)
ImageWindow.FWHM_color = (255, 255, 0)
ImageWindow.center_color = (0, 255, 0)
ImageWindow.ROI = [[-0.099414, -0.130448], [0.11572, 0.1315]]
ImageWindow.ROI_color = wx.Colour(255, 255, 0, 255)
ImageWindow.show_saturated_pixels = False
ImageWindow.mask_bad_pixels = False
ImageWindow.saturation_threshold = 233
ImageWindow.saturated_color = (255, 255, 255, 255)
ImageWindow.linearity_correction = False
ImageWindow.bad_pixel_threshold = 233
ImageWindow.bad_pixel_color = (0, 0, 0)
ImageWindow.show_grid = False
ImageWindow.grid_type = u'x'
ImageWindow.grid_color = (82, 82, 82)
ImageWindow.grid_x_spacing = 0.055
ImageWindow.grid_x_offset = 0.0006999999999999437
ImageWindow.grid_y_spacing = 1.0
ImageWindow.grid_y_offset = 0.0
show_edge_controls = False
stepsize = 0.005
camera_angle = -30
x_scale = -1.0
y_scale = 1.0
z_scale = -1.0
phi_stepsize = 90.0
learn_center = False
click_center_enabled = False
<file_sep>filename = '/net/mx340hs/data/anfinrud_1901/Archive/NIH.XRAY_SCOPE.TRACE_COUNT.txt'<file_sep>#!/bin/env python
"""
Measure the poistion of the laser beam at the sample, based on a camera image.
<NAME>, APS, 8 Jul 2010 - 1 Jul 2012
"""
__version__ = "2.0.2"
from GigE_camera import GigE_camera
from sys import stdout
#IP_address = "id14b-prosilica3.cars.aps.anl.gov"
IP_address = "id14b-prosilica3.biocarsvideo.net"
pixelsize = 0.00465 # 1:1 imaging, same as CCD pixelsize
# Under Linux, The Prosilica library requires administrative privileges
# to use multicast. Unless the calling prgram is registered in sudoers
# data base, 'use_multicast' needs to be set to False.
# If multicast is set to False, the image acquisition will fail if a
# another application acquires images from the beam profilter camera at
# the same time.
use_multicast = False
def get_image():
"""Acquire a single image from the camera and return as PIL image.
This function is *NOT SAFE* to use for Python applications using network
communication ("Interrupted system call"), because loads the Prosilica
library."""
from time import time
import Image # Python Imaging Library
camera = GigE_camera(IP_address)
# Under Linux use_multicast requires administrative priviledges.
# Program needs to be registered in sudoers data base.
camera.use_multicast = use_multicast
camera.last_timestamp = 0
camera.start()
t = time()
while not camera.has_image or camera.timestamp == 0:
if time()-t > 2.0 and not "started" in camera.state:
log ("Prosilica image unreadable (%s)" % camera.state); break
if time()-t > 5.0:
log ("Prosilica image acquistion timed out (%s)" % camera.state); break
sleep(0.1)
camera.stop()
log("Info: read image image with %dx%d pixels, %d bytes" %
(camera.width,camera.height,len(camera.rgb_data)))
image = Image.new('RGB',(camera.width,camera.height))
image.fromstring(camera.rgb_data)
return image
def get_center():
"""Beam center pixel occordinates, without rotation applied.
This function is *NOT SAFE* to use for Python applications using network
communication ("Interrupted system call"), because loads the Prosilica
library."""
camera = GigE_camera(IP_address)
return camera.center
def get_image_size():
"""Image width and height, without rotation applied.
This function is *NOT SAFE* to use for Python applications using network
communication ("Interrupted system call"), because loads the Prosilica
library."""
camera = GigE_camera(IP_address)
return camera.width,camera.height
def subprocess(command):
"""Execute the given command in a subprocess.
The standard ouput of the command is returned as a string with trailing
newline.
If you need the result of the command, the command should contain a 'print'
statement. E.g. 'print get_center()'. Multiple commands can be
concatenated, separated by semicolons.
Functions that load the Prosilica library interfere with network
communication ("Interrupted system call").
Executing them in a subprocess makes it safe for applications that use
network communications to call them."""
from sys import executable as python
from subprocess import Popen,PIPE
from sys import stderr
command = "from %s import *; %s" % (modulename(),command)
process = Popen([python,"-c",command],stdout=PIPE,stderr=PIPE,
universal_newlines=True)
output,error = process.communicate()
if "Traceback" in error: raise RuntimeError(repr(command)+"\n"+error)
if error: stderr.write(error)
return output
def acquire_image(rotate=True):
"""Acquire a single image from the camera and return it as PIL image.
If rotate = True, apply the same rotation as in the 'Laser Beam Profile'
ImageViewer application.
This function is safe to use from any Python application, because it does
not load the Prosilica library. The task is preformed in a subprocess
instead."""
import Image
w,h = image_size()
image = Image.new('RGB',(w,h))
global image_data # for debugging
image_data = eval(subprocess("print repr(get_image().tostring())"))
##image_data = subprocess("stdout.write(get_image().tostring())")
log("Info: got %d bytes of image data from subprocess" % len(image_data))
log("Expecting %d, got %d bytes of image data" % (w*h*3,len(image_data)))
if (len(image_data) == w*h*3): image.fromstring(image_data)
else: log("Image data corrupted, substituting blank image")
return rotated_image(image) if rotate else image
def rotated_image(image):
"""Apply the same rotation as in the 'Laser Beam Profile' ImageViewer
application."""
orientation = parameter('Orientation',90) # in degrees counter-clockwise
if orientation == None: orienation = 0
return image.rotate(orientation)
def center():
"""Beam center pixel occordinates, without rotation applied.
This function is safe to use from any Python application, because it does
not load the Prosilica library. The task is preformed in a subprocess
instead."""
return eval(subprocess("print get_center()"))
def image_size():
"""Image width and height, without rotation applied
This function is safe to use from any Python application, because it does
not load the Prosilica library. The task is preformed in a subprocess
instead."""
return eval(subprocess("print get_image_size()"))
def modulename():
"""Name of this Python module, without directory and extension,
as used for 'import'"""
from inspect import getmodulename,getfile
return getmodulename(getfile(center))
def crosshair():
"""Cross hair coordinates in pixels with respect to the top left
corner of the rotated image"""
return rotate(center())
def rotate((x,y)):
"""Apply the same rotation as in the 'Laser Beam Profile' ImageViewer
application to the cross-hair"""
orientation = parameter('Orientation',90) # in degrees counter-clockwise
if orientation == None: orienation = 0
w,h = image_size()
if orientation == 0: return (x,y)
if orientation == -90: return (h-y,x)
if orientation == 90: return (y,w-x)
if orientation == 180: return (w-x,h-y)
return (x,y)
def parameter(name,default_value=None):
"""Retreive a parameter used by the 'Laser Beam Profile' CameraViewer
application."""
settings = file(settings_file()).read()
for line in settings.split("\n"):
line = line.strip(" \n\r")
if len(line.split("=")) != 2: continue
keyword,value = line.split(" = ")
keyword = keyword.strip(" ")
if keyword == name: return eval(value)
return default_value
def settings_file():
"pathname of the file used to store persistent parameters"
return settings_dir()+"/BeamProfile_settings.py"
def settings_dir():
"pathname of the file used to store persistent parameters"
path = module_dir()+"/settings"
return path
def module_dir():
"directory of the current module"
from os.path import dirname
module_dir = dirname(module_path())
if module_dir == "": module_dir = "."
return module_dir
def module_path():
"full pathname of the current module"
from sys import path
from os import getcwd
from os.path import basename,exists
from inspect import getmodulename,getfile
# 'getfile' retreives the source file name name compiled into the .pyc file.
pathname = getfile(lambda x: None)
##print "module_path: pathname: %r" % pathname
if exists(pathname): return pathname
# The module might have been compiled on a different machine or in a
# different directory.
pathname = pathname.replace("\\","/")
filename = basename(pathname)
##print "module_path: filename: %r" % filename
dirs = [dir for dir in [getcwd()]+path if exists(dir+"/"+filename)]
if len(dirs) == 0: print "pathname of file %r not found" % filename
dir = dirs[0] if len(dirs) > 0 else "."
pathname = dir+"/"+filename
##print "module_path: pathname: %r" % pathname
return pathname
def ROI(image):
"""Image clipped to the region of interest as defined by the 'Laser Beam
Profile' ImageViewer application."""
# Get the region of interest
ROI = parameter('ImageWindow.ROI',[[-1.0,-1.0],[1.0,1.0]])
##print "using ROI [%+.3f,%+.3f], "%tuple(ROI[0])+"[%+.3f,%+.3f] mm"%tuple(ROI[1])
cx,cy = crosshair()
##print "using center",(cx,cy)
dx = dy = pixelsize
xmin = int(round(ROI[0][0]/dx+cx)) ; xmax = int(round(ROI[1][0]/dx+cx))
ymin = int(round(cy-ROI[1][1]/dy)) ; ymax = int(round(cy-ROI[0][1]/dy))
if xmin > xmax: xmin,xmax = xmax,xmin
if ymin > ymax: ymin,ymax = ymax,ymin
##print "ROI [%d:%d,%d:%d]" % (xmin,xmax,ymin,ymax)
return image.crop((xmin,ymin,xmax,ymax))
def xy_projections(image):
"""Calculate a horizonal and vertical projections of a region of interest
of the image. The region of interest is the one define by the 'Laser Beam
Profile' CameraViewer application.
A rotated image as displayed and saved by the 'Laser Beam Profile'
ImageViewer application must be passed in PIL format.
"""
from numpy import array,sum,nansum,isnan
image = ROI(image)
R,G,B = image.split()
R,G,B = array(R,float).T,array(G,float).T,array(B,float).T
RGB = array([R,G,B])
# Select which channels to use.
R,G,B = RGB
use_channels = (1,1,1) # use all channels R,G,B
r,g,b = use_channels
I = r*R + b*B + g*G
# Generate projection on the X and Y axis.
xproj = nansum(I,axis=1)/sum(~isnan(I),axis=1)
yproj = nansum(I,axis=0)/sum(~isnan(I),axis=0)
# Scale projections in units of mm.
roi = parameter('ImageWindow.ROI',[[-1.0,-1.0],[1.0,1.0]])
cx,cy = crosshair()
dx = dy = pixelsize
xmin = int(round(roi[0][0]/dx+cx)) ; xmax = int(round(roi[1][0]/dx+cx))
ymin = int(round(cy-roi[1][1]/dy)) ; ymax = int(round(cy-roi[0][1]/dy))
if xmin > xmax: xmin,xmax = xmax,xmin
if ymin > ymax: ymin,ymax = ymax,ymin
xscale = [(xmin+i-cx)*dx for i in range(0,len(xproj))]
yscale = [(cy-(ymin+i))*dy for i in range(0,len(yproj))]
xprofile = zip(xscale,xproj)
yprofile = zip(yscale,yproj)
return xprofile,yprofile
def FWHM(data):
"""Calculates full-width at half-maximum of a positive peak of a curve
given as list of [x,y] values"""
x = xvals(data); y = yvals(data); n = len(data)
if n == 0: return nan
HM = (min(y)+max(y))/2
for i in range (0,n):
if y[i]>HM: break
if i == 0: x1 = x[0]
else: x1 = interpolate_x((x[i-1],y[i-1]),(x[i],y[i]),HM)
r = range(0,n); r.reverse()
for i in r:
if y[i]>HM: break
if i == n-1: x2 = x[n-1]
else: x2 = interpolate_x((x[i+1],y[i+1]),(x[i],y[i]),HM)
return abs(x2-x1)
def CFWHM(data):
"""Calculates the center of the full width half of the positive peak of
a curve given as list of [x,y] values"""
x = xvals(data); y = yvals(data); n = len(data)
if n == 0: return nan
HM = (min(y)+max(y))/2
for i in range (0,n):
if y[i]>HM: break
if i == 0: x1 = x[0]
else: x1 = interpolate_x((x[i-1],y[i-1]),(x[i],y[i]),HM)
r = range(0,n); r.reverse()
for i in r:
if y[i]>HM: break
if i == n-1: x2 = x[n-1]
else: x2 = interpolate_x((x[i+1],y[i+1]),(x[i],y[i]),HM)
return (x2+x1)/2.
def SNR(data):
"""Calculate the signal-to-noise ratio of a beam profile.
It is defined as the ratio the peak height relative to the baseline and the
RMS of the base line.
The base line is the outer 20% of the profile on either end."""
from numpy import rint,std,mean,mean,nan
y = yvals(data); n = len(data)
# Assume that the base line is the outer 20% of the data.
n1 = int(rint(n*0.2)) ; n2 = int(rint(n*0.8))
baseline = y[0:n1]+y[n2:-1]
signal = max(y)-mean(baseline)
noise = std(baseline)
if noise != 0: return signal/noise
else: return nan
def interpolate_x((x1,y1),(x2,y2),y):
"Linear inteposition between two points"
# In case the result is undefined, midpoint is as good as any value.
if y1==y2: return (x1+x2)/2.
x = x1+(x2-x1)*(y-y1)/float(y2-y1)
#print "interpolate_x [%g,%g,%g][%g,%g,%g]" % (x1,x,x2,y1,y,y2)
return x
def xvals(xy_data):
"xy_data = list of (x,y)-tuples. Returns list of x values only."
xvals = []
for i in range (0,len(xy_data)): xvals.append(xy_data[i][0])
return xvals
def yvals(xy_data):
"xy_data = list of (x,y)-tuples. Returns list of y values only."
yvals = []
for i in range (0,len(xy_data)): yvals.append(xy_data[i][1])
return yvals
def log(message):
"Append a message to the log file (/tmp/beam_profiler.log)"
from tempfile import gettempdir
from time import strftime
from sys import stderr
timestamp = strftime("%d-%b-%y %H:%M:%S")
if len(message) == 0 or message[-1] != "\n": message += "\n"
stderr.write("%s: %s" % (timestamp,message))
logfile = gettempdir()+"/beam_profiler.log"
file(logfile,"a").write(timestamp+" "+message)
def sleep(seconds):
"""Return after for the specified number of seconds"""
# After load and initializing the PvAPI Python's built-in 'sleep' function
# stops working (returns too early). The is a replacement.
from time import sleep,time
t = t0 = time()
while t < t0+seconds: sleep(t0+seconds - t); t = time()
def test():
global image,xprofile,yprofile
image = acquire_image()
##image = Image.open("/net/id14bxf/data/anfinrud_0907/Photos/2009.07.08 20.40 Laser profile.png")
print "image size",image.size
print "using center",crosshair()
print "using ROI",parameter('ImageWindow.ROI',[[-1.0,-1.0],[1.0,1.0]])
xprofile,yprofile = xy_projections(image)
print "FWHM: %.3f x %.3f mm" % ( FWHM(xprofile), FWHM(yprofile))
print "center: %+.3f mm, %+.3f mm" % (CFWHM(xprofile),CFWHM(yprofile))
print "S/N: %.3g:1, %.3g:1" % (SNR(xprofile),SNR(yprofile)),
OK = min(SNR(xprofile),SNR(yprofile)) > 15
if OK: print "(OK)"
else: print "(insufficient)"
from Plot import Plot
Plot(xprofile,title="xprofile")
Plot(yprofile,title="yprofile")
import wx
wx.GetApp().MainLoop()
def test_direct():
print "Running test ..."
camera = GigE_camera("id14b-prosilica3.cars.aps.anl.gov",use_multicast=False)
camera.start()
print "Camera started..."
sleep(2)
print camera.state
print "has_image",camera.has_image
print "pixel_format",camera.pixel_format
print "width*height",camera.width*camera.height
image = camera.rgb_array
from numpy import average,sum
I = float(sum(image))/image.size
print "average intensity",I
def test_average():
global image_data,image
image_data = subprocess("stdout.write(get_image().tostring())")
from numpy import frombuffer,uint8,average
image = frombuffer(image_data,uint8).reshape(1360,1024,3)
I = float(image.sum())/image.size
print "average: %g counts/pixel" % I
print "fraction of pixels >0: %g" % average(image != 0)
def test_single_image():
from time import time
from numpy import average,sum
global camera,image,I
camera = GigE_camera("id14b-prosilica4.cars.aps.anl.gov",
use_multicast=False)
camera.start()
t = time()
while not camera.has_image:
if time()-t > 2.0 and not "started" in camera.state:
print ("Prosilica image unreadable (%s)" % camera.state)
break
if time()-t > 5.0:
print ("image acquistion timed out (%s)" % camera.state)
break
sleep(0.1)
print "acquisition time %.3fs" % (time()-t)
image = camera.rgb_array
I = float(sum(image))/image.size
print "average: %g counts/pixel" % I
print "fraction of pixels >0: %g" % average(image != 0)
if __name__ == "__main__":
"for testing"
test()
<file_sep>line0.Phi = nan
line0.SamplePhi = +140.500
line0.SampleX = -2.909
line0.SampleY = +7.915
line0.SampleZ = +8.392
line0.description = #Chip 7,7,5,5
line0.updated = 03 Dec 03:33
line1.Phi =
line1.SamplePhi = +140.500
line1.SampleX = -3.134
line1.SampleY = +7.785
line1.SampleZ = -5.550
line1.description = #Chip 7,0,5,5
line1.updated = 03 Dec 03:29
line10.SamplePhi = +140.500
line10.SampleX = -3.465
line10.SampleY = -6.280
line10.SampleZ = -5.513
line10.description = Chip 0,0,5,5
line10.updated = 03 Dec 08:40
line11.SamplePhi = +140.500
line11.SampleX = -3.554
line11.SampleY = -7.005
line11.SampleZ = +7.548
line11.description = Chip 0,7,1,0
line11.updated = 03 Dec 08:43
line12.SamplePhi = +140.500
line12.SampleX = -3.545
line12.SampleY = +6.750
line12.SampleZ = +7.556
line12.description = Chip 7,7,0,0
line12.updated = 03 Dec 08:44
line2.Phi =
line2.SamplePhi = +75.000
line2.SampleX = +2.128
line2.SampleY = +0.054
line2.SampleZ = +3.293
line2.description = YAG
line2.updated = 01 Dec 21:07
line3.Phi =
line3.SamplePhi = +169.320
line3.SampleX = -0.658
line3.SampleY = +0.610
line3.SampleZ = +7.097
line3.description = Bismuth
line3.updated = 30 Nov 02:22
line4.Phi =
line4.SamplePhi = +30.000
line4.SampleX = -0.235
line4.SampleY = +0.622
line4.SampleZ = -0.588
line4.description = Alignment Pin 2
line4.updated = 03 Dec 03:54
line5.Phi =
line5.SamplePhi = -105.000
line5.SampleX = -0.757
line5.SampleY = +0.553
line5.SampleZ = -3.766
line5.description = Phosphor Pin 2
line5.updated = 27 Nov 20:19
line6.Phi =
line6.SamplePhi = +75.000
line6.SampleX = +3.184
line6.SampleY = +0.858
line6.SampleZ = +2.811
line6.description = Glass for Pin 2 (Microscope)
line6.updated = 28 Nov 11:15
line7.Phi =
line7.SamplePhi = +140.500
line7.SampleX = +1.336
line7.SampleY = -2.781
line7.SampleZ = +2.811
line7.description = Glass for Pin 2 (Wide-Field)
line7.updated = 28 Nov 11:27
line8.SamplePhi = +140.500
line8.SampleX = -3.462
line8.SampleY = -6.992
line8.SampleZ = -6.397
line8.description = Chip 0,0,1,0
line8.updated = 03 Dec 08:46
line9.SamplePhi = +140.500
line9.SampleX = -3.462
line9.SampleY = -6.992
line9.SampleZ = -5.512
line9.description = Chip 0,0,1,5
line9.updated = 03 Dec 08:40
<file_sep>"""EPICS Channel Access Protocol
<NAME>, 26 Apr 2009 - 8 Oct 2010
based on: 'Channel Access Protocol Specification', version 4.11
http://epics.cosylab.com/cosyjava/JCA-Common/Documentation/CAproto.html
"""
__version__ = "1.12"
import socket
timeout = 1.0 # s
DEBUG = False
class PV_info:
"State information for each process variable"
def __init__(self):
self.connection_requested = 0 # first time a PV was asked for
self.connection_initiated = 0 # time a CA connection for PV was initiated
self.servers_queried = [] # for address resolution
self.addr = None # IP address and port number of IOC
self.channel_ID = None # client-provided reference number for PV
self.channel_SID = None # server-provided reference number for PV
self.data_type = None # DOUBLE,INT,STRING,...
self.data_count = None # 1 if a scalar, >1 if an array
self.access_bits = None # premissions bit map (bit 0: read, 1: write)
self.IOID = 0 # last used read/write transaction reference number
self.subscription_ID = None # locally assiged reference number for server updates
self.response_time = 0 # timestamp of last reply from server
self.data = None # value in CA representation (big-edian binary data)
self.last_updated = 0 # timestamp of data, time update event received
self.update_events = [] # for synchronization with client threads
self.write_data = None # if put in progres, new value in CA representation
self.write_requested = 0 # time WRITE_NOTIFY command sent
self.write_confirmed = 0 # time WRITE_NOTIFY reply received
self.write_event = None # for synchronization with client threads
PVs = {} # Unique list of active process variables
class connection_info:
"Per CA server (IOC) state information"
socket = None
access_bits = None
connections = {} # list of known CA servers (IOCs)
# Used for IOC disocvery broadcasts
UDP_socket = None
# Protocol version 4.11:
major_version = 4
minor_version = 11
# CA server port = 5056 + major version * 2
# CA repeater port = 5056 + major version * 2 + 1
CA_port_number = 5056 + major_version * 2
# CA Message command codes:
VERSION = 0
EVENT_ADD = 1
WRITE = 4
SEARCH = 6
NOT_FOUND = 14
READ_NOTIFY = 15
WRITE_NOTIFY = 19
CLIENT_NAME = 20
HOST_NAME = 21
CREATE_CHAN = 18
ACCESS_RIGHTS = 22
commands = {
"VERSION": 0,
"EVENT_ADD": 1,
"WRITE": 4,
"SEARCH": 6,
"NOT_FOUND": 14,
"READ_NOTIFY": 15,
"WRITE_NOTIFY": 19,
"CLIENT_NAME": 20,
"HOST_NAME": 21,
"CREATE_CHAN": 18,
"ACCESS_RIGHTS": 22,
}
# CA Message data type codes:
STRING = 0
INT = 1
SHORT = 1
FLOAT = 2
ENUM = 3
CHAR = 4
LONG = 5
DOUBLE = 6
NO_ACCESS = 7
types = {
"STRING": 0,
"INT": 1,
"SHORT": 1,
"FLOAT": 2,
"ENUM": 3,
"CHAR": 4,
"LONG": 5,
"DOUBLE": 6,
"NO_ACCESS": 7,
}
# CA Message monitor mask bits
VALUE = 0x01 # Value change events are reported.
LOG = 0x02 # Log events are reported (different dead band than VALUE)
ALARM = 0x04 # Alarm events are reported
class PV (object):
"""EPICS Process Variable"""
def __init__(self,name):
"""name: PREFIX:Record.Field"""
self.name = name
def get_value(self): return caget(self.name)
def set_value(self,value): caput(self.name,value)
value = property(get_value,set_value)
def get_info(self): return cainfo(self.name,printit=False)
info = property(get_info)
def caget(PV_name):
"Retreive the current value of a process variable"
from time import time
from threading import Event
if not PV_name in PVs: PVs[PV_name] = PV_info()
pv = PVs[PV_name]
# If a PV is not yet connected wait for it to connect for the number
# of seconds specified by the variable timeout.
if not pv.connection_requested: wait = True
elif pv.connection_requested+timeout > time(): wait = True
else: wait = False
if not pv.subscription_ID:
if not pv.connection_requested: pv.connection_requested = time()
request_sockets[0].send("get "+PV_name) # Wake up server thread.
if pv.data == None and wait:
event = Event()
pv.update_events += [event]
event.wait(timeout)
pv.update_events.remove(event)
if pv.data == None: return
return value(pv.data_type,pv.data_count,pv.data)
def caput(PV_name,value,wait=False,timeout=60):
"""Modify the value of a process variable
If wait=True the call returns only after the server has confirmed
that is has finished processing the write request or the timeout
has expired."""
from time import time
from threading import Event
if not PV_name in PVs: PVs[PV_name] = PV_info()
pv = PVs[PV_name]
if not pv.subscription_ID and not pv.connection_requested:
pv.connection_requested = time()
pv.write_data = value
pv.write_requested = time()
pv.write_confirmed = 0
if pv.write_event == None: pv.write_event = Event()
pv.write_event.clear()
request_sockets[0].send("put "+PV_name) # Wake up server thread.
if wait: pv.write_event.wait(timeout)
def camonitor(PV_name,timeout=None):
"""Wait for the server to send an update event for the PV."""
from time import time
from threading import Event
if timeout == None: timeout = globals()["timeout"]
if not PV_name in PVs: PVs[PV_name] = PV_info()
pv = PVs[PV_name]
##if pv.last_updated:
## print "%s changed to %r %.4f s ago" % (PV_name,
## pv.data,time()-pv.last_updated)
if not pv.subscription_ID:
if not pv.connection_requested: pv.connection_requested = time()
request_sockets[0].send("monitor "+PV_name) # Wake up server thread.
# If the PV has changed in the past 70 ms, let it count as 'changed now'.
if pv.last_updated - time() > -0.070: return
event = Event()
pv.update_events += [event]
event.wait(timeout)
pv.update_events.remove(event)
##if pv.last_updated:
## print "%s changed to %r %.4f s ago" % (PV_name,
## pv.data,time()-pv.last_updated)
def connect_PV (PV_name):
"""Establish a connection the the server for the process variable
and request update events"""
from os import environ
from socket import socket,gethostname,error,timeout as socket_timeout
from getpass import getuser
from struct import pack
from time import time
request_time = time()
if not PV_name in PVs: PVs[PV_name] = PV_info()
pv = PVs[PV_name]
if "EPICS_CA_ADDR_LIST" not in environ: addr_list = []
else: addr_list = environ["EPICS_CA_ADDR_LIST"].split()
global UDP_socket
if UDP_socket == None:
from socket import SOCK_DGRAM,SOL_SOCKET,SO_BROADCAST
UDP_socket = socket(type=SOCK_DGRAM)
UDP_socket.setsockopt(SOL_SOCKET,SO_BROADCAST,1)
for addr in addr_list:
for port in range(CA_port_number,CA_port_number+3):
# Establish a TCP/IP connection to a known server if there is
# not one already.
if not (addr,port) in connections:
s = socket()
s.settimeout(timeout)
try: s.connect((addr,port))
except error,msg: debug("%s:%r: %r\n" % (addr,port,msg)); continue
except socket_timeout: debug("%s: timeout\n" % (addr)); continue
debug("Connected to %s:%r\n" % (addr,port))
connections[addr,port] = connection_info()
connections[addr,port].socket = s
send(s,message(VERSION,0,10,minor_version,0,0)) # 10 = priority
send(s,message(CLIENT_NAME,0,0,0,0,0,getuser()))
send(s,message(HOST_NAME,0,0,0,0,0,gethostname()))
process_replies()
if len(addr_list) > 0 and len(connections) == 0: return
if pv.addr == None and not addr_list:
# Use UDP broadcast to find the server.
reply_flag = 5 # Do not reply
if pv.channel_ID == None: pv.channel_ID = new_channel_ID()
request = message(SEARCH,0,reply_flag,minor_version,pv.channel_ID,
pv.channel_ID,PV_name+"\0")
for addr in broadcast_addresses():
sendto(UDP_socket,(addr,CA_port_number),request)
pv.servers_queried += [addr]
process_replies()
while pv.addr == None and time() - request_time < timeout:
process_replies()
if pv.addr == None:
debug("UDP broadcast: %r not found\n" % PV_name); return
if not pv.addr in connections:
addr,cport = pv.addr
s = socket()
s.settimeout(timeout)
try: s.connect((addr,cport))
except error,msg: debug("%s:%r: %r\n" % (addr,cport,msg)); return
except socket_timeout: debug("%s: timeout\n" % (addr)); return
connections[addr,cport] = connection_info()
connections[addr,cport].socket = s
send(s,message(VERSION,0,10,minor_version,0,0)) # 10 = priority
send(s,message(CLIENT_NAME,0,0,0,0,0,getuser()))
send(s,message(HOST_NAME,0,0,0,0,0,gethostname()))
process_replies()
if pv.addr == None and pv.channel_SID == None:
# Use the list of known servers to find the server hosting the PV.
for connection in connections.values():
s = connection.socket
if pv.channel_ID == None: pv.channel_ID = new_channel_ID()
send(s,message(CREATE_CHAN,0,0,0,pv.channel_ID,minor_version,
PV_name+"\0"))
pv.servers_queried += [s.getpeername()[0]]
process_replies()
while (pv.channel_SID == None or pv.addr == None) and \
time() - request_time < timeout:
process_replies()
if pv.channel_SID == None or pv.addr == None:
debug("%r not found in %r\n" % (PV_name,addr_list))
return
if pv.addr and pv.channel_SID == None and pv.addr in connections:
# Directly connect to the server hosting the PV.
s = connections[pv.addr].socket
if pv.channel_ID == None: pv.channel_ID = new_channel_ID()
send(s,message(CREATE_CHAN,0,0,0,pv.channel_ID,minor_version,
PV_name+"\0"))
process_replies()
while pv.channel_SID == None and time() - request_time < timeout:
process_replies()
if pv.channel_SID == None:
debug("request for %r timed out at %r\n" % (PV_name,pv.addr))
return
if pv.subscription_ID == None and pv.addr in connections:
s = connections[pv.addr].socket
pv.subscription_ID = new_subscription_ID()
send(s,message(EVENT_ADD,16,pv.data_type,pv.data_count,pv.channel_SID,
pv.subscription_ID,pack(">fffHxx",0.0,0.0,0.0,VALUE|LOG|ALARM)))
process_replies()
while pv.data == None and time() - request_time < timeout:
process_replies()
if pv.data == None:
debug("Update of %r timed out at %r\n" % (PV_name,pv.addr))
def process_replies(timeout = 0.001):
"""Interpret any packets comming from the IOC waiting in the system's
receive queue.
If timeout > 0 wait for more packets to arrive for the specified number
of seconds."""
import socket
from select import select,error as select_error
from struct import unpack
process_pending_connection_requests()
process_pending_write_requests()
while True:
# Use 'select' to check which sockets have data pending in the input
# queue.
sockets = []
if request_sockets[1]: sockets += [request_sockets[1]]
if UDP_socket: sockets += [UDP_socket]
for connection in connections.values(): sockets += [connection.socket]
try: ready_to_read,x,in_error = select(sockets,[],sockets,timeout)
except select_error: continue # 'Interrupted system call'
# This indicates that main thread has been terminated.
if request_sockets == None: break
if request_sockets[1] in ready_to_read:
# This indicates that a connected to new PV has been requested.
request = request_sockets[1].recv(2048)
debug("Got request: %r\n" % request)
process_pending_connection_requests()
process_pending_write_requests()
if UDP_socket in ready_to_read:
try: messages,addr = UDP_socket.recvfrom(2048)
except socket.error: messages = ""
# Several replies may be concantenated. Break them up.
while len(messages) > 0:
# The minimum message size is 16 bytes. If the 'payload size'
# field has value > 0, the total size if 16+'payload size'.
payload_size, = unpack(">H",messages[2:4])
message = messages[0:16+payload_size]
messages = messages[16+payload_size:]
debug ("Recv upd:%s:%s %s\n" % (addr[0],addr[1],message_info
(message)))
process_message(addr,message)
if UDP_socket in in_error: debug("UDP error\n")
for addr in connections.keys():
connection = connections[addr]
s = connection.socket
if s in in_error:
debug("Lost connection to server %s:%s\n" % addr)
reset_PVs(addr)
del connections[addr]
continue
if s in ready_to_read:
# Several replies may be concatenated. Read one at a time.
# The minimum message size is 16 bytes.
try: message = s.recv(16)
except socket.error:
debug("Recv: lost connection to server %s:%s\n" % addr)
reset_PVs(addr)
del connections[addr]
continue
if len(message) == 0:
debug("Server %s:%s closed connection\n" % addr)
reset_PVs(addr)
del connections[addr]
break
# If the 'payload size' field has value > 0, 'payload size'
# more bytes are part of the message.
payload_size, = unpack(">H",message[2:4])
if payload_size > 0: message += s.recv(payload_size)
debug ("Recv %s:%s %s\n" % (addr[0],addr[1],
message_info(message)))
process_message(addr,message)
process_pending_connection_requests()
process_pending_write_requests()
if len(ready_to_read) == 0 and len(in_error) == 0: break # select timed out
def process_pending_connection_requests():
"""Check list of PVs unconnected PVs and conntect them."""
from time import time
for name in PVs.keys():
pv = PVs[name]
if not pv.connection_requested: continue # nothing to do
if pv.connection_initiated: continue # already in progress...
debug ("Processing connection request for PV %r\n" % name)
pv.connection_initiated = time()
connect_PV(name)
def process_pending_write_requests():
"""Check list of PVs for pending write requests and execute them when possible."""
for name in PVs.keys():
pv = PVs[name]
if pv.write_data == None: continue # nothing to do
if pv.addr == None: continue # need to postpone
if pv.channel_SID == None: continue # need to postpone
if pv.data_type == None: continue # need to postpone
debug("Processing write request for PV %r\n" % name)
s = connections[pv.addr].socket
pv.IOID = pv.IOID + 1
pv.write_confirmed = 0
data = network_data(pv.write_data,pv.data_type)
count = data_count(pv.write_data,pv.data_type)
send(s,message(WRITE_NOTIFY,0,pv.data_type,count,
pv.channel_SID,pv.IOID,data))
pv.write_data = None
def process_message(addr,message):
"Interpret a CA protocol datagram"
from struct import unpack
from time import time
header = message[0:16]
payload = message[16:]
command,payload_size,data_type,data_count,parameter1,parameter2 = \
unpack(">HHHHII",header)
if command == SEARCH: # Reply to a SEARCH request.
debug ("SEARCH ")
port_number = data_type
channel_SID = parameter1 # 'temporary server ID': 0xFFFFFFFF
channel_ID = parameter2
debug ("port_number=%r, " % port_number)
debug ("channel_ID=%r, channel_SID=%r\n" % (channel_ID,channel_SID))
for name in PVs:
if PVs[name].channel_ID == channel_ID:
# Ignore duplicate replies.
if PVs[name].addr != None:
debug ("Ignoring duplicate SEARCH reply for %r from "
"%r:%r\n" % (name,addr[0],addr[1]))
continue
PVs[name].addr = (addr[0],port_number)
debug ("PVs[%r].addr = %r\n" % (name,addr))
PVs[name].response_time = time()
elif command == CREATE_CHAN: # Reply to a 'Create Channel' request.
debug ("CREATE_CHAN ")
channel_ID = parameter1
channel_SID = parameter2
debug ("channel_ID=%r, channel_SID=%r\n" % (channel_ID,channel_SID))
for name in PVs:
if PVs[name].channel_ID == channel_ID:
if PVs[name].channel_SID != None:
debug ("Ignoring duplicate CREATE_CHAN reply for %r from "
"%r:%r\n" % (name,addr[0],addr[1]))
continue
PVs[name].addr = addr
debug ("PVs[%r].addr = %r\n" % (name,addr))
PVs[name].channel_SID = channel_SID
debug ("PVs[%r].channel_SID = %r\n" % (name,channel_SID))
PVs[name].data_type = data_type
debug ("PVs[%r].data_type = %r\n" % (name,data_type))
PVs[name].data_count = data_count
debug ("PVs[%r].data_count = %r\n" % (name,data_count))
PVs[name].response_time = time()
elif command == ACCESS_RIGHTS:
# Reply to the CLIENT_NAME/HOST_NAME greeting.
debug ("ACCESS_RIGHTS ")
channel_ID = parameter1
access_bits = parameter2
debug ("channel_ID %r, %s\n" % (channel_ID,access_bits))
for name in PVs:
if PVs[name].channel_ID == channel_ID:
PVs[name].access_bits = access_bits
debug ("PVs[%r].access_bits = %r\n" % (name,access_bits))
PVs[name].response_time = time()
elif command == READ_NOTIFY:
# Reply to a synchronous read request (never used).
debug ("READ_NOTIFY ")
# Channel Access Protocol Specification, section 6.15.2, says:
# parameter 1: channel_SID, parameter 2: IOID
# However, I always get: parameter 1 = 1, parameter 2 = 1.
channel_SID = parameter1
IOID = parameter2
debug ("channel_SID=%r, IOID=%r, " % (channel_SID,IOID))
val = value(data_type,data_count,payload)
debug ("value=%r\n" % val)
for name in PVs:
if PVs[name].channel_SID == channel_SID:
debug ("PVs[%r].data = %r\n" % (name,payload))
PVs[name].data = payload
PVs[name].data_type = data_type
PVs[name].data_count = data_count
PVs[name].response_time = time()
elif command == EVENT_ADD: # Asynchronous notification that PV changed.
debug ("EVENT_ADD ")
status_code = parameter1
subscription_ID = parameter2
debug ("status_code=%r, subscription_ID=%r, " % (status_code,subscription_ID))
val = value(data_type,data_count,payload)
debug ("value=%r\n" % val)
for name in PVs:
if PVs[name].subscription_ID == subscription_ID and \
PVs[name].addr == addr:
PVs[name].data_type = data_type
PVs[name].data_count = data_count
debug ("PVs[%r].data = %r\n" % (name,payload))
t = time()
if PVs[name].data != None: PVs[name].last_updated = t
PVs[name].data = payload
PVs[name].response_time = t
# Notify client threads waiting for this PV to update.
for event in PVs[name].update_events: event.set()
elif command == WRITE_NOTIFY: # Confirmation of a sucessful write.
debug ("WRITE_NOTIFY ")
status = parameter1
IOID = parameter2
debug ("status_code=%r, IOID=%r\n" % (status,IOID))
for name in PVs:
if PVs[name].IOID == IOID and \
PVs[name].addr == addr:
t = time()
debug ("PVs[%r].write_confirmed = %r\n" % (name,t))
PVs[name].write_confirmed = t
PVs[name].response_time = t
# Notfiy client threads waiting for a put operation to complete.
if PVs[name].write_event: PVs[name].write_event.set()
elif command == NOT_FOUND:
channel_ID = parameter1
PV_name = "unknown"
for name in PVs:
if PVs[name].channel_ID == channel_ID: PV_name = name
debug ("NOT_FOUND: %r\n" % PV_name)
else: debug ("%r: unknown command code\n" % command)
def new_channel_ID():
"""Return a unique integer to be used as 'Channel ID' for a PV.
A Channel ID is a client-provided integer number, which the CA server (IOC)
includes as reference when replying to 'create channel' requests."""
IDs = [pv.channel_ID for pv in PVs.values()]
ID = 1
while ID in IDs: ID += 1
return ID
def new_subscription_ID():
"""Return a unique integer to be used as 'Subscription ID' for a PV.
A subscription ID is a client-provided integer number, which the CA server
(IOC) includes as reference number when sending update events."""
IDs = [pv.subscription_ID for pv in PVs.values()]
ID = 1
while ID in IDs: ID += 1
return ID
def reset_PVs(addr):
"""If the connection to the server 'addr' is lost, clear outdate PV state
info."""
for name in PVs: PVs[name] = PV_info()
def message(command=0,payload_size=0,data_type=0,data_count=0,
parameter1=0,parameter2=0,payload=""):
"""Assemble a Channel Access message datagram for network transmission"""
assert data_type is not None
assert data_count is not None
assert parameter1 is not None
assert parameter2 is not None
from math import ceil
from struct import pack
if payload_size == 0 and len(payload) > 0:
# Pad to multiple of 8.
payload_size = int(ceil(len(payload)/8.)*8)
while len(payload) < payload_size: payload += "\0"
# 16-byte header consisting of four 16-bit integers
# and two 32-bit integers in big-edian byte order.
header = pack(">HHHHII",command,payload_size,data_type,data_count,
parameter1,parameter2)
message = header + payload
return message
def message_info(message):
"Text representation of the CA message datagram"
from struct import unpack
header = message[0:16]
payload = message[16:]
command,payload_size,data_type,data_count,parameter1,parameter2 = \
unpack(">HHHHII",header)
s = str(command)
if command in commands.values():
s += "("+commands.keys()[commands.values().index(command)]+")"
s += ","+str(payload_size)
s += ","+str(data_type)
if data_type in types.values():
s += "("+types.keys()[types.values().index(data_type)]+")"
s += ","+str(data_count)
s += ", %r, %r" % (parameter1,parameter2)
if payload:
s += ", %r" % payload
if command in (EVENT_ADD,WRITE,READ_NOTIFY,WRITE_NOTIFY):
s += "(%r)" % value(data_type,data_count,payload)
return s
def send(socket,message):
"Transmit a Channel Access message to an IOC via TCP"
from socket import error as socket_error
addr,port = socket.getpeername()
debug ("Send %s:%s %s\n" % (addr,port,message_info(message)))
try: socket.sendall(message)
except socket_error,error: debug ("Send failed: %r\n" % error)
def sendto(socket,addr,message):
"Transmit a Channel Access message to an IOC via UDP"
debug ("Send UDP %s:%s %s\n" % (addr[0],addr[1],message_info(message)))
socket.sendto(message,addr)
def value(data_type,data_count,payload):
"Convert received network binary data to a Python data type"
if payload == None: return None
from struct import unpack
if data_type == STRING:
# Null-terminated string.
# data_count is the number of null-terminated strings (characters)
value = payload.split("\0")[0:data_count]
if len(value) == 1: value = value[0]
elif data_type == SHORT:
value = unpack(">%dH"%data_count,payload[0:2*data_count])
if len(value) == 1: value = value[0]
elif data_type == FLOAT:
value = unpack(">%df"%data_count,payload[0:4*data_count])
if len(value) == 1: value = value[0]
elif data_type == ENUM:
value = unpack(">%dH"%data_count,payload[0:2*data_count])
if len(value) == 1: value = value[0]
elif data_type == CHAR: value = payload[0:data_count]
elif data_type == LONG:
value = unpack(">%dI"%data_count,payload[0:4*data_count])
if len(value) == 1: value = value[0]
elif data_type == DOUBLE:
value = unpack(">%dd"%data_count,payload[0:8*data_count])
if len(value) == 1: value = value[0]
elif data_type == None: value = payload
else:
debug ("unsupported data type %r\n" % data_type)
value = payload
return value
def data_count(value,data_type):
"""If value is an array return the number of elements, else return 1.
In CA, a string counts as a single element."""
# If the data type is STRING the data count is the number of NULL-
# terminated strings, if the data type if CHAR the data count is the
# number is characters in the string, including any NULL characters
# inside and at the end.
if issubclass(type(value),basestring) and data_type != CHAR: return 1
if hasattr(value,"__len__"): return len(value)
return 1
def network_data(value,data_type):
"Convert a Python data type to binary data for network transmission"
from struct import pack
payload = ""
if data_type == STRING:
payload = str(value)
# EPICS requires that strings are NULL-terminated.
if not payload.endswith("\0"): payload += "\0"
elif data_type == SHORT:
if hasattr(value,"__len__"):
for v in value: payload += pack(">H",v)
else: payload = pack(">H",value)
elif data_type == FLOAT:
if hasattr(value,"__len__"):
for v in value: payload += pack(">f",v)
else: payload = pack(">f",value)
elif data_type == ENUM:
if hasattr(value,"__len__"):
for v in value: payload += pack(">H",v)
else: payload = pack(">H",value)
elif data_type == CHAR: payload = str(value)
elif data_type == LONG:
if hasattr(value,"__len__"):
for v in value: payload += pack(">I",v)
else: payload = pack(">I",value)
elif data_type == DOUBLE:
if hasattr(value,"__len__"):
for v in value: payload += pack(">d",v)
else: payload = pack(">d",value)
else:
debug ("network_data: unsupported data type %r\n" % data_type)
payload = str(value)
return payload
def broadcast_addresses():
"A list if IP adresses to use for name resolution broadcasts"
from os import environ
if "EPICS_CA_AUTO_ADDR_LIST" in environ and \
environ["EPICS_CA_AUTO_ADDR_LIST"] == "NO": return []
# You can override the automatic selection of broadcast
# addresses by setting the variable 'broadcast_address'.
if "broadcast_address" in globals() and broadcast_address:
return [broadcast_address]
from socket import inet_aton,inet_ntoa,error
from struct import pack,unpack
addresses = []
for address in network_interfaces():
try: num_address = inet_aton(address)
except: continue # E.g. IPv6 address
if not address in addresses: addresses += [address]
ipaddr, = unpack(">I",num_address)
ipaddr |= 0x000000FF
address = inet_ntoa(pack(">I",ipaddr))
if not address in addresses: addresses += [address]
return addresses
def network_interfaces():
"""A list of IP adresses of the local network interfaces,
as strings in numerical dot notation"""
from socket import getaddrinfo,gethostname
addresses = [local_ip_address()]
for addrinfo in getaddrinfo(None,0)+getaddrinfo(gethostname(),0):
address = addrinfo[4][0]
if not address in addresses: addresses += [address]
return addresses
def local_ip_address():
"IP address of the local network interface as string in dot notation"
# Unfortunately, Python has no platform-indepdent function to find
# the IP address of the local machine.
# As a work-around let us pretend we want to send a UDP datagram to a
# non existing external IP address.
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect(("172.16.58.3",1024))
# This code does not geneate any network traffic, because UDP is not
# a connection-orientation protocol.
# Now, Python can tell us what would be thet "source address" of the packets
# if we would sent a packet (but we won't actally sent a packet).
address,port = s.getsockname()
return address
def cainfo(PV_name="all",printit=True):
"Print status info string"
from socket import gethostbyaddr,herror
from datetime import datetime
from time import time
if PV_name == "all":
for name in PVs: cainfo(name)
return
caget(PV_name)
s = PV_name+"\n"
if PV_name in PVs: pv = PVs[PV_name]
else: pv = PV_info()
fmt = " %-14s %.60s\n"
if pv.channel_SID: val = "connected"
else: val = "not connected"
if pv.subscription_ID: val += ", receiving notifications"
if pv.connection_requested and not pv.subscription_ID:
val += ", pending for %.0f s" % (time() - pv.connection_requested)
s += fmt % ("State:",val)
if pv.addr:
val = pv.addr[0]
# Try to translate numeric IP address to host name.
try: val = gethostbyaddr(val)[0]
except herror: pass
val += ":%s" % pv.addr[1]
else: val = "N/A"
s += fmt % ("Host:",val)
if pv.access_bits != None:
val = ""
if pv.access_bits & 1: val += "read/"
if pv.access_bits & 2: val += "write/"
val = val.strip("/")
if val == "": val = "none"
else: val = "N/A"
s += fmt % ("Access:",val)
if pv.data_type != None:
val = repr(pv.data_type)
for t in types:
if types[t] == pv.data_type: val = t
else: val = "N/A"
s += fmt % ("Data type:",val)
if pv.data_count != None: val = str(pv.data_count)
else: val = "N/A"
s += fmt % ("Element count:",val)
if pv.data != None: val = repr(value(pv.data_type,pv.data_count,pv.data))
else: val = "N/A"
s += fmt % ("Value:",val)
if pv.last_updated != 0:
t = pv.last_updated
val = "%s (%s)" % (t,datetime.fromtimestamp(t))
s += fmt % ("Last changed:",val)
if pv.response_time != 0:
t = pv.response_time
val = "%s (%s)" % (t,datetime.fromtimestamp(t))
s += fmt % ("Time stamp:",val)
if printit: print s
else: return s
def PV_status():
"print status info"
for name in PVs:
s = "%s: " % name
pv = PVs[name]
for attr in dir(pv):
if not "__" in attr: s += "%s = %r, " % (attr,getattr(pv,attr))
s = s.strip(", ")
print s
def debug(message):
"Print diagnsotics message, if DEBUG is set to True."
global debug_t0, debug_last, debug_messages
if not DEBUG: return
from time import time
if not "debug_t0" in globals(): debug_t0 = time()
if not "debug_last" in globals() or debug_last.endswith("\n"):
message = ("%.3f " % (time() - debug_t0)) + message
debug_last = message
if DEBUG == "silent":
if not "debug_messages" in globals(): debug_messages = ""
debug_messages += message
else:
from sys import stderr
stderr.write(message)
debug_messages = ""
def socketpair(family=socket.AF_INET,type=socket.SOCK_STREAM,proto=0):
"""Create a pair of connected socket objects using TCP/IP protocol.
This is a replacement for the socket library's 'socketpair' function,
which is not portalbe to Windows.
"""
from socket import socket,error
global listen_socket
listen_socket = socket(family,type,proto)
port = 1024
while port < 16535:
try: listen_socket.bind(("127.0.0.1",port)); break
except error: port += 1
listen_socket.listen(1)
s1 = socket(family,type,proto)
s1.connect(("127.0.0.1",port))
s2,addr = listen_socket.accept()
return s1,s2
# Used to wake up the CA background (server) thread
request_sockets = socketpair()
def background_thread():
"""Server thread.
Handle CA network communication in background."""
while True:
process_replies(1)
##except Exception,message: print message
from thread import start_new_thread
background_thread_id = start_new_thread (background_thread,())
if __name__ == "__main__": # for testing
from time import sleep
from os import environ
print('DEBUG = "verbose"')
print('environ["EPICS_CA_ADDR_LIST"] = "172.16.58.3"')
print('caget("NIH:TEMP.VAL")')
<file_sep>#!/usr/bin/env python
"""Control panel for Lecroy Oscilloscope
Author: <NAME>
Date created: 2018-10-26
Date last modified: 2018-03-22
"""
__version__ = "1.6" # auto_acquire
from logging import debug,info,warn,error
import wx
from instrumentation import * # passed on in "globals()"
class Scope_Panel(wx.Frame):
"""Control panel for Lecroy Oscilloscope"""
name = "Scope_Panel"
icon = "Tool"
def __init__(self,parent=None,scope_name="xray_scope"):
wx.Frame.__init__(self,parent=parent)
self.scope_name = scope_name
self.update()
self.Show()
# Refresh
self.timer = wx.Timer(self)
self.Bind (wx.EVT_TIMER,self.OnTimer,self.timer)
self.timer.Start(5000,oneShot=True)
@property
def scope(self):
scope = eval(self.scope_name)
return scope
@property
def title(self):
title = self.scope_name
title = title.replace("xray","X-Ray")
title = title.replace("_"," ")
title = title.title()
return title
def update(self):
self.Title = self.title
from Icon import SetIcon
SetIcon(self,self.icon)
panel = self.ControlPanel
if hasattr(self,"panel"): self.panel.Destroy()
self.panel = panel
self.Fit()
def OnTimer(self,event):
"""Perform periodic updates"""
try: self.update_controls()
except Exception,msg:
error("%s" % msg)
import traceback
traceback.print_exc()
self.timer.Start(5000,oneShot=True)
def update_controls(self):
if self.code_outdated:
self.update_code()
self.update()
@property
def code_outdated(self):
if not hasattr(self,"timestamp"): self.timestamp = self.module_timestamp
outdated = self.module_timestamp != self.timestamp
return outdated
@property
def module_timestamp(self):
from inspect import getfile
from os.path import getmtime,basename
filename = getfile(self.__class__).replace(".pyc",".py")
##debug("module: %s" % basename(filename))
timestamp = getmtime(filename)
return timestamp
def update_code(self):
from inspect import getfile
from os.path import getmtime,basename
filename = getfile(self.__class__).replace(".pyc",".py")
##debug("module: %s" % basename(filename))
module_name = basename(filename).replace(".pyc",".py").replace(".py","")
module = __import__(module_name)
reload(module)
self.timestamp = self.module_timestamp
debug("Reloaded module %r" % module.__name__)
debug("Updating class of %r instance" % self.__class__.__name__)
self.__class__ = getattr(module,self.__class__.__name__)
@property
def ControlPanel(self):
# Controls and Layout
panel = wx.Panel(self)
from EditableControls import ComboBox,TextCtrl,Choice
from Controls import Control
from BeamProfile_window import BeamProfile
flag = wx.ALIGN_CENTRE_HORIZONTAL|wx.ALL
border = 2
l = wx.ALIGN_LEFT; r = wx.ALIGN_RIGHT; cv = wx.ALIGN_CENTER_VERTICAL
a = wx.ALL; e = wx.EXPAND; c = wx.ALIGN_CENTER
frame = wx.BoxSizer()
panel.SetSizer(frame)
layout = wx.BoxSizer(wx.VERTICAL)
frame.Add(layout,flag=e|a,border=10,proportion=1)
layout_flag = wx.ALIGN_CENTRE|wx.ALL
border = 0
width,height = 220,25
control = Control(panel,type=wx.ComboBox,
globals=globals(),
locals=locals(),
name=self.name+".setup",
size=(width,height),
style=wx.ALIGN_CENTER_HORIZONTAL,
)
layout.Add(control,flag=layout_flag,border=border)
control = Control(panel,type=wx.ToggleButton,
globals=globals(),
locals=locals(),
name=self.name+".recall",
label="Recall",
size=(width,height),
)
layout.Add(control,flag=layout_flag,border=border)
control = Control(panel,type=wx.ToggleButton,
globals=globals(),
locals=locals(),
name=self.name+".save",
label="Save",
size=(width,height),
)
layout.Add(control,flag=layout_flag,border=border)
control = Control(panel,type=wx.StaticText,
globals=globals(),
locals=locals(),
name=self.name+".trace_directory_size",
size=(width,height),
style=wx.ALIGN_CENTER_HORIZONTAL,
)
layout.Add(control,flag=layout_flag,border=border)
control = Control(panel,type=wx.ToggleButton,
globals=globals(),
locals=locals(),
name=self.name+".emptying_trace_directory",
size=(width,height),
)
layout.Add(control,flag=layout_flag,border=border)
control = Control(panel,type=wx.ToggleButton,
globals=globals(),
locals=locals(),
name=self.name+".acquiring_waveforms",
label="Auto Save",
size=(width,height),
)
layout.Add(control,flag=layout_flag,border=border)
control = Control(panel,type=wx.CheckBox,
globals=globals(),
locals=locals(),
name=self.name+".auto_acquire",
label="Auto Record Traces",
size=(width,height),
style=wx.ALIGN_CENTER_HORIZONTAL,
)
layout.Add(control,flag=layout_flag,border=border)
control = Control(panel,type=wx.StaticText,
globals=globals(),
locals=locals(),
name=self.name+".trace_count",
size=(width,height),
style=wx.ALIGN_CENTER_HORIZONTAL,
)
layout.Add(control,flag=layout_flag,border=border)
control = Control(panel,type=wx.StaticText,
globals=globals(),
locals=locals(),
name=self.name+".trigger_count",
size=(width,height),
style=wx.ALIGN_CENTER_HORIZONTAL,
)
layout.Add(control,flag=layout_flag,border=border)
control = Control(panel,type=wx.StaticText,
globals=globals(),
locals=locals(),
name=self.name+".trace_count_offset",
size=(width,height),
style=wx.ALIGN_CENTER_HORIZONTAL,
)
layout.Add(control,flag=layout_flag,border=border)
control = Control(panel,type=wx.StaticText,
globals=globals(),
locals=locals(),
name=self.name+".timing_jitter",
size=(width,height),
style=wx.ALIGN_CENTER_HORIZONTAL,
)
layout.Add(control,flag=layout_flag,border=border)
control = Control(panel,type=wx.StaticText,
globals=globals(),
locals=locals(),
name=self.name+".timing_offset",
size=(width,height),
style=wx.ALIGN_CENTER_HORIZONTAL,
)
layout.Add(control,flag=layout_flag,border=border)
control = Control(panel,type=wx.ToggleButton,
globals=globals(),
locals=locals(),
name=self.name+".trace_count_synchronized",
label="Synchronized",
size=(width,height),
)
layout.Add(control,flag=layout_flag,border=border)
control = Control(panel,type=wx.CheckBox,
globals=globals(),
locals=locals(),
name=self.name+".auto_synchronize",
label="Auto Synchronize",
size=(width,height),
style=wx.ALIGN_CENTER_HORIZONTAL,
)
layout.Add(control,flag=layout_flag,border=border)
control = Control(panel,type=wx.ToggleButton,
globals=globals(),
locals=locals(),
name=self.name+".trace_acquisition_running",
label="Data Collection Running",
size=(width,height),
)
layout.Add(control,flag=layout_flag,border=border)
panel.Fit()
return panel
if __name__ == '__main__':
from pdb import pm
import logging; from tempfile import gettempdir
logfile = gettempdir()+"/Scope_Panel.log"
logging.basicConfig(level=logging.DEBUG,
format="%(asctime)s %(levelname)s %(module)s.%(funcName)s, line %(lineno)d: %(message)s",
filename=logfile,
)
from sys import argv
scope_name = "xray_scope"
##scope_name = "laser_scope"
if len(argv) >= 2: scope_name = argv[1]
import autoreload
# Needed to initialize WX library
wx.app = wx.App(redirect=False)
panel = Scope_Panel(scope_name=scope_name)
wx.app.MainLoop()
<file_sep>#!/bin/env python
from __future__ import with_statement
"""
<NAME>, 31 Jan 2016 - 31 Oct 2017
"""
from pdb import pm # for debugging
from logging import debug,warn,error
__version__ = "1.0.4" # "if value == "": ..." FutureWarning: elementwise comparison failed
verbose_logging = True
class EnsembleClient(object):
""""""
__attributes__ = [
"ip_address_and_port",
"caching_enabled",
"connection",
"integer_registers_","floating_point_registers_",
"integer_registers","floating_point_registers",
"ip_address","port",
"write","send","query",
]
name="Ensemble"
from persistent_property import persistent_property
ip_address_and_port = persistent_property("ip_address",
"nih-instrumentation.cars.aps.anl.gov:2000")
caching_enabled = persistent_property("caching_enabled",True)
timeout = 5.0
# This is to make the query method multi-thread safe.
from thread import allocate_lock
lock = allocate_lock()
def __init__(self):
"""ip_address may be given as address:port. If :port is omitted, port
number 2000 is assumed."""
self.connection = None # network connection
self.integer_registers_ = ArrayWrapper(self,"integer_registers")
self.floating_point_registers_ = ArrayWrapper(self,"floating_point_registers")
self.integer_registers = CachedArrayWrapper(self,"integer_registers")
self.floating_point_registers = CachedArrayWrapper(self,"floating_point_registers")
def __repr__(self):
return "EnsembleClient('"+self.ip_address+":"+str(self.port)+"')"
def get_ip_address(self):
return self.ip_address_and_port.split(":")[0]
def set_ip_address(self,value):
self.ip_address_and_port = value+":"+str(self.port)
ip_address = property(get_ip_address,set_ip_address)
def get_port(self):
if not ":" in self.ip_address_and_port: return 2000
return int(self.ip_address_and_port.split(":")[-1])
def set_port(self,value):
self.ip_address_and_port = str(self.ip_address)+":"+str(value)
port = property(get_port,set_port)
def write(self,command):
"""Sends a command to the server that does not generate a reply,
e.g. "ClearSweeps.ActNow()" """
debug("write %s" % torepr(command))
import socket
command = command.replace("\n","") # "\n" is command terminator.
if not command.endswith("\n"): command += "\n"
with self.lock: # Allow only one thread at a time inside this function.
for attempt in range(1,2):
try:
if self.connection == None:
self.connection = socket.socket()
self.connection.settimeout(self.timeout)
self.connection.connect((self.ip_address,self.port))
# Flush reception buffer before sending.
self.connection.settimeout(1e-6)
try: junk = self.connection.recv(65536)
except socket.timeout: pass
self.connection.settimeout(self.timeout)
self.connection.sendall (command)
return
except Exception,message:
error("write %s attempt %d/3 failed: %s" %
(torepr(command),attempt,message))
self.connection = None
send = write
def query(self,command):
"""To send a command that generates a reply, e.g. "InstrumentID.Value".
Returns the reply"""
debug("query %s" % torepr(command))
import socket
command = command.replace("\n","") # "\n" is command terminator.
if not command.endswith("\n"): command += "\n"
reply = ""
with self.lock: # Allow only one thread at a time inside this function.
for attempt in range(1,2):
try:
if self.connection == None:
self.connection = socket.socket()
self.connection.settimeout(self.timeout)
self.connection.connect((self.ip_address,self.port))
# Flush reception buffer before sending.
self.connection.settimeout(1e-6)
try: junk = self.connection.recv(65536)
except socket.timeout: pass
self.connection.settimeout(self.timeout)
self.connection.sendall (command)
reply = self.connection.recv(65536)
while reply.find("\n") == -1:
reply += self.connection.recv(65536)
debug("reply %s" % torepr(reply))
return reply.rstrip("\n")
except Exception,message:
error("query %s attempt %d/3 failed: %s "
"(reply=%s, %r bytes)" %
(torepr(command),attempt,message,torepr(reply),len(reply)))
self.connection = None
return ""
def __getattr__(self,name):
"""A property"""
# Called when 'x.name' is evaluated.
# It is only invoked if the attribute wasn't found the usual ways.
if name.startswith("__") and name.endswith("__"):
return object.__getattribute__(self,name)
##debug("EnsembleWrapper.__getattr__(%r)" % name)
value = self.query("ensemble."+name)
##debug("Got reply %s" % torepr(value))
if "ArrayWrapper(" in value:
value = value.replace("ArrayWrapper(","").replace(")","")
from numpy import array,nan,int32,float32,float64 # for eval
try: value = eval(value)
except: pass
return value
def __setattr__(self,name,value):
"""Set a property"""
# Called when 'x.name = y' is evaluated.
alt_name = name.replace("_on",".on")
if (name.startswith("__") and name.endswith("__")) or \
name in self.__attributes__:
object.__setattr__(self,name,value)
else: self.write("ensemble.%s = %r" % (name,value))
class ArrayWrapper(object):
def __init__(self,object,name):
self.object = object
self.name = name
def __getitem__(self,index):
"""Called when [0] is used.
index: integer or list/array of intergers or array of booleans"""
##debug("ArrayWrapper.__getitem__(%r)" % (index,))
command = ("ensemble.%s[%r]" % (self.name,index))
value = self.object.query(command)
if "ArrayWrapper(" in value:
value = value.replace("ArrayWrapper(","").replace(")","")
from numpy import array,nan,int32,float32,float64 # for eval
try: value = eval(value)
except Exception,msg:
debug("%s: %s" % (torepr(value),msg))
self.last_reply = value # for debugging
value = self.default_value(index)
if type(value) == str and value == "":
value = self.default_value(index)
debug("Ensemble: Value: %s" % torepr(value))
return value
def __setitem__(self,index,value):
"""Called when [0]= is used.
index: single index, slice or list of indices
value: single value or array of values"""
##debug("ArrayWrapper.__setitem__(%r,%r)" % (index,value))
command = ("ensemble.%s[%r] = %r" % (self.name,index,value))
self.object.send(command)
def __len__(self):
"""Length of array. Called when len(x) is used."""
command = ("len(ensemble.%s)" % (self.name))
value = self.object.query(command)
try: value = eval(value)
except Exception,msg:
debug("%s: %s" % (torepr(value),msg))
value = 0
return value
def default_value(self,index):
"""Return this when a comminocation error occurs"""
from numpy import array,nan
if type(index) != slice and not hasattr(index,"__len__"): return nan
return array([nan]*len(tolist(index)))
class CachedArrayWrapper(ArrayWrapper):
def __init__(self,object,name):
ArrayWrapper.__init__(self,object,name)
self.cache = {}
def __getitem__(self,index):
"""Called when [0] is used.
index: integer or list/array of intergers or array of booleans"""
##debug("CachedArrayWrapper.__getitem__(%r)" % (index,))
from numpy import array
items = tolist(index,len(self))
cache = dict(self.cache)
if self.caching_enabled:
items_to_get = [i for i in items if not i in cache]
else: items_to_get = items
if len(items_to_get) > 0:
new_values = ArrayWrapper.__getitem__(self,items_to_get)
for (i,v) in zip(items_to_get,new_values): cache[i]=v
values = array([cache[i] for i in items])
if isscalar(index): values = values[0]
return values
def __len__(self):
"""Length of array. Called when len(x) is used."""
if not "__len__" in self.cache or not self.caching_enabled:
self.cache["__len__"] = ArrayWrapper.__len__(self)
return self.cache["__len__"]
def __setitem__(self,index,value):
"""Called when [0]= is used.
index: single index, slice or list of indices
value: single value or array of values"""
##debug("CachedArrayWrapper.__setitem__(%r,%r)" % (index,value))
from numpy import atleast_1d
ArrayWrapper.__setitem__(self,index,value)
items = tolist(index,len(self))
values = atleast_1d(value)
for (i,v) in zip(items,values): self.cache[i]=v
def get_caching_enabled(self): return self.object.caching_enabled
def set_caching_enabled(self,value): self.object.caching_enabled = value
caching_enabled = property(get_caching_enabled,set_caching_enabled)
def timestamp():
"""Current date and time as formatted ASCII text, precise to 1 ms"""
from datetime import datetime
timestamp = str(datetime.now())
return timestamp[:-3] # omit microsconds
def torepr(x,nchars=80):
"""limit string length using ellipses (...)"""
s = repr(x)
if len(s) > nchars: s = s[0:nchars-10-3]+"..."+s[-10:]
return s
def tolist(index,length=1000):
"""Convert index (which may be a slice) to a list"""
from numpy import atleast_1d,arange
index_list = atleast_1d(arange(0,length)[index])
##debug("tolist: converted %s to %s" % (torepr(index),torepr(index_list)))
return index_list
def isscalar(x):
if hasattr(x,"__len__") or type(x) == slice: return False
return True
ensemble = EnsembleClient()
if __name__ == "__main__": # for testing
import logging
from tempfile import gettempdir
logfile = gettempdir()+"/lauecollect_debug.log"
logging.basicConfig(level=logging.DEBUG,format="%(asctime)s: %(message)s")
from pdb import pm # for debugging
self = ensemble # for debugging
print('ensemble.ip_address = %r' % ensemble.ip_address)
print('ensemble.caching_enabled = %r' % ensemble.caching_enabled)
print('ensemble.program_filename = "Home (safe).ab"')
print('ensemble.program_filename = "PVT_Fly-thru.ab"')
print('ensemble.program_filename')
print('ensemble.program_running')
print('ensemble.floating_point_registers[0]')
print('ensemble.floating_point_registers[0] = -1')
| 99249dad36df26a712ae8d900041d53acf3901ea | [
"INI",
"Python",
"Text",
"Shell"
] | 473 | Python | bopopescu/Lauecollect | 60ae2b05ea8596ba0decf426e37aeaca0bc8b6be | f1f79c2cc5ff106df0dedbd6939ec92630d2b305 |
refs/heads/main | <file_sep>from flask import request
#To convert the Task class as a resource we import from flask_restful Resource
from flask_restful import Resource
from flask import jsonify
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="root",
password="123",
database="ToDo"
)
mycursor = mydb.cursor()
#This means that TAsk class is inherited from a Resource class so that Task class acts as a Resource
class TaskByID(Resource):
#get,post,put and delete are http methods
def get(self,taskId):
mycursor.execute("SELECT text, status FROM Tasks where id=2")
myresult = mycursor.fetchall()
for x in myresult:
print(x)
#pass statement is not ignored by the interpreter, but does nothing, useful when you haveto implement the function in future.
return {"message": "inside get method of task by id. TAsk-id-{}".format(taskId)},200
def post(self,taskId):
# pass statement is not ignored by the interpreter, but does nothing, useful when you haveto implement the function in future.
return {"message": "inside post method"}, 200
def put(self,taskId):
_json = request.get_json()
_text = _json['text']
_status = _json['status']
sql = 'UPDATE Tasks SET text = %s,status = %s Where id=2'
val = (_text, _status)
mycursor.execute(sql, val)
mydb.commit()
return jsonify({"text": _text, "status": _status})
# pass statement is not ignored by the interpreter, but does nothing, useful when you haveto implement the function in future.
return {"message": "inside put method"}, 200
def delete(self,taskId):
sql = "DELETE FROM Tasks WHERE id = '1'"
mycursor.execute(sql)
mydb.commit()
print(mycursor.rowcount, "record(s) deleted")
# pass statement is not ignored by the interpreter, but does nothing, useful when you haveto implement the function in future.
return {"message": "inside delete method"}, 200<file_sep>from flask import Flask,render_template
app = Flask(__name__)
if __name__ == '__main__':
# Make flask instance run on default port:5000 and host:127.0.0.1
from api import *
app.run(debug=True)
<file_sep>import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="root",
password="123",
database="ToDo"
)
mycursor = mydb.cursor()
#create a new to-do
# sql = "INSERT INTO Tasks (text,status) VALUES (%s, %s)"
# val = ("second to do ", "Incomplete")
# mycursor.execute(sql, val)
#
# mydb.commit()
#
# print(mycursor.rowcount, "to do inserted.")
#update a to-do
# sql = "UPDATE Tasks SET status = 'Complete' WHERE id = '2'"
#
# mycursor.execute(sql)
#
# mydb.commit()
#deleting a to-do
# sql = "DELETE FROM Tasks WHERE id = '1'"
#
# mycursor.execute(sql)
#
# mydb.commit()
#
# print(mycursor.rowcount, "record(s) deleted")
#read a to do
mycursor.execute("SELECT text, status FROM Tasks")
myresult = mycursor.fetchall()
for x in myresult:
print(x)<file_sep>from flask import request
#To convert the Task class as a resource we import from flask_restful Resource
from flask_restful import Resource
#new code
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="root",
password="123",
database="ToDo"
)
mycursor = mydb.cursor()
#This means that TAsk class is inherited from a Resource class so that Task class acts as a Resource
class Task(Resource):
#get,post,put and delete are http methods
def get(self):
mycursor.execute("SELECT text, status FROM Tasks")
myresult = mycursor.fetchall()
for x in myresult:
print(x)
#pass statement is not ignored by the interpreter, but does nothing, useful when you haveto implement the function in future.
print ("inside get method")
return {"message": "inside get method"},200
def post(self):
_json = request.get_json()
_text = _json['text']
_status = _json['status']
sql = ' INSERT INTO Tasks (text,status) VALUES (%s, %s)'
val = (_text, _status)
mycursor.execute(sql, val)
mydb.commit()
# pass statement is not ignored by the interpreter, but does nothing, useful when you haveto implement the function in future.
return {"message": "inside post method"}, 200
def put(self):
# pass statement is not ignored by the interpreter, but does nothing, useful when you haveto implement the function in future.
return {"message": "inside put method"}, 200
def delete(self):
# pass statement is not ignored by the interpreter, but does nothing, useful when you haveto implement the function in future.
return {"message": "inside delete method"}, 200<file_sep>#This Api class from flask_restful module will create a new server.
from flask_restful import Api
#the app=flask(__name__) that is the flask instance created, we importit here .
from app import app
#We import from Task file the Task class
from .Task import Task
from .TaskByID import TaskByID
#Then we create the rest server using the flask_restful module
#And we pass Flasj instance that is app in it.
restServer=Api(app)
#we will add a resource TAsk and give a URl mapped to the resource
restServer.add_resource(Task,"/api/project/task")
restServer.add_resource(TaskByID,"/api/project/task/id/<int:taskId>")
| f43ec12e611f7c49854671bda152886ee4c5d203 | [
"Python"
] | 5 | Python | Zeenat-Hassan/flask-Api | e3d1657fc0c44c97006b3e09b892e7956c703567 | 7b1d2042ae3b3ec59c680ac8422edc3f8f5e5ed6 |
refs/heads/master | <repo_name>yinnie/faceBank<file_sep>/extractFace/extractFaceMesh/src/testApp.cpp
#include "testApp.h"
using namespace ofxCv;
void testApp::setup() {
ofSetVerticalSync(true);
ofSetDrawBitmapMode(OF_BITMAPMODE_MODEL_BILLBOARD);
cam.listDevices();
cam.setDeviceID(6);
cam.initGrabber(640, 480);
ofEnableAlphaBlending();
camTracker.setup();
posX=ofGetWindowWidth()/2;
posY=ofGetWindowHeight()/2;
imageCounter =2;
substitute= false;
savedTime =0;
//face tracker on source
srcTracker.setup();
srcTracker.setRescale(.5);
srcTracker.setup();
srcTracker.setIterations(25);
srcTracker.setAttempts(2);
srcTracker.setClamp(4);
srcTracker.setTolerance(.01);
img1.loadImage(ofToString(imageCounter) + ".png");
img2.loadImage(ofToString(imageCounter-1) + ".png");
srcImg=img2;
srcTracker.update(toCv(srcImg));
srcPoints = srcTracker.getImagePoints();
//************************************
#ifdef _USE_LIVE_VIDEO
vidGrabber.setVerbose(true);
vidGrabber.setDeviceID(4);
vidGrabber.initGrabber(320,240);
#else
vidPlayer.loadMovie("fingers.mov");
vidPlayer.play();
#endif
colorImg.allocate(320,240);
grayImage.allocate(320,240);
grayBg.allocate(320,240);
grayDiff.allocate(320,240);
bLearnBakground = true;
threshold = 80;
leftBowl = false;
rightBowl = false;
circleColor1 = 0;
circleColor2=0;
border = 220;
}
void testApp::update() {
double interval = 5;
cam.update();
currentTime = ofGetElapsedTimeMillis()/1000;
if(cam.isFrameNew()) {
camTracker.update(toCv(cam));
scale = camTracker.getScale();
orientation = camTracker.getOrientation();
rotationMatrix = camTracker.getRotationMatrix();
}
if(!camTracker.getFound() && substitute){
cout<<"camtracker isnt found"<<endl;
if(currentTime - savedTime>interval){
substitute=false;
cout<<substitute<<" is substitute "<<endl;
}
cout<<savedTime<<" is the previous time "<<currentTime<<" is the current time ";
}
if (camTracker.getFound()){
savedTime = currentTime;
}
//*****************************************
circleColor1 = 255;
circleColor2=255;
leftBowl = false;
bool bNewFrame = false;
#ifdef _USE_LIVE_VIDEO
vidGrabber.grabFrame();
bNewFrame = vidGrabber.isFrameNew();
#else
vidPlayer.idleMovie();
bNewFrame = vidPlayer.isFrameNew();
#endif
if (bNewFrame){
#ifdef _USE_LIVE_VIDEO
colorImg.setFromPixels(vidGrabber.getPixels(), 320,240);
#else
colorImg.setFromPixels(vidPlayer.getPixels(), 320,240);
#endif
grayImage = colorImg;
if (bLearnBakground == true){
grayBg = grayImage; // the = sign copys the pixels from grayImage into grayBg (operator overloading)
bLearnBakground = false;
}
// take the abs value of the difference between background and incoming and then threshold:
grayDiff.absDiff(grayBg, grayImage);
grayDiff.threshold(threshold);
// find contours which are between the size of 20 pixels and 1/3 the w*h pixels.
// also, find holes is set to true so we will get interior contours as well....
contourFinder.findContours(grayDiff, 50, (340*240)/3, 1, true); // find holes
for (int i = 0; i < contourFinder.nBlobs; i++){
//cout << contourFinder.blobs[i].centroid.x << endl;
if(contourFinder.nBlobs>0) {
substitute=true;
if (contourFinder.blobs[i].centroid.x< border) {
leftBowl = true;
srcImg = img1;
circleColor1 = 0;
//cout << leftBowl << endl;
}
else if (contourFinder.blobs[i].centroid.x > border) {
leftBowl= false;
srcImg=img2;
circleColor2 = 0;
//cout << leftBowl<<endl;
}
}
}
}
}
void testApp::draw() {
ofSetColor(255);
vidGrabber.draw(1280,0, 1280,800);
cam.draw(0, 0,1280,800 );
ofDrawBitmapString(ofToString((int) ofGetFrameRate()), 10, 20);
img2.draw(0,0, 300,300); //draw srcimg thumbnail
img1.draw(0,300,300,300);
if(camTracker.getFound() && substitute) {
ofMesh camMesh = camTracker.getImageMesh();
ofMesh objectMesh = camTracker.getObjectMesh();
//move the object mesh to the corner of the screen
cam.getTextureReference().bind();
ofPushMatrix();
ofSetupScreenOrtho(640, 480, OF_ORIENTATION_UNKNOWN, true, -1000, 1000);
ofTranslate(posX,posY);
applyMatrix(rotationMatrix);
ofScale(3.3,3.3,3.3);
ofDrawAxis(3.3);
objectMesh.draw();
ofPopMatrix();
cam.getTextureReference().unbind();
//substitute the imageMesh with srcImg
camMesh.clearTexCoords();
camMesh.addTexCoords(srcPoints);
srcImg.getTextureReference().bind();
ofSetupScreenOrtho(640, 480, OF_ORIENTATION_UNKNOWN, true, -1000, 1000);
camMesh.draw();
srcImg.getTextureReference().unbind();
/*
leftEye = tracker.getImageFeature(ofxFaceTracker::EYE_LEFT);
mouth = tracker.getImageFeature(ofxFaceTracker::OUTER_MOUTH);
*/
mouth.setClosed(true);
ofPushStyle();
ofFill();
ofSetColor(60,0,0);
ofBeginShape();
for(int i =0; i<mouth.size(); i++){
ofVertex(mouth[i]);
}
ofEndShape(true);
ofPopStyle();
mouth.draw();
}
if (posY < 400 && posX >0 ) {
posY ++;
posX --;}
else {
posY = 400;
posX = 50;
}
/* distort the mouth
ofSetLineWidth(1);
tracker.draw();
ofPolyline leftEye = tracker.getImageFeature(ofxFaceTracker::LEFT_EYE);
ofPolyline rightEye = tracker.getImageFeature(ofxFaceTracker::RIGHT_EYE);
ofPolyline faceOutline = tracker.getImageFeature(ofxFaceTracker::FACE_OUTLINE);
ofSetLineWidth(2);
ofSetColor(ofColor::red);
leftEye.draw();
ofSetColor(ofColor::green);
rightEye.draw();
ofSetColor(ofColor::blue);
faceOutline.draw();
if(tracker.getFound()) {
ofSetColor(255);
bool inside = faceOutline.inside(mouseX, mouseY);
ofDrawBitmapString(inside ? "inside" : "outside", 10, 40);
}
*/
//********************************bowls
ofPushStyle();
ofSetLineWidth(3);
ofFill();
ofSetColor(circleColor1,255,255);
ofCircle(1600, 400, 80);
ofSetColor(circleColor2, 255,255);
ofCircle(2170, 400, 80);
ofPopStyle();
//draw the blobs
for (int i = 0; i < contourFinder.nBlobs; i++){
contourFinder.blobs[i].draw(300,200);
}
}
void testApp::keyPressed(int key) {
switch (key) {
case 'r':
camTracker.reset();
posX =0;
posY =0;
break;
case 'l':
substitute = !substitute;
srcTracker.update(toCv(srcImg));
srcPoints = srcTracker.getImagePoints();
break;
case 's':
img2.grabScreen(200,0,(ofGetWindowWidth()-200),ofGetWindowHeight());
img2.saveImage(ofToString(imageCounter-1) + ".png");
img1.loadImage(ofToString(imageCounter-2) + ".png");
imageCounter ++;
break;
case ' ':
bLearnBakground = true;
break;
case '+':
threshold ++;
if (threshold > 255) threshold = 255;
break;
case '-':
threshold --;
if (threshold < 0) threshold = 0;
break;
}
}
<file_sep>/extractFaceMesh/src/testApp.h
#pragma once
#include "ofMain.h"
#include "ofxCv.h"
#include "ofxFaceTracker.h"
class testApp : public ofBaseApp {
public:
void setup();
void update();
void draw();
void keyPressed(int key);
ofVideoGrabber cam;
ofxFaceTracker srcTracker;
ofxFaceTracker camTracker;
ofPolyline mouth;
ofPolyline leftEye;
ofImage srcImg;
int imageCounter;
vector<ofVec2f> srcPoints;
vector<ofVec2f> camPoints;
ofVec2f camPosition;
int posX, posY;
float scale;
ofVec3f orientation;
ofMatrix4x4 rotationMatrix;
};
<file_sep>/justFace/justFace/src/testApp.cpp
#include "testApp.h"
using namespace ofxCv;
void testApp::setup() {
ofSetVerticalSync(true);
ofSetDrawBitmapMode(OF_BITMAPMODE_MODEL_BILLBOARD);
cam.listDevices();
cam.setDeviceID(6);
cam.initGrabber(640, 480);
ofEnableAlphaBlending();
camTracker.setup();
posX=ofGetWindowWidth()/2;
posY=ofGetWindowHeight()/2;
imageCounter =4;
imgID=1;
substitute = false;
currentFound = true;
lastFound = true;
savedtime =0;
currentTime =0;
//face tracker on source
srcTracker.setup();
srcTracker.setRescale(.5);
srcTracker.setup();
srcTracker.setIterations(25);
srcTracker.setAttempts(2);
srcTracker.setClamp(4);
srcTracker.setTolerance(.01);
srcImg.loadImage("face.jpeg");
srcTracker.update(toCv(srcImg));
srcPoints = srcTracker.getImagePoints();
img1.loadImage(ofToString(imageCounter-2) + ".png");
img2.loadImage(ofToString(imageCounter-3) + ".png");
img3.loadImage(ofToString(imageCounter-4) + ".png");
/*
faces.allowExt("jpg");
faces.allowExt("png");
faces.listDir("faces");
currentFace = 0;
if(faces.size()!=0){
loadFace(faces.getPath(currentFace));
}
*/
}
void testApp::update() {
cam.update();
if(cam.isFrameNew()) {
camTracker.update(toCv(cam));
scale = camTracker.getScale();
orientation = camTracker.getOrientation();
rotationMatrix = camTracker.getRotationMatrix();
}
currenTime = ofGetElapsedTimeMillis()/1000;
if (!camTracker.getFound() && substitute && resetting) {
resetting = false;
int timePassed = currentTime-savedtime;
//cout << timePassed <<endl;
if (timePassed >= 5) {
substitute = false;
resetting = true;
savedtime=currentTime;
}
//ofGetElapsedTimeMicros()...
}
void testApp::draw() {
ofSetColor(255);
cam.draw(0, 0);
ofDrawBitmapString(ofToString((int) ofGetFrameRate()), 10, 20);
srcImg.draw(0,0, 100,100); //draw srcimg thumbnail
//srcImg.draw
img1.draw(0,100,100,100);
img2.draw(0,200,100,100);
img3.draw(0,300,100,100);
if(camTracker.getFound() && substitute ) {
ofMesh camMesh = camTracker.getImageMesh();
ofMesh objectMesh = camTracker.getObjectMesh();
//move the object mesh to the corner of the screen
cam.getTextureReference().bind();
ofPushMatrix();
ofSetupScreenOrtho(640, 480, OF_ORIENTATION_UNKNOWN, true, -1000, 1000);
ofTranslate(posX,posY);
applyMatrix(rotationMatrix);
ofScale(3.3,3.3,3.3);
ofDrawAxis(3.3);
objectMesh.draw();
ofPopMatrix();
cam.getTextureReference().unbind();
//substitute the imageMesh with srcImg
camMesh.clearTexCoords();
camMesh.addTexCoords(srcPoints);
srcImg.getTextureReference().bind();
ofSetupScreenOrtho(640, 480, OF_ORIENTATION_UNKNOWN, true, -1000, 1000);
camMesh.draw();
srcImg.getTextureReference().unbind();
/*
leftEye = tracker.getImageFeature(ofxFaceTracker::EYE_LEFT);
mouth = tracker.getImageFeature(ofxFaceTracker::OUTER_MOUTH);
*/
mouth.setClosed(true);
ofPushStyle();
ofFill();
ofSetColor(60,0,0);
ofBeginShape();
for(int i =0; i<mouth.size(); i++){
ofVertex(mouth[i]);
}
ofEndShape(true);
ofPopStyle();
mouth.draw();
}
if (posY < 400 && posX >0 ) {
posY ++;
posX --;}
else {
posY = 400;
posX = 50;
}
/* distort the mouth
ofSetLineWidth(1);
tracker.draw();
ofPolyline leftEye = tracker.getImageFeature(ofxFaceTracker::LEFT_EYE);
ofPolyline rightEye = tracker.getImageFeature(ofxFaceTracker::RIGHT_EYE);
ofPolyline faceOutline = tracker.getImageFeature(ofxFaceTracker::FACE_OUTLINE);
ofSetLineWidth(2);
ofSetColor(ofColor::red);
leftEye.draw();
ofSetColor(ofColor::green);
rightEye.draw();
ofSetColor(ofColor::blue);
faceOutline.draw();
if(tracker.getFound()) {
ofSetColor(255);
bool inside = faceOutline.inside(mouseX, mouseY);
ofDrawBitmapString(inside ? "inside" : "outside", 10, 40);
}
*/
}
void testApp::keyPressed(int key) {
switch (key) {
case 'r':
camTracker.reset();
posX =0;
posY =0;
break;
case 'l':
substitute= true;
srcImg.loadImage(ofToString(imageCounter-1) + ".png");
//cout << imageCounter;
srcTracker.update(toCv(srcImg));
srcPoints = srcTracker.getImagePoints();
//loadFace(currentFace);
break;
case 's':
srcImg.grabScreen(200,0,(ofGetWindowWidth()-200),ofGetWindowHeight());
srcImg.saveImage(ofToString(imageCounter) + ".png");
img1.loadImage(ofToString(imageCounter-2) + ".png");
img2.loadImage(ofToString(imageCounter-3) + ".png");
img3.loadImage(ofToString(imageCounter-4) + ".png");
cout<<imageCounter<<" is the counter "<<endl;
imageCounter ++;
break;
case ' ':
bLearnBakground = true;
break;
case '+':
threshold ++;
if (threshold > 255) threshold = 255;
break;
case '-':
threshold --;
if (threshold < 0) threshold = 0;
break;
}
}
void testApp :: mouseMoved(int mouseX, int mouseY) {
if (mouseX < ofGetWindowWidth()/2) {
imgID = imageCounter-1;
//cout << imgID;
}
else if (mouseX >= ofGetWindowWidth()/2) {
imgID = imageCounter-2;
//cout << imgID;
}
}
/*
void testApp::loadFace(string face){
src.loadImage(face);
if(src.getWidth() > 0) {
srcTracker.update(toCv(src));
srcPoints = srcTracker.getImagePoints();
}
}
*/
<file_sep>/extractFace/extractFaceMesh/src/testApp.h
#pragma once
#include "ofMain.h"
#include "ofxCv.h"
#include "ofxOpenCv.h"
#define _USE_LIVE_VIDEO // uncomment this to use a live camera
#include "ofxFaceTracker.h"
class testApp : public ofBaseApp {
public:
void setup();
void update();
void draw();
void keyPressed(int key);
ofVideoGrabber cam;
ofxFaceTracker srcTracker;
ofxFaceTracker camTracker;
ofPolyline mouth;
ofPolyline leftEye;
ofImage srcImg;
int imageCounter;
vector<ofVec2f> srcPoints;
vector<ofVec2f> camPoints;
ofVec2f camPosition;
int posX, posY;
float scale;
ofVec3f orientation;
ofMatrix4x4 rotationMatrix;
bool substitute;
ofImage img1, img2;
int currentTime,savedTime;
//handDetection
#ifdef _USE_LIVE_VIDEO
ofVideoGrabber vidGrabber;
#else
ofVideoPlayer vidPlayer;
#endif
ofxCvColorImage colorImg;
ofxCvGrayscaleImage grayImage;
ofxCvGrayscaleImage grayBg;
ofxCvGrayscaleImage grayDiff;
ofxCvContourFinder contourFinder;
int threshold;
bool bLearnBakground;
bool leftBowl;
bool rightBowl;
int circleColor1;
int circleColor2, border;
};
| 74218e993fc8db1b740b9cc774b57e84632fc795 | [
"C++"
] | 4 | C++ | yinnie/faceBank | 30fcfc99b50f02ebfd44117f1ab0fcf5bff6f141 | f1696e51468a1b3a1e83ff67f70d7750a9c98b87 |
refs/heads/master | <repo_name>AdamGackiewicz/ProjektyDodatkowe<file_sep>/ProjektyDodatkowe/Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjektyDodatkowe
{
class Program
{
static void Main(string[] args)
{
DateTime dt = new DateTime(2017, 1, 1);
for (int i = 0; i < 84; i++)
{
bool a = dt.ToString("MM").Equals("03");
if (a != true)
{
Console.WriteLine(dt.ToString("yyyy'-'MM"));
}
dt = dt.AddMonths(1);
}
Console.ReadLine();
}
}
}
| 6aff87ef81f6b103e558bdf29a0e75d76d22051b | [
"C#"
] | 1 | C# | AdamGackiewicz/ProjektyDodatkowe | 661ec7842ba95c0269d8d98bd8a6199611e9d64f | eae92a0b912f3e9fcea218211d182af21f7ac652 |
refs/heads/master | <file_sep>huh i dont know js
lol same<file_sep>import React from "react"
export default const Hello = 'test'
| 1c0ca7ef915f40c0f95ce84276fd30d2a172fe78 | [
"JavaScript"
] | 2 | JavaScript | tsefrebotkcah/tsefrebotkcah.github.io | 2c8c1e11faa8c176978bdd49ecf3b565af09c256 | a0a2ea3096240058d2664709980a27afec7ea2af |
refs/heads/master | <repo_name>ericdaat/flask-template<file_sep>/tests/conftest.py
import pytest
from application.app import create_app
from application.admin import init_db
@pytest.fixture
def app():
app = create_app(dict(
TESTING=True,
SQLALCHEMY_DATABASE_URI='sqlite:///:memory:',
SERVER_NAME='127.1'
))
with app.app_context():
init_db()
yield app
@pytest.fixture
def client(app):
"""A test client for the app."""
return app.test_client()
@pytest.fixture
def runner(app):
"""A test runner for the app's Click commands."""
return app.test_cli_runner()
<file_sep>/requirements.txt
alabaster==0.7.12
atomicwrites==1.3.0
attrs==18.2.0
Babel==2.6.0
certifi==2018.11.29
chardet==3.0.4
Click==7.0
docutils==0.14
Flask==1.0.2
Flask-SQLAlchemy==2.3.2
idna==2.8
imagesize==1.1.0
itsdangerous==1.1.0
Jinja2==2.10.1
m2r==0.2.1
MarkupSafe==1.1.0
marshmallow==3.0.1
marshmallow-sqlalchemy==0.17.0
mistune==0.8.4
more-itertools==5.0.0
packaging==18.0
pluggy==0.8.1
py==1.7.0
Pygments==2.3.1
pyparsing==2.3.0
pytest==4.2.0
pytz==2018.7
requests==2.21.0
six==1.12.0
snowballstemmer==1.2.1
Sphinx==1.8.2
sphinx-rtd-theme==0.4.2
sphinxcontrib-websupport==1.1.0
SQLAlchemy==1.3.7
SQLAlchemy-Utils==0.33.9
urllib3==1.24.3
uWSGI==2.0.18
werkzeug>=0.15.3
<file_sep>/.flake8
[flake8]
max-line-length = 90
exclude = docs/*,
<file_sep>/application/blueprints/home.py
import logging
import flask
from application.model import User
bp = flask.Blueprint("home", __name__)
@bp.route("/")
def index():
users = User.query.all()
logging.info("{0} user(s) in the db".format(len(users)))
return flask.render_template("home/index.html")
<file_sep>/docs/source/application.rst
application package
===================
.. automodule:: application
:members:
:undoc-members:
:show-inheritance:
Subpackages
-----------
.. toctree::
application.blueprints
Submodules
----------
application.admin module
------------------------
.. automodule:: application.admin
:members:
:undoc-members:
:show-inheritance:
application.app module
----------------------
.. automodule:: application.app
:members:
:undoc-members:
:show-inheritance:
application.cli module
----------------------
.. automodule:: application.cli
:members:
:undoc-members:
:show-inheritance:
application.config module
-------------------------
.. automodule:: application.config
:members:
:undoc-members:
:show-inheritance:
application.errors module
-------------------------
.. automodule:: application.errors
:members:
:undoc-members:
:show-inheritance:
application.model module
------------------------
.. automodule:: application.model
:members:
:undoc-members:
:show-inheritance:
application.schema module
-------------------------
.. automodule:: application.schema
:members:
:undoc-members:
:show-inheritance:
application.wsgi module
-----------------------
.. automodule:: application.wsgi
:members:
:undoc-members:
:show-inheritance:
<file_sep>/application/admin.py
from application.model import db, User
def init_db():
db.drop_all()
db.create_all()
# add a user
admin = User(username='admin', email='<EMAIL>')
db.session.add(admin)
db.session.commit()<file_sep>/application/schema.py
from marshmallow_sqlalchemy import ModelSchema
from application.model import session, User
class UserSchema(ModelSchema):
class Meta:
sqla_session = session
model = User
fields = (
"username", "email"
)<file_sep>/application/cli.py
import click
from flask.cli import with_appcontext
from application.admin import init_db
@click.command('init-db')
@with_appcontext
def init_db_command():
init_db()
click.echo('Initialized the database.')<file_sep>/README.md
# Flask Web Application template
[](https://flask-template.readthedocs.io/en/latest/?badge=latest)
[](https://circleci.com/gh/ericdaat/flask-template)
This is a template for a basic Flask web application that responds
an HTML page on `localhost:8080`.
This template comes with support for:
- [SQLlite database](https://www.sqlite.org/index.html)
- [Sphinx documentation](http://www.sphinx-doc.org/en/master/)
- [Twitter Bootstrap](https://getbootstrap.com/)
- [Font Awesome](https://fontawesome.com/)
- [Docker](https://www.docker.com/) and [docker-compose](https://docs.docker.com/compose/)
Don't hesitate to contribute!
## Install
Create a virtual environment and install the requirements.
``` bash
make venv/bin/activate
```
Init the database by creating all tables.
``` bash
export DATABASE_URL=sqlite:///../db.sqlite3
export FLASK_APP="application.app"
flask init-db
```
## Run
Run the application debug mode.
``` bash
FLASK_DEBUG=True flask run
```
If you wish to use Docker for deploying the app, run the following:
``` bash
docker-compose up -d
```
## Docs
Automatically create and build the code documentation using Sphinx.
You can use [Read the Docs](https://readthedocs.org/) to build and host the documentation,
like I did [here](https://flask-template.readthedocs.io/en/latest/).
``` bash
make docs
```
## Clone the template to another directory
``` bash
./install.sh /path/to/your/dir
```
<file_sep>/docs/source/application.blueprints.rst
application.blueprints package
==============================
.. automodule:: application.blueprints
:members:
:undoc-members:
:show-inheritance:
Submodules
----------
application.blueprints.home module
----------------------------------
.. automodule:: application.blueprints.home
:members:
:undoc-members:
:show-inheritance:
<file_sep>/application/config.py
import os
ENV = os.environ.get("ENV", "development")
DEBUG = True if ENV == "development" else False
TESTING = os.environ.get("TESTING", False)
SECRET_KEY = os.environ.get("SECRET_KEY", "dev")
SQLALCHEMY_TRACK_MODIFICATIONS = False
SQLALCHEMY_DATABASE_URI = os.environ.get("DATABASE_URL", "sqlite:///:memory:")
<file_sep>/install.sh
#!/bin/bash
# usage: ./install.sh /path/to/dir
if [ -z "$1" ] || [ ! -d $(dirname "$1") ]; then
echo "Non valid path"
exit 1
fi
rsync -av "$(dirname "$0")/" "$1" \
--exclude venv \
--exclude .git \
--exclude docs/build \
--exclude __pycache__ \
--exclude instance \
--exclude .idea \
--exclude .pytest_cache \
--exclude install.sh \
--exclude README.md;
cd $1;
echo "#$(basename $1)" > README.md;
git init;
exit 0
<file_sep>/pytest.ini
[pytest]
python_files=**/test*.py
testpaths=application
log_level=DEBUG
log_format=%(asctime)s %(levelname)s %(name)s (%(filename)s:%(lineno)s) %(message)s
log_date_format = %Y-%m-%d %H:%M:%S
<file_sep>/application/model.py
import uuid
from datetime import datetime
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy_utils import EmailType, UUIDType
db = SQLAlchemy()
session = db.session
class User(db.Model):
__tablename__ = "user"
uuid = db.Column(UUIDType, primary_key=True, default=uuid.uuid4, nullable=False)
created_at = db.Column(db.DateTime, default=datetime.utcnow)
username = db.Column(db.String(80), unique=True, nullable=False)
email = db.Column(EmailType(), unique=True, nullable=False)
def __repr__(self):
return '<User %r>' % self.username
<file_sep>/docker-compose.yml
version: "3"
services:
python:
build: .
app:
image: flask-template_python:latest
ports:
- 8080:8080
volumes:
- ./application:/src/application
- ./foo.sqlite:/src/foo.sqlite
working_dir: /src/
environment:
PYTHONPATH: /src
DATABASE_URL: sqlite:///../db.sqlite3
command: ["python", "application/wsgi.py"]
<file_sep>/application/errors.py
from flask import render_template
def page_not_found(e):
""" Renders template for 404 error
Args:
e: Error
Returns: 404 error template
"""
return render_template('errors/404.html', error=e), 404<file_sep>/tests/test_factory.py
from flask import url_for
def test_home(client):
response = client.get(url_for('home.index'))
assert response.status_code == 200
<file_sep>/application/app.py
import os
from flask import Flask
from application import errors, cli
from application.model import db, session
def create_app(config=None):
""" Flask app factory that creates and configure the app.
Args:
test_config (str): python configuration filepath
Returns: Flask application
"""
app = Flask(__name__)
app.config.from_pyfile('config.py')
if config:
app.config.update(config)
db.init_app(app)
# instance dir
try:
os.makedirs(app.instance_path)
except OSError:
pass
# register cli commands
app.cli.add_command(cli.init_db_command)
# HTTP errors
app.register_error_handler(404, errors.page_not_found)
# blueprints
from application.blueprints import home
app.register_blueprint(home.bp)
# request handlers
@app.after_request
def commit_db_session(response):
session.commit()
return response
return app
<file_sep>/Makefile
venv: venv/bin/activate
venv/bin/activate: requirements.txt
test -d venv || virtualenv venv
. venv/bin/activate; pip install -Ur requirements.txt
touch venv/bin/activate
build:
docker-compose build;
tests:
. venv/bin/activate; \
pytest tests;
start:
docker-compose up -d;
start-debug: venv
docker-compose up -d postgres metabase;
. venv/bin/activate; \
FLASK_APP="application" \
FLASK_DEBUG=True \
DATABASE_URL=postgresql://user:password@localhost/webstats \
flask run;
docs:
cd docs; \
make clean; \
find source/*.rst ! -name 'index.rst' -type f -exec rm -f {} +; \
sphinx-apidoc ../application -o source -M; \
sphinx-build source build; \
echo "done";
<file_sep>/docs/source/index.rst
.. Flask Template documentation master file, created by
sphinx-quickstart on Fri Dec 21 17:23:03 2018.
You can adapt this file completely to your liking, but it should at least
contain the root `toctree` directive.
.. mdinclude:: ../../README.md
.. toctree::
:maxdepth: 2
:caption: Contents:
application
Indices and tables
==================
* :ref:`genindex`
* :ref:`modindex`
* :ref:`search`
<file_sep>/Dockerfile
FROM python:3.6
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt | 449975131ba63898beae74f581b865abf7864aac | [
"YAML",
"reStructuredText",
"Markdown",
"Makefile",
"INI",
"Python",
"Text",
"Dockerfile",
"Shell"
] | 21 | Python | ericdaat/flask-template | bae5ed4068dd024031a209b45bbbc7449afa9e31 | bafae6789016526aa6ad9430efbbb938a42fe4bc |
refs/heads/master | <file_sep>/* global dest */
import 'pixi'
import 'p2'
import Phaser from 'phaser'
import BootState from './states/Boot'
import config from './config'
class Game extends Phaser.Game {
constructor () {
super(config.gameWidth, config.gameHeight, Phaser.AUTO, 'content', null)
this.state.add('Boot', BootState, true)
}
}
// Check for a target to load after the splash screen
var query = window.location.search.substring(1)
var vars = query.split('&')
var pair = vars[0].split('=')
if (pair.length > 1) {
window.dest = pair[1]
}
// Instantiate the game object
window.game = new Game()
<file_sep># Fish People Splash Screen
#### A splash screen to play before games from Spring 2017 in GDD 325
Originally forked from the Phaser + ES6 + Webpack project on GitHub
| 37aca411cc7f9eb4fb6dce952109bf7d29bc75ed | [
"JavaScript",
"Markdown"
] | 2 | JavaScript | Olliebrown/fish-people-splashscreen | d50f4ce3c708cfdc3ba78c3e0ed75fed18377d3b | aae6faf50fb68c4e77e5b9adf8b036e8adfda299 |
refs/heads/main | <file_sep><?php
session_start();
?>
<!DOCTYPE html>
<html lang="en">
<head>
<title>Create account</title>
<!-- Required meta tags -->
<meta charset="utf-8" />
<meta
name="viewport"
content="width=device-width, initial-scale=1, shrink-to-fit=no"
/>
<!-- Bootstrap CSS -->
<link
rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css"
integrity="<KEY>"
crossorigin="anonymous"
/>
</head>
<body>
<?php
include "dbcon.php";
if(isset($_POST['submit'])){
$firstname = mysqli_real_escape_string($con , $_POST['firstname']);
$lastname = mysqli_real_escape_string($con, $_POST['lastname']);
$email = mysqli_real_escape_string($con , $_POST['email']);
$password = mysqli_real_escape_string($con, $_POST['password']);
$cpassword = mysqli_real_escape_string($con, $_POST['cpassword']);
$pass = password_hash($password, PASSWORD_BCRYPT);
$cpass = password_hash($cpassword, PASSWORD_BCRYPT);
$emailquery = " select * from registration where email = '$email' ";
$query = mysqli_query($con, $emailquery);
$emailcount = mysqli_num_rows($query);
if($emailcount>0){
?>
<script>
alert("Email exists")
</script>
<?php
}
else{
if($password == $cpassword){
$insertquery = "insert into registration(firstname, lastname, email, password, cpassword) values('$firstname', '$lastname', '$email', '$pass', '$cpass')";
$_SESSION['firstname'] = $firstname;
header('location:index.php');
}
}
if($password != $cpassword){
?>
<script>
alert("Please try again")
</script>
<?php
}
// mysqli_real_escape_string()
}
?>
<div class="jumbotron jumbotron-fluid">
<div class="container">
<div class="row">
<div
class="col-12 col-sm-8 col-md-6 col-lg-4 offset-sm-2 offset-md-3 offset-lg-4"
>
<h1 class="mb-3 text-center">Wheels R'Us</h1>
<p class="lead">
</p>
<form action="" method="POST">
<div class="row">
<div class="form-group col-12 col-sm-6">
<label for="firstName">First name:</label>
<input
type="text"
name = "firstname"
class="form-control"
placeholder="First name"
id="firstName"
required
/>
</div>
<div class="form-group col-12 col-sm-6">
<label for="lastName">Last name:</label>
<input
type="text"
name = "lastname"
class="form-control"
placeholder="Last name"
id="lastName"
required
/>
</div>
</div>
<div class="form-group">
<label for="email">Email:</label>
<input
type="email"
class="form-control"
placeholder="<EMAIL>"
name = "email"
id="email"
required
/>
</div>
<div class="form-group">
<label for="password">Password:</label>
<input
type="<PASSWORD>"
name = "password"
class="form-control"
id="password"
required
/>
</div>
<div class="form-group">
<label for="password"> Repeat Password:</label>
<input
type="<PASSWORD>"
class="form-control"
name = "cpassword"
id="password"
required
/>
</div>
<button type="submit" name = "submit" class="btn btn-primary btn-block mb-3">
Create account
</button>
<div class="alert alert-info small" role="alert">
By clicking above you agree to our
<a href="#" class="alert-link">Terms & Conditions</a> and
our <a href="#" class="alert-link">Privacy Policy</a>.
</div>
<div class="text-center">
<p>or ...</p>
<a href="login.php" class="btn btn-success">Login</a>
</div>
</form>
</div>
</div>
</div>
</div>
<!-- Optional JavaScript -->
<script
src="https://code.jquery.com/jquery-3.2.1.slim.min.js"
integrity="<KEY>"
crossorigin="anonymous"
></script>
<script
src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.3/umd/popper.min.js"
integrity="<KEY>"
crossorigin="anonymous"
></script>
<script
src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/js/bootstrap.min.js"
integrity="<KEY>"
crossorigin="anonymous"
></script>
</body>
</html><file_sep><?php
session_start();
if(!isset($_SESSION['firstname'])){
echo "You have logged out";
header('location:login.php');
}
?>
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>WHEELS 'R' US</title>
<link rel="stylesheet" href="index88.css">
</head>
<body>
<div class="hold">
<div class="header">
<div class="container">
<div id="logo">
</div>
<ul class="nav">
<li><a href="#">HOME</a></li>
<li><a href="aboutus.html">ABOUT</a></li>
<li><a href="#products">PRODUCTS</a></li>
<li><a href="#">Hello <?php echo $_SESSION['firstname']; ?></a></li>
<li><a href="logout.php">Logout</a></li>
</ul>
</div>
</div>
</div>
<div class="section">
<div class="slider">
<div class="container slidercontent">
<h1 class="hero">WELCOME<br>TO</h1>
<h2 class="hero">WHEELS 'R' US!</h2>
<a href="#explore"><div class="call"><span>EXPLORE MORE</span></div></a>
</div>
</div>
</div>
<div class="section">
<div class="container">
<div class="col four">
<h2 class="icon">Women</h2>
<a href="shoppingw.html"> <h1 class="service">Women's Bicycles</h1></a>
</div>
<div class="col four">
<h2 class="icon">Men</h2>
<a href="shoppingm.html"> <h1 class="service">Men's Bicycles</h1></a>
</div>
<div class="responsivegroup"></div>
<div class="col four">
<h2 class="icon">Kids</h2>
<a href="shopping.html"><h1 class="service">Kid's Bicycles</h1></a>
</div>
<div class="col four">
<h3 class="icon">[]</h3>
<h2 class="service">Accessories</h2>
</div>
<div class="group"></div>
</div>
</div>
<div class="section bg">
<div id="products"class="container">
<h1>Featured Products</h1>
<h2>Check out the favourites!</h2>
<div class="col three bg nopad pointer">
<div class="imgholder">
<img src="https://images.pexels.com/photos/5851030/pexels-photo-5851030.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500" />
</div>
<h1 class="feature"></h1>
<a href="shoppingw.html"><p>Women<br>Professional Cycles</p></a>
</div>
<div class="col three bg nopad pointer">
<div class="imgholder">
</div>
<h1 class="feature"></h1>
<p></p>
</div>
<div class="col three bg nopad pointer">
<div class="imgholder">
<img src="https://images.pexels.com/photos/7242978/pexels-photo-7242978.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500"/>
</div>
<h1 class="feature"></h1>
<a href="shoppingw.html"><p>Women<br>Casual Cycles</p></a>
</div>
<div class="group margin"></div>
<div class="col three bg nopad pointer">
<div class="imgholder">
<img src="https://images.pexels.com/photos/5851033/pexels-photo-5851033.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500"/>
</div>
<h1 class="feature"></h1>
<a href="shoppingm.html"><p>Men<br>Professional Cycles</p></a>
</div>
<div class="col three bg nopad pointer">
<div class="imgholder">
</div>
<h1 class="feature"></h1>
<p></p>
</div>
<div class="col three bg nopad pointer">
<div class="imgholder">
<img src="https://images.pexels.com/photos/2270328/pexels-photo-2270328.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500"/>
</div>
<h1 class="feature"></h1>
<a href="shoppingm.html"><p>Men<br>Casual Cycles</p></a>
</div>
<div class="group"></div>
</div>
</div>
<div class="section">
<div id = "explore" class="container">
<h1>Why Choose Wheels 'R' Us?</h1>
<h2></h2>
<div class="col three">
<h1 class="icon side"></h1>
<h1 class="feature side">Insurance</h1>
<p class="side">Free 2 year insurance!</p>
</div>
<div class="col three">
<h1 class="icon side"></h1>
<h1 class="feature side">Maintainance</h1>
<p class="side">Free regular maintainance upto 3 years!</p>
</div>
<div class="col three">
<h1 class="icon side"></h1>
<h1 class="feature side">High Quality</h1>
<p class="side">High quality material only used!</p>
</div>
<div class="group margin"></div>
<div class="col three">
<h1 class="icon side"></h1>
<h1 class="feature side">Free Delivery</h1>
<p class="side">Free and safe delivery at our cost!</p>
</div>
<div class="col three">
<h1 class="icon side"></h1>
<h1 class="feature side">Fast Delivery</h1>
<p class="side">Cycles are delivered within 3 hours of purchase</p>
</div>
<div class="col three">
<h1 class="icon side"></h1>
<h1 class="feature side">Resourcing</h1>
<p class="side">We recruit local business for supplies!</p>
</div>
<div class="group margin"></div>
</div>
</div>
<div class="section bg">
<div id="reviews" class="container">
<h1>Customer Reviews</h1>
<h2></h2>
<div class="col two bg margin extrapad">
<h1 class="icon side"></h1>
<span class="feature side">Anushka</span><span class="side"> - CEO Crowdworks</span>
<p class="side">Amazing quality of cycle! Kudos to Wheels 'R' Us!</p>
</div>
<div class="col two bg margin extrapad">
<h1 class="icon side"></h1>
<span class="feature side">Samiksha</span><span class="side"> - Engineer</span>
<p class="side">Looks as good as the day i bought it 3 years ago!</p>
</div>
<div class="group margin"></div>
<div class="col two bg margin extrapad">
<h1 class="icon side"></h1>
<span class="feature side">Advait</span><span class="side"> - Developer</span>
<p class="side">its great you guys source raw materials from local businesses here! Kudos!</p>
</div>
<div class="col two bg margin extrapad">
<h1 class="icon side"></h1>
<span class="feature side">Anvesh</span><span class="side"> - Pro Cyclist</span>
<p class="side">Great quality and long lasting material! Worth the money!</p>
</div>
<div class="group"></div>
</div>
</div>
<div class="section">
<div class="container">
<div class="col two">
<h1 class="icon">[]</h1>
<h1 class="service">ABOUT</h1>
<p>To learn more about us, click here!</p>
</div>
<div class="col two">
<h1 class="icon">[]</h1>
<h1 class="service">CONTACT</h1>
<p>We would love to hear from you!</p>
</div>
<div class="group"></div>
</div>
</div>
<div class="section">
<div class="container">
<h1 class="reset"></h1>
</div>
</div>
<div class="section">
<div class="footer">
<div class="container white">
<div class="col four left">
<h1>Services</h1>
<p>Insurance and Free Maintainance</p>
<p>Fast and Safe Delivery</p>
<p>High Quality and Long-Lasting Products</p>
</div>
<div class="col four left">
<h1>Quick Links</h1>
<p>Home</p>
<p>About</p>
<p>Contact</p>
</div>
<div class="col four left">
<h1>Locations</h1>
<p>India</p>
<p>Germany</p>
<p>France</p>
</div>
<div class="col four left">
<h1>Contact Us</h1>
<p>9867536784</p>
<p>Email-<EMAIL>></p>
</div>
<div class="group"></div>
</div>
</div>
</div>
</body>
</html>
<file_sep><?php
session_start();
?>
<!DOCTYPE html>
<html lang="en">
<head>
<title>Create account</title>
<!-- Required meta tags -->
<meta charset="utf-8" />
<meta
name="viewport"
content="width=device-width, initial-scale=1, shrink-to-fit=no"
/>
<!-- Bootstrap CSS -->
<link
rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css"
integrity="<KEY>"
crossorigin="anonymous"
/>
</head>
<body>
<?php
include 'dbcon.php';
if(isset($_POST['submit'])){
$email = $_POST['email'];
$password = $_POST['password'];
$email_search = " select * from registration where email='$email' ";
$query = mysqli_query($con, $email_search);
$email_count = mysqli_num_rows($query);
if($email_count){
$email_pass = mysqli_fetch_assoc($query);
$db_pass = $email_pass['password'];
$_SESSION['firstname'] = $email_pass['firstname'];
$pass_decode = password_verify($password, $db_pass);
if($pass_decode){
?>
<script>
location.replace("index.php");
</script>
<?php
}
else{
?>
<script>
alert("Wrong password")
</script>
<?php
}
}else{
?>
<script>
alert("Invalid Email")
</script>
<?php
}
}
?>
<div class="jumbotron jumbotron-fluid">
<div class="container">
<div class="row">
<div
class="col-12 col-sm-8 col-md-6 col-lg-4 offset-sm-2 offset-md-3 offset-lg-4"
>
<h1 class="mb-3 text-center">Login to <br> Wheels R'Us</h1>
<p class="lead">
</p>
<form action="<?php echo htmlentities($_SERVER['PHP_SELF']); ?>" method="POST">
<div class="row">
<div class="form-group">
<label for="email">Email:</label>
<input
type="email"
class="form-control"
placeholder="<EMAIL>"
name = "email"
id="email"
required
/>
</div>
<div class="form-group">
<label for="password">Password:</label>
<input
type="<PASSWORD>"
name = "password"
class="form-control"
id="password"
required
/>
</div>
<button type="submit" name = "submit" class="btn btn-primary btn-block mb-3">
Login
</button>
<div class="text-center">
<a href="registration.php" class="btn btn-success">Signup</a>
</div>
</form>
</div>
</div>
</div>
</div>
<!-- Optional JavaScript -->
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script
src="https://code.jquery.com/jquery-3.2.1.slim.min.js"
integrity="<KEY>"
crossorigin="anonymous"
></script>
<script
src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.3/umd/popper.min.js"
integrity="<KEY>"
crossorigin="anonymous"
></script>
<script
src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/js/bootstrap.min.js"
integrity="<KEY>"
crossorigin="anonymous"
></script>
</body>
</html><file_sep># Hacksprint_PS14_HopelessCoders
Project under HackSprint v3.0 by <NAME>
All the code and presentation of the project given to us will be saved here.
The project was made under 36 hours with having all the functionalities
Here is the demo of the website
https://user-images.githubusercontent.com/82866677/136758864-a79cf2bf-3a18-4ae1-a562-4e8d72e34ac6.mp4
| e44b8067a7e57176f812b902d96d4df4f9d94280 | [
"Markdown",
"PHP"
] | 4 | PHP | gaurav-sarage/Hacksprint_PS14_HopelessCoders | 8350827b853e72d14ca01699e308646c67fc29dc | 34c63e858537df840c707eaba7923fe3a97c65d5 |
refs/heads/master | <file_sep># SWFLoader
A website that plays flash content
http://programistazpolski.ct8.pl/FlashPlayerServer/<br>

### Q&A
Q: Is this a flash player emulator?<br>
A: No, it just downloads a swf file and embeds it into the website.<br><br>
Q: Why PHP?<br>
A: cors-anywhere does not like SWF files.<br><br>
Q: Can i use this after December 2020?<br>
A: As long you have Adobe Flash Player and a compatible browser installed on your PC.<br><br>
Q: How do i get a link to a swf file?
A: Open DevTools in your browser, and navigate to the network tab. Reload the page with your flash program, and find a link to a swf file in there.
<file_sep><?php
// cors-anywhere does not support flash, so i had to resort to this thing.
header('Content-Type: application/x-shockwave-flash');
$url = $_GET['swfURL'];
$resp = file_get_contents($url);
echo $resp;
| 79a57246d2c7085b67de46ce4f0ce88eb3930f8d | [
"Markdown",
"PHP"
] | 2 | Markdown | ProgramistaZpolski/swfloader | c6681fea0d0275361baa321bcc6eb6d67efbe3c3 | 177a037e1657242dfac3ce0b65063e6b72674882 |
refs/heads/master | <repo_name>huiyuandiknow/Cracking_the_coding_interview<file_sep>/array/1.1_IsUnique.py
# Is Unique: implement an algorithm to determine if
# a string has all unique characters. What if you
# cannot use additional data structures?
import sys
def IsUnique(s):
for i in s:
if s.count(i) > 1: return False
return True
if __name__ == '__main__':
input = sys.stdin.readline()
#data = int(input)
print(IsUnique(input))
<file_sep>/array/1.2_CheckPermutation.py
# Check Permutation: Given two strings, write a method
# to decide if one is a permutation of the other
import sys
def perm(s1, s2):
if len(s1) != len(s2):
return False
for i in s1:
if s1.count(i) != s2.count(i):
return False
return True
if __name__ == '__main__':
input = sys.stdin.readline()
data = list(input.strip().split(' '))
print(perm(data[0], data[1]))
<file_sep>/linked lists/1.3_URLify.py
# Given a singly linked list of integers l and an integer k,
# remove all elements from list l that have a value equal to k.
def removeKFromList(l, k):
begin = l
head = True
# check first node
if l is not None:
while l is not None and l.value == k:
l = l.next
begin = l
if l is not None and l.value != k:
while l.next is not None:
if l.next.value == k:
l.next = l.next.next
else:
l = l.next
return begin
<file_sep>/array/firstNotRepeatingCharacter.py
# Given a string s, find and return the first instance of a non-repeating
# char in it. If there is no such char, return '_'.
def firstNotRepeatingCharacter(s):
seen = set(); ignore_list = []
for i in s:
if i in seen:
ignore_list.append(i)
else:
seen.add(i)
for i in s:
if i not in ignore_list:
return i
return '_'
<file_sep>/array/1.4_PalindromePermutation.py
# Palindrome Permutation: Given a string, write a function to check if
# it is a permutation of a palindrome. A palindrome is a word or phrase
# that is the same forwards and backwards. A permutation is a rearrangement
# of letters. The palindrome does not need to be limited to just dictionary
# words.
import sys
def permPalindrome(st):
# remove space
s = st.replace(' ', '').strip()
s = s.lower()
if len(s) % 2 == 0:
for i in s:
if s.count(i) % 2 != 0:
return False
return True
else:
length= []
for i in s:
if s.count(i) % 2 == 0:
length.append(0)
else:
length.append(1)
if sum(length) != 1:
return False
else:
return True
if __name__ == '__main__':
input = sys.stdin.readline()
print(permPalindrome(input))
<file_sep>/array/rotateImage.py
# Given a n x n 2D matrix that represents an image. Rotate the image
# by 90 degree clockwise.
def rotateImage(a):
overall = []
for i in range(len(a)):
current = []
n = len(a)
while n!= 0:
current.append(a[n-1][i])
n-= 1
overall.append(current)
return overall
<file_sep>/array/firstDuplicate.py
# given an array a that contains only numbers in the range from 1 to
# a.length, find the first duplicate number for which the second occurrence
# has the minimal index.
def firstDuplicate(a):
seen=set()
for el in a:
if el in seen:
return el
seen.add(el)
return -1
<file_sep>/array/1.3_URLify.py
# URLify: Write a method to replace all string with '%20'. You may
# assume that the string has sufficient space at the end to hold the
# additional characters, and that you are given the "true" length of
# the string.
import sys
def URLify(s, n):
s = s.strip()
l = list(s.split(' '))
k = ''
num_blank = n - len(l)
for i in l:
if num_blank > 0:
k+= i + '%20'
num_blank -= 1
else:
k+= i
return k
if __name__ == '__main__':
input = sys.stdin.readline()
data = list(input.split(','))
s = data[0][1:]
index = s.index('"')
s = s[:index].strip()
n = int(data[1].strip())
print(URLify(s, n))
| 6e45e7343470cf66a69acfff22595e335d67f65f | [
"Python"
] | 8 | Python | huiyuandiknow/Cracking_the_coding_interview | 0830c8947eec13486f4a1622fa6d0b58779dba45 | 5496ab82dd0772e96282df2689591ea0e1cfab74 |
refs/heads/master | <file_sep>//created in 2016-5-21 by wz
//interval tree (for poj 3468)
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
#define MAX 100100
#define LL long long
#define lson root<<1,l,mid
#define rson root<<1|1,mid+1,r
using namespace std;
int n,q;
LL tree[MAX<<2],add[MAX<<2];
void pushdown(int root,int l){//两个功能:1、将root结点的add加到tree。2、将root结点add下放并清空add
if(l>1){
add[root<<1]+=add[root];
add[root<<1|1]+=add[root];
}
tree[root]+=add[root]*l;
add[root]=0;
}
void pushup(int root,int l){//两个功能:1、将两个子节点的add作用到tree上并下放add。2、将两个子节点的tree赋给root
pushdown(root<<1,l-l/2);
pushdown(root<<1|1,l/2);
tree[root]=tree[root<<1]+tree[root<<1|1];
}
void build(int root,int l,int r){
if(l==r){
scanf("%lld",&tree[root]);
add[root]=0LL;
return;
}
int mid=(l+r)>>1;
build(lson);
build(rson);
pushup(root,r-l+1);
}
void update(int root,int l,int r,int front,int rear,int v){
if(l>=front&&r<=rear){
add[root]+=v;
//tree[root]+=add[root]*(r-l+1);
pushdown(root,r-l+1);
return ;
}
int mid=(l+r)>>1;
pushdown(root,r-l+1);
if(mid>=front)
update(lson,front,rear,v);
if(mid+1<=rear)
update(rson,front,rear,v);
pushup(root,r-l+1);
}
LL query(int root,int l,int r,int front,int rear){
if(l>=front&&r<=rear){
pushdown(root,r-l+1);
return tree[root];
}
int mid=(l+r)>>1;
pushdown(root,r-l+1);
LL ret=0LL;
if(mid>=front)
ret+=query(lson,front,rear);
if(mid+1<=rear)
ret+=query(rson,front,rear);
return ret;
}
int main(){
char com;
int a,b,c;
while(cin>>n>>q){
build(1,1,n);
for(int i=0;i<q;i++){
getchar();
scanf("%c %d %d",&com,&a,&b);
if(com=='C'){
scanf("%d",&c);
update(1,1,n,a,b,c);
}
else
printf("%lld\n",query(1,1,n,a,b));
}
}
return 0;
}
<file_sep># standard-code-library
scl for some algorithms
<file_sep>/*
hdu 1237
simulate easy calculation + - * /
*/
#include<cstdio>
#include<iostream>
#include<cstring>
#include<algorithm>
#include<stack>
#define MAX 210
using namespace std;
char s[MAX];
int l,p;
int command[MAX],com;
/*
+ -11
- -12
* -21
/ -22
*/
void getcommand(){
for(int i=0;i<l;){
int t=0;
if(s[i]>='0'&&s[i]<='9'){
while(i<l&&s[i]>='0'&&s[i]<='9'){
t=t*10+s[i]-'0';
i++;
}
command[com++]=t;
i++;
}
else{
switch(s[i]){
case '+':command[com++]=-11;break;
case '-':command[com++]=-12;break;
case '*':command[com++]=-21;break;
case '/':command[com++]=-22;break;
}
i+=2;
}
}
command[com++]=-11;
}
int main(){
while(gets(s)){
l=strlen(s);
if(l==1&&s[0]=='0')
break;
com=0;
getcommand();
stack<double>para;
stack<int>op;
para.push(0.0);
op.push(-11);
for(int i=0;i<com;i++){
if(command[i]>=0)
para.push(command[i]);
else{
int op1=op.top(),op2=command[i];
while(op2/10>=op1/10){
op.pop();
double para2=para.top();
para.pop();
double para1=para.top();
para.pop();
double temp;
switch(op1){
case -11:temp=para1+para2;break;
case -12:temp=para1-para2;break;
case -21:temp=para1*para2;break;
case -22:temp=para1/para2;break;
}
para.push(temp);
if(op.empty())
break;
op1=op.top();
}
op.push(op2);
}
}
double ans=para.top();
printf("%.2lf\n",ans);
}
return 0;
}
| 45907b949141c2839d7d3a202fd5931bb33394ce | [
"Markdown",
"C++"
] | 3 | C++ | wzbazinga/standard-code-library | b6df60d3dae5c802045befb31d15b8dec41bdc25 | b20134a0b3f442cf415be1689e6bd91dcc86026f |
refs/heads/master | <file_sep>class BackgroundWorker
include Sidekiq::Worker
def perform(patient_id, doctor_id, for_person)
if for_person == 'for_doctor'
UserMailer.with(doctor: doctor_id, patient: patient_id).reminder_email_for_doctor.deliver_later
else
UserMailer.with(doctor: doctor_id, patient: patient_id).reminder_email_for_patient.deliver_later
end
end
end<file_sep>class WelcomeController < ApplicationController
def index
if user_signed_in?
if current_user.is_doctor
# Fetch appointment here and display it on ui
@appointments = Appointment.all.where(doctor_id: current_user.id)
render "patients/appointments"
else
@doctors = User.where(is_doctor: true)
@appointments = Appointment.all.where(patient_id: current_user.id)
render "doctors/listing"
end
end
end
def book
doctor = User.find(params[:doc_id])
patient = User.find(params[:user_id])
if !Appointment.where(doctor_id: doctor.id, patient_id: patient.id).present?
Appointment.create(doctor_id: doctor.id, patient_id: patient.id)
BackgroundWorker.perform_at(4.hours.from_now, current_user.id, doctor.id, 'for_patient')
BackgroundWorker.perform_at(4.hours.from_now, current_user.id, doctor.id, 'for_doctor')
redirect_to :root
else
redirect_to :root, notice: "You already have appointment"
end
end
def cancel
doctor = User.find(params[:doc_id])
patient = User.find(params[:user_id])
appointment = Appointment.find_by(doctor_id: doctor.id, patient_id: patient.id)
if appointment.created_at + 1.hour > DateTime.now
appointment.destroy
redirect_to :root
else
redirect_to :root, notice: "You can not cancel this appointment"
end
end
def cancel_by_doctor
doctor = User.find(params[:doc_id])
patient = User.find(params[:user_id])
appointment = Appointment.find_by(doctor_id: doctor.id, patient_id: patient.id)
appointment.destroy
redirect_to :root
end
def accept_by_doctor
doctor = User.find(params[:doc_id])
patient = User.find(params[:user_id])
appointment = Appointment.find_by(doctor_id: doctor.id, patient_id: patient.id)
appointment.accepted = true
appointment.accepted_by = current_user.id
appointment.save
redirect_to :root
end
end
<file_sep>class AddAcceptedToAppointment < ActiveRecord::Migration[5.2]
def change
add_column :appointments, :accepted, :boolean, default: false
add_column :appointments, :accepted_by, :string
end
end
<file_sep>class UserMailer < ApplicationMailer
default from: '<EMAIL>'
def reminder_email_for_doctor(doctor_id, patient_id)
@doctor = User.find(doctor_id)
@patient = User.find(patient_id)
@url = 'http://example.com/login'
mail(to: @doctor.email, subject: 'Reminder of Appointment')
end
def reminder_email_for_patient(doctor_id, patient_id)
@doctor = User.find(doctor_id)
@patient = User.find(patient_id)
@url = 'http://example.com/login'
mail(to: @patient.email, subject: 'Reminder of Appointment')
end
end<file_sep># README
Rails version - Rails 5.2.4.3
Ruby version - ruby 2.5.1p57
rails db:create
rails db:migrate
rails s
start redis
start sidekiq
Create doctors account
Create patients account
Note: If you want to send email then you have to config it from "development.rb" or "production.rb".<file_sep>module WelcomeHelper
def get_doctor_email(doc_id)
User.find(doc_id).email
end
def get_doctor_username(doc_id)
User.find(doc_id).username
end
def get_patient_email(pat_id)
User.find(pat_id).email
end
def get_patient_username(pat_id)
User.find(pat_id).username
end
end
<file_sep>class AddisDoctorisAdminToUsers < ActiveRecord::Migration[5.2]
def change
add_column :users, :is_doctor, :boolean, default: false
add_column :users, :is_admin, :boolean, default: false
add_column :users, :username, :string
end
end
| cb3e1f395edbc2ea9970a35fe5dc10f3e588d56b | [
"Markdown",
"Ruby"
] | 7 | Ruby | kishangit/sample | 03d2c9ee6553e3281581c769d706a46ba4cf7944 | a1efc2a23c346799e448381dce577cc19ab7882b |
refs/heads/master | <repo_name>liuminjie1willturnpositive/iFantasy<file_sep>/app/controller/user.py
from flask import Blueprint, jsonify
from flask_restful import Api, Resource, reqparse
from .utils import MobSMS
from ..config import sms_key
user_bp = Blueprint("user_bp",__name__)
user_api = Api(user_bp)
parse = reqparse.RequestParser()
parse.add_argument('phone',type=str)
parse.add_argument('code',type=str)
parse.add_argument('zone',type=str)
class UserApi(Resource):
def post(self):
args = parse.parse_args(strict=True)
phone = args['phone']
code = args['code']
zone = args['zone']
res = MobSMS(sms_key).verify_sms_code(zone,phone,code)
if res == 200:
return jsonify({'resutl':'ok'})
else:
return jsonify({'result':'no'})
user_api.add_resource(UserApi,'/user')
<file_sep>/venv/lib/python3.6/os.py
/home/xdzwk/anaconda3/lib/python3.6/os.py<file_sep>/venv/lib/python3.6/token.py
/home/xdzwk/anaconda3/lib/python3.6/token.py<file_sep>/venv/lib/python3.6/heapq.py
/home/xdzwk/anaconda3/lib/python3.6/heapq.py<file_sep>/app/controller/__init__.py
from app.controller.game import game_bp
#from app.controller.activity import activity_bp
from app.controller.bag import bag_bp
from app.controller.chat import chat_bp
from app.controller.recruit import recruit_bp
from app.controller.tactics import tactics_bp
from app.controller.team import team_bp
from app.controller.user import user_bp
from .activity import activity_bp<file_sep>/venv/lib/python3.6/__future__.py
/home/xdzwk/anaconda3/lib/python3.6/__future__.py<file_sep>/venv/lib/python3.6/bisect.py
/home/xdzwk/anaconda3/lib/python3.6/bisect.py<file_sep>/app/config.py
sms_key = "24be6ffdbdc18"
BASE = "mysql+pymysql://team1:12345qwert@192.168.0.{0}:3306/team1"
READ_DATABASE = BASE.format(250)
WRITE_DATABASE = BASE.format(251)
class Config:
SECRET_KEY = "miyao"
SQLALCHEMY_DATABASE_URI = "mysql+pymysql://root:zwk19950102@localhost:3306/nba" #WRITE_DATABASE
class DeveploeConfig(Config):
DEBUG = True
class ReleaseConfig(Config):
DEBUG=False
config = {
'develop':DeveploeConfig,
'release':ReleaseConfig
}<file_sep>/app/controller/bag.py
from flask import Blueprint
from flask_restful import Api, Resource
bag_bp = Blueprint('bag_bp',__name__)
bag_api = Api(bag_bp)
#your code<file_sep>/venv/lib/python3.6/io.py
/home/xdzwk/anaconda3/lib/python3.6/io.py<file_sep>/venv/lib/python3.6/ntpath.py
/home/xdzwk/anaconda3/lib/python3.6/ntpath.py<file_sep>/venv/lib/python3.6/linecache.py
/home/xdzwk/anaconda3/lib/python3.6/linecache.py<file_sep>/venv/lib/python3.6/stat.py
/home/xdzwk/anaconda3/lib/python3.6/stat.py<file_sep>/venv/lib/python3.6/copy.py
/home/xdzwk/anaconda3/lib/python3.6/copy.py<file_sep>/venv/lib/python3.6/hashlib.py
/home/xdzwk/anaconda3/lib/python3.6/hashlib.py<file_sep>/venv/lib/python3.6/imp.py
/home/xdzwk/anaconda3/lib/python3.6/imp.py<file_sep>/venv/lib/python3.6/tarfile.py
/home/xdzwk/anaconda3/lib/python3.6/tarfile.py<file_sep>/venv/lib/python3.6/re.py
/home/xdzwk/anaconda3/lib/python3.6/re.py<file_sep>/app/controller/recruit.py
from flask import Blueprint
from flask_restful import Api, Resource
recruit_bp = Blueprint('recruit_bp',__name__)
recruit_api = Api(recruit_bp)
#your code<file_sep>/test/test.py
from flask import Flask, Blueprint, request
from flask_restful import Api, Resource, url_for
app = Flask(__name__)
@app.route("/api/v1/login",methods=['POST'])
def login():
phone = request.get_json().get('phone')
zone = request.get_json().get('zone')
code = request.get_json().get('code')
api.add_resource(TodoItem, '/todos/<int:id>')
app.register_blueprint(api_bp,url_prefix='/api')
app.run(debug=True)<file_sep>/venv/lib/python3.6/abc.py
/home/xdzwk/anaconda3/lib/python3.6/abc.py<file_sep>/venv/lib/python3.6/warnings.py
/home/xdzwk/anaconda3/lib/python3.6/warnings.py<file_sep>/venv/lib/python3.6/sre_compile.py
/home/xdzwk/anaconda3/lib/python3.6/sre_compile.py<file_sep>/venv/lib/python3.6/locale.py
/home/xdzwk/anaconda3/lib/python3.6/locale.py<file_sep>/venv/lib/python3.6/_dummy_thread.py
/home/xdzwk/anaconda3/lib/python3.6/_dummy_thread.py<file_sep>/venv/lib/python3.6/tempfile.py
/home/xdzwk/anaconda3/lib/python3.6/tempfile.py<file_sep>/app/__init__.py
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from .config import config
db = SQLAlchemy()
api_version = 'v1'
def create_app(config_name):
app = Flask(__name__)
app.config.from_object(config[config_name])
db.init_app(app)
from app.controller import user_bp, bag_bp, game_bp, \
tactics_bp, team_bp, activity_bp, chat_bp,recruit_bp
app.register_blueprint(user_bp, url_prefix='/api/v1/user')
app.register_blueprint(game_bp, url_prefix="/api/v1/game")
app.register_blueprint(bag_bp, url_prefix="/api/v1/bag")
app.register_blueprint(tactics_bp, url_prefix="/api/v1/tactics")
app.register_blueprint(team_bp, url_prefix="/api/v1/team")
app.register_blueprint(activity_bp, url_prefix="/api/v1/activity")
app.register_blueprint(chat_bp, url_prefix="/api/v1/chat")
app.register_blueprint(recruit_bp, url_prefix="recruit")
return app<file_sep>/venv/lib/python3.6/sre_parse.py
/home/xdzwk/anaconda3/lib/python3.6/sre_parse.py<file_sep>/venv/lib/python3.6/genericpath.py
/home/xdzwk/anaconda3/lib/python3.6/genericpath.py<file_sep>/venv/lib/python3.6/types.py
/home/xdzwk/anaconda3/lib/python3.6/types.py<file_sep>/README.md
# iFantasy
XDU 2014 software school
进度:
3.26 database model Done
<file_sep>/venv/lib/python3.6/_bootlocale.py
/home/xdzwk/anaconda3/lib/python3.6/_bootlocale.py<file_sep>/venv/lib/python3.6/functools.py
/home/xdzwk/anaconda3/lib/python3.6/functools.py<file_sep>/venv/lib/python3.6/sre_constants.py
/home/xdzwk/anaconda3/lib/python3.6/sre_constants.py<file_sep>/venv/lib/python3.6/keyword.py
/home/xdzwk/anaconda3/lib/python3.6/keyword.py<file_sep>/venv/lib/python3.6/struct.py
/home/xdzwk/anaconda3/lib/python3.6/struct.py<file_sep>/venv/lib/python3.6/weakref.py
/home/xdzwk/anaconda3/lib/python3.6/weakref.py<file_sep>/venv/lib/python3.6/tokenize.py
/home/xdzwk/anaconda3/lib/python3.6/tokenize.py<file_sep>/venv/lib/python3.6/operator.py
/home/xdzwk/anaconda3/lib/python3.6/operator.py<file_sep>/app/controller/activity.py
from flask import Blueprint
from flask_restful import Api, Resource
activity_bp = Blueprint('activity_bp',__name__)
activity_api = Api(activity_bp)
#your code
<file_sep>/app/controller/team.py
from flask import Blueprint
from flask_restful import Api, Resource
team_bp = Blueprint("team_bp",__name__)
team_api = Api(team_bp)
<file_sep>/venv/lib/python3.6/fnmatch.py
/home/xdzwk/anaconda3/lib/python3.6/fnmatch.py<file_sep>/venv/lib/python3.6/codecs.py
/home/xdzwk/anaconda3/lib/python3.6/codecs.py<file_sep>/venv/lib/python3.6/posixpath.py
/home/xdzwk/anaconda3/lib/python3.6/posixpath.py<file_sep>/venv/lib/python3.6/shutil.py
/home/xdzwk/anaconda3/lib/python3.6/shutil.py<file_sep>/venv/lib/python3.6/reprlib.py
/home/xdzwk/anaconda3/lib/python3.6/reprlib.py<file_sep>/venv/lib/python3.6/base64.py
/home/xdzwk/anaconda3/lib/python3.6/base64.py<file_sep>/venv/lib/python3.6/_collections_abc.py
/home/xdzwk/anaconda3/lib/python3.6/_collections_abc.py<file_sep>/venv/lib/python3.6/_weakrefset.py
/home/xdzwk/anaconda3/lib/python3.6/_weakrefset.py<file_sep>/venv/lib/python3.6/rlcompleter.py
/home/xdzwk/anaconda3/lib/python3.6/rlcompleter.py<file_sep>/app/controller/game.py
from flask import Blueprint
from flask_restful import Api, Resource
game_bp = Blueprint('game_bp',__name__,static_folder="../static/game")
game_api = Api(game_bp)<file_sep>/venv/lib/python3.6/copyreg.py
/home/xdzwk/anaconda3/lib/python3.6/copyreg.py<file_sep>/venv/lib/python3.6/hmac.py
/home/xdzwk/anaconda3/lib/python3.6/hmac.py<file_sep>/app/controller/tactics.py
from flask import Blueprint
from flask_restful import Api, Resource
tactics_bp = Blueprint("tactics_bp",__name__)
tactics_api = Api(tactics_bp)
<file_sep>/venv/lib/python3.6/enum.py
/home/xdzwk/anaconda3/lib/python3.6/enum.py<file_sep>/venv/lib/python3.6/random.py
/home/xdzwk/anaconda3/lib/python3.6/random.py | d02f4c6fbce98cabc3053729811608e63301e33c | [
"Markdown",
"Python"
] | 56 | Python | liuminjie1willturnpositive/iFantasy | 9eabb9069ad1b4c450e120e995cfeffd3e8ec785 | 7216b619e780af48fbd713c02aa0e9d910ddeb40 |
refs/heads/master | <repo_name>thesides/TriviaGame<file_sep>/assets/javascript/app.js
//Global var declarations
//an array to hold 4 questions
var intervalId;
var clockRunning = false;
var firstQuestion;
var userGuess;
var guessed = false;
var computerGuess;
var end;
var correctGuesses = 0;
var wrongGuesses = 0;
var alreadyAnswered = false;
//an object for each question with a key:value pairing aka question/answer pairing; need 3 dummy pairings for each (aka possible wrong answers)
var question1 = {
question: "What is the distance from the Earth to the Moon?",
a1: "51, 006 miles",
a2: "332,236 miles",
a3: "157,200 miles",
a4: "238,900 miles"
};
var question2 = {
question: "What is the distance from Austin to Houston?",
a1: "165 miles",
a2: "202 miles",
a3: "176 miles",
a4: "133 miles"
};
var question4 = {
question: "What is the distance from point A to point B",
a1: "100",
a2: "200",
a3: "300",
a4: "400"
};
var question3 = {
question: "end",
a1: "end",
a2: "end",
a3: "end",
a4: "end"
}
var wordAtPlay = [question1, question2, question3, question4];
//when the user presses play start the clock
window.onload = function() {
$("#play").click(clock.start)
$("#play").click(displayQuestion);
};
//record what the user guesses and calls the validation function
$(".list-group-item").on("click", function recordVote(){
if (clockRunning === true && firstQuestion != wordAtPlay.length){ //Need to add an && that prevents the user from selecting more than one answer
userGuess = $(this).html()
console.log(userGuess)
clock.loadNext();
clock.reset();
}
else if (firstQuestion === wordAtPlay.length){
clock.endGame();
}
validate();
});
//validate answers; still cannot get it to track correct v. incorrect answers; trying to assign it to a specific object value
function validate (){
if (userGuess === computerGuess.a1){
correctGuesses++
console.log("Right: " + correctGuesses);
}
else {
wrongGuesses++
console.log("Wrong: " + wrongGuesses);
}
}
function displayQuestion () {
if (clockRunning = true){
computerGuess = wordAtPlay[0];
firstQuestion = wordAtPlay.indexOf(computerGuess);
$("#question").html(computerGuess.question);
$("#answerA").html(computerGuess.a1);
$("#answerB").html(computerGuess.a2);
$("#answerC").html(computerGuess.a3);
$("#answerD").html(computerGuess.a4);
}
else {
alert();
}
}
var clock = {
time: 5,
reset: function() {
clock.time = 5;
$("#currentTime").html("00:05");
},
start: function() {
if (!clockRunning) {
clockRunning = true;
intervalId = setInterval(clock.count, 1000);
}
},
count: function() {
if (clock.time != 0){
clock.time--
//console.log(clock.time)
$("#currentTime").html(clock.timeConverter(clock.time));
}
else if (clock.time === 0 && firstQuestion != wordAtPlay.length){
clock.reset();
clock.loadNext();
}
else if (computerGuess === wordAtPlay[4]) {
clockRunning = false;
clock.endGame();
//clock.start();
}
},
timeConverter: function(t) {
// Takes the current time in seconds and convert it to minutes and seconds (mm:ss).
var minutes = Math.floor(t / 60);
var seconds = t - (minutes * 60);
if (seconds < 10) {
seconds = "0" + seconds;
}
if (minutes === 0) {
minutes = "00";
}
else if (minutes < 10) {
minutes = "0" + minutes;
}
return minutes + ":" + seconds;
},
loadNext: function() {
firstQuestion++;
if(firstQuestion === wordAtPlay.length){
alert()
}
else {
computerGuess = wordAtPlay[firstQuestion++];
$("#question").html(computerGuess.question);
$("#answerA").html(computerGuess.a1);
$("#answerB").html(computerGuess.a2);
$("#answerC").html(computerGuess.a3);
$("#answerD").html(computerGuess.a4);
}
},
//temporarily using an alert to end the game and show # of right/wrong guesses
endGame: function (){
alert("Wrong: " + wrongGuesses + " Right: " + correctGuesses);
}
};
//Still Need to:
//1) have a restart function that doesn't just use an alert to break the game
//2) fix validation of answers so that it can check the userGuess against the correct object value
//3) fix answer button click event so the user can only select one answer
| d8626f8650c33763829426911557aa6848a9375e | [
"JavaScript"
] | 1 | JavaScript | thesides/TriviaGame | 12c4acb859c9eafe59fe6933b942951698b021c5 | 9da848f53359a477758f86ad36b496fe9145fdc7 |
refs/heads/master | <repo_name>Isidore-Newman-School/reflectionsNOMA<file_sep>/_site/js/sketchTrym.js
var video;
var vidW = 640;
var vidH = 480;
var vidX = 0;
var vidY = 300;
var vScale = 20;
var runningArray = [];
var flag_Algerian;
var flag_American;
var flag_Argentinian;
var flag_Austrian;
var flag_Bahamas;
var flag_Bangladesh;
var flag_Belgium;
var flag_Bhutan;
var flag_Brazil;
var flag_Canada;
var flag_Chile;
var flag_China;
var flag_Columbia;
var flag_Croatia;
var flag_Cuba;
var flag_Cyprus;
var flag_Czech;
var flag_Danish;
var flag_English;
var flag_Estonian;
var flag_Finland;
var flag_French;
var flag_Georgia;
var flag_German;
var flag_Greek;
var flag_Iceland;
var flag_India;
var flag_Indonesia;
var flag_Ireland;
var flag_Israel;
var flag_Italian;
var flag_Jamaican;
var flag_Japanese;
var flag_Kenyan;
var flag_Kuwait;
var flag_Lebanese;
var flag_Lesotho;
var flag_Libya;
var flag_Luxembourg;
var flag_Malta;
var flag_Nepal;
var flag_Nigeria;
var flag_North_Korea;
var flag_Norway;
var flag_Panama;
var flag_Poland;
var flag_Portugal;
var flag_Qatar;
var flag_Saudi_Arabia;
var flag_Seychelles;
var flag_South_Africa;
var flag_South_Korean;
var flag_Spain;
var flag_Swedish;
var flag_Swiss;
var flag_Thai;
var flag_Trinidad;
var flag_Tunisia;
var flag_Turkey;
var flag_UAE;
var flag_Venezuela;
var flag_Vietnam;
var flag_Yemen;
var flag_Zambia;
var flag_Zimbabwe;
var flagArray;
var flagQuestion = prompt("What is your favorite country?");
var flagObj;
var lastChecked = 0;
var ind = 0;
function preload(){
flag_Algerian = loadImage("assets/Algerian_Flag_Emoji.PNG");
flag_American = loadImage("assets/American_Flag_Emoji.PNG");
flag_Argentinian = loadImage("assets/Argentinian_Flag_Emoji.PNG");
flag_Austrian = loadImage("assets/Austrian_Flag_Emoji.PNG");
flag_Bahamas = loadImage("assets/Bahamas_Flag_Emoji.PNG");
flag_Bangladesh = loadImage("assets/Bangladesh_Flag_Emoji.PNG");
flag_Belgium = loadImage("assets/Belgium_Flag_Emoji.PNG");
flag_Bhutan = loadImage("assets/Bhutan_Flag_Emoji.PNG");
flag_Brazil = loadImage("assets/Brazilian_Flag_Emoji.PNG");
flag_Canada = loadImage("assets/Canadian_Flag_Emoji.PNG");
flag_Chile = loadImage("assets/Chilean_Flag_Emoji.PNG");
flag_China = loadImage("assets/Chinese_Flag_Emoji.PNG");
flag_Columbia = loadImage("assets/Columbian_Flag_Emoji.PNG");
flag_Croatia = loadImage("assets/Croatian_Flag_Emoji.PNG");
flag_Cuba = loadImage("assets/Cuban_Flag_Emoji.PNG");
flag_Cyprus = loadImage("assets/Cyrpus'_Flag_Emoji.PNG");
flag_Czech = loadImage("assets/Czech_Republic's_Flag_Emoji.PNG");
flag_Danish = loadImage("assets/Danish_Flag_Emoji.PNG");
flag_English = loadImage("assets/English_Flag_Emoji.PNG");
flag_Estonian = loadImage("assets/Estonian_Flag_Emoji.PNG");
flag_Finland = loadImage("assets/Finland's_Flag_Emoji.PNG");
flag_French = loadImage("assets/French_Flag_Emoji.PNG");
flag_Georgia = loadImage("assets/Georgian_Flag_Emoji.PNG");
flag_German = loadImage("assets/German_Flag_Emoji.PNG");
flag_Greek = loadImage("assets/Greek_Flag_Emoji.PNG");
flag_Iceland = loadImage("assets/Icelandic_Flag_Emoji.PNG");
flag_India = loadImage("assets/Indian_Flag_Emoji.PNG");
flag_Indonesia = loadImage("assets/Indonesian_Flag_Emoji.PNG");
flag_Ireland = loadImage("assets/Ireland's_Flag_Emoji.PNG");
flag_Israel = loadImage("assets/Israel's_Flag_Emoji.PNG");
flag_Italian = loadImage("assets/Italian_Flag_Emoji.PNG");
flag_Jamaican = loadImage("assets/Jamaican_Flag_Emoji.PNG");
flag_Japanese = loadImage("assets/Japanese_Flag_Emoji.PNG");
flag_Kenyan = loadImage("assets/Kenyan_Flag_Emoji.PNG");
flag_Kuwait = loadImage("assets/Kuwait_Flag_Emoji.PNG");
flag_Lebanese = loadImage("assets/Lebanese_Flag_Emoji.PNG");
flag_Lesotho = loadImage("assets/Lesotho_Flag_Emoji.PNG");
flag_Libya = loadImage("assets/Libyan_Flag_Emoji.PNG");
flag_Luxembourg = loadImage("assets/Luxembourg_Flag_Emoji.PNG");
flag_Malta = loadImage("assets/Maltan_Flag_Emoji.PNG");
flag_Nepal = loadImage("assets/Nepal's_Flag_Emoji.PNG");
flag_Nigeria = loadImage("assets/Nigerian_Flag_Emoji.PNG");
flag_North_Korea = loadImage("assets/North_Korean_Flag_Emoji.PNG");
flag_Norway = loadImage("assets/Norwegian_Flag_Emoji.PNG");
flag_Panama = loadImage("assets/Panama_Flag_Emoji.PNG");
flag_Poland = loadImage("assets/Polish_Flag_Emoji.PNG");
flag_Portugal = loadImage("assets/Portuguese_Flag_Emoji.PNG");
flag_Qatar = loadImage("assets/Qatar_Flag_Emoji.PNG");
flag_Saudi_Arabia = loadImage("assets/Saudi_Arabian_Flag_Emoji.PNG");
flag_Seychelles = loadImage("assets/Seychelles_Flag_Emoji.PNG");
flag_South_Africa = loadImage("assets/South_African_Flag_Emoji.PNG");
flag_South_Korean = loadImage("assets/South_Korean_Flag_Emoji.PNG");
flag_Spain = loadImage("assets/Spanish_Flag_Emoji.PNG");
flag_Swedish = loadImage("assets/Swedish_Flag_Emoji.PNG");
flag_Swiss = loadImage("assets/Swiss_Flag_Emoji.PNG");
flag_Thai = loadImage("assets/Thai_Flag_Emoji.PNG");
flag_Trinidad = loadImage("assets/Trinidad_and_Tobago_Flag_Emoji.PNG");
flag_Tunisia = loadImage("assets/Tunisian_Flag_Emoji.PNG");
flag_Turkey = loadImage("assets/Turkey_Flag_Emoji.PNG");
flag_UAE = loadImage("assets/UAE_Flag_Emoji.PNG");
flag_Venezuela = loadImage("assets/Venezuelan_Flag_Emoji.PNG");
flag_Vietnam = loadImage("assets/Vietnamese_Flag_Emoji.PNG");
flag_Yemen = loadImage("assets/Yemen_Flag_Emoji.PNG");
flag_Zambia = loadImage("assets/Zambian_Flag_Emoji.PNG");
flag_Zimbabwe = loadImage("assets/Zimbabwe_Flag_Emoji.PNG");
// flag_Algerian.resize(vScale, vScale);
// flag_American.resize(vScale, vScale);
// flag_Argentinian.resize(vScale, vScale);
// flag_Austrian.resize(vScale, vScale);
// flag_Bahamas.resize(vScale, vScale);
// flag_Bangladesh.resize(vScale, vScale);
// flag_Belgium.resize(vScale, vScale);
// flag_Bhutan.resize(vScale, vScale);
// flag_Brazil.resize(vScale, vScale);
// flag_Canada.resize(vScale, vScale);
// flag_Chile.resize(vScale, vScale);
// flag_China.resize(vScale, vScale);
// flag_Columbia.resize(vScale, vScale);
// flag_Croatia.resize(vScale, vScale);
// flag_Cuba.resize(vScale, vScale);
// flag_Cyprus.resize(vScale, vScale);
// flag_Czech.resize(vScale, vScale);
// flag_Danish.resize(vScale, vScale);
// flag_English.resize(vScale, vScale);
// flag_Estonian.resize(vScale, vScale);
// flag_Finland.resize(vScale, vScale);
// flag_French.resize(vScale, vScale);
// flag_Georgia.resize(vScale, vScale);
// flag_German.resize(vScale, vScale);
// flag_Greek.resize(vScale, vScale);
// flag_Iceland.resize(vScale, vScale);
// flag_India.resize(vScale, vScale);
// flag_Indonesia.resize(vScale, vScale);
// flag_Ireland.resize(vScale, vScale);
// flag_Israel.resize(vScale, vScale);
// flag_Italian.resize(vScale, vScale);
// flag_Jamaican.resize(vScale, vScale);
// flag_Japanese.resize(vScale, vScale);
// flag_Kenyan.resize(vScale, vScale);
// flag_Kuwait.resize(vScale, vScale);
// flag_Lebanese.resize(vScale, vScale);
// flag_Lesotho.resize(vScale, vScale);
// flag_Libya.resize(vScale, vScale);
// flag_Luxembourg.resize(vScale, vScale);
// flag_Malta.resize(vScale, vScale);
// flag_Nepal.resize(vScale, vScale);
// flag_Nigeria.resize(vScale, vScale);
// flag_North_Korea.resize(vScale, vScale);
// flag_Norway.resize(vScale, vScale);
// flag_Panama.resize(vScale, vScale);
// flag_Poland.resize(vScale, vScale);
// flag_Portugal.resize(vScale, vScale);
// flag_Qatar.resize(vScale, vScale);
// flag_Saudi_Arabia.resize(vScale, vScale);
// flag_Seychelles.resize(vScale, vScale);
// flag_South_Africa.resize(vScale, vScale);
// flag_South_Korean.resize(vScale, vScale);
// flag_Spain.resize(vScale, vScale);
// flag_Swedish.resize(vScale, vScale);
// flag_Swiss.resize(vScale, vScale);
// flag_Thai.resize(vScale, vScale);
// flag_Trinidad.resize(vScale, vScale);
// flag_Tunisia.resize(vScale, vScale);
// flag_Turkey.resize(vScale, vScale);
// flag_UAE.resize(vScale, vScale);
// flag_Venezuela.resize(vScale, vScale);
// flag_Vietnam.resize(vScale, vScale);
// flag_Yemen.resize(vScale, vScale);
// flag_Zambia.resize(vScale, vScale);
// flag_Zimbabwe.resize(vScale, vScale);
}
function setup() {
vidX = (windowWidth - vidW) / 2;
canvas = createCanvas(640, 480);
canvas.position(vidX, vidY);
pixelDensity(1);
video = createCapture(VIDEO);
video.size(64, 48);
video.id("video");
video.hide();
flagObj = new Flags();
flagObj.shuffleFlags();
setName();
}
function draw() {
background(0);
flagObj.display();
if(millis() - lastChecked > 3500){
flagObj.shuffleFlags();
lastChecked = millis();
//ind++;
}
}
function Flags(){
this.flagArray = [flag_Algerian, flag_American, flag_Argentinian, flag_Austrian, flag_Bahamas, flag_Bangladesh, flag_Belgium, flag_Bhutan, flag_Brazil, flag_Canada, flag_Chile, flag_China, flag_Columbia, flag_Croatia, flag_Cuba, flag_Cyprus, flag_Czech, flag_Danish, flag_English, flag_Estonian, flag_Finland, flag_French, flag_Georgia, flag_German, flag_Greek, flag_Iceland, flag_India, flag_Indonesia, flag_Ireland, flag_Israel, flag_Italian, flag_Jamaican, flag_Japanese, flag_Kenyan, flag_Kuwait, flag_Lebanese, flag_Lesotho, flag_Libya, flag_Luxembourg, flag_Malta, flag_Nepal, flag_Nigeria, flag_North_Korea, flag_Norway, flag_Panama, flag_Poland, flag_Portugal, flag_Qatar, flag_Saudi_Arabia, flag_Seychelles, flag_South_Africa, flag_South_Korean, flag_Spain, flag_Swedish, flag_Swiss, flag_Thai, flag_Trinidad, flag_Tunisia, flag_Turkey, flag_UAE, flag_Venezuela, flag_Vietnam, flag_Yemen, flag_Zambia, flag_Zimbabwe];
this.currentFlags = [0, 0, 0, 0, 0];
this.shuffleFlags = function() {
this.currentFlags[0] = getFirstFlag();
for(var i = 1; i < this.currentFlags.length; i++) {
this.currentFlags[i] = floor(random(this.flagArray.length));
}
}
this.display = function(){
video.loadPixels();
//loadPixels();
if (video.pixels.length > 0) {
for (var y = 0; y < 48; y++) {
for (var x = 0; x < 64; x++) {
var index = (64 - x - 1 + (y * 64))*4;
var r = video.pixels[index+0];
var g = video.pixels[index+1];
var b = video.pixels[index+2];
var average = (r + g + b) / 3;
var maxV = this.currentFlags.length - 1;
var flagIndex = constrain(floor(map(average,0, 255, 0, maxV+3)), 0, maxV);
rectMode(CENTER);
// console.log(flagIndex, this.flagArray[this.currentFlags[flagIndex]]);
image(this.flagArray[this.currentFlags[flagIndex]], x*vScale, y*vScale,vScale, vScale);
//image(this.flagArray[ind%this.flagArray.length], x*vScale, y*vScale);
//image(this.flagArray[this.currentFlags[0]], x*vScale, y*vScale,vScale, vScale);
}
}
}
}
}
function getFirstFlag() {
if (flagQuestion === "") return 1;
flagQuestion = flagQuestion.charAt(0).toUpperCase() + flagQuestion.slice(1);
// this.flagArray = [flag_Algerian, flag_American, flag_Argentinian, flag_Austrian, flag_Bahamas, flag_Bangladesh, flag_Belgium, flag_Bhutan, flag_Brazil, flag_Canada, flag_Chile, flag_China, flag_Columbia, flag_Croatia, flag_Cuba, flag_Cyprus, flag_Czech, flag_Danish, flag_English, flag_Estonian, flag_Finland, flag_French, flag_Georgia, flag_German, flag_Greek, flag_Iceland, flag_India, flag_Indonesia, flag_Ireland, flag_Israel, flag_Italian, flag_Jamaican, flag_Japanese, flag_Kenyan, flag_Kuwait, flag_Lebanese, flag_Lesotho, flag_Libya, flag_Luxembourg, flag_Malta, flag_Nepal, flag_Nigeria, flag_North_Korea, flag_Norway, flag_Panama, flag_Poland, flag_Portugal, flag_Qatar, flag_Saudi_Arabia, flag_Seychelles, flag_South_Africa, flag_South_Korean, flag_Spain, flag_Swedish, flag_Swiss, flag_Thai, flag_Trinidad, flag_Tunisia, flag_Turkey, flag_UAE, flag_Venezuela, flag_Vietnam, flag_Yemen, flag_Zambia, flag_Zimbabwe];
var countries = ["Algeria", "America", "Argentina", "Austria", "Bahamas", "Banglagesh", "Belgium", "Bhutan", "Brazil", "Canada","Chile", "China", "Columbia","Croatia","Cuba", "Cyprus", "Czech Republic", "Denmark", "United Kingdom","Estonia", "Finland", "France","Georgia", "Germany", "Greece", "Iceland", "India", "Indonesia", "Ireland","Israel", "Italy","Jamaica","Japan","Kenya", "Kuwait","Lebanon", "Lesotho", "Libya","Luxembourg","Malta","Nepal","Nigeria","North Korea","Norway","Panama", "Poland","Portugal","Qatar", "Saudi Arabia","Seychelles","South Africa","South Korea","Spain","Sweden","Switzerland" ,"Thailand","Trinidad", "Tunisia","Turkey","UAE","Venezuela","Vietnam","Yemen","Zambia", "Zimbabwe"];
var flag = countries.indexOf(flagQuestion);
if(flag === -1) return 1;
console.log("flag:", flag, countries[flag]);
return flag;
}
function setName() {
// textSize(30);
// var n = names[currentEffect];
// text("by " + n, (width - textWidth(n)) / 2, 40);
nameDiv = select("#nameDiv");
nameDiv.html("<NAME>");
}
<file_sep>/js/sketchNicholas.js
var points = [];
var canvasP5;
var videoP5;
var vidW = 640;
var vidH = 480;
var vidX = 0;
var vidY = 300;
var img;
function setup() {
vidX = (windowWidth - vidW) / 2;
videoP5 = createCapture(VIDEO);
videoP5.id("video");
videoP5.size(vidW, vidH);
videoP5.position(vidX, vidY);
canvasP5 = createCanvas(vidW, vidH);
canvasP5.position(vidX, vidY);
var tracker = new tracking.LandmarksTracker();
tracker.setInitialScale(4);
tracker.setStepSize(2);
tracker.setEdgesDensity(0.1);
tracking.track('#video', tracker, { camera: true });
tracker.on('track', function(event) {
if(!event.data) return;
event.data.landmarks.forEach(function(landmarks) {
points = [];
for(var l in landmarks){
points.push({x: landmarks[l][0], y: landmarks[l][1]});
}
});
});
// load image here
img = loadImage("assets/hand.png");
setName();
}
function draw() {
image(videoP5, 0, 0);
fill(255, 0, 0);
// for (var i = 0; i < points.length; i++) {
// text(i, points[i].x, points[i].y);
// }
// image is placed
if (points.length > 24) {
image(img, vidW, points[7].y - 20);
if (vidW > points[7].x - 100) {
vidW -= 20;
} else if (vidW < points[7].x - 100) {
vidW = points[7].x - 100;
textSize(30)
text("YOU'VE BEEN SLAPPED", vidW/10, vidH/10)
}
}
}
function setName() {
// textSize(30);
// var n = names[currentEffect];
// text("by " + n, (width - textWidth(n)) / 2, 40);
nameDiv = select("#nameDiv");
nameDiv.html("<NAME>");
}
| b4830649f792c92f4d6e807682b930a9e5bcb35b | [
"JavaScript"
] | 2 | JavaScript | Isidore-Newman-School/reflectionsNOMA | 8cde2db104e5272e03ab83374dbf4f92d9c30ebb | fd4aeb85398fc377d118a4e540927d771bc7bd89 |
refs/heads/master | <repo_name>davidyoon85/goodreads<file_sep>/src/components/Pagination.js
import React from "react";
const Pagination = ({ currentPage, results, nextPage, prevPage }) => (
<div className="pagination">
<button className="pagination-button" type="button" onClick={prevPage}>
<
</button>
<div className="pagination-dashboard">
<p>
Page {currentPage} of {Math.ceil(results / 20) || 1}
</p>
<p>{results} results</p>
</div>
<button className="pagination-button" type="button" onClick={nextPage}>
>
</button>
</div>
);
export default Pagination;
<file_sep>/src/components/landing.js
import React, { Component } from "react";
import axios from "axios";
import BookItem from "./BookItem";
import SearchBar from "./SearchBar";
import Pagination from "./Pagination";
const goodReadsAPI = axios.create({
baseURL: "https://good-reads--85davidyoon.repl.co"
});
class Landing extends Component {
state = {
searchParam: "",
results: 1,
currentPage: 1,
errorMsg: "",
loading: false,
books: []
};
handleSearch = e => {
const searchParam = e.target.value;
this.setState(() => ({ searchParam }));
};
handleClick = e => {
e.preventDefault();
this.setState({
searchParam: "",
results: 1,
currentPage: 1,
errorMsg: "",
loading: false,
books: []
});
};
handleSubmit = e => {
e.preventDefault();
this.setState({ currentPage: 1 });
this.getBooks();
};
getBooks = () => {
if (this.state.searchParam) {
this.setState({ loading: true });
const { searchParam, currentPage } = this.state;
const url = `/search/${searchParam}/${currentPage}`;
goodReadsAPI
.get(url)
.then(({ data: { data: books, results } }) => {
if (books) {
this.setState(() => ({
books,
results,
errorMsg: "",
loading: false
}));
} else {
this.setState(() => ({
errorMsg: "No books match your search.",
books: [],
loading: false
}));
}
})
.catch(err => {
this.setState(() => ({
errorMsg: "Try a new search.",
loading: false
}));
});
}
};
prevPage = () => {
if (this.state.currentPage > 1) {
this.setState(
prevState => ({ currentPage: prevState.currentPage - 1 }),
() => this.getBooks()
);
}
};
nextPage = () => {
const displayPages = Math.ceil(this.state.results / 20);
if (this.state.currentPage < displayPages) {
this.setState(
prevState => ({ currentPage: prevState.currentPage + 1 }),
() => this.getBooks()
);
}
};
render() {
const { books } = this.state;
debugger;
return (
<main className="main">
<SearchBar
handleSearch={this.handleSearch}
handleClick={this.handleClick}
handleSubmit={this.handleSubmit}
searchParam={this.state.searchParam}
/>
{this.state.loading ? (
<p className="loading">
<img
className="spinner"
src="http://freepreloaders.com/wp-content/uploads/2019/05/5-1.svg"
alt="spinner"
/>
</p>
) : (
<div>
{this.state.errorMsg ? (
<p className="search-error">{this.state.errorMsg}</p>
) : null}
<div className="book-list">
{books.map(book => {
const id = book["id"][0]["_"];
const title = book["best_book"][0]["title"][0];
const author = book["best_book"][0]["author"][0]["name"][0];
const imgUrl = book["best_book"][0]["image_url"][0];
debugger;
return (
<BookItem
key={id}
title={title}
author={author}
imgUrl={imgUrl}
/>
);
})}
</div>
{this.state.results > 1 && !this.state.errorMsg.length && (
<div>
<Pagination
results={this.state.results}
currentPage={this.state.currentPage}
nextPage={this.nextPage}
prevPage={this.prevPage}
/>
</div>
)}
</div>
)}
</main>
);
}
}
export default Landing;
<file_sep>/routes/index.js
const express = require("express");
const router = express.Router();
const searchMiddleware = require("../middleware");
const searchController = require("../controllers");
router.get("/", (req, res) => {
res.send("Sending dummy res to postmen");
});
router.get(
"/search/:term/:page",
searchMiddleware,
searchController.searchBook
);
module.exports = router;
<file_sep>/routes/middleware/index.js
const request = require("request");
const parseString = require("xml2js").parseString;
const get = require("lodash.get");
module.exports = (req, res, next) => {
// SEARCH TERM
console.log("Dog");
const { term, page = 1 } = req.params;
// GET RES FROM GOOD READS API
request(
`https://www.goodreads.com/search.xml?key=<KEY>&q=${term}&page=${page}`,
(err, res, body) => {
if (!err && res.statusCode === 200) {
parseString(body, (error, result) => {
const search = get(result, "GoodreadsResponse.search[0]", "");
req.jsonData = get(search, "results[0].work", "");
req.total = get(search, "total-results[0]", 0);
});
next();
}
}
);
};
<file_sep>/src/components/SearchBar.js
import React from "react";
const SearchBar = props => {
const { handleSearch, handleSubmit, searchParam, handleClick } = props;
return (
<form className="search-bar" onSubmit={handleSubmit}>
<input
className="search-bar-input"
type="text"
placeholder="Search by title or author..."
value={searchParam}
onChange={handleSearch}
/>
<div className="search-buttons">
<button className="search-bar-button" type="submit">
Search
</button>
<button
className="search-bar-button"
type="button"
onClick={handleClick}
>
Reset
</button>
</div>
</form>
);
};
export default SearchBar;
<file_sep>/controllers/index.js
exports.searchBook = (req, res) => {
res.json({ data: req.jsonData, total: req.total });
};
| 01545c685a519c836db911ca715c4d3adf866da6 | [
"JavaScript"
] | 6 | JavaScript | davidyoon85/goodreads | c60dc7ecacf33bd77a5fff99302aab1f38d148d4 | bbd81a1fa31f3b5b26481961187aed7b0166245c |
refs/heads/master | <file_sep>## These two functions use a cacheing system to compute the inverse of a matrix
## This function creates a special "matrix" object that can cache its inverse
makeCacheMatrix <- function(x = matrix()) {
# for the first call, initializes the inverse matrix to NULL
inverse <- NULL
# sets a matrix given the function's input, gets rid of cached inverse
set <- function(y) {
x <<- y
inverse <<- NULL
}
# returns matrix from part 1
get <- function() x
# sets value of inverse of matrix from part 1
setinverse <- function(solve) inverse <<- solve
# returns inverse of matrix from part 1
getinverse <- function() inverse
# returns list of functions
list(set = set, get = get,
setinverse = setinverse,
getinverse = getinverse)
}
## This function computes the inverse of the special "matrix" returned by
## makeCacheMatrix above. If the inverse has already been calculated (and
## the matrix has not changed), then the cachesolve should retrieve the inverse
## from the cache. If the matrix has been changed, it will compute the inverse
## of the new matrix
cacheSolve <- function(x=matrix(), ...) {
# gives a matrix that is the inverse of 'x'
inverse <- x$getinverse()
if(!is.null(inverse)) {
message("getting cached data")
return(inverse)
}
# get the initial matrix
data <- x$get()
# compute the inverse matrix
inverse <- solve(data, ...)
# cache the inverse matrix in the list from the initial function
x$setinverse(inverse)
# return the inverse
inverse
}
#### test script
size <- 10
mymatrix <- matrix(rnorm(size^2), nrow=size, ncol=size)
mymatrix.inverse <- solve(mymatrix)
special.matrix <- makeCacheMatrix(mymatrix)
special.solved.1 <- cacheSolve(special.matrix)
special.solved.2 <- cacheSolve(special.matrix)
identical(mymatrix.inverse, special.solved.1) & identical(mymatrix.inverse, special.solved.2) | 461534347a96da8622fea7adcde8f907d01641c6 | [
"R"
] | 1 | R | JLewyckyj/ProgrammingAssignment2 | 0d4c6749d98a686209675552a7e777b69fe14724 | 2b2248b44f64207075c9caec1aca5bae9feb4e9f |
refs/heads/master | <file_sep>package com.jghg.twitterforandroid;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends Activity {
private Button profile;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main);
init();
}
private void init() {
profile = (Button) findViewById(R.id.profile);
}
public void onClickProfile(View view) {
Toast.makeText(this, "Show Profile Twitter", Toast.LENGTH_SHORT).show();
startActivity(new Intent(MainActivity.this, ProfileActivity.class));
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
//getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
<file_sep>package configure;
import twitter4j.Twitter;
import twitter4j.TwitterFactory;
import twitter4j.auth.AccessToken;
import twitter4j.conf.Configuration;
import twitter4j.conf.ConfigurationBuilder;
/**
* Created by jghg on 2013-11-17.
*/
public class TwitterConfig {
private ConfigurationBuilder configurationBuilder;
private Twitter twitter;
private TwitterFactory twitterFactory;
private final static String CONSUMER_KEY = "uj3Xt9grf4C0IUOFufyvBg";
private final static String CONSUMER_SECRET_KEY = "<KEY>";
private final static String ACCESS_TOKEN = "<KEY>";
private final static String ACCES_TOKEN_SECRET = "<KEY>";
private final static String TWITTER_USERNAME = "";
/**
* Metodo que nos permite configurar todas las credenciales necesarias para poder
* hacer uso del API v1.1 de Twitter desde nuestra Aplicacion.
*/
public void configTwitter() {
configurationBuilder = new ConfigurationBuilder();
configurationBuilder.setUseSSL(true);
configurationBuilder.setApplicationOnlyAuthEnabled(true);
configurationBuilder.setOAuthConsumerKey(CONSUMER_KEY);
configurationBuilder.setOAuthConsumerSecret(CONSUMER_SECRET_KEY);
configurationBuilder.setOAuthAccessToken(ACCESS_TOKEN);
configurationBuilder.setOAuthAccessTokenSecret(ACCES_TOKEN_SECRET);
configurationBuilder.setJSONStoreEnabled(true);
configurationBuilder.setIncludeEntitiesEnabled(true);
configurationBuilder.setIncludeMyRetweetEnabled(true);
configurationBuilder.setIncludeRTsEnabled(true);
Configuration configuration = configurationBuilder.build();
twitterFactory = new TwitterFactory(configuration);
AccessToken accessToken = new AccessToken(ACCESS_TOKEN, ACCES_TOKEN_SECRET);
twitter = twitterFactory.getInstance(accessToken);
}
}
<file_sep>Twitter-For-Android
===================
Integracion de la libreria twitter4j para una app en Android.
- Lo primero que se necesita para poder trabajar con el nuevo API v1.1 de Twitter desde __Android__ es agregar a nuestro proyecto la libreria __Twitter4j__. La cual puedes descargarte desde este [link](http://twitter4j.org/en/)
- Lo segundo es agregar estas librerias __.jar__ (que ya hemos descargado) a nuestro proyecto en _Android_.
Para poder agregar dichas librerias .jar a nuestro proyecto, desde
el Android Studio, es necesario realizar los siguientes pasos:
1.- Copiar todo el contenido de la carpeta twitter4j/lib a la carpeta
lib de nuestro proyecto.
2.- Desde el Android Studio nos dirigimos a la carpeta lib en el cual
hemos colcado los .jar. Sobre cada .jar que agregemos debemos hacer click
derecho sobre ella y seleccionamos Agregar como Libreria (Add as Library)
3.- Al hacer esto nos sale un dialogo donde nos indica el nombre de la
libreria que estamos agregando y a que proyecto se lo estamos agregando.
- _Referencias_
- 
- 
- Luego debemos registrar una aplicacion en el site de __Developer de twitter__. [TwiterDev](http://dev.twitter.com)
- Una vez registrada la aplicacion, es importante tomar en consdieracion los valores que se crean al momento de registrar dicha aplicacion, como lo son:
- CONSUMER KEY
- CONSUMER SECRET
- ACCESS TOKEN
- ACCESS TOKEN SECRET
Todas estos valores son necesarios para poder hacer uso del API v1.1
- Una vez realizado esto iniciaremos con el _codigo_.
#Configuracion
- Lo primero que debemos realizar es definir toda nuestra configuracion de acceso desde nuestro codigo __Java__, para esto se debe de realizar lo siguiente:
1.-Creamos una nueva clase llamada __TwitterConfig__ y en ella colocaremos lo siguiente:
Definimos nuestras variables con los valores que ya comente.
private final static String CONSUMER_KEY = "";
private final static String CONSUMER_SECRET_KEY = "";
private final static String ACCESS_TOKEN = "";
private final static String ACCES_TOKEN_SECRET = "";
| 5fc5f1d2daa2a5a592067f9ec9ebc9eaaca00c8e | [
"Markdown",
"Java"
] | 3 | Java | bcernesto/Twitter-For-Android | e715e6a82e7c28eaa82afb3f419df3a5d9ce5158 | 9ceec71b12a7f9ea19b6774e7c2f41ff9681ecdc |
refs/heads/master | <repo_name>xsqasxz/studyspringboot4<file_sep>/README.md
# studyspringboot4
JavaEE开发的颠覆者 Spring Boot实战学习记录
<file_sep>/src/main/java/com/config/DiConfig.java
package com.config;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
/**
* 这里是一个基本的配置类
* @author xueshiqi
* @since 2018/9/13
*/
//将该类型声明为一个配置类
@Configuration
//这里配置一下扫描路径, 会扫描对应路径下面的全部的 @Service @Component @Repository @Controller
@ComponentScan("com.study")
//开启对自定义注解的扫描 如果没有使用自定义注解这里就不需要使用该注解
@EnableAspectJAutoProxy
public class DiConfig {
}<file_sep>/src/main/java/com/AopMain.java
package com;
import com.config.ConditionConfig;
import com.config.DemoConfig;
import com.study.service.DemoService;
import com.study.service.ListService;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
/**
* 切面注解,注入例子
* @author xueshiqi
* @since 2018/9/13
*/
public class AopMain {
public static void main(String [] s){
/*AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(DiConfig.class);
//基础注解使用方式,为1.0章节学习内容
DemoAnnotationService demoAnnotationService = context.getBean(DemoAnnotationService.class);
demoAnnotationService.add();
//得到Bean的名称,还有读取文件
AwareService awareService = context.getBean(AwareService.class);
awareService.outputResult();
context.close();*/
/*//多线程异步任务
AnnotationConfigApplicationContext conTask = new AnnotationConfigApplicationContext(TaskExecutorConfig.class);
AsyncTaskService asyncTaskService = conTask.getBean(AsyncTaskService.class);
for (int i = 0;i<100;i++){
asyncTaskService.executeAsyncTask(i);
asyncTaskService.executeAsyncTaskPlus(i);
}
conTask.close();*/
/*//计划任务
AnnotationConfigApplicationContext conTimer = new AnnotationConfigApplicationContext(TaskSchedulerConfig.class);*/
/*//条件注解演示
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(ConditionConfig.class);
ListService listService = context.getBean(ListService.class);
System.out.println(listService.showListCmd());*/
/*//组合注解演示
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(DemoConfig.class);
DemoService demoService = context.getBean(DemoService.class);
demoService.outputResult();
context.close();*/
}
}<file_sep>/src/main/java/com/study/annotation/WiselyConfiguration.java
package com.study.annotation;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import java.lang.annotation.*;
/**
* @author xueshiqi
* @since 2020/1/9
* 这里是组合注解,就是说自定义一个注解的方式,将多个注解的功能组合到这个自定义注解上去
* 这里组合了@Configuration和@ComponentScan注解
* value() 是属于覆盖参数
*/
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Configuration
@ComponentScan
public @interface WiselyConfiguration {
String[] value() default {};
}
<file_sep>/src/main/java/com/study/service/DemoAnnotationService.java
package com.study.service;
/**
* @author xueshiqi
* @since 2020/1/8
*/
public interface DemoAnnotationService {
void add();
}
<file_sep>/src/main/java/com/config/TaskExecutorConfig.java
package com.config;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import java.util.concurrent.Executor;
/**
* @author xueshiqi
* @since 2020/1/8
* 利用@EnableAsync注解开启异步任务支持
* 配置类实现了AsyncConfigurer接口并重写了getAsyncExecutor方法,返回一个 ,这样我们就可以获得一个基础线程池TaskExecutor
*/
@Configuration
@ComponentScan("com.study.task")
@EnableAsync
public class TaskExecutorConfig implements AsyncConfigurer {
@Override
public Executor getAsyncExecutor() {
ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
//线程池维护线程的最少数量
taskExecutor.setCorePoolSize(5);
//线程池维护线程的最大数量
taskExecutor.setMaxPoolSize(100);
////线程池所使用的缓冲队列
taskExecutor.setQueueCapacity(200);
//线程池维护线程所允许的空闲时间
taskExecutor.setKeepAliveSeconds(30000);
taskExecutor.initialize();
return taskExecutor;
}
}
<file_sep>/src/main/java/com/config/DemoConfig.java
package com.config;
import com.study.annotation.WiselyConfiguration;
/**
* @author xueshiqi
* @since 2020/1/9
*/
@WiselyConfiguration("com.study.service")
public class DemoConfig {
}
<file_sep>/src/main/java/com/config/ConditionConfig.java
package com.config;
import com.study.condition.LinuxCondition;
import com.study.condition.WindowsCondition;
import com.study.service.ListService;
import com.study.service.impl.LinuxListService;
import com.study.service.impl.WindowsListService;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Conditional;
import org.springframework.context.annotation.Configuration;
/**
* @author xueshiqi
* @since 2020/1/9
*/
@Configuration
public class ConditionConfig {
@Bean
@Conditional(WindowsCondition.class)
public ListService windowsListService(){
return new WindowsListService();
}
@Bean
@Conditional(LinuxCondition.class)
public ListService linuxListService(){
return new LinuxListService();
}
}
| da0e28ae7a4701b7ab6f74db92d37f54ed8749ee | [
"Markdown",
"Java"
] | 8 | Markdown | xsqasxz/studyspringboot4 | 9e9e2b8104b5b45a7c54fc8d6d55c515cb0c5d2e | 421fc4b413a24a6defc5c676c1a107f3f775b2ee |
refs/heads/master | <file_sep>import fmeobjects as FME
import xml.etree.ElementTree as ET
import os,fnmatch
from collections import OrderedDict
#------------------------------------------------------------------------------------------------------------
#
# Python code writen by <NAME>, <NAME> BV (<EMAIL>), jun 2014
#
#------------------------------------------------------------------------------------------------------------
# DESCRIPTION
#
# This file will be used in the GEOBASEII validation and mapping process. This file will read the INCONTROL
# delivery location and then use INCONTROL rules file together with the GIS rules file to supply the FME
# workbenches with parameters.
#
#------------------------------------------------------------------------------------------------------------
# PYTHON CLASSES
#
# Initialiser(): Class to perform initial set-up tasks
# switch(): Utility class to implement the C# switch structure
# FeatureProcessor(object): FME PyCaller interface
#------------------------------------------------------------------------------------------------------------
# PYTHON FUNCTIONS
#
# LocateFiles: Scan a specific directory for the INCONTROL rules and text files.
# ExtractTVSData: Inspects the INCONTROL rule file and returns the TVS and it's version
# CollectXPathValues: Returns an array with values from given XPath
# case: Needed by the switch class
#
#
#
#------------------------------------------------------------------------------------------------------------
# HISTORY
# 12-June-2014: Initial Creation <NAME>
# 23-June-2014: Adapted for PythonCaller transformer in FME <NAME>
# 26-June-2014: Added rule# to ruleset and return as sorted <NAME>
#
#
#------------------------------------------------------------------------------------------------------------
# Declarations
gisRulesFile = 'C:\\Users\\A575716\\Documents\\Atos\\ProRail\\TVS7\\GeobaseGis_Rules_V08.xml'
searchDir = 'C:\\Users\\A575716\\Documents\\Atos\\ProRail\\TVS7\\INCONTROL'
# Scan recursive through sourceDir for XML files
def LocateFiles(sourceDir):
resultList = list()
try:
if os.path.exists(sourceDir):
for file in fnmatch.filter(os.listdir(searchDir),"*.xml"):
resultList.append(file)
else:
raise
except:
resultList = None
finally:
return resultList
#extract the TVS and it's version from the received xml file
def ExtractTVSData(ruleFileName):
data = {}
try:
data["version"] = ruleFileName[str.rfind(ruleFileName,"-") + 2:str.rfind(ruleFileName,".")]
data["type"] = ruleFileName[str.rfind(ruleFileName,"_") + 1:str.rfind(ruleFileName,"-")]
except:
raise Exception
finally:
return data
#fetches the values from the xpath string
def CollectXPathValues(xpathValue,tvsType):
results = {}
doc = ET.parse(gisRulesFile)
for parent in doc.findall(str(xpathValue).replace('%TVSPLACEHOLDER%',tvsType)):
if parent.text != '\n ' and parent.text != None:
parentValue = parent.text
results["values"] = parentValue.split(",")
else:
attribValue = parent.get("values")
if attribValue != None:
results["values"] = attribValue.split()
else:
for child in parent:
if child.get("name") != None:
results[child.get("name")] = child.text
else:
results[child.text] = child.text
return results
def case(*args):
return any((arg == switch.value for arg in args))
class Initialiser():
""""
This container class handles all the pre-validation tasks
"""
def __init__(self, gisrulesFile, sourceDir ):
self.tvsData = {}
self._ruleFile = gisrulesFile
self._dropLocation = sourceDir
self.ErrorMessage = ""
self.StateIsOk = bool(1!=1)
self.DgnFilesOk = bool(1!=1)
def GetRules(self):
"""
Method to parse the INControl rules and control files and produce
a list of rules.
"""
incontrolFiles = LocateFiles(self._dropLocation)
try:
if incontrolFiles != None:
for item in incontrolFiles:
if str.find(item,"_errors") != -1: #We look for the INCONTROL error file
#Now we open this file to see if the INCONTROL process was successful
errorDoc = ET.parse(self._dropLocation + "\\{0}".format(item))
errorRootNode = errorDoc.getroot()
errorChildNodes = errorRootNode.getchildren()
if errorChildNodes: #Process was not ok
raise Exception("The error controlfile {0} contains errors! Process wil terminate.".format(item))
settingFileName = errorRootNode.get("xmlFile")
self.tvsData = ExtractTVSData(settingFileName)
if self.tvsData:
rulesCollection = {}
ruleCounter = 0
gisRuleDoc = ET.parse(self._ruleFile)
for node in gisRuleDoc.findall(".//rules/validations/*/rule[@version='{0}']".format(self.tvsData["version"])):
ruleValues = {} #Collection of all the rules
ruleCounter += 1
ruleValues["ruleNumber"] = ruleCounter
ruleValues["name"] = node.get("name")
ruleValues["what"] = node.get("what")
if node.get("levels") == "*":
ruleValues["levels"] = node.get("levels")
else:
ruleValues["levels"] = CollectXPathValues(node.get("levels"),self.tvsData["type"])
ruleValues["transformerTypes"] = node.get("transformerTypes")
ruleValues["errorCode"] = node.get("errorCode")
ruleValues["errorMessage"] = node.text
if node.get("conditionIsXpath") == "true":
ruleValues["condition"] = CollectXPathValues(node.get("condition"),self.tvsData["type"])
else:
ruleValues["condition"] = node.get("condition")
rulesCollection[ruleCounter] = ruleValues
self.StateIsOk = bool(1==1)
except Exception as exc:
self.ErrorMessage = "The following message was received from verification process \n {0}".format(exc.args[0])
rulesCollection = None
finally:
return OrderedDict(sorted(rulesCollection.items()))
def GetDrawingFileNames(self):
fileList = []
try:
for dirpath, dirnames, filenames in os.walk(self._dropLocation):
for entry in filenames:
if str(entry).endswith(".dgn"):
fullFileName = os.path.join(dirpath,entry)
#Only add if it's a file and not already added
if os.path.isfile(fullFileName) and fileList.count(fullFileName) <= 0:
fileList.append(fullFileName)
except:
fileList = None
finally:
self.DgnFilesOk = bool(1==1)
fileList.sort()
return fileList
def close(self):
pass
class switch(object):
value = None
def __new__(class_, value):
class_.value = value
return True
class FeatureProcessor(object):
"""
This class handles the FME Python caller interfacing
"""
def __init__(self):
pass
def input(self,feature):
try:
# logging prints
print("validationCounter: " + str(feature.getAttribute("_validationCounter")))
print("Verwerken van feature " + str(feature.getAttribute("igds_graphic_group")))
#<TODO> Check constructor parameter!!!
starter = Initialiser(FME.MacroValues["SearchDir"])
validationRules = starter.GetRules()
#<TODO> Name to be determined from list of validations
validationName = "objectInsideCountry"
currentValidationParameters = validationRules[validationName]
# print(currentValidationParameters)
# set feauture attributes from current validation
feature.setAttribute("_validationName", validationName)
feature.setAttribute("_validationWhat", str(currentValidationParameters["what"]))
feature.setAttribute("_validationCondition", str(currentValidationParameters["condition"]))
feature.setAttribute("_validationLevels", str(currentValidationParameters["levels"]))
feature.setAttribute("_validationErrorcode", str(currentValidationParameters["errorCode"]))
feature.setAttribute("_validationTransformerType", str(currentValidationParameters["transformerTypes"])) #todo : 's' te veel?
except Exception as err:
print('ERROR: %s\n' % str(err))
finally:
self.pyoutput(feature)
def close(self):
pass<file_sep>__author__ = '<NAME>'
"""" Suite aan unit tests voor Py.test """
import GeoBaseIntakeScript as RulesParser
import pytest
@pytest.fixture
def initializer():
test_gis_rules_file = "C:/Users/a503449/Documents/Projecten/Py\GitHub/tuinkabouter_bevrijdingsfront/XML" \
"/poc_geobase_rules_xml_GeobaseGis_Rules_V08.xml"
test_source_dir = "C:/Users/a503449/Documents/Projecten/Py\GitHub/tuinkabouter_bevrijdingsfront/XML/"
test_incontrol_errors_xml = "C:/Users/a503449/Documents/Projecten/Py/GitHub/tuinkabouter_bevrijdingsfront/XML/" \
"poc_incontrol_errors_xml_090BBKS07_incontrol_errors.xml"
test_incontrol_rules_xml = "C:/Users/a503449/Documents/Projecten/Py/GitHub/tuinkabouter_bevrijdingsfront/XML" \
"/poc_incontrol_rules_xml_DR_BBKS_TVS00002-V007-test voorbeeld voor ATOS.xml"
test_initializer = RulesParser.Initializer(test_gis_rules_file, test_source_dir, test_incontrol_errors_xml,
test_incontrol_rules_xml)
return test_initializer
def test_finding_rules_file(initializer):
assert initializer.ErrorMessage == ""
def test_extract_tvs_data(initializer):
test_incontrol_error_file = 'C:\\Users\\a503449\\Documents\\Projecten\\Py\GitHub\\tuinkabouter_bevrijdingsfront\\' \
'XML\\poc_incontrol_errors_xml_090BBKS07_incontrol_errors.xml'
tvs_data = initializer.extract_tvs_data(test_incontrol_error_file)
assert tvs_data["version"] == "007"
assert tvs_data["type"] == "TVS00002"
assert tvs_data["collection"] == "BBKS"
# todo test voor Spoorkruising 1:200
# todo test dat aanhaallijnen NIET meegenomen worden
# todo uitzoeken: assetnames wel of geen hoofdletter
def test_get_sample_assetname_and_assetname_id_rules(initializer):
assert initializer.get_all_assets()["Lichtsein hoog"]["level"] == "$(lvlPrefix)SYMBOLEN-SYMBOOLTEKSTEN-018" #todo level prefix vervangen door collctie/KS-
def test_incontrol_error_file_containing_errors_ends_process(initializer):
pass
def test_parse_incontrol_error_file():
pass
def test_parse_incontrol_rule_file():
pass
def test_parse_gis_rule_file():
pass
def test_get_rules_collection(initializer):
assert initializer.get_all_rules()
def test_total_number_of_rules(initializer):
_gis_rules_collection = initializer.get_all_rules()
assert len(_gis_rules_collection) == 28
def test_get_sample_incontrol_validation_rule(initializer):
_gis_rules_collection = initializer.get_all_rules()
assert _gis_rules_collection["objectInsideCountry"]["condition"] == "input\shapes\land.shp"
def test_get_sample_gis_validation_rule(initializer):
_gis_rules_collection = initializer.get_all_rules()
assert _gis_rules_collection["objectOkforNetworkTraceLevels"]["condition"] == "no under or overshoot"
def test_get_sample_mapping_rule(initializer):
pass
# todo: incontrol rules bestand moet net als ~error bestand autonoom ontdekt worden<file_sep># noinspection PyPep8Naming
import xml.etree.ElementTree as ET
import os
import fnmatch
# ------------------------------------------------------------------------------------------------------------
#
# Python code writen by <NAME>, <NAME> (<EMAIL>), jun 2014
#
# ------------------------------------------------------------------------------------------------------------
# DESCRIPTION
#
# This file will be used in the GEOBASEII validation and mapping process. This file will read the INCONTROL
# delivery location and then use INCONTROL rules file together with the GIS rules file to supply the FME
# workbenches with parameters within an FME workspace PyCaller transformer
#
# ------------------------------------------------------------------------------------------------------------
# PYTHON CLASSES
#
# Initializer(): Class to perform initial set-up tasks
# Switch(): Utility class to implement the C# Switch structure
# FeatureProcessor(object) FME PyCaller interface
# ------------------------------------------------------------------------------------------------------------
# PYTHON FUNCTIONS
#
# locate_files: Scan a specific directory for the INCONTROL rules and text files.
# extract_tvs_version: Inspects the INCONTROL rule file and returns the TVS and it's version
# collect_xpath_values: Returns an array with values from given XPath
# case: Needed by the Switch class
#
#
#
#------------------------------------------------------------------------------------------------------------
# HISTORY
# 12-June-2014: Initial Creation <NAME>
# 23-June-2014: Adapted for PythonCaller transformer in FME <NAME>
#
#------------------------------------------------------------------------------------------------------------
# Declarations
gis_rules_file = 'C:\\Users\\a503449\\Documents\\Projecten\\ProRail\\GeobaseTVS7\\PoC\Input\\' \
'GeobaseGis_Rules_TVS00002_V04.xml'
search_dir = 'C:\\Users\\a503449\\Documents\\Projecten\\ProRail\\GeobaseTVS7\\PoC\\Input'
# test method for FME coupling test
def test_appeltaart():
print("appeltaart")
# Scan recursive through sourceDir for XML files
def locate_files(source_dir):
"""
:rtype :
"""
result_list = list()
try:
if os.path.exists(source_dir):
for file in fnmatch.filter(os.listdir(source_dir), "*.xml"):
result_list.append(source_dir + file)
else:
raise
except:
result_list = None
finally:
return result_list
# Fetches the values from the xpath string
def collect_xpath_values(gis_rules_file, xpath_value, tvs_type):
results = {}
doc = ET.parse(gis_rules_file)
for parent in doc.findall(str(xpath_value).replace('%TVSPLACEHOLDER%', tvs_type)):
if parent.text != '\n ' and parent.text is not None:
parent_value = parent.text
results["values"] = parent_value.split(",")
else:
attrib_value = parent.get("values")
if attrib_value is not None:
results["values"] = attrib_value.split()
else:
for child in parent:
if child.get("name") is not None:
results[child.get("name")] = child.text
else:
results[child.text] = child.text
return results
class Initializer():
def __init__(self, geobase_rules_xml, source_dir, incontrol_errors_xml, incontrol_rules_xml):
self.tvs_data = {} # todo: should this be declared here?
# source xml files
self._incontrol_errors_xml = incontrol_errors_xml
self._incontrol_rules_xml = incontrol_rules_xml
self._geobase_rules_xml = geobase_rules_xml
self._drop_location = source_dir
# state and message files
self.ErrorMessage = ""
self.state_is_ok = bool(1 != 1)
self.dgn_files_ok = bool(1 != 1)
# GIS rule xml consists of two types of validation rules, both of which need to be extracted
self.rule_types = ["incontrol", "gis"]
def extract_rules_collection(self, gis_rules_collection):
gis_rules_doc = ET.parse(self._geobase_rules_xml)
for type_ in self.rule_types:
for node in gis_rules_doc.findall(".//rules/validations/"
"{0}/rule[@version='{1}']".format(type_, self.tvs_data["version"])):
# ToDo: Mapping rules moeten ook opgehaald worden
rule_values = {} # Collection of all the rules
rule_values["what"] = node.get("what")
if node.get("levels") == "*":
rule_values["levels"] = node.get("levels")
else:
rule_values["levels"] = collect_xpath_values(self._geobase_rules_xml, node.get("levels"),
self.tvs_data["type"])
rule_values["transformerTypes"] = node.get("transformerTypes")
rule_values["errorCode"] = node.get("errorCode")
rule_values["errorMessage"] = node.text
if node.get("conditionIsXpath") == "true":
rule_values["condition"] = collect_xpath_values(self._geobase_rules_xml, node.get("condition"),
self.tvs_data["type"])
else:
rule_values["condition"] = node.get("condition")
gis_rules_collection[node.get("name")] = rule_values
self.state_is_ok = bool(1 == 1)
def get_all_rules(self):
"""
Parses GeoBase Loader GIS Rules XML and returns a dictionary of rules for validation and mapping.
"""
gis_rules_collection = {}
incontrol_files = locate_files(self._drop_location)
try:
if incontrol_files is not None:
# noinspection PyTypeChecker
for item in incontrol_files:
if str.find(item, "_errors") != -1: # We look for the INCONTROL error file
# Now we open this file to see if the INCONTROL process was successful
error_doc = ET.parse(item)
error_root_node = error_doc.getroot()
error_child_nodes = error_root_node.getchildren()
if error_child_nodes: # Process was not ok
raise Exception(
"The error controlfile {0} contains errors! Process wil terminate.".format(item))
#Parse name of INControl rule file used and distill tvs (rules) version from it
self.tvs_data = self.extract_tvs_data(item)
else: # We process the rule file NB! We assume that we only have two xml files
# in directory ; todo also process incontrol_rules file for asset names
if self.tvs_data:
self.extract_rules_collection(gis_rules_collection)
except Exception as exc:
self.ErrorMessage = "The following message was received from verification process \n {0}".format(
exc.args[0])
gis_rules_collection = None
finally:
return gis_rules_collection
def get_all_assets(self):
"""
Parses Fugro INControl Rules XML and returns a dictionary of asset names and rules.
"""
asset_rules_collection = {}
try:
# parse nodes containing assetnames
_tree = ET.parse(self._incontrol_rules_xml)
_root = _tree.getroot()
_nodes = _root.findall(".//*[@assetname]")
for child in _nodes:
_properties = child.findall(".//properties")[0]
asset_rules_collection[child.attrib["assetname"]] = _properties.attrib
except Exception as exc:
self.ErrorMessage = "The following message was received from verification process \n {0}".format(
exc.args[0])
asset_rules_collection = None
finally:
return asset_rules_collection
@staticmethod
def extract_tvs_data(error_file_name):
tvs_data = {}
tree = ET.parse(error_file_name)
root = tree.getroot()
tvs_data["collection_type_version"] = root.attrib["xmlFile"].rsplit("DR_")[1].split(".xml")[0]
tvs_data["version"] = root.attrib["xmlFile"].split(".xml")[0].split("-V")[1]
tvs_data["type"] = root.attrib["xmlFile"].split("-")[0].rsplit("_")[3]
tvs_data["collection"] = root.attrib["xmlFile"].split(".xml")[0].rsplit("_")[2]
# $(lvlPrefix) in asset_names_rules should be replaced with this value, based on collection
tvs_data["level_prefix"] = tvs_data["collection"] + "-"
return tvs_data
def close(self):
pass
# FME Python Caller Interface: ToDo: Should be removed from this file
class FeatureProcessor(object):
def __init__(self):
pass
def input(self, feature):
try:
# logging prints
print("validationCounter: " + str(feature.getAttribute("_validationCounter")))
print("Verwerken van feature " + str(feature.getAttribute("igds_graphic_group")))
starter = Initializer(gis_rules_file, search_dir)
validation_rules = starter.get_all_rules()
# ToDo Name to be determined from list of validations
validation_name = "objectInsideCountry"
current_validation_parameters = validation_rules[validation_name]
# set feature attributes from current validation
feature.setAttribute("_validationName", validation_name)
feature.setAttribute("_validationWhat", str(current_validation_parameters["what"]))
feature.setAttribute("_validationCondition", str(current_validation_parameters["condition"]))
feature.setAttribute("_validationLevels", str(current_validation_parameters["levels"]))
feature.setAttribute("_validationErrorcode", str(current_validation_parameters["errorCode"]))
feature.setAttribute("_validationTransformerType",
str(current_validation_parameters["transformerTypes"])) # ToDo : 's' te veel?
except Exception as err:
print('ERROR: %s\n' % str(err))
finally:
self.pyoutput(feature)
def close(self):
pass
<file_sep>tuinkabouter_bevrijdingsfront
=============================
Py voor o.m. PR
| 6592a4424e2035368cf86acc7606ffcb1c8adbc2 | [
"Markdown",
"Python"
] | 4 | Python | BartholomeusM/tuinkabouter_bevrijdingsfront | 6d62bd871cfbab019a3771dba6da626ce925951a | a2bf1dcfefedbb3b30a4cba56d8e65614d360598 |
refs/heads/master | <file_sep><?php
class Users{
public function selectUserById($pdo, $id){
$stmt = $pdo->prepare("SELECT pseudo FROM users INNER JOIN toilettes ON users.id = toilettes.users_id WHERE toilettes.id=$id");
$stmt->execute();
$result = $stmt->fetchAll();
return $result;
}
}
?>
<file_sep><?php
$error = [];
$error['pseudo'] = $error['ville'] = $error['email'] = $error['msg'] = "";
if (isset($_POST["pseudo"])){
$pseudo = $_POST["pseudo"];
if(empty($_POST["pseudo"]) || strlen($_POST["pseudo"]) < 3 )
{
$error['pseudo'] = true;
}
}
if (isset($_POST["ville"])){
$ville = $_POST["ville"];
if(empty($_POST["ville"]) || strlen($_POST["ville"]) < 3 )
{
$error['ville'] = true;
}
}
if (isset($_POST["email"])){
$email = $_POST["email"];
if(empty($_POST["email"]) || !preg_match('#^[\w.-]+@[\w.-]+\.[a-z]{2,6}$#i', $email))
{
$error['email'] = true;
}
}
if (isset($_POST["msg"])){
$msg = $_POST["msg"];
if(empty($_POST["msg"]) || strlen($_POST["msg"]) < 16 )
{
$error['msg'] = true;
}
}
if (empty($error)){
$message = " Pseudo ".$pseudo." Ville ".$ville." E-mail ".$email." Message : ".$msg;
mail("<EMAIL>", "Envoi du formulaire", $message);
}
echo json_encode($error);
?><file_sep><?php
class Ville{
public function selectVilleById($pdo, $id){
$stmt = $pdo->prepare("SELECT nom_ville FROM ville INNER JOIN toilettes ON ville.id = toilettes.ville_id WHERE toilettes.id=$id");
$stmt->execute();
$result = $stmt->fetchAll();
return $result;
}
}
?>
<file_sep><?php
$msg = "";
$pseudo = "";
$adresse = "";
$ville = "";
if (isset($_REQUEST['pseudo'])){
if(!empty($_REQUEST['pseudo'])){
$pseudo = $_REQUEST['pseudo'];
$tab['pseudo'] = true;
}else{
$tab['pseudo'] = false;
}
}else{
$tab['pseudo'] = false;
}
if (isset($_REQUEST['adresse'])){
if(!empty($_REQUEST['adresse'])){
$adresse = $_REQUEST['adresse'];
$tab['adresse'] = true;
}else{
$tab['adresse'] = false;
}
}else{
$tab['adresse'] = false;
}
if (isset($_REQUEST['ville'])){
if(!empty($_REQUEST['ville'])){
$ville = $_REQUEST['ville'];
$tab['ville'] = true;
}else{
$tab['ville'] = false;
}
}else{
$tab['ville'] = false;
}
if (isset($_REQUEST['msg'])){
if(!empty($_REQUEST['msg']) && strlen($_REQUEST['msg']) > 15){
$msg = $_REQUEST['msg'];
$tab['msg'] = true;
}else{
$tab['msg'] = false;
}
}else{
$tab['msg'] = false;
}
$han = $_REQUEST['han'];
$tab['han'] = true;
$pay = $_REQUEST['pay'];
$tab['pay'] = true;
$lat = $_REQUEST['lat'];
$lng = $_REQUEST['lng'];
echo json_encode($tab);
if($han != '' && $pay != '' && $msg != '' && $pseudo != '' && $adresse != '' && $ville != ''){
$servername = "localhost";
$username = "root";
$password = "";
try {
$options = array(
PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8'
);
$pdo = new PDO("mysql:host=$servername;dbname=poop_time", $username, $password, $options);
// set the PDO error mode to exception
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e)
{
// echo "Connection failed: " . $e->getMessage();
}
// SELECTION DE L'ID DU PSEUDO DANS LA TABLE USERS
$stmt3 = $pdo->prepare("SELECT id FROM users WHERE users.pseudo = '".$pseudo."'");
$stmt3->execute();
$result2 = $stmt3->fetchAll();
if(empty($result2)){
// INSERTION DU PSEUDO DANS LA TABLE USERS
$stmt1 = $pdo->prepare("INSERT INTO users (pseudo) VALUES (:pseudo)");
$stmt1->bindParam(':pseudo', $pseudo);
$result1 = $stmt1->execute();
// SELECTION DE L'ID DU PSEUDO DANS LA TABLE USERS
$stmt3 = $pdo->prepare("SELECT id FROM users WHERE users.pseudo = '".$pseudo."'");
$stmt3->execute();
$result2 = $stmt3->fetchAll();
}
// SELECTION DE L'ID DE LA VILLE DANS LA TABLE VILLE
$stmt4 = $pdo->prepare("SELECT id FROM ville WHERE ville.nom_ville='".$ville."' ");
$stmt4->execute();
$result3 = $stmt4->fetchAll();
if(empty($result3)){
// INSERTION DE LA VILLE DANS LA TABLE VILLE
$stmt = $pdo->prepare("INSERT INTO ville (nom_ville) VALUES (:ville)");
$stmt->bindParam(':ville', $ville);
$result = $stmt->execute();
// SELECTION DE L'ID DE LA VILLE DANS LA TABLE VILLE
$stmt4 = $pdo->prepare("SELECT id FROM ville WHERE ville.nom_ville='".$ville."' ");
$stmt4->execute();
$result3 = $stmt4->fetchAll();
}
//print_r($_REQUEST);
//INSERTION D'UN NOUVEAU TOILETTE DANS LA TABLE TOILETTE
$stmt5 = $pdo->prepare("INSERT INTO toilettes (latitude, longitude, adresse, handicape, payant, description, ville_id, users_id)
VALUES (".$lat.", ".$lng.", '".$adresse."' , ".$han." , ".$pay.", '".$msg."', ".$result3[0][0].", ".$result2[0][0]." )");
$result4 = $stmt5->execute();
}
?>
<file_sep>$(document).ready(function() {
$("#contact").submit(function(event) {
event.preventDefault();
var formulaire = {
"pseudo": $("#pseudo").val(),
"email" : $("#email").val(),
"ville" : $("#ville").val(),
"msg" : $("#msg").val()
}
$.ajax({
url: "http://localhost/poop_time_v2/verif",
type : 'POST',
dataType: 'json',
data : formulaire,
success: function(success){
if(success.pseudo == ""){
$('#pseudo').css('border', "1px green solid");
}else{
$('#pseudo').css('border', "1px red solid");
}
if(success.msg == ""){
$('#msg').css('border', "1px green solid");
}else{
$('#msg').css('border', "1px red solid");
}
if(success.email == ""){
$('#email').css('border', "1px green solid");
}else{
$('#email').css('border', "1px red solid");
}
if(success.ville == ""){
$('#ville').css('border', "1px green solid");
}else{
$('#ville').css('border', "1px red solid");
}
},
error: function(){
console.log('REQUETE AJAX DEAD ');
},
});
});
});
<file_sep><?php
class Toilettes {
public function selectionToilettes($pdo){
$stmt = $pdo->prepare("SELECT * FROM toilettes");
$stmt->execute();
$result = $stmt->fetchAll();
return $result;
}
public function selectInfoToiletteById($pdo, $id){
$stmt = $pdo->prepare("SELECT adresse, handicape, payant, description, type FROM toilettes WHERE toilettes.id=$id");
$stmt->execute();
$result = $stmt->fetchAll();
return $result;
}
public function insertInfoIntoToilette($pdo, $infos){
$stmt = $pdo->prepare("INSERT INTO toilettes (latitude, longitude, adresse, handicape, payant, description, ville_id, users_id)
VALUES (".$infos['lat'].", ".$infos['lng'].", '".$infos['adresse']."' , ".$infos['han']." , ".$infos['pay'].", '".$infos['msg']."', ".$infos['ville_id'].", ".$infos['users_id']." )");
$stmt->execute();
}
}
?>
<file_sep>$(document).ready(function() {
$("#insert").submit(function(event) {
event.preventDefault();
var formulaire = {
"pseudo": $("#pseudo").val(),
"lat": $("#lat").val(),
"lng": $("#lng").val(),
"adresse": $("#adresse").val(),
"han": $("#han").val(),
"pay": $("#pay").val(),
"ville" : $("#ville").val(),
"msg" : $("#msg").val()
}
$.ajax({
url: "http://localhost/poop_time_v2/insertV",
type : 'POST',
dataType: 'json',
data : formulaire,
success: function(success){
console.log(success);
if(success.pseudo && success.adresse && success.han && success.pay && success.ville && success.msg){
$("#insert").html("");
$("#insert").append("<div class='container'><div class='row'><div class='col s12 center-align'><h4>Toilette ajouté!</h4></div></div></div>");
}
if(!success.ville){
$('#ville').css('border', "1px red solid");
}else {
$('#ville').css('border', "1px green solid");
}
if(!success.pseudo){
$('#pseudo').css('border', "1px red solid");
}else {
$('#pseudo').css('border', "1px green solid");
}
if(!success.adresse){
$('#adresse').css('border', "1px red solid");
}else {
$('#adresse').css('border', "1px green solid");
}
if(!success.msg){
$('#msg').css('border', "1px red solid");
}else {
$('#msg').css('border', "1px green solid");
}
},
error: function(){
console.log('REQUETE AJAX DEAD ');
},
});
});
})
<file_sep><?php
require "./vendor/autoload.php";
$router = new AltoRouter();
$router->setBasePath('poop_time_v2/');
$loader = new Twig_Loader_Filesystem('views');
$twig = new Twig_Environment($loader, array(
'cache' => false,
'debug' => true
));
header('Access-Control-Allow-Origin', '*');
// map homepage
$router->map('GET', '/index.php',function(){
header('Location: http://localhost/poop_time_v2/home');
});
$router->map('GET', '/',function(){
header('Location: http://localhost/poop_time_v2/home');
});
$router->map( 'GET', '/home', function() {
include_once "db_config.php";
include_once "./models/Toilettes.class.php";
$mark = new Toilettes;
$mark2 = $mark->selectionToilettes($pdo);
//print_r($mark2);
global $twig;
echo $twig->render('index.html.twig', array('mark2' => $mark2));
});
$router->map( 'GET', '/[i:id]', function($id) {
include_once "db_config.php";
include_once "./models/Toilettes.class.php";
$toilette = new Toilettes;
$tabInfo['adresse'] = $toilette->selectInfoToiletteById($pdo, $id)[0][0];
$tabInfo['handicape'] = $toilette->selectInfoToiletteById($pdo, $id)[0][1];
$tabInfo['payant'] = $toilette->selectInfoToiletteById($pdo, $id)[0][2];
$tabInfo['description'] = $toilette->selectInfoToiletteById($pdo, $id)[0][3];
$tabInfo['type'] = $toilette->selectInfoToiletteById($pdo, $id)[0][4];
include_once "./models/Ville.class.php";
$ville = new Ville;
$tabInfo['ville'] = $ville->selectVilleById($pdo, $id)[0][0];
include_once "./models/Users.class.php";
$user = new Users;
$tabInfo['user'] = $user->selectUserById($pdo, $id)[0][0];
global $twig;
echo $twig->render('description.html.twig', array('tabInfo' => $tabInfo));
//print_r($tabInfo);
});
$router->map( 'GET', '/description', function() {
global $twig;
echo $twig->render('description.html.twig');
});
$router->map( 'GET', '/form', function() {
$a = ['one' => 1, 'two' => 2, 'three' => 3, 'four' => 4];
global $twig;
echo $twig->render('form.html.twig', array('data' => $a));
});
$router->map( 'GET', '/history', function() {
global $twig;
echo $twig->render('history.html.twig');
});
$router->map( 'GET', '/apropos', function() {
global $twig;
echo $twig->render('apropos.html.twig');
});
$router->map( 'GET', '/contact', function() {
global $twig;
echo $twig->render('contact.html.twig');
});
$router->map( 'GET', '/merci', function() {
global $twig;
echo $twig->render('contactOk.html.twig');
});
$router->map( 'GET', '/insert', function() {
require_once "db_config.php";
global $twig;
echo $twig->render('insert.html.twig');
});
$router->map( 'POST', '/insertV', function() {
include "./models/insert.php";
});
$router->map( 'POST', '/verif', function() {
include "./models/contact.php";
});
$router->map( 'GET', '/test', function() {
echo "Bonjour";
});
$match = $router->match();
// call closure or throw 404 status
if( $match && is_callable( $match['target'] ) ) {
call_user_func_array( $match['target'], $match['params'] );
} else {
// no route was matched
header( $_SERVER["SERVER_PROTOCOL"] . ' 404 Not Found');
}
?>
<file_sep>-- MySQL Script generated by MySQL Workbench
-- lun. 18 déc. 2017 16:14:59 CET
-- Model: New Model Version: 1.0
-- MySQL Workbench Forward Engineering
SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0;
SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0;
SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='TRADITIONAL,ALLOW_INVALID_DATES';
-- -----------------------------------------------------
-- Schema poop_time
-- -----------------------------------------------------
DROP SCHEMA IF EXISTS `poop_time` ;
-- -----------------------------------------------------
-- Schema poop_time
-- -----------------------------------------------------
CREATE SCHEMA IF NOT EXISTS `poop_time` DEFAULT CHARACTER SET utf8 ;
USE `poop_time` ;
-- -----------------------------------------------------
-- Table `poop_time`.`ville`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `poop_time`.`ville` ;
CREATE TABLE IF NOT EXISTS `poop_time`.`ville` (
`id` INT NOT NULL AUTO_INCREMENT,
`nom_ville` VARCHAR(245) NULL,
PRIMARY KEY (`id`))
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `poop_time`.`users`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `poop_time`.`users` ;
CREATE TABLE IF NOT EXISTS `poop_time`.`users` (
`id` INT NOT NULL AUTO_INCREMENT,
`pseudo` VARCHAR(245) NULL,
PRIMARY KEY (`id`))
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `poop_time`.`toilettes`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `poop_time`.`toilettes` ;
CREATE TABLE IF NOT EXISTS `poop_time`.`toilettes` (
`id` INT NOT NULL AUTO_INCREMENT,
`longitude` DECIMAL(11,8) NOT NULL,
`latitude` DECIMAL(10,8) NOT NULL,
`adresse` VARCHAR(245) NULL,
`handicape` TINYINT(1) NULL,
`payant` TINYINT(1) NULL,
`description` LONGTEXT NULL,
`type` VARCHAR(245) NULL,
`ville_id` INT NOT NULL,
`users_id` INT NOT NULL,
PRIMARY KEY (`id`),
INDEX `fk_toilettes_ville_idx` (`ville_id` ASC),
INDEX `fk_toilettes_users1_idx` (`users_id` ASC),
CONSTRAINT `fk_toilettes_ville`
FOREIGN KEY (`ville_id`)
REFERENCES `poop_time`.`ville` (`id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fk_toilettes_users1`
FOREIGN KEY (`users_id`)
REFERENCES `poop_time`.`users` (`id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `poop_time`.`avis`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `poop_time`.`avis` ;
CREATE TABLE IF NOT EXISTS `poop_time`.`avis` (
`id` INT NOT NULL AUTO_INCREMENT,
`note` INT NULL,
`commentaire` LONGTEXT NULL,
`users_id` INT NOT NULL,
`toilettes_id` INT NOT NULL,
PRIMARY KEY (`id`),
INDEX `fk_avis_users1_idx` (`users_id` ASC),
INDEX `fk_avis_toilettes1_idx` (`toilettes_id` ASC),
CONSTRAINT `fk_avis_users1`
FOREIGN KEY (`users_id`)
REFERENCES `poop_time`.`users` (`id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fk_avis_toilettes1`
FOREIGN KEY (`toilettes_id`)
REFERENCES `poop_time`.`toilettes` (`id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `poop_time`.`fun_fact`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `poop_time`.`fun_fact` ;
CREATE TABLE IF NOT EXISTS `poop_time`.`fun_fact` (
`id` INT NOT NULL,
`description` LONGTEXT NULL,
PRIMARY KEY (`id`))
ENGINE = InnoDB;
SET SQL_MODE=@OLD_SQL_MODE;
SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS;
SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS;
| 5c38a8917e66347b6565ff65ff749a00fbd59c0b | [
"JavaScript",
"SQL",
"PHP"
] | 9 | PHP | Fawlia/poop_time_v2 | 00db9330b0184a34846bce3cfa5748b9de656e49 | b38dcc437a5c43f03518d3cc7d4cf88883350fe7 |
refs/heads/master | <repo_name>hellogoodbyemae/bamazon<file_sep>/bamazonManager.js
var mysql = require("mysql");
var inquirer = require("inquirer");
var consoletable = require("console.table");
var connection = mysql.createConnection({
host: "localhost",
port: 3306,
user: "root",
password: "<PASSWORD>",
database: "bamazon_DB"
});
connection.connect(function (err) {
if (err) throw err;
console.log("connected as id " + connection.threadId + "\n");
managementView();
});
function managementView() {
inquirer
.prompt({
name: "action",
type: "list",
message: "What would you like to do?",
choices: [
"View Products for Sale",
"View Low Inventory",
"Add to Inventory",
"Add New Product",
"Exit"
]
})
.then(function(answer) {
switch (answer.action) {
case "View Products for Sale":
displayInventory();
break;
case "View Low Inventory":
inventoryLow();
break;
case "Add to inventory":
inventoryAdd();
break;
case "Add New Product":
newProduct();
break;
case "exit":
connection.end();
break;
}
});
}
function displayInventory() {
connection.query("SELECT * FROM products", function (err, res) {
if (err) throw err;
console.table(res);
managementView();
})
}
function inventoryLow() {
connection.query("SELECT * FROM products WHERE stock_quantity BETWEEN 1 AND 50", function (err, res) {
if (err) throw err;
for (var i = 0; i < res.length; i++) {
console.table(res);
}
managementView();
})
}
// function inventoryAdd() {
// inquirer
// .prompt([
// {
// name: "item",
// type: "list",
// message: "What item would you like to increase inventory for?"
// },
// {
// name: "stock",
// type: "input",
// message: "How many are you adding?",
// validate: function(value) {
// if (isNaN(value) === false) {
// return true;
// }
// return false;
// }
// }
// ])
// .then(function(answer) {
// connection.query(
// "UPDATE products SET ? WHERE ?",
// [
// {
// product_name: answer.item
// },
// {
// stock_quantity: answer.stock
// }
// ],
// function(err) {
// if (err) throw err;
// console.log("Your item was updated successfully!");
// managementView();
// }
// );
// });
// }
function newProduct() {
inquirer
.prompt([
{
name: "item",
type: "input",
message: "What is the item you would like to add?"
},
{
name: "department",
type: "input",
message: "What department does this item belong in?"
},
{
name: "price",
type: "input",
message: "How much does this cost?",
validate: function(value) {
if (isNaN(value) === false) {
return true;
}
return false;
}
},
{
name: "stock",
type: "input",
message: "How many?",
validate: function(value) {
if (isNaN(value) === false) {
return true;
}
return false;
}
}
])
.then(function(answer) {
connection.query(
"INSERT INTO products SET ?",
{
product_name: answer.item,
department_name: answer.department,
price: answer.price,
stock_quantity: answer.stock
},
function(err) {
if (err) throw err;
console.log("Your item was created successfully!");
managementView();
}
);
});
}<file_sep>/bamazonSchema.sql
DROP DATABASE IF EXISTS bamazon_DB;
CREATE DATABASE bamazon_DB;
USE bamazon_DB;
CREATE TABLE products(
item_id INT NOT NULL AUTO_INCREMENT,
product_name VARCHAR(100) NOT NULL,
department_name VARCHAR(45) NOT NULL,
price DECIMAL(10,2) NULL,
stock_quantity INT default 0,
PRIMARY KEY (item_id)
);
INSERT INTO products (product_name, department_name, price, stock_quantity)
VALUES ("queen mattress", "bedroom", 899.99, 45);
INSERT INTO products (product_name, department_name, price, stock_quantity)
VALUES ("night stand", "bedroom", 199.99, 145);
INSERT INTO products (product_name, department_name, price, stock_quantity)
VALUES ("5pc bed set", "bedroom", 49.99, 50);
INSERT INTO products (product_name, department_name, price, stock_quantity)
VALUES ("picture frame", "decor", 9.99, 500);
INSERT INTO products (product_name, department_name, price, stock_quantity)
VALUES ("wall clock", "decor", 63.99, 100);
INSERT INTO products (product_name, department_name, price, stock_quantity)
VALUES ("welcome mats", "decor", 5.99, 150);
INSERT INTO products (product_name, department_name, price, stock_quantity)
VALUES ("island with 2 stools", "kitchen", 1112.99, 60);
INSERT INTO products (product_name, department_name, price, stock_quantity)
VALUES ("refrigerator", "kitchen", 1999.99, 50);
INSERT INTO products (product_name, department_name, price, stock_quantity)
VALUES ("microwave", "kitchen", 299.99, 45); | bae581e4158709a1441dc868f448f81759be6de0 | [
"JavaScript",
"SQL"
] | 2 | JavaScript | hellogoodbyemae/bamazon | c38ed8013928beb5d3a08807c287101cf429e361 | 81dff0eb85f559da604445e7f0016b2124534f76 |
refs/heads/master | <repo_name>Hyunsik-Yoo/retrofit-example-kotlin<file_sep>/app/src/main/java/com/example/hyunsikyoo/retrofit_example_kotlin/model/GithubRepoModel.kt
package com.example.hyunsikyoo.retrofit_example_kotlin.model
import com.google.gson.annotations.SerializedName
class GithubRepoModel {
@SerializedName("id")
val id: Long = 0
@SerializedName("name")
val name: String = ""
@SerializedName("full_name")
val fullName: String = ""
}<file_sep>/README.md
# retrofit-example-kotlin<file_sep>/app/src/main/java/com/example/hyunsikyoo/retrofit_example_kotlin/MainActivity.kt
package com.example.hyunsikyoo.retrofit_example_kotlin
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.widget.Toast
import com.example.hyunsikyoo.retrofit_example_kotlin.model.GithubResponseModel
import com.example.hyunsikyoo.retrofit_example_kotlin.retrofit.GithubApi
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.schedulers.Schedulers
class MainActivity : AppCompatActivity() {
lateinit var compositeDisposable: CompositeDisposable
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
compositeDisposable = CompositeDisposable()
compositeDisposable.add(GithubApi.getRepoList("test")
.observeOn(AndroidSchedulers.mainThread())
.subscribeOn(Schedulers.newThread())
.subscribe({ response: GithubResponseModel ->
for (item in response.items) {
Log.d("MainActivity", item.name)
}
}, { error: Throwable ->
Log.d("MainActivity", error.localizedMessage)
Toast.makeText(this, "Error ${error.localizedMessage}", Toast.LENGTH_SHORT).show()
}))
}
override fun onDestroy() {
super.onDestroy()
compositeDisposable.dispose()
}
}
| af4289ca2a765108065b89d2a8df5f1080fb8afe | [
"Markdown",
"Kotlin"
] | 3 | Kotlin | Hyunsik-Yoo/retrofit-example-kotlin | 2bfaaf163d1d0fc5ea5323e8226839a267ff5cfd | 81d46395c2b8e92d5bddf6499a82a72f07ffc02d |
refs/heads/master | <repo_name>pkun/birq<file_sep>/balance.h
#ifndef _balance_h
#define _balance_h
#include "lub/list.h"
#include "irq.h"
#include "cpu.h"
typedef enum {
BIRQ_CHOOSE_MAX,
BIRQ_CHOOSE_MIN,
BIRQ_CHOOSE_RND
} birq_choose_strategy_e;
int remove_irq_from_cpu(irq_t *irq, cpu_t *cpu);
int move_irq_to_cpu(irq_t *irq, cpu_t *cpu);
int balance(lub_list_t *cpus, lub_list_t *balance_irqs,
float load_limit, cpumask_t *exclude_cpus, int non_local_cpus);
int apply_affinity(lub_list_t *balance_irqs);
int choose_irqs_to_move(lub_list_t *cpus, lub_list_t *balance_irqs,
float threshold, birq_choose_strategy_e strategy,
cpumask_t *exclude_cpus);
#endif
| 9098d5d65889ff81f855d78dc119f5a326576542 | [
"C"
] | 1 | C | pkun/birq | 44e6a590db31f89e44737db19a1b0d13f98b80ee | be3bcdcf8b4853100e93ade4bf8b19849d43e805 |
refs/heads/develop | <repo_name>Eazybee/useFormBee<file_sep>/webpack/development.js
const ErrorOverlayPlugin = require('error-overlay-webpack-plugin');
module.exports = {
devServer: {
historyApiFallback: true,
port: 8000
},
plugins: [new ErrorOverlayPlugin()],
};
<file_sep>/test/fixtures/app.js
export const validInputs = {
username: 'Eazybee',
age: 12,
};
export const inValidInputs = {
username: 'Eazybee123',
age: '12A',
};
<file_sep>/src/hooks/useFormBee.js
import { useState } from 'react';
import Validator from 'validatorjs';
import formatter from '../helpers/formatter';
const useForm = ({ callback, rules }) => {
const initialState = () => {
const state = {};
Object.keys(rules).forEach((key) => { state[key] = ''; });
return state;
};
const [values, setValues] = useState(initialState());
const [errors, setErrors] = useState({});
Validator.setAttributeFormatter(attribute => formatter(attribute));
const validateOnSubmit = () => {
let hasError = true;
const newErrors = { ...errors };
Object.keys(rules).forEach((key) => {
const validate = (name, value) => {
const validation = new Validator(
{ [name]: value },
{ [name]: rules[name] },
);
const errorMessage = validation.fails() && validation.errors.first(name);
if (errorMessage) {
newErrors[name] = errorMessage;
hasError = false;
} else {
delete newErrors[name];
}
};
if (Array.isArray(values[key])) {
values[key].forEach(value => validate(key, value));
} else {
validate(key, values[key]);
}
});
setErrors({ ...newErrors });
return hasError;
};
const errorHandler = (name, value, message) => {
setErrors({
...errors,
[name]: message,
});
setValues({
...values,
[name]: value,
});
return false;
};
const validateOnChange = (event) => {
const { target } = event;
const { required, name, type } = target;
let { value } = target;
if (type === 'checkbox') {
value = target.checked;
if (required && !value) {
return errorHandler(name, value, `The ${formatter(name)} must be accepted.`);
}
} else if (required && value.trim() === '') {
return errorHandler(name, value, `The ${formatter(name)} field cannot be empty.`);
}
const validation = new Validator(
{ [name]: value },
{ [name]: rules[name] },
);
if (validation.fails()) {
return errorHandler(name, value, validation.errors.first(name));
}
return true;
};
const getMultipleSelection = (event) => {
const { options } = event.target;
const selected = Object.entries(options).filter(([, option]) => option.selected);
const value = selected.map(([, option]) => option.value);
return value;
};
const handleChange = (event) => {
const { target } = event;
if (validateOnChange(event)) {
let { value } = target;
if (target.type === 'select-multiple') {
value = getMultipleSelection(event);
}
if (target.type === 'checkbox') {
value = target.checked;
}
setValues({
...values,
[target.name]: value,
});
delete errors[target.name];
setErrors({ ...errors });
return true;
}
return false;
};
const sanitizeData = () => {
const data = {};
Object.keys(values).forEach((field) => {
if (Array.isArray(values[field])) {
data[field] = values[field].map(value => value.trim());
} else if (typeof values[field] === 'boolean') {
data[field] = values[field];
} else {
data[field] = values[field].trim();
}
});
return data;
};
const handleSubmit = (event) => {
event.preventDefault();
if (validateOnSubmit()) {
const data = sanitizeData();
return callback(data);
}
return false;
};
const handleReset = () => {
setValues(initialState());
setErrors({});
};
return {
values, handleChange, handleSubmit, errors, handleReset,
};
};
export default useForm;
<file_sep>/jest.config.js
const config = {
verbose: true,
moduleNameMapper: {
'\\.(css)$': '<rootDir>/test/config/assetTransformer.js',
},
collectCoverage: true,
coveragePathIgnorePatterns: [
'<rootDir>/test/config/assetTransformer.js',
'<rootDir>/(build|dist|docs|node_modules)/',
],
};
module.exports = config;
<file_sep>/webpack/production.js
const UglifyJsPlugin = require('uglifyjs-webpack-plugin');
const OptimizeCSSAssetsPlugin = require('optimize-css-assets-webpack-plugin');
module.exports = {
devtool: 'source-map',
performance: {
hints: false,
},
optimization: {
minimizer: [
new UglifyJsPlugin({
test: /\.(js|jsx)$/,
exclude: /node_modules/,
cache: true,
parallel: true,
}),
new OptimizeCSSAssetsPlugin({})
]
},
};
<file_sep>/src/helpers/formatter.spec.js
import formatter from './formatter';
describe('App Component', () => {
it('should format PasCal name convention', () => {
const pascalCase = 'PasCal';
const formatted = formatter(pascalCase);
expect(formatted).not.toBe(pascalCase);
expect(formatted).toBe('pas cal');
});
it('should format camelCase name convention', () => {
const camelCase = 'camelCaseConvention';
const formatted = formatter(camelCase);
expect(formatted).not.toBe(camelCase);
expect(formatted).toBe('camel case convention');
});
it('should format sanke_case name convention', () => {
const snakeCase = 'snake_case_convention';
const formatted = formatter(snakeCase);
expect(formatted).not.toBe(snakeCase);
expect(formatted).toBe('snake case convention');
});
});
<file_sep>/test/fixtures/useFormBee.js
export const rules = {
username: 'required|alpha',
age: 'numeric',
};
export const event = {
target: {
value: 'EazyBee',
name: 'username',
},
};
export const checkBoxEvent = {
type: 'checkbox', checked: true, name: 'agreement', required: true,
};
export const multipleSelectEvent = {
type: 'select-multiple',
name: 'friends',
value: '',
options: {
0: {
selected: true,
value: 'simi',
},
1: {
selected: true,
value: 'mosimi',
},
2: {
selected: false,
value: 'eazybee',
},
},
};
export const getEvent = newValues => ({
target: {
...event.target,
...newValues,
},
});
export const callback = values => ['callback called', values];
<file_sep>/src/hooks/useFormBee.spec.js
import { renderHook, act } from '@testing-library/react-hooks';
import useFormBee from './useFormBee';
import {
callback, rules, event, getEvent, checkBoxEvent, multipleSelectEvent,
} from '../../test/fixtures/useFormBee';
describe('userForm hook', () => {
it(' should render', () => {
const { result } = renderHook(() => useFormBee({ callback, rules }));
const {
values, errors, handleChange, handleSubmit, handleReset,
} = result.current;
expect(values.age).toBe('');
expect(errors.age).toBe(undefined);
expect(values.username).toBe('');
expect(errors.ausername).toBe(undefined);
expect(typeof handleChange).toBe('function');
expect(typeof handleSubmit).toBe('function');
expect(typeof handleReset).toBe('function');
});
describe('handleChange function', () => {
it('should update username field value', () => {
const { result } = renderHook(() => useFormBee({ callback, rules }));
const { handleChange } = result.current;
let valid;
act(() => {
valid = handleChange(event);
});
const {
values: { username }, errors,
} = result.current;
expect(valid).toBe(true);
expect(username).toBe('EazyBee');
expect(errors.username).toBe(undefined);
});
it('should have error when passed empty string for a required field',
() => {
const { result } = renderHook(() => useFormBee({ callback, rules }));
const { handleChange } = result.current;
let valid;
act(() => {
valid = handleChange(getEvent({ required: true, value: ' ' }));
});
const { values: { username }, errors } = result.current;
expect(valid).toBe(false);
expect(username).toBe(' ');
expect(errors.username).toBe('The username field cannot be empty.');
});
it('should have error when passed data with invalid data type', () => {
const { result } = renderHook(() => useFormBee({ callback, rules }));
const { handleChange } = result.current;
let valid;
act(() => {
valid = handleChange(getEvent({ required: true, value: '1234' }));
});
const { values: { username }, errors } = result.current;
expect(valid).toBe(false);
expect(username).toBe('1234');
expect(errors.username)
.toBe('The username field must contain only alphabetic characters.');
});
it('should update checkbox', () => {
const { result } = renderHook(() => useFormBee({ callback, rules: { agreement: 'required|boolean' } }));
const { handleChange } = result.current;
let valid;
act(() => {
valid = handleChange(getEvent(checkBoxEvent));
});
const { values: { agreement }, errors } = result.current;
expect(valid).toBe(true);
expect(agreement).toBe(true);
expect(errors.agreement).toBe(undefined);
});
it('should update checkbox and display required messaged for a required field', () => {
const { result } = renderHook(() => useFormBee({ callback, rules: { agreement: 'required|boolean' } }));
const { handleChange } = result.current;
let valid;
act(() => {
valid = handleChange(getEvent({ ...checkBoxEvent, checked: false, required: true }));
});
const { values: { agreement }, errors } = result.current;
expect(valid).toBe(false);
expect(agreement).toBe(false);
expect(errors.agreement).toBe('The agreement must be accepted.');
});
it('should update multiple select', () => {
const { result } = renderHook(() => useFormBee({
callback, rules: { friends: ['alpha', { in: ['simi', 'mosimi', 'eazybee'] }] },
}));
const { handleChange } = result.current;
let valid;
act(() => {
valid = handleChange(getEvent(multipleSelectEvent));
});
const { values: { friends }, errors } = result.current;
expect(valid).toBe(true);
expect(Array.isArray(friends)).toBe(true);
expect(friends[0]).toBe('simi');
expect(friends[1]).toBe('mosimi');
expect(errors.friends).toBe(undefined);
});
});
describe('handleSubmit function', () => {
it('should submit and call calback function', () => {
const { result } = renderHook(() => useFormBee(
{ callback, rules: { username: 'alpha' } },
));
const { handleSubmit } = result.current;
let callbackResponse;
act(() => {
callbackResponse = handleSubmit({ preventDefault: () => '' });
});
expect(callbackResponse).toBeInstanceOf(Array);
expect(callbackResponse.length).toBe(2);
expect(callbackResponse[0]).toBe('callback called');
});
it('should not submit nor call calback function', () => {
const { result } = renderHook(() => useFormBee({ callback, rules }));
const { handleSubmit } = result.current;
let callbackResponse;
act(() => {
callbackResponse = handleSubmit({ preventDefault: () => '' });
});
const { values: { username }, errors } = result.current;
expect(callbackResponse).toBe(false);
expect(username).toBe('');
expect(errors.username).toBe('The username field is required.');
});
});
describe('handleReset function', () => {
it('should clear all inputs field when called', () => {
const { result } = renderHook(() => useFormBee({ callback, rules }));
const { handleReset } = result.current;
act(() => {
handleReset();
});
const {
values: { username }, errors,
} = result.current;
expect(username).toBe('');
expect(Object.keys(errors).length).toBe(0);
});
});
});
<file_sep>/README.md
<div align="center">
<h1>useFormBee</h1>
<a href="https://www.emojione.com/emoji/1f989">
<img
height="80"
width="80"
alt="owl"
src="https://scontent-lht6-1.xx.fbcdn.net/v/t1.0-9/46520271_2143919952537259_6137294672965402624_o.png?_nc_cat=106&_nc_oc=AQmkRe0pNN2W6XUOobH_m5wkJpRRhFxu3UJCUwgL21tTvHVDvAqRoDR43GP47-Vmhxo&_nc_ht=scontent-lht6-1.xx&oh=bf069a21d65b435c567b576e9284ccb5&oe=5DD222FF"
/>
</a>
<p>This is a react form handler</p>
</div>
<hr />
[](https://travis-ci.com/Eazybee/useFormBee) <a href="https://codeclimate.com/github/Eazybee/useFormBee/test_coverage"><img src="https://api.codeclimate.com/v1/badges/d103b30217999d81e940/test_coverage" /></a> <a href="https://codeclimate.com/github/Eazybee/useFormBee/maintainability"><img src="https://api.codeclimate.com/v1/badges/d103b30217999d81e940/maintainability" /></a> [](https://opensource.org/licenses/MIT) [](http://makeapullrequest.com) [](https://www.npmjs.com/package/useformbee)
## The problem
Handling forms in react can be a little bit tedious especially for new beginners like me 😃. **I often find myself re-writing the same stateful logic and form validations**, especially when I have different forms in different components (such as _signup, login, profile update form_).
## Inspiration
My mentor <a href='https://github.com/benfluleck'>@benfluleck</a> suggested I abstract my form logic so that it can easily be reusable. I created a useForm hook and showed it to him and my other colleague. To my surprise, they loved it and adviced that I made some improvements on it and also upload it to [npm](https://npmjs.com/package/useformbee) as a library.
## The solution
**useFormBee** is a custom react hook that helps me manage and abstract form logic.<br>
Form logic such as
- values
- onChange
- onSubmit
- onReset
Harnessing the power of <a href='https://www.npmjs.com/package/validatorjs'>validatorjs</a>, I integrated validations to the useForm hooks.
<hr>
## Installation
This module is distributed via <a href='https://www.npmjs.com/'>npm</a>
```bash
npm install useformbee
```
## Usage
##### Import
```javascript
import useFormBee from 'useformbee';
```
```javascript
const { values, errors, handleChange, handleSubmit, handleReset } = useFormBee({ callback, rules });
```
##### Parameter
useformbee takes an object as its parameter. The object parameter must have two attribute `callback` and `rules`.
- The `callback` is the function that will be called when the form is submitted and passes all validation.
- The `rules` is an object of <a href='https://www.npmjs.com/package/validatorjs'>validatorjs</a> rules
##### Returns
useformbee returns an object of 5 attributes.
- values (object)
- errors (object)
- handleChange (function)
- handleSubmit (function)
- handleReset (function)
## Form Example
```javascript
const Form = () => {
// prepare your inputs rules
// read more about validatorjs rule -> https://www.npmjs.com/package/validatorjs
const rules = {
firstName: 'alpha|required',
age: 'numeric',
};
// create you callback function
const saveFormData = (values) => {
// ...your logic
};
const {
values, handleChange, handleSubmit, errors, handleReset,
} = useFormBee({ callback: saveFormData, rules });
// destructure field values
// the values is created from Object.keys(rules)
const { firstName, age } = values;
return (
<form onSubmit={handleSubmit} onReset={handleReset}>
<input
type='text'
value ={firstName}
onChange={handleChange}
name='firstName'
required
/>
{/* display username error if there is an error */}
{errors.firstName && <p>{errors.firstName }</p>}
<br />
<input
type='text'
value ={age}
onChange={handleChange}
name='age'
/>
{/* display age error if there is an error */}
{errors.age && <p>{errors.age}</p>}
<br />
<button type='submit'>Submit</button>
<button type='reset'>Reset</button>
</form>
);
};
```
## Contributors
Thanks goes to these people <a href='https://allcontributors.org/docs/en/emoji-key'>(emoji key)</a>
<table>
<tr>
<td align="center"><a href="https://github.com/Eazybee"><img src="https://avatars3.githubusercontent.com/u/36575414?s=460&v=4" width="100px;" alt="<NAME>"/><br /><sub><b><NAME></b></sub></a><br /><a href="#" title="Idea">🤔</a> <a href="#" title="Code">💻</a> <a href="#" title="Tests">⚠️</a> <a href="#" title="Doc">📖</a></td>
<td align="center"><a href="https://github.com/benfluleck"><img src="https://avatars0.githubusercontent.com/u/26222856?s=400&v=4" width="100px;" alt="<NAME>"/><br /><sub><b><NAME></b></sub></a><br /><a href="#" title="Review">👀</a> <a href="#" title="Tests">⚠️</a></td>
</tr>
</table>
## LICENSE
- [MIT](https://github.com/Eazybee/useFormBee/blob/develop/LICENSE)<file_sep>/webpack.config.js
const webpackMerge = require('webpack-merge');
const commonConfig = require('./webpack/common');
module.exports = env => {
let envConfig;
!env.mode
? (envConfig = require(`./webpack/development`))
: (envConfig = require(`./webpack/${env.mode}`))
console.log(env);
return webpackMerge({ mode: env.mode }, commonConfig, envConfig);
};
| 096530a31bc75a87b470f9a1ce4d0c30eb51f99b | [
"JavaScript",
"Markdown"
] | 10 | JavaScript | Eazybee/useFormBee | 1d1d1f722569f15e33f501cf5fc5d78d4acb171f | cf27bb6dc9e79882442042695e35a7311316b571 |
refs/heads/master | <repo_name>trzy/realsense<file_sep>/util/format.h
#ifndef INCLUDED_FORMAT_H
#define INCLUDED_FORMAT_H
#include <string>
#include <sstream>
#include <iomanip>
#include <cstdint>
#include <vector>
namespace Util
{
class Format
{
public:
template <typename T>
Format &operator<<(const T &data)
{
m_stream << data;
return *this;
}
operator std::string() const
{
return str();
}
std::string str() const
{
return m_stream.str();
}
template <typename T>
Format &Join(const T &collection)
{
std::string separator = m_stream.str();
clear();
for (auto it = collection.begin(); it != collection.end(); )
{
m_stream << *it;
++it;
if (it != collection.end())
m_stream << separator;
}
return *this;
}
std::vector<std::string> Split(char separator)
{
// Very inefficient: lots of intermediate string copies!
std::string str = m_stream.str();
const char *start = str.c_str();
const char *end = start;
std::vector<std::string> parts;
do
{
if (*end == separator || !*end)
{
size_t len = end - start;
if (len)
parts.emplace_back(start, len);
else
parts.emplace_back();
start = end + 1;
}
++end;
} while (end[-1]);
return parts;
}
Format(const std::string &str)
: m_stream(str)
{
}
Format()
{
}
private:
std::stringstream m_stream;
void clear()
{
m_stream.str(std::string());
}
};
const std::string Hex(uint32_t n, size_t num_digits);
const std::string Hex(uint32_t n);
const std::string Hex(uint16_t n);
const std::string Hex(uint8_t n);
} // Util
#endif // INCLUDED_FORMAT_H
<file_sep>/util/realsense_formatters.cpp
#include "util/realsense_formatters.h"
#include "util/format.h"
#include <map>
namespace Util {
namespace RealSense {
const std::map<PXCImage::PixelFormat, const char *> s_pixel_format
{
{ PXCImage::PixelFormat::PIXEL_FORMAT_YUY2, "PIXEL_FORMAT_YUY2" },
{ PXCImage::PixelFormat::PIXEL_FORMAT_NV12, "PIXEL_FORMAT_NV12" },
{ PXCImage::PixelFormat::PIXEL_FORMAT_RGB32, "PIXEL_FORMAT_RGB32" },
{ PXCImage::PixelFormat::PIXEL_FORMAT_RGB24, "PIXEL_FORMAT_RGB24" },
{ PXCImage::PixelFormat::PIXEL_FORMAT_Y8, "PIXEL_FORMAT_Y8" },
{ PXCImage::PixelFormat::PIXEL_FORMAT_Y8_IR_RELATIVE, "PIXEL_FORMAT_Y8_IR_RELATIVE" },
{ PXCImage::PixelFormat::PIXEL_FORMAT_Y16, "PIXEL_FORMAT_Y16" },
{ PXCImage::PixelFormat::PIXEL_FORMAT_DEPTH, "PIXEL_FORMAT_DEPTH" },
{ PXCImage::PixelFormat::PIXEL_FORMAT_DEPTH_RAW, "PIXEL_FORMAT_DEPTH_RAW" },
{ PXCImage::PixelFormat::PIXEL_FORMAT_DEPTH_F32, "PIXEL_FORMAT_DEPTH_F32" },
{ PXCImage::PixelFormat::PIXEL_FORMAT_DEPTH_CONFIDENCE, "PIXEL_FORMAT_DEPTH_CONFIDENCE" }
};
static const char * ToString(PXCImage::PixelFormat fmt)
{
auto it = s_pixel_format.find(fmt);
if (it == s_pixel_format.end())
return "UNKNOWN";
return it->second;
}
const std::map<pxcStatus, const char *> s_status
{
{ PXC_STATUS_NO_ERROR, "PXC_STATUS_NO_ERROR" },
{ PXC_STATUS_DEVICE_BUSY, "PXC_STATUS_DEVICE_BUSY" },
{ PXC_STATUS_PARAM_UNSUPPORTED, "PXC_STATUS_UNSUPPORTED" },
{ PXC_STATUS_ITEM_UNAVAILABLE, "PXC_STATUS_ITEM_UNAVAILABLE" }
// Still more to add...
};
static const char * ToString(pxcStatus status)
{
auto it = s_status.find(status);
if (it == s_status.end())
return "UNKNOWN";
return it->second;
}
} // RealSense
} // Util
std::ostream & operator<<(std::ostream &os, PXCImage::PixelFormat fmt)
{
os << Util::RealSense::ToString(fmt);
return os;
}
std::ostream & operator<<(std::ostream &os, pxcStatus status)
{
os << Util::RealSense::ToString(status);
return os;
}
<file_sep>/capture/main.cpp
#include "util/format.h"
#include "util/realsense_formatters.h"
#include <pxcsensemanager.h>
#include <wx/wx.h>
#include <wx/rawbmp.h>
#include <wx/dcbuffer.h>
#include <map>
#include <mutex>
#include <cstdint>
static void Error(wxWindow *parent, const std::string &message)
{
wxMessageDialog msg(parent, wxString(message), wxT("Error"), wxOK | wxCENTER | wxICON_ERROR);
msg.ShowModal();
}
class MyPanel : public wxPanel
{
private:
wxBitmap m_bmp{ 640, 480, 24 }; // must be 24-bit to access with wxNativePixelData
public:
MyPanel(wxFrame *parent)
: wxPanel(parent, wxID_ANY, wxDefaultPosition, wxSize(640, 480))
{
SetBackgroundStyle(wxBG_STYLE_PAINT);
}
wxBitmap & GetBitmap()
{
return m_bmp;
}
void PaintEvent(wxPaintEvent &evt)
{
wxAutoBufferedPaintDC dc(this);
Render(dc);
}
void PaintNow()
{
wxClientDC dc(this);
Render(dc);
}
void Render(wxDC &dc)
{
dc.DrawBitmap(m_bmp, 0, 0);
}
DECLARE_EVENT_TABLE();
};
BEGIN_EVENT_TABLE(MyPanel, wxPanel)
EVT_PAINT(MyPanel::PaintEvent)
END_EVENT_TABLE()
class MyApp : public wxApp
{
private:
wxFrame *m_frame;
MyPanel *m_color_panel;
MyPanel *m_depth_panel;
PXCSenseManager *m_sense_mgr;
bool m_render_loop_active = false;
public:
void DrawColorFrame(wxBitmap *bmp, PXCImage *color)
{
PXCImage::ImageInfo info = color->QueryInfo();
PXCImage::ImageData data;
pxcStatus status = color->AcquireAccess(PXCImage::Access::ACCESS_READ, PXCImage::PixelFormat::PIXEL_FORMAT_RGB24, &data);
if (PXC_STATUS_NO_ERROR != status)
m_frame->SetStatusText(std::string(Util::Format() << status));
else
{
wxNativePixelData pixels(*bmp);
if (!pixels || bmp->GetWidth() != info.width || bmp->GetHeight() != info.height || data.pitches[0] != info.width * 3)
return; //TODO: display an error if could not get pixels or if image is not of expected type
auto p = pixels.GetPixels();
int i = 0;
for (int y = 0; y < info.height; y++)
{
auto row_start = p;
for (int x = 0; x < info.width; x++)
{
p.Blue() = data.planes[0][i + 0];
p.Green() = data.planes[0][i + 1];
p.Red() = data.planes[0][i + 2];
i += 3;
++p;
}
p = row_start;
p.OffsetY(pixels, 1);
}
}
}
//TODO: templatize
void DrawDepthFrame(wxBitmap *bmp, PXCImage *depth)
{
PXCImage::ImageInfo info = depth->QueryInfo();
PXCImage::ImageData data;
pxcStatus status = depth->AcquireAccess(PXCImage::Access::ACCESS_READ, PXCImage::PixelFormat::PIXEL_FORMAT_DEPTH, &data);
if (PXC_STATUS_NO_ERROR != status)
m_frame->SetStatusText(std::string(Util::Format() << status));
else
{
wxNativePixelData pixels(*bmp);
if (!pixels || bmp->GetWidth() != info.width || bmp->GetHeight() != info.height || data.pitches[0] != info.width * 2)
return; //TODO: display an error if could not get pixels or if image is not of expected type
auto p = pixels.GetPixels();
int i = 0;
for (int y = 0; y < info.height; y++)
{
auto row_start = p;
for (int x = 0; x < info.width; x++)
{
uint16_t z_raw = uint16_t(data.planes[0][i + 0] << 8) | data.planes[0][i + 1];
//uint16_t z_raw = *(uint16_t *) &(data.planes[0][i]);
uint8_t z = uint8_t(255.0f * float(z_raw) / float(0xffff));
p.Blue() = z;
p.Green() = z;
p.Red() = z;
i += 2;
++p;
}
p = row_start;
p.OffsetY(pixels, 1);
}
}
}
void OnIdle(wxIdleEvent &evt)
{
if (!m_render_loop_active)
return;
if (m_sense_mgr->AcquireFrame(true) != PXC_STATUS_NO_ERROR)
goto do_nothing;
PXCCapture::Sample *sample = m_sense_mgr->QuerySample();
DrawColorFrame(&m_color_panel->GetBitmap(), sample->color);
DrawDepthFrame(&m_depth_panel->GetBitmap(), sample->depth);
m_sense_mgr->ReleaseFrame();
static int frame = 0;
//m_frame->SetStatusText((std::string) (Util::Format() << "Frame: " << frame++));
m_color_panel->Refresh(false);
m_depth_panel->Refresh(false);
do_nothing:
evt.RequestMore();
}
void ActivateRenderLoop(bool on)
{
//TODO: create MyFrame inherited from wxFrame and catch OnClose() (https://wiki.wxwidgets.org/Making_a_render_loop)
if (on && !m_render_loop_active)
{
Connect(wxID_ANY, wxEVT_IDLE, wxIdleEventHandler(MyApp::OnIdle));
m_render_loop_active = true;
}
else if (!on && m_render_loop_active)
{
Disconnect(wxEVT_IDLE, wxIdleEventHandler(MyApp::OnIdle));
m_render_loop_active = false;
}
}
bool InitRealSense()
{
m_sense_mgr = PXCSenseManager::CreateInstance();
if (!m_sense_mgr)
{
Error(m_frame, "Unable to initialize Intel RealSense camera.");
return false;
}
m_sense_mgr->EnableStream(PXCCapture::STREAM_TYPE_COLOR, 640, 480, 30);
m_sense_mgr->EnableStream(PXCCapture::STREAM_TYPE_DEPTH, 640, 480, 30);
pxcStatus status = m_sense_mgr->Init();
if (PXC_STATUS_NO_ERROR != status)
{
Error(m_frame, Util::Format() << status);
return false;
}
return true;
}
virtual bool OnInit() wxOVERRIDE
{
if (!wxApp::OnInit())
return false;
m_frame = new wxFrame(0, -1, wxT("RealSense Capture"), wxDefaultPosition, wxDefaultSize, wxDEFAULT_FRAME_STYLE & ~wxRESIZE_BORDER & ~wxMAXIMIZE_BOX);
wxBoxSizer *sizer = new wxBoxSizer(wxHORIZONTAL);
m_color_panel = new MyPanel(m_frame);
m_depth_panel = new MyPanel(m_frame);
sizer->Add(m_color_panel, 1, wxEXPAND);
sizer->Add(m_depth_panel, 1, wxEXPAND);
m_frame->CreateStatusBar();
m_frame->SetSizer(sizer);
m_frame->SetAutoLayout(true);
m_frame->Fit(); // setting size in wxFrame() ctor doesn't seem to work
m_frame->Show(true);
if (!InitRealSense())
return false;
ActivateRenderLoop(true);
return true;
}
virtual int OnExit() wxOVERRIDE
{
m_sense_mgr->Release();
return 0;
}
};
wxIMPLEMENT_APP(MyApp);
<file_sep>/util/realsense_formatters.h
#ifndef INCLUDED_REALSENSE_FORMATTER_HPP
#define INCLUDED_REALSENSE_FORMATTER_HPP
#include <pxcsensemanager.h>
#include <ostream>
std::ostream & operator<<(std::ostream &os, PXCImage::PixelFormat fmt);
std::ostream & operator<<(std::ostream &os, pxcStatus status);
#endif // INCLUDED_REALSENSE_FORMATTER_HPP
<file_sep>/util/format.cpp
#include "util/format.h"
namespace Util
{
static const char hex_digits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
const std::string Hex(uint32_t n, size_t num_digits)
{
Util::Format f;
f << "0x";
for (size_t b = num_digits * 4; b; )
{
b -= 4;
f << hex_digits[(n >> b) & 0xf];
}
return f;
}
const std::string Hex(uint32_t n)
{
return Hex(n, 8);
}
const std::string Hex(uint16_t n)
{
return Hex(n, 4);
}
const std::string Hex(uint8_t n)
{
return Hex(n, 2);
}
} // Util
| b2e0a68b390f9f38a91223ec5d4146c20606a095 | [
"C++"
] | 5 | C++ | trzy/realsense | 06fbc1cbff9b143c7d28724f602b9bb3637027a2 | 7f6c43713c6057e684a71483187756046a477157 |
HEAD | <repo_name>l7263626/liu-tian<file_sep>/class/dbtable/system/config.php
<?php
class Dbtable_System_Config extends Dbtable_Abstract{
//可修改的欄位
protected $table = "system_config";
protected $pk = "sc_id";
}
?>
<file_sep>/pop_ad.php
<?php
//error_reporting(15);
include_once("libs/libs-sysconfig.php");
$ad = new AD;
class AD{
function AD(){
global $db,$cms_cfg,$tpl,$main;
//show page
$this->ws_tpl_file = "templates/ws-ad-tpl.html";
$this->ws_load_tp($this->ws_tpl_file);
$this->ws_seo=($cms_cfg["ws_module"]["ws_seo"])?1:0;
$this->ad_show();
$tpl->printToScreen();
}
//載入對應的樣板
function ws_load_tp($ws_tpl_file){
global $tpl,$cms_cfg,$db,$ws_array,$TPLMSG,$main;
$tpl = new TemplatePower( $ws_tpl_file );
$tpl->assignInclude( "HEADER", $cms_cfg['base_header_tpl']); //頭檔title,meta,js,css
$tpl->prepare();
$main->header_footer("ad");
}
function ad_show(){
global $db,$tpl,$cms_cfg,$TPLMSG,$main;
$sql="select * from ".$db->prefix("ad")." where ad_cate='10' and (ad_status='1' or (ad_status='2' and ad_startdate <= '".date("Y-m-d")."' and ad_enddate >= '".date("Y-m-d")."') ) order by ad_sort desc limit 0,1";
$selectrs = $db->query($sql);
$rsnum = $db->numRows($selectrs);
if($rsnum >0){
while ( $row = $db->fetch_array($selectrs,1) ) {
$row['ad_file'] = $main->content_file_str_replace($row['ad_file']);
$tpl->assignGlobal("VALUE_AD_FILE",$row["ad_file"]);
}
}
}
}
?><file_sep>/class/dbtable/knowmeby.php
<?php
class Dbtable_KnowMeBy extends Dbtable_Abstract{
//可修改的欄位
protected $table = "knowmeby";
protected $pk = "id";
protected $pre_data;
function tablename() {
return $this->table;
}
protected function prepare_data($post) {
if($post['knowMeBy']){
$source = $post['knowMeBy'];
if($source['other'] && $source['value']){
$source[] = $source['value'];
}
unset($source['other']);
unset($source['value']);
$origin_data = array();
foreach($source as $keyword){
list($row) = $this->getDataList("item='{$keyword}'");
if($row){
$row['count']+=1;
}else{
$row['item'] = $keyword;
$row['count'] = 1;
}
$origin_data[] = $row;
}
$this->pre_data = $origin_data;
}
}
function writeData($post) {
$this->prepare_data($post);
if($this->pre_data){
foreach($this->pre_data as $row){
parent::writeData($row);
}
}
}
}
?>
<file_sep>/shopping-result3.php
<?php
include_once("libs/libs-sysconfig.php");
$notcard = new Model_Order_Payment_Neweb_Notcreditcard($cms_cfg['notcreditcard']);
$notcard->update_order(App::getHelper('dbtable')->order,$_POST);<file_sep>/class/model/order/payment/neweb/returncode/notcreditcard.php
<?php
class Model_Order_Payment_Neweb_Returncode_Notcreditcard {
//授權碼
static $code = array(
'0' => '作業順利完成',
'2' => '找不到指定的物件',
'3' => '找不到必要參數',
'6' => '必要參數的格式不正確',
'7' => '必要參數的值不正確',
'8' => '有重複物件存在',
'10' => '剖析輸入串流時發生錯誤',
'11' => '對此動作而言,物件未處於正確狀態',
'12' => 'Payment Manager 中發生通信錯誤',
'13' => 'Payment Manager 遇到非預期的內部錯誤',
'14' => '發生資料庫通信錯誤',
'15' => '發生卡匣特定錯誤',
'32' => '不容許 API 指令中所指定的參數組合',
'34' => '因金融理由導致作業失敗',
'43' => '為特定商店做的風險控管',
'52' => '進行使用者授權期間發生錯誤',
'55' => '指令名稱未被視為有效的 $til; 指令。',
);
static $scode = array(
'0' => '無其它資訊可用',
'3' => '不明指令',
'4' => '發生異常錯誤',
'10' => '不支援之編碼',
'110' => '此回應與商家號碼參數有關',
'111' => '此回應與訂單號碼參數有關',
'112' => '此回應與 ORDERDATE 參數有關',
'113' => '此回應與 BATCHCLOSEDATE 參數有關',
'114' => '此回應與 BATCHNUMBER 參數有關',
'117' => '此回應與 AMOUNT 參數有關',
'118' => '此回應與 AMOUNTEXP10 參數有關',
'119' => '此回應與 CURRENCY 參數有關',
'130' => '此回應與訂單URL 參數有關',
'171' => '查看卡匣特定資料取得進一步資訊',
'202' => '此回應與商家付款系統(如 SET)有關',
'204' => '此回應與訂單實體有關',
'205' => '此回應與付款實體有關',
'206' => '此回應與退款實體有關',
'207' => '此回應與批次實體有關',
'309' => '發生通信錯誤',
'512' => '連接資料庫或執行 SQL 陳述式時發生錯誤',
'554' => '指定的使用者無權執行所要求的作業',
'1015' => '此回應與 PAN 參數(指定於通信協定資料中)有關',
'1016' => '此回應與過期參數(指定於通信協定資料中)有關',
'1200' => '此回應與請款指標參數有關',
'1201' => '此回應與訂單明細參數有關',
'1202' => '此回應與信用卡卡號參數有關',
'2005' => 'XIDINDEX',
'2006' => 'CAVV',
'2007' => 'ECI',
'2009' => 'ERRORCODE',
'2011' => 'PINCODE',
'2015' => 'ID',
'2016' => '此回應與分期付款期數參數有關',
'2017' => 'CVV2',
'2018' => '此回應與授權碼參數有關',
'2050' => '此回應與訂單說明參數有關',
'2052' => 'REDEMPTION',
'2053' => '此回應與起始日期參數有關',
'2054' => '此回應與結束日期參數有關',
'2055' => '此回應與郵遞區號參數有關',
'4001' => '限額阻擋,交易超過額度上限',
'4003' => '限額阻擋,單筆交易金額低於下限',
'4003' => '限額阻擋,單筆交易金額低於下限',
'4004' => '系統黑名單',
'4005' => '商店黑名單',
'4006' => '白名單',
'4007' => '僅接受國內卡',
'4008' => '僅接受國外卡',
'4009' => '僅接受自行卡',
'4010' => '請款天數限制',
'4011' => '退款天數限制',
'5005' => '銀行Payment Gateway 商家代碼,非特店代號',
'5013' => '此回應與商品代號參數有關',
'5014' => '此回應與交易序號參數有關',
'5020' => '此回應與商品總數參數有關',
);
}
<file_sep>/class/dbtable/member.php
<?php
class Dbtable_Member extends Dbtable_Abstract{
//可修改的欄位
protected $table = "member";
protected $pk = "m_id";
//取得post資料欄位
protected function _retrieve_cols($post){
parent::_retrieve_cols($post);
$this->values['m_modifydate'] = date("Y-m-d H:i:s");
$password = $this->_get_password($post);
if($password)$this->values['m_password'] = $password;
//沒有m_id代表是新註冊會員
if(empty($this->values['m_id'])){
if(!isset($this->values['m_account'])){
$this->values['m_account'] = $this->values['m_cellphone'];
}
$this->values['mc_id'] = 1;
}
}
protected function _get_password($post){
if($post['m_password'] && $post['v_password']){
if($post['m_password']==$post['v_password']){
return trim($post['m_password']);
// return md5(trim($post['m_password']));
}
}
}
}
?>
<file_sep>/class/dbtable/order.php
<?php
class Dbtable_Order extends Dbtable_Abstract{
//可修改的欄位
protected $table = "order";
protected $pk = "o_id";
protected function _retrieve_cols($post,$op) {
parent::_retrieve_cols($post);
if($op=='insert'){
$this->values['o_createdate'] = date("Y-m-d H:i:s");
}
}
//寫入(更新)訂單
function writeData($post,$shopping=array(),$op='update') {
global $cms_cfg;
$this->_retrieve_cols($post,$op);
if($op=='update'){
$this->con[] = sprintf("`%s`='%s'",$this->pk,$this->values[$this->pk]);
}
$mk_method = "_mk_{$op}_sql";
$sql = $this->{$mk_method}();
$this->_query($sql);
if(($err = $this->report())==''){
if(!empty($shopping)){
$db_items = new Dbtable_Order_Items($this->db,$this->prefix);
foreach($shopping as $item){
$data_box = array('o_id'=>$post['o_id'],'m_id'=>$post['m_id']);
$data_box['p_id']=$item["p_id"];
$data_box['p_name']=$item["p_name"];
$data_box['oi_amount']=$_SESSION[$cms_cfg['sess_cookie_name']]["amount"][$item["p_id"]];
$data_box['shipping_type']=$item["shipping_type"];
$price = $item["p_special_price"]?$item["p_special_price"]:$item["p_list_price"];
if(!empty($_SESSION[$cms_cfg['sess_cookie_name']]["MEMBER_DISCOUNT"]) && $_SESSION[$cms_cfg['sess_cookie_name']]["MEMBER_DISCOUNT"]!=100){
$data_box['p_sell_price']=floor($_SESSION[$cms_cfg['sess_cookie_name']]["MEMBER_DISCOUNT"]/100*$price);
}else{
$data_box['p_sell_price']=$price;
}
$db_items->writeData($data_box);
}
}
}
}
}
?>
<file_sep>/class/dbtable/order/paymentinfo.php
<?php
class Dbtable_Order_Paymentinfo extends Dbtable_Abstract{
//可修改的欄位
protected $table = "order_paymentinfo";
protected $pk = "o_id";
function writeData($post) {
$origin = $this->getData($post['o_id'])->getDataRow();
if($origin){
$targetData = array_merge($origin, $post);
parent::writeData($targetData);
}else{
$this->insert($post);
}
}
}
?>
<file_sep>/cmsadmin/order.php
<?php
//error_reporting(15);
//ob_start();
session_start();
include_once("../conf/config.inc.php");
if(empty($_SESSION[$cms_cfg['sess_cookie_name']]["USER_ACCOUNT"]) || $_SESSION[$cms_cfg['sess_cookie_name']]["AUTHORITY"]["aa_order"]==0){
header("location: /");
exit;
}
include_once("../libs/libs-manage-sysconfig.php");
$order = new ORDER;
class ORDER{
function ORDER(){
global $db,$cms_cfg,$tpl;
switch($_REQUEST["func"]){
case "ajax_op_temp_store":
$this->ajax_op_temp_store();
break;
case "ajax_get_tsrec":
$this->ajax_get_tsrec();
break;
case "ajax_new_temp_store":
$this->ajax_new_temp_store();
break;
case "mod_temp_store":
case "add_temp_store":
$this->current_class="OTS";
$this->ws_tpl_file = "templates/ws-manage-temp-store-form-tpl.html";
$this->ws_load_tp($this->ws_tpl_file);
$tpl->newBlock("JS_JQ_UI");
$this->tempstore_form();
$this->ws_tpl_type=1;
break;
case "o_temp_store":
$this->current_class="OTS";
$this->ws_tpl_file = "templates/ws-manage-temp-store-list-tpl.html";
$this->ws_load_tp($this->ws_tpl_file);
$this->tempstore_list();
$this->ws_tpl_type=1;
break;
case "o_bonus_config":
$this->current_class="OBC";
$this->ws_tpl_file = "templates/ws-manage-order-bonus-config-form-tpl.html";
$this->ws_load_tp($this->ws_tpl_file);
$this->o_bonus_config();
$this->ws_tpl_type=1;
break;
case "o_bonus_list":
$this->current_class="OBL";
$this->ws_tpl_file = "templates/ws-manage-order-bonus-list-tpl.html";
$this->ws_load_tp($this->ws_tpl_file);
$this->o_bonus_list();
$this->ws_tpl_type=1;
break;
case "o_ex"://匯出新訂單
if($_GET['act']){
$this->export_order();
}else{
$this->current_class="OE";
$this->ws_tpl_file = "templates/ws-manage-export-form-tpl.html";
$this->ws_load_tp($this->ws_tpl_file);
$tpl->newBlock("JS_MAIN");
$this->export_form();
$this->ws_tpl_type=1;
}
break;
case "o_ex2"://匯出新訂單
$this->export_order2();
break;
case "o_list"://訂單列表
$this->current_class="O";
$this->ws_tpl_file = "templates/ws-manage-order-list-tpl.html";
$this->ws_load_tp($this->ws_tpl_file);
$tpl->newBlock("JS_MAIN");
$tpl->newBlock("JS_JQ_UI");
$tpl->newBlock("DATEPICKER_SCRIPT");
if($cms_cfg["ws_module"]["ws_vaccount"]==1) {
$this->check_atm();//檢查新匯款紀錄
}
$this->order_list();
$this->ws_tpl_type=1;
break;
case "o_replace"://訂單更新資料(replace)
$this->ws_tpl_file = "templates/ws-manage-msg-action-tpl.html";
$this->ws_load_tp($this->ws_tpl_file);
$this->order_replace();
$this->ws_tpl_type=1;
break;
case "o_reply"://訂單檢視及更新狀態
$this->current_class="O";
$this->ws_tpl_file = "templates/ws-manage-order-reply-form-tpl.html";
$this->ws_load_tp($this->ws_tpl_file);
$this->order_reply_form();
$this->ws_tpl_type=1;
break;
case "o_del"://訂單刪除
$this->ws_tpl_file = "templates/ws-manage-msg-action-tpl.html";
$this->ws_load_tp($this->ws_tpl_file);
$this->order_del();
$this->ws_tpl_type=1;
break;
case "data_processing"://多筆刪除,複製,啟用,停用 處理
$this->ws_tpl_file = "templates/ws-manage-msg-action-tpl.html";
$this->ws_load_tp($this->ws_tpl_file);
$this->data_processing();
$this->ws_tpl_type=1;
break;
default: //訂單列表
$this->current_class="O";
$this->ws_tpl_file = "templates/ws-manage-order-list-tpl.html";
$this->ws_load_tp($this->ws_tpl_file);
$tpl->newBlock("JS_MAIN");
$tpl->newBlock("JS_JQ_UI");
$tpl->newBlock("DATEPICKER_SCRIPT");
if($cms_cfg["ws_module"]["ws_vaccount"]==1) {
$this->check_atm();//檢查新匯款紀錄
}
$this->order_list();
$this->ws_tpl_type=1;
break;
}
if($this->ws_tpl_type){
$tpl->printToScreen();
}
}
//載入對應的樣板
function ws_load_tp($ws_tpl_file){
global $tpl,$cms_cfg,$db,$main;
$tpl = new TemplatePower( $cms_cfg['manage_all_tpl'] );
$tpl->assignInclude( "LEFT", $cms_cfg['manage_left_tpl']);
$tpl->assignInclude( "TOP_MENU", $cms_cfg['manage_top_menu_tpl']);
$tpl->assignInclude( "MAIN", $ws_tpl_file);
$tpl->prepare();
$tpl->assignGlobal("TAG_".$this->current_class."_CURRENT","class=\"current\"");
$tpl->assignGlobal("CSS_BLOCK_ORDER","style=\"display:block\"");
//依權限顯示項目
$main->mamage_authority();
}
//訂單--列表================================================================
function order_list(){
global $db,$tpl,$cms_cfg,$TPLMSG,$main,$ws_array;
//顯示ATM匯款標題
if($cms_cfg["ws_module"]["ws_vaccount"]) {
$tpl->newBlock("TITLE_ATM_TRANSFER");
}
//訂單列表
$sql="select * from ".$cms_cfg['tb_prefix']."_order where o_id > '0' and del='0' ";
$searchfields = new searchFields_order();
//附加條件
$and_str = $searchfields->find_multiple_search_value($and_str);
$sql .= ($and_str?" and ".$and_str:"")." order by o_modifydate desc ";
//取得總筆數
$selectrs = $db->query($sql);
$total_records = $db->numRows($selectrs);
//取得分頁連結
parse_str($_SERVER['QUERY_STRING'],$q);
foreach($q as $k=>$v){
if($k!='nowp' && $k!='jp'){
$qs[] = sprintf("%s=%s",$k,$v);
}
}
$func_str="order.php?".implode('&',$qs);
//分頁且重新組合包含limit的sql語法
$sql=$main->pagination($cms_cfg["op_limit"],$cms_cfg["jp_limit"],$_REQUEST["nowp"],$_REQUEST["jp"],$func_str,$total_records,$sql);
$selectrs = $db->query($sql);
$rsnum = $db->numRows($selectrs);
$tpl->assignGlobal( array("VALUE_TOTAL_BOX" => $rsnum,
"VALUE_SEARCH_KEYWORD" => $_REQUEST["sk"],
"TAG_DELETE_CHECK_STR" => $TPLMSG['DELETE_CHECK_STR'],
'TAG_SEARCH_FIELD' => $searchfields->list_multiple_search_fields(),
));
$i = $main->get_pagination_offset($cms_cfg["op_limit"]);
while ( $row = $db->fetch_array($selectrs,1) ) {
$i++;
$tpl->newBlock( "ORDER_LIST" );
if($i%2){
$tpl->assign("TAG_TR_CLASS","class='altrow'");
}
$tpl->assign( array(
"VALUE_O_ID" => $row["o_id"],
"VALUE_O_NAME" => $row["o_name"],
"VALUE_O_CREATEDATE" => $row["o_createdate"],
"VALUE_O_MODIFYDATE" => $row["o_modifydate"],
"VALUE_O_TOTAL_PRICE" => $row["o_total_price"],
"VALUE_O_STATUS" => $ws_array["order_status"][$row["o_status"]],
"VALUE_O_SERIAL" => $i
));
//顯示ATM匯款狀態
if($cms_cfg["ws_module"]["ws_vaccount"]) {
$tpl->newBlock("ATM_TRANSFER_STATE");
$tpl->assign( array(
"VALUE_O_REMIT_STATUS" => ($row["o_payment_type"] == 1) ? $row["o_remit_status"] ? "完成匯款":"<font color=\"#ff0000\">未匯款</font>" :"",
"VALUE_O_CURAMT" => $row["o_curamt"],
"VALUE_O_TRN_TIME" => $row["o_trn_time"]
));
}
}
}
//訂單--刪除--資料刪除可多筆處理================================================================
function order_del(){
global $db,$tpl,$cms_cfg,$TPLMSG;
if($_REQUEST["o_id"]){
$cu_id=array(0=>$_REQUEST["o_id"]);
}else{
$cu_id=$_REQUEST["id"];
}
if(!empty($cu_id)){
foreach($cu_id as $k=>$v){
$cu_id[$k] = sprintf("'%s'",$v);
}
$cu_id_str = implode(",",$cu_id);
//刪除勾選的訂單
// $sql="delete from ".$cms_cfg['tb_prefix']."_order where o_id in (".$cu_id_str.")";
// $rs = $db->query($sql);
// $sql="delete from ".$cms_cfg['tb_prefix']."_order_items where o_id in (".$cu_id_str.")";
$sql = "UPDATE ".$db->prefix("order")." AS o INNER JOIN ".$db->prefix("order_items")." AS oi ON o.o_id = oi.o_id SET o.del = '1' , oi.del = '1' WHERE o.o_id in(".$cu_id_str.")";
$rs = $db->query($sql);
$db_msg = $db->report();
if ( $db_msg == "" ) {
$tpl->assignGlobal( "MSG_ACTION_TERM" , $TPLMSG["ACTION_TERM"]);
$goto_url=$cms_cfg["manage_url"]."order.php?func=o_list&cuc_id=".$_REQUEST["cuc_id"]."&st=".$_REQUEST["st"]."&sk=".$_REQUEST["sk"]."&nowp=".$_REQUEST["nowp"]."&jp=".$_REQUEST["jp"];
$this->goto_target_page($goto_url);
}else{
$tpl->assignGlobal( "MSG_ACTION_TERM" , "DB Error: $db_msg, please contact MIS");
}
}
}
//訂單回覆--表單================================================================
function order_reply_form(){
global $db,$tpl,$cms_cfg,$TPLMSG,$main,$ws_array;
//欄位名稱
$tpl->assignGlobal( array("MSG_MODE" => $TPLMSG['MODIFY'],
"MSG_PRODUCT_SPECIAL_PRICE" => $TPLMSG['PRODUCT_PRICE']
));
//相關參數
if(!empty($_REQUEST['nowp'])){
$tpl->assignGlobal( array("VALUE_SEARCH_TARGET" => $_REQUEST['st'],
"VALUE_SEARCH_KEYWORD" => $_REQUEST['sk'],
"VALUE_NOW_PAGE" => $_REQUEST['nowp'],
"VALUE_JUMP_PAGE" => $_REQUEST['jp'],
));
}
if($cms_cfg["ws_module"]['ws_delivery_timesec']){ //是否顯示配送區間
$tpl->newBlock("DELIVERY_TIMESEC");
}
//帶入要回覆的訂單資料
if(!empty($_REQUEST["o_id"])){
$sql="select o.*,op.serialnumber,op.writeoffnumber,op.timepaid,op.paymenttype,op.amount,op.tel from ".$cms_cfg['tb_prefix']."_order as o left join ".$db->prefix("order_paymentinfo")." as op on o.o_id=op.o_id where o.o_id='".$_REQUEST["o_id"]."' and del='0' ";
$selectrs = $db->query($sql);
$row = $db->fetch_array($selectrs,1);
$rsnum = $db->numRows($selectrs);
if ($rsnum > 0) {
$dts = strtotime($row['o_delivery_date']);
$tpl->assignGlobal( array("VALUE_M_ID" => $row["m_id"],
"VALUE_O_ID" => $row["o_id"],
"VALUE_O_NAME" => $row["o_name"],
"VALUE_O_TEL_AREA" => $row["o_tel_area"],
"VALUE_O_TEL" => $row["o_tel"],
"VALUE_O_CELLPHONE" => $row["o_cellphone"],
"VALUE_O_ZIP" => $row["o_zip"],
"VALUE_O_ADDRESS" => $row["o_city"].$row["o_area"].$row["o_address"],
"VALUE_O_EMAIL" => $row["o_email"],
"VALUE_O_RECI_NAME" => $row["o_reci_name"],
"VALUE_O_RECI_TEL_AREA" => $row["o_reci_tel_area"],
"VALUE_O_RECI_TEL" => $row["o_reci_tel"],
"VALUE_O_RECI_CELLPHONE" => $row["o_reci_cellphone"],
"VALUE_O_RECI_ZIP" => $row["o_reci_zip"],
"VALUE_O_RECI_ADDRESS" => $row["o_reci_address"],
"VALUE_O_RECI_EMAIL" => $row["o_reci_email"],
"VALUE_O_CONTENT" => $row["o_content"],
"VALUE_O_CHARGE_FEE" => $row["o_charge_fee"],
"VALUE_O_MINUS_PRICE" => $row["o_minus_price"],
"VALUE_O_SUBTOTAL_PRICE" => $row["o_subtotal_price"],
"VALUE_O_TOTAL_PRICE" => $row["o_total_price"],
"VALUE_O_STATUS" => $ws_array["order_status"][$row["o_status"]],
"VALUE_O_PAYMENT_TYPE"=>$ws_array["payment_type"][$row["o_payment_type"]],
"VALUE_O_SHIPPMENT_TYPE" => $ws_array["shippment_type"][$row['o_shippment_type']],
"VALUE_O_INVOICE_TYPE" => $ws_array["invoice_type"][$row['o_invoice_type']],
"VALUE_O_DELIVERY_STR" => sprintf("%s %s",date("Y年m月d日",$dts),$ws_array["deliery_timesec"][$row['o_deliver_time_sec']]),
"VALUE_O_COMPANY_NAME" => $row["o_company_name"],
"VALUE_O_VAT_NUMBER" => $row["o_vat_number"],
"USER_AGENT" => $row["user_agent"],
"TCAT_NO" => $row["tcat_no"],
"ORIGIN_STATUS" => $row['o_status'],
));
//流物公司
$main->multiple_radio("logistics",$ws_array['logistics'],$row['logistics']);
//發票類型
$main->multiple_radio("invoice_type",$ws_array['invoice_type'],$row['o_invoice_type']);
if($cms_cfg["ws_module"]["ws_vaccount"] & $row["o_virtual_account"]) {
$tpl->newBlock("ATM_DATA");
$tpl->assignGlobal( array(
"VALUE_O_VIRTUAL_ACCOUNT" => $row["o_virtual_account"],
"VALUE_O_CURAMT" => $row["o_curamt"]
));
}
//訂單狀態
foreach($ws_array["order_status"] as $key =>$value){
$i++;
$tpl->newBlock( "ORDER_STATUS_LIST" );
$tpl->assign( array(
"VALUE_O_STATUS_SUBJECT" => $value,
"VALUE_O_STATUS" => $key,
"VALUE_O_SERIAL" => $i,
"TAG_DISABLED" => $row['o_status']>=3?"disabled":'',
));
if($i%4==0){
$tpl->assign("TAG_BR","<br>");
}
if($key==$row["o_status"]){
$tpl->assign("TAG_STATUS_CHECKED","checked");
}
}
if($row['o_payment_type']==1){
$tpl->newBlock("ATM_INFO");
$tpl->assign(array(
"VALUE_O_ATM_LAST5" => $row["o_atm_last5"],
));
}elseif($row['o_payment_type']==3){
$tpl->newBlock("CART_AUTHOR_INFO");
$tpl->assign(array(
"VALUE_PRC" => $row['PRC'],
"VALUE_SRC" => $row['SRC'],
"VALUE_PRC_MSG" => Model_Order_Payment_Returncode_Neweb::$code[$row['PRC']],
"VALUE_APPROVALCODE" => $row['ApprovalCode'],
"VALUE_BANKRESPONSECODE" => $row['BankResponseCode'],
"VALUE_BATCHNUMBER" => $row['BatchNumber'],
));
if($row['SRC']){
$tpl->newBlock("CART_AUTHOR_SINFO");
$tpl->assign(array(
"VALUE_SRC_MSG" => Model_Order_Payment_Returncode_Neweb::$scode[$row['SRC']],
));
}
}else{
//非信用卡繳款記錄
if(!empty($row['serialnumber'])) {
$tpl->newBlock("NONCARD_AUTH_INFO_INFO");
$tpl->assign( array(
"NC_SERIALNUMBER" => $row['serialnumber'],
"NC_WRITEOFFNUMBER" => $row['writeoffnumber'],
"NC_TIMEPAID" => $row['timepaid'],
"NC_PAYMENTTYPE" => $row['paymenttype'],
"NC_AMOUNT" => $row['amount'],
"NC_TEL" => $row['tel'],
));
}
}
//運費
for($s=0;$s<=2;$s++){
if($row['o_plus_price'.$s]>0){
$tpl->newBlock("SHIPTYPE_SHIPPING_PRICE");
$tpl->assign(array(
'SID' => $s,
'SHIPTYPE' => $ws_array['shipping_type'][$s],
'SHIPPING_PRICE' => $row['o_plus_price'.$s],
));
}
}
//訂購產品列表
$sql="select * from ".$cms_cfg['tb_prefix']."_order_items where o_id='".$_REQUEST["o_id"]."' and del='0' ";
$selectrs = $db->query($sql);
$total_price=0;
$i=0;
while($row = $db->fetch_array($selectrs,1)){
$i++;
$sub_total_price = $row["p_sell_price"] * $row["oi_amount"];
$total_price = $total_price+$sub_total_price;
$tpl->newBlock( "ORDER_ITEMS_LIST" );
$tpl->assign( array("VALUE_P_ID" => $row["p_id"],
"VALUE_P_NAME" => $row["p_name"],
"VALUE_P_SELL_PRICE" => $row["p_sell_price"],
"VALUE_P_AMOUNT" => $row["oi_amount"],
"VALUE_P_SUBTOTAL_PRICE" => $sub_total_price,
"VALUE_P_SERIAL" => $i,
"SHIP_TYPE" => $ws_array['shipping_type'][$row['shipping_type']],
));
}
}else{
header("location : order.php?func=o_list");
}
}
}
//訂單回覆--資料更新================================================================
function order_replace(){
global $db,$tpl,$cms_cfg,$TPLMSG;
// $sql="update ".$cms_cfg['tb_prefix']."_order set o_status='".$_REQUEST["o_status"]."' , o_modifydate='".date("Y-m-d H:i:s")."' where o_id='".$_REQUEST["o_id"]."'";
// $rs = $db->query($sql);
App::getHelper('dbtable')->order->writeData($_POST);
$db_msg = App::getHelper('dbtable')->order->report();
if ( $db_msg == "" ) {
if($_REQUEST["o_status"] == 2) $this->mail_delivery_notice(); //寄送出貨通知信
$tpl->assignGlobal( "MSG_ACTION_TERM" , $TPLMSG["ACTION_TERM"]);
$goto_url=$cms_cfg["manage_url"]."order.php?func=o_list&st=".$_REQUEST["st"]."&sk=".$_REQUEST["sk"]."&nowp=".$_REQUEST["nowp"]."&jp=".$_REQUEST["jp"];
$this->goto_target_page($goto_url);
}else{
$tpl->assignGlobal( "MSG_ACTION_TERM" , "DB Error: $db_msg, please contact MIS");
}
}
//顯示訊息並重新導向
function goto_target_page($url,$sec=0){
global $tpl;
if(!empty($url)){
$tpl->assignGlobal( "TAG_META_REFRESH" , "<meta http-equiv=\"refresh\" content=\"$sec;URL=$url\">");
}
}
//資料處理
function data_processing(){
switch ($_REQUEST["process_type"]){
case "del":
$this->order_del();
break;
}
}
//寄送出貨通知信
function mail_delivery_notice() {
global $db,$TPLMSG,$cms_cfg;
$this->ws_tpl_file = "templates/ws-manage-mail-tpl.html";
$tpl = new TemplatePower( $this->ws_tpl_file );
$tpl->prepare();
$sql = "select * from ".$cms_cfg['tb_prefix']."_order where o_id='".$_REQUEST["o_id"]."'";
$selectrs = $db->query($sql);
$row = $db->fetch_array($selectrs,1);
$tpl->newBlock( "DELIVERY_NOTICE_MAIL" );
$tpl->assign( array("MSG_DELIVERY_ID" => $TPLMSG['DELIVERY_ID'],
"MSG_DELIVERY_TOTAL_PRICE" => $TPLMSG['DELIVERY_TOTAL_PRICE'],
"MSG_DELIVERY_DATE" => $TPLMSG['DELIVERY_DATE'],
"VALUE_DELIVERY_ID" => $row['o_id'],
"VALUE_DELIVERY_TOTAL_PRICE" => $row['o_total_price'],
"VALUE_DELIVERY_DATE" => date("Y-m-d H:i:s") ));
$tpl->assignGlobal( "VALUE_TERM" , $TPLMSG['DELIVERY_NOTICE']);
$mail_content=$tpl->getOutputContent();
$this->mail_send($_SESSION[$cms_cfg['sess_cookie_name']]['sc_email'],$row['o_email'],$mail_content,$TPLMSG["DELIVERY_NOTICE"]);
return true;
}
function mail_send($from,$to,$mail_content,$mail_subject){
global $TPLMSG,$cms_cfg;
$from_email=explode(",",$from);
$from_name=(trim($_SESSION[$cms_cfg['sess_cookie_name']]["sc_company"]))?$_SESSION[$cms_cfg['sess_cookie_name']]["sc_company"]:$from_email[0];
//寄給送信者
$MAIL_HEADER = "MIME-Version: 1.0\n";
$MAIL_HEADER .= "Content-Type: text/html; charset=\"utf-8\"\n";
$MAIL_HEADER .= "From: =?UTF-8?B?".base64_encode($from_name)."?= <".$from_email[0].">\n";
$MAIL_HEADER .= "X-Priority: 1\n";
//$MAIL_HEADER = "From: ".$from_name."<".$from_email[0].">"."\r\n";
//$MAIL_HEADER .= "Reply-To: ".$from_name."<".$from_email[0].">\r\n";
//$MAIL_HEADER .= "Return-Path: ".$from_name."<".$from_email[0].">\r\n"; // these two to set reply address
//$MAIL_HEADER .= "Content-Type: text/html; charset=\"utf-8\"\n";
//$MAIL_HEADER .= "X-Priority: 1\r\n";
$MAIL_HEADER .= "Message-ID: <".time()."-".$from_email[0].">\r\n";
$MAIL_HEADER .= "X-Mailer: PHP v".phpversion()."\r\n"; // These two to help avoid spam-filters
$mail_subject = "=?UTF-8?B?".base64_encode($mail_subject)."?=";
$to_email = explode(",",$to);
for($i=0;$i<count($to_email);$i++){
mail($to_email[$i], $mail_subject, $mail_content,$MAIL_HEADER);
}
return true;
}
//檢查匯款
function check_atm(){
global $db,$tpl,$cms_cfg,$TPLMSG;
$xml_dir = "../atm/";
$xml_pack = "../atm_pack/";
if(is_dir($xml_dir)) {
if($dh = opendir($xml_dir)) {
$i = 0;
while(($xml_file = readdir($dh)) !== false) {
if(filetype($xml_dir.$xml_file) == "file") {
$i++;
$xml_str = file_get_contents($xml_dir.$xml_file);
$str = str_replace("<?xml version=\"1.0\" encoding=\"BIG5\"?>","",$xml_str);
$xml = simplexml_load_string($str);
foreach($xml as $text) {
foreach($text as $key => $data) {
$atm[$key] = $data;
}
}
//比對資料庫
$sql="select * from ".$cms_cfg['tb_prefix']."_order where o_virtual_account='".$atm["RCPTId"]."'";
$selectrs = $db->query($sql);
if($db->numRows($selectrs)) {
$row = $db->fetch_array($selectrs,1);
$atm["CurAmt"] = sprintf("%d", $atm["CurAmt"]);
if($row["o_total_price"] == $atm["CurAmt"]) {
$sql="update ".$cms_cfg['tb_prefix']."_order set o_curamt='".$atm["CurAmt"]."' , o_trn_time='".$atm["TrnDt"]." ".$atm["TrnTime"]."' , o_remit_status='1' where o_virtual_account='".$atm["RCPTId"]."'";
$rs = $db->query($sql);
$db_msg = $db->report();
if($db_msg != "") {
$tpl->assignGlobal( "MSG_ACTION_TERM" , "DB Error: $db_msg, please contact MIS");
}elseif(!file_exists($xml_pack)){
mkdir($xml_pack);
copy($xml_dir.$xml_file, $xml_pack.$xml_file);
unlink($xml_dir.$xml_file);
}else{
copy($xml_dir.$xml_file, $xml_pack.$xml_file);
unlink($xml_dir.$xml_file);
}
}
}
}
}
closedir($dh);
}
}
}
function o_bonus_config(){
global $db,$cms_cfg,$tpl;
if($_POST){
if($_POST['act']=="save"){
$sc = new Dbtable_System_Config($db,$cms_cfg['tb_prefix']);
$sc->writeData($_POST);
}
header("location: order.php?func=o_bonus_config");
die();
}
$bonus = new Model_Bonus();
$bonus_array = $bonus->get_field_array();
foreach($bonus_array as $name => $value){
$tpl->assign("_ROOT.".strtoupper($name),$value);
}
}
function o_bonus_list(){
global $db,$cms_cfg,$tpl,$main;
$sql = "select o.*,m_fname,m_lname from (select o.*,ob_points,ob_valid_date,ob_status from ".$cms_cfg['tb_prefix']."_order as o inner join ".$cms_cfg['tb_prefix']."_order_bonus as ob on o.o_id=ob.o_id ) as o inner join ".$cms_cfg['tb_prefix']."_member as m on o.m_id=m.m_id order by o_createdate desc";
$res = $db->query($sql);
$total_records = $db->numRows($res);
$func_str = "order.php?func=o_bonus_list";
$sql=$main->pagination(30,$cms_cfg["jp_limit"],$_REQUEST["nowp"],$_REQUEST["jp"],$func_str,$total_records,$sql);
$res = $db->query($sql);
$offset = (($_GET['nowp'])?$_GET['nowp']-1:0)*$cms_cfg["op_limit"];
while($row = $db->fetch_array($res,1)){
$offset++;
$tpl->newBlock("ORDER_BONUS_LIST");
switch($row['ob_status']){
case "-1": $status_str = "<span class='bonus_overtime'>過期</span>"; break;
case "0": $status_str = "<span class='bonus_invalid'>無效</span>"; break;
case "1": $status_str = "<span class='bonus_valid'>有效</span>"; break;
case "2": $status_str = "<span class='bonus_used'>已使用</span>"; break;
}
$tpl->assign(array(
"VALUE_OB_SERIAL" => $offset,
"VALUE_O_ID" => $row['o_id'],
"VALUE_O_CREATEDATE" => date("Y-m-d",strtotime($row['o_createdate'])),
"VALUE_O_SUBTOTAL_PRICE" => $row['o_subtotal_price'],
"VALUE_O_TOTAL_PRICE" => $row['o_total_price'],
"VALUE_M_NAME" => $row['m_fname'].$row['m_lname'],
"VALUE_OBC_POINTS" => $row['ob_points'],
"VALUE_OBC_VALID_DATE" => $row['ob_valid_date'],
"VALUE_OBC_STATUS" => $status_str,
));
}
}
function export_order(){
global $db,$cms_cfg,$ws_array;
if(isset($_POST['exportAll'])){
$type = "exportAll";
}elseif(isset($_POST['exportNew'])){
$type = "exportNew";
}else{
throw new Exception('no proper type of export order');
}
$exportData = $this->get_export_order_data($type);
if($exportData['data']){
require_once "../class/phpexcel/PHPExcel.php";
$xlsexpotor = new XLSExportor();
$xlsexpotor->setTitle($exportData['title']);
$xlsexpotor->setData($exportData['data']);
$xlsexpotor->setFilename($exportData['filename']);
// $xlsexpotor->setFontSize(10);
$xlsexpotor->export();
}else{
App::getHelper('main')->js_notice('無匯出資料', $cms_cfg['manage_root'].'order.php?func=o_ex');
}
}
function export_order2(){
global $db,$cms_cfg,$ws_array;
$exportData = $this->get_export_order_data("exportAll");
if($exportData['data']){
require_once "../class/phpexcel/PHPExcel.php";
$xlsexpotor = new XLSExportor();
$xlsexpotor->setTitle($exportData['title']);
$xlsexpotor->setData($exportData['data']);
$xlsexpotor->setFilename($exportData['filename']);
// $xlsexpotor->setFontSize(10);
$xlsexpotor->export();
}else{
App::getHelper('main')->js_notice('無匯出資料', $cms_cfg['manage_root'].'order.php?func=o_ex');
}
}
function getdatefromjd($val,$format="Y-m-d"){
$jd = GregorianToJD(1, 1, 1970);
$gregorian = JDToGregorian($jd+intval($val)-25569);
return date($format,strtotime($gregorian));
}
function pid2serial($pid){
global $db,$cms_cfg;
$sql = "select p_serial from ".$cms_cfg['tb_prefix']."_products where p_id='".$pid."'";
list($serial) = $db->query_firstrow($sql,false);
if(!empty($serial)){
return $serial;
}else{
return $pid;
}
}
function _writeToSheet($sheet,$row,$r){
unset($row['o_plus_price']);
unset($row['o_charge_fee']);
$i=0;
foreach($row as $v){
if(in_array($i,array(0,7,10,11,12,16,17,18))){
$pDataType = PHPExcel_Cell_DataType::TYPE_STRING;
$sheet->setCellValueExplicit(chr(65+$i).$r, $v, $pDataType);
}else{
$sheet->setCellValueByColumnAndRow($i, $r, $v);
}
$i++;
}
}
function _writeFee($sheet,$row,&$r){
$shipFee = $row['o_plus_price'];
$chargeFee = $row['o_charge_fee'];
$row['oi_amount'] = 1;//重設費用的數量為1
if($shipFee>0){//寫入運費
$row['p_name'] = "運費";
$row['p_sell_price'] = $shipFee;
$row['p_id'] = "F05-0033";
$this->_writeToSheet($sheet,$row,$r++);
}
if($chargeFee>0){//寫入手續費
$row['p_name'] = "手續費";
$row['p_sell_price'] = $chargeFee;
$row['p_id'] = "F06-0103";
$this->_writeToSheet($sheet,$row,$r++);
}
}
//輸出訂單
function export_form(){
}
//取得輸出的訂單資料
function get_export_order_data($type){
global $ws_array,$cms_cfg;
$db = App::getHelper('db');
$exportData = array(
'exportAll' => array(
'title' => array(
0 => array('data'=>"訂單編號",'width'=>16.5),
1 => array('data'=>"訂單狀態",'width'=>16.5),
2 => array('data'=>"付款方式",'width'=>22.5),
3 => array('data'=>"配送日期",'width'=>16.5),
4 => array('data'=>"配送時段",'width'=>16.5),
5 => array('data'=>"備註",'width'=>16.5),
6 => array('data'=>"公司名稱",'width'=>16.5),
7 => array('data'=>"統一編號",'width'=>16.5),
8 => array('data'=>"傳真",'width'=>16.5),
9 => array('data'=>"會員編號",'width'=>16.5),
10 => array('data'=>"訂購者姓名",'width'=>16.5),
11 => array('data'=>"訂購者電話",'width'=>16.5),
12 => array('data'=>"訂購者手機",'width'=>16.5),
13 => array('data'=>"訂購者區號",'width'=>16.5),
14 => array('data'=>"訂購者住址",'width'=>16.5),
15 => array('data'=>"訂購者Email",'width'=>28),
16 => array('data'=>"收件者姓名",'width'=>16.5),
17 => array('data'=>"收件者電話",'width'=>16.5),
18 => array('data'=>"收件者手機",'width'=>16.5),
19 => array('data'=>"收件者區號",'width'=>16.5),
20 => array('data'=>"收件者地址",'width'=>16.5),
21 => array('data'=>"收件者Email",'width'=>28),
22 => array('data'=>"小計",'width'=>10),
23 => array('data'=>"手續費",'width'=>10),
24 => array('data'=>"運費",'width'=>10),
25 => array('data'=>"折扣",'width'=>10),
26 => array('data'=>"總價",'width'=>10),
27 => array('data'=>"發票",'width'=>16.5),
28 => array('data'=>"訂購商品",'width'=>25),
),
'filename' => "full_order_".date("Y-m-d"),
'data' => array(),
),
'exportNew' => array(
'title' => array(
0 => array("data"=>'訂單編號','width'=>16.5),
1 => array("data"=>'訂貨人','width'=>16.5),
2 => array("data"=>'訂貨人電話','width'=>16.5),
3 => array("data"=>'訂貨人手機','width'=>16.5),
4 => array("data"=>'收件人','width'=>16.5),
5 => array("data"=>'收件人電話','width'=>16.5),
6 => array("data"=>'收件人手機','width'=>16.5),
7 => array("data"=>'收件人E-mail','width'=>28),
8 => array('data'=>'收件人住址','width'=>50),
9 => array("data"=>'訂購產品','width'=>28),
),
'filename' => "new_order_".date("Y-m-d"),
'data' => array(),
)
);
switch($type){
case "exportAll":
//附加條件
$searchfields = new searchFields_order();
$and_str = $searchfields->find_multiple_search_value($and_str);
$sql = "select o_id,o_status,o_payment_type,o_delivery_date,o_deliver_time_sec,o_content,o_company_name,o_vat_number,o_fax,m_id,o_name,o_tel,o_cellphone,o_zip,concat(o_city,o_area,o_address) as address1,o_email,o_reci_name,o_reci_tel,o_reci_cellphone,o_reci_zip,concat(o_reci_city,o_reci_area,o_reci_address) as address2,o_reci_email,o_subtotal_price,o_charge_fee,o_plus_price,o_minus_price,o_total_price,o_invoice_type from ".$db->prefix("order")." where del='0' ".($and_str?'and '.$and_str:"")." order by o_createdate ";
$res = $db->query($sql,true);
while($row = $db->fetch_array($res,0)){
$sql = "select * from ".$db->prefix("order_items")." where o_id='".$row[0]."' and del='0' order by oi_id ";
$res2 = $db->query($sql,true);
$row[0] = array('data'=>$row[0],'type'=>'s');
$row[1] = $ws_array["order_status"][$row[1]];
$row[2] = $ws_array["payment_type"][$row[2]];
$row[3] = ($ts=strtotime($row[3]))?date("Y-m-d",$ts):"";
$row[4] = $ws_array["deliery_timesec"][$row[4]];
$row[11] = array('data'=>$row[11],'type'=>'s');
$row[12] = array('data'=>$row[12],'type'=>'s');
$row[17] = array('data'=>$row[17],'type'=>'s');
$row[18] = array('data'=>$row[18],'type'=>'s');
$row[24] = $row[24]<0?"運費另議":$row[24];
$row[25] = ($row[25]>0)?0-$row[25]:0;
$row[27] = $ws_array['invoice_type'][$row[27]];
$tmp = array();
while($prod = $db->fetch_array($res2,1)){
$tmp[] = sprintf("%s*%d",$prod['p_name'],$prod['oi_amount']);
}
$row[] = array('data'=> implode("\n",$tmp),'type'=>'s','wrap'=>true);
$exportData[$type]['data'][] = $row;
}
break;
case "exportNew":
$sql = "select o_id,o_name,o_tel,o_cellphone,o_reci_name,o_reci_tel,o_reci_cellphone,o_reci_email,concat(o_reci_city,o_reci_area,o_reci_address) as address from ".$db->prefix("order")." where o_status='0' and del='0' order by o_createdate ";
$res = $db->query($sql,true);
while($row = $db->fetch_array($res,0)){
$sql = "select * from ".$db->prefix("order_items")." where o_id='".$row[0]."' and del='0' order by oi_id ";
$res2 = $db->query($sql,true);
$row[0] = array('data'=>$row[0],'type'=>'s');
$row[2] = array('data'=>$row[2],'type'=>'s');
$row[3] = array('data'=>$row[3],'type'=>'s');
$row[5] = array('data'=>$row[5],'type'=>'s');
$row[6] = array('data'=>$row[6],'type'=>'s');
$tmp = array();
while($prod = $db->fetch_array($res2,1)){
if($prod['spec']){
$tmp[] = sprintf("%s(%s)*%d",$prod['p_name'],$prod['spec'],$prod['oi_amount']);
}else{
$tmp[] = sprintf("%s*%d",$prod['p_name'],$prod['oi_amount']);
}
}
$row[] = array('data'=> implode("\n",$tmp),'type'=>'s','wrap'=>true);
$exportData[$type]['data'][] = $row;
}
break;
}
return $exportData[$type];
}
function tempstore_list(){
global $db,$cms_cfg,$tpl,$main,$TPLMSG;
$sql = "select ts.m_id,sum(ts.amounts) as amounts, m.m_fname,m.m_lname,m_account from ".$db->prefix("temp_store")." as ts inner join ".$db->prefix("member")." as m on ts.m_id=m.m_id group by ts.m_id order by amounts desc ";
$res = $db->query($sql,true);
$i=1;
while($row = $db->fetch_array($res,1)){
$tpl->newBlock("TEMP_STORE_LIST");
foreach($row as $k => $v){
$tpl->assign(strtoupper($k),$v);
}
$tpl->assign(array(
"SERIAL" => $i++,
"M_NAME" => sprintf($TPLMSG['MEMBER_NAME_SET_'.$cms_cfg['ws_module']['ws_contactus_s_style']],$row['m_fname'],$row['m_lname']),
));
}
}
function tempstore_form(){
global $TPLMSG,$cms_cfg,$tpl;
$db = App::gethelper('db');
if($_GET['m_id']){
$member = App::getHelper('dbtable')->member->getData($_GET['m_id'])->getDataRow();
if($member){
$tpl->assignGlobal(array(
"M_NAME" => sprintf($TPLMSG['MEMBER_NAME_SET_'.$cms_cfg['ws_module']['ws_contactus_s_style']],$member['m_fname'],$member['m_lname']),
"M_ID" => $member['m_id'],
));
//顯示寄放記錄
$tsRecArr = $this->get_temp_store_record($member['m_id']);
if($tsRecArr){
foreach($tsRecArr as $j => $tsRec){
$tpl->newBlock("TSREC_ROW");
foreach($tsRec as $k => $v){
$tpl->assign(strtoupper($k),$v);
}
$tpl->assign(array(
"SERIAL" => $j+1,
));
}
}
}
}
$sql = "select min(p_id) as p_id,p_name from ".$db->prefix("products")." where p_status='1' group by p_name order by p_sort ";
$res = $db->query($sql,true);
while($row = $db->fetch_array($res,1)){
$productOption[$row['p_id']] = $row['p_name'];
}
App::gethelper("main")->multiple_select("stprod",$productOption,"");
}
function ajax_new_temp_store(){
$db = App::gethelper("db");
$sql = "select * from ".$db->prefix("temp_store")." where m_id='{$_POST['m_id']}' and p_id='{$_POST['p_id']}'";
if($exists = $db->query_firstRow($sql)){
$result['code'] = 0;
$result['error'] = "已存在寄放記錄!";
}else{
$sql = "insert into ".$db->prefix("temp_store")."(m_id,p_id)values('{$_POST['m_id']}','{$_POST['p_id']}')";
$db->query($sql,true);
if(($db_msg = $db->report())==""){
$id = $db->get_insert_id();
$sql = "select a.*,b.p_name from ".$db->prefix("temp_store")." as a inner join ".$db->prefix("products")." as b on a.p_id=b.p_id where id='{$id}'";
$tempStore = $db->query_firstRow($sql,true);
$result['code'] = 1;
$result['data'] = $tempStore;
}else{
$result['code'] = 0;
$result['error'] = $db_msg;
}
}
echo json_encode($result);
}
function get_temp_store_record($m_id){
$db = App::getHelper('db');
$sql = "select a.*,b.p_name from ".$db->prefix("temp_store")." as a inner join ".$db->prefix("products")." as b on a.p_id=b.p_id where m_id='{$m_id}' order by b.p_sort ";
$res = $db->query($sql,true);
while($tsRec = $db->fetch_array($res,1)){
$record[] = $tsRec;
}
return $record;
}
function ajax_get_tsrec(){
$result['code'] = 1;
$result['data'] = $this->get_temp_store_record($_POST['m_id']);
echo json_encode($result);
}
function ajax_op_temp_store(){
$db = App::getHelper('db');
$sql = "select * from ".$db->prefix('temp_store')." where id='".$_POST['id']."'";
$tsRec = $db->query_firstRow($sql);
if($tsRec){
if(trim($_POST['store'])){
$updateInfo[] = "store='".trim($_POST['store'])."'";
}
if(trim($_POST['note'])){
$updateInfo[] = "note='".trim($_POST['note'])."'";
}
if($updateInfo){
$sql = "update ".$db->prefix('temp_store')." set ".implode(',',$updateInfo)." where id='".$_POST['id']."'";
$db->query($sql,true);
}
$result['code'] = 1;
$amounts = ($_POST['keepAmounts']>0)? $_POST['keepAmounts'] : 0 - $_POST['getAmounts'];
$tsRec['amounts']+=$amounts;
//更新主記錄
$sql = "update ".$db->prefix('temp_store')." set amounts='".$tsRec['amounts']."' where id='".$_POST['id']."'";
$db->query($sql);
//加入執行記錄
$sql = "insert into ".$db->prefix("temp_store_op")."(ts_id,amounts)values('".$_POST['id']."','".$amounts."')";
$db->query($sql);
$result['data'] = $tsRec;
echo json_encode($result);
}
}
}
//ob_end_flush();
?><file_sep>/class/model/bonus.php
<?php
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
* Description of bonus
*
* @author Administrator
*/
class Model_Bonus {
//put your code here
protected $fields = array(
"sc_bonus_purchase" => "",
"sc_bonus_points" => "",
"sc_bonus_valid_days" => "",
"sc_bonus_pay_as" => "",
);
function __construct(){
$sc = $this->get_dbtable()->getData(1)->getDataRow();
$cols = array_keys($this->fields);
foreach($cols as $k){
if(isset($sc[$k])){
$this->fields[$k] = $sc[$k];
}
}
}
function __get($name){
return $this->fields[$name];
}
function __set($name,$value){
if(isset($this->fields[$name])){
$this->fields[$name] = $value;
}else{
throw new Exception("no field:".$name." in class: ".__CLASS__);
}
}
function get_dbtable(){
return App::getHelper('dbtable')->system_config;
}
function get_rec_dbtable(){
return App::getHelper('dbtable')->order_bonus;
}
function get_field_array(){
return $this->fields;
}
function save(){
$this->get_dbtable()->writeData($this->fields);
}
//購物金額兌換點數
function exchange($purchase){
return floor($purchase / $this->sc_bonus_purchase) * $this->sc_bonus_points;
}
//點數兌換購物金
function exchange_fee($bonus_points){
return floor($bonus_points / $this->sc_bonus_points) * $this->sc_bonus_pay_as;
}
//計算當日起算點數有效日期
function get_bonus_valid_date(){
return date("Y-m-d",strtotime("+ ".$this->sc_bonus_valid_days."days"));
}
function writeRec($m_id,$o_id,$bonus_points){
global $db,$cms_cfg;
$times = intval($bonus_points / $this->sc_bonus_points);
for($i=0;$i<$times;$i++){
$rec = array(
'o_id' => $o_id,
'm_id' => $m_id,
'ob_points' => $this->sc_bonus_points,
'ob_valid_date' => $this->get_bonus_valid_date(),
);
$this->get_rec_dbtable()->insert($rec);
}
}
function cancelBonus($o_id){
$rec['obc_status']=0;
$this->get_rec_dbtable()->update($rec,array('o_id'=>$o_id));
}
function get_bonus_of($m_id){
return $this->get_rec_dbtable()->get_valid_bonus($m_id);
}
function using_bonus_on($m_id,$o_id){
$data = array(
'obc_status' => 2,
'obc_use_on' => $o_id,
);
$con = array('m_id' => $m_id);
$this->get_rec_dbtable()->update($data,$con);
}
function checkValidBonusByMid($m_id){
$this->get_rec_dbtable()->update(array('obc_status'=>-1)," m_id='{$m_id}' and obc_status='1' and obc_valid_date<curdate() ");
return $this->get_rec_dbtable()->affected_rows();
}
}
?>
<file_sep>/class/model/order/payment/neweb.php
<?php
require_once "returncode/neweb.php";
class Model_Order_Payment_Neweb {
//put your code here
protected $config;
protected $code;
protected $mode;
protected $codedata = array();
protected $url = array(
'testing' => "https://testmaple2.neweb.com.tw/NewebmPP/cdcard.jsp",
'running' => "https://taurus.neweb.com.tw/NewebmPP/cdcard.jsp",
);
protected $template = "templates/ws-cart-card-transmit-tpl.html";
function __construct($config) {
$this->config = $config;
$this->code = $config['code'];
$this->mode = $config['exe_mode'];
$this->codedata['MerchantNumber'] = $config['MerchantNumber'];
$this->codedata = array_merge($this->codedata,$this->config['params']);
}
//結帳
function checkout($o_id,$total_price,$extra_info=array()){
$this->codedata['OrderNumber'] = strtoupper($o_id);
$this->codedata['Amount'] = $total_price;
if(!empty($extra_info)){
foreach($extra_info as $k => $v){
$this->codedata[$k] = $v;
// if(!isset($this->codedata[$k])){
// $this->codedata[$k] = $v;
// }
}
}
$tpl = new TemplatePower($this->template);
$tpl->prepare();
foreach($this->codedata as $k => $v){
$tpl->newBlock("CARD_FIELD_LIST");
$tpl->assign(array(
"TAG_KEY" => $k,
"TAG_VALUE" => $v,
));
}
$code = $this->make_code($this->codedata);
$tpl->assignGlobal("TAG_INPUT_STR",$code[0]);
$tpl->newBlock("CARD_FIELD_LIST");
$tpl->assign(array(
"TAG_KEY" => 'checksum',
"TAG_VALUE" => $code[1]
));
$tpl->assignGlobal("AUTHORIZED_URL",$this->url[$this->mode]);
$tpl->printToScreen();
die();
}
//製作押碼
function make_code($codedata,$direction='out'){
if($direction=='out'){
$input_str = $codedata['MerchantNumber'].$codedata['OrderNumber'].$this->code.$codedata['Amount'];
}elseif($direction=='in'){
$input_str = $codedata['MerchantNumber'].$codedata['OrderNumber'].$codedata['PRC'].$codedata['SRC'].$this->code.$codedata['Amount'];
}
return array($input_str,md5($input_str));
}
//更新訂單
function update_order(Dbtable_Order $db,$result){
$oid = $result['OrderNumber'];
$result['o_id'] = $oid;
if($result['PRC']=='0'){ //交易成功
if($this->validate($result)){
//更新訂單資料
$result['o_status'] = 1;
//寄發繳款通知信
$tpl = App::getHelper('main')->get_mail_tpl('receipt-notification');
$tpl->newBlock("SHOPPING_ORDER");
$tpl->assign("MSG_O_ID",$result['o_id']);
$mailContent = $tpl->getOutputContent();
$order = $db->getData($oid)->getDataRow("o_email");
App::getHelper('main')->ws_mail_send(App::getHelper('session')->sc_email,$order['o_email'],$mailContent,"繳款通知","","",null,1);
}else{
throw new Exception("return result doesn't valiated!");
}
}else{
//更新訂單狀態
if($result['PRC']!='8'){ //錯誤原因非訂單編號重複
$result['o_status'] = 21;
}
}
$db->writeData($result, "", 'update');
//$db->query($sql,true);
//$sql = "select * from ".$db->prefix("order")." where o_id='".$oid."'";
//return $db->query_firstRow($sql,true);
// return $sql;
}
//驗證回傳結果
function validate($result){
$code = $this->make_code($result,'in');
return ($result['CheckSum']==$code[1]);
}
}
<file_sep>/class/model/order/payment/neweb/notcreditcard.php
<?php
require_once "returncode/notcreditcard.php";
class Model_Order_Payment_Neweb_Notcreditcard {
//put your code here
protected $config;
protected $code;
protected $mode;
protected $codedata = array();
//串接網址
protected $url = array(
'testing' => "http://testmaple2.neweb.com.tw/CashSystemFrontEnd/Payment",
'running' => "https://aquarius.neweb.com.tw/CashSystemFrontEnd/Payment",
);
//查詢網址
protected $qurl = array(
'testing' => "http://testmaple2.neweb.com.tw/CashSystemFrontEnd/Query",
'running' => "https://aquarius.neweb.com.tw/CashSystemFrontEnd/Query",
);
protected $template = "templates/ws-cart-card-transmit-tpl.html";
protected $qtemplate = "templates/ws-cart-card-query-tpl.html";
function __construct($config) {
$this->config = $config;
$this->code = $config['code'];
$this->mode = $config['exe_mode'];
$this->codedata['merchantnumber'] = $config['merchantnumber'];
$this->codedata = array_merge($this->codedata,$this->config['params']);
}
//結帳
function checkout($o_id,$total_price,$extra_info=array()){
$this->codedata['ordernumber'] = strtoupper($o_id);
$this->codedata['amount'] = $total_price;
if(!empty($extra_info)){
foreach($extra_info as $k => $v){
$this->codedata[$k] = $v;
// if(!isset($this->codedata[$k])){
// $this->codedata[$k] = $v;
// }
}
}
$code = $this->make_code($this->codedata);
$this->codedata['hash'] = $code[1];
if($this->codedata['returnvalue']==1){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $this->url[$this->mode]);
// curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-type: multipart/form-data"));
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_TIMEOUT, 15);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($this->codedata));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$returnValue = curl_exec($ch);
parse_str($returnValue,$result);
if($this->validate($result)){
App::getHelper('session')->paymentInfo = $result;
$query = array(
'status' => 'OK',
'pno' => $o_id,
);
//寫入訂單付款資料表
$result['o_id'] = $result['ordernumber'];
App::getHelper('dbtable')->order_paymentinfo->insert($result);
}else{
$query = array(
'status' => 'FAIL',
'pno' => $o_id,
);
//設定訂單為授權失敗
$order = array(
'o_id' => $o_id,
'o_status' => 21,
);
App::getHelper('dbtable')->order->writeData($order);
}
header("location: ".$this->codedata['nexturl']."?". http_build_query($query));
}else{
$tpl = new TemplatePower($this->template);
$tpl->prepare();
foreach($this->codedata as $k => $v){
if(!empty($v)){
$tpl->newBlock("CARD_FIELD_LIST");
$tpl->assign(array(
"TAG_KEY" => $k,
"TAG_VALUE" => $v,
));
}
}
// $tpl->assignGlobal("TAG_INPUT_STR",$code[0]);
// $tpl->newBlock("CARD_FIELD_LIST");
// $tpl->assign(array(
// "TAG_KEY" => 'hash',
// "TAG_VALUE" => $code[1]
// ));
$tpl->assignGlobal("AUTHORIZED_URL",$this->url[$this->mode]);
$tpl->printToScreen();
}
die();
}
//查詢
function query($o_id,$total_price,$extra_info=array()){
$this->codedata['ordernumber'] = strtoupper($o_id);
$this->codedata['amount'] = $total_price;
if(!empty($extra_info)){
foreach($extra_info as $k => $v){
$this->codedata[$k] = $v;
}
}
$tpl = new TemplatePower($this->template);
$tpl->prepare();
foreach($this->codedata as $k => $v){
if(!empty($v)){
$tpl->newBlock("CARD_FIELD_LIST");
$tpl->assign(array(
"TAG_KEY" => $k,
"TAG_VALUE" => $v,
));
}
}
$code = $this->make_code($this->codedata);
$tpl->assignGlobal("TAG_INPUT_STR",$code[0]);
$tpl->newBlock("CARD_FIELD_LIST");
$tpl->assign(array(
"TAG_KEY" => 'hash',
"TAG_VALUE" => $code[1]
));
$tpl->assignGlobal("AUTHORIZED_URL",$this->qurl[$this->mode]);
$tpl->printToScreen();
die();
}
//製作押碼
function make_code($codedata,$direction='out'){
if($direction=='out'){
$input_str = $codedata['merchantnumber'].$this->code.$codedata['amount'].$codedata['ordernumber'];
}elseif($direction=='in'){
$input_str = "rc=0&bankid=".$codedata['bankid']."&virtualaccount=".$codedata['virtualaccount']."&amount=".$codedata['amount']."&merchantnumber=".$codedata['merchantnumber']."&ordernumber=".$codedata['ordernumber']."&code=".$this->code;
}elseif($direction=='in2'){
$input_str = "merchantnumber=".$codedata['merchantnumber'].
"&ordernumber=".$codedata['ordernumber'].
"&serialnumber=".$codedata['serialnumber'].
"&writeoffnumber=".$codedata['writeoffnumber'].
"&timepaid=".$codedata['timepaid'].
"&paymenttype=".$codedata['paymenttype'].
"&amount=".$codedata['amount'].
"&tel=".$codedata['tel'].$this->code;
}
return array($input_str,md5($input_str));
}
//更新訂單
function update_order(Dbtable_Order $db,$result){
if($this->validatePay($result)){
$order = $db->getData($result['ordernumber'])->getDataRow(" o_id,o_email ");
$order['o_status']=1;
$db->writeData($order);
//更新付款資訊
$result['o_id'] = $result['ordernumber'];
App::getHelper('dbtable')->order_paymentinfo->writeData($result);
//寄發繳款通知信
$tpl = App::getHelper('main')->get_mail_tpl('receipt-notification');
$tpl->newBlock("SHOPPING_ORDER");
$tpl->assign("MSG_O_ID",$result['ordernumber']);
$mailContent = $tpl->getOutputContent();
App::getHelper('main')->ws_mail_send(App::getHelper('session')->sc_email,$order['o_email'],$mailContent,"繳款通知","","",null,1);
// $db->query($sql,true);
// $sql = "select * from ".$db->prefix("order")." where o_id='".$oid."'";
// return $db->query_firstRow($sql,true);
// return $sql;
}
}
//驗證回傳結果
function validate($result){
$code = $this->make_code($result,'in');
return ($result['checksum']==$code[1]);
}
//驗證繳款通知
function validatePay($result){
$code = $this->make_code($result,'in2');
return ($result['hash']==$code[1]);
}
}
| 11bec7d7c4c4d98189902123abd95584fe19e32b | [
"PHP"
] | 12 | PHP | l7263626/liu-tian | b5c29e2fa624abb763ec07126c383aab7ca24295 | 790413d8258d04a9d32743ff7117fcaa4b8a716b |
refs/heads/master | <repo_name>aldahick/spacegame-launcher<file_sep>/src/net/tiin57/energizedwarfare/launcher/LogThread.java
package net.tiin57.energizedwarfare.launcher;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintStream;
public class LogThread implements Runnable {
private BufferedReader in;
private String prefix;
private PrintStream out;
public LogThread(String prefix, BufferedReader in, PrintStream out) {
this.in = in;
this.out = out;
this.prefix = prefix;
}
@Override
public void run() {
String line;
try {
while ((line=in.readLine()) != null) {
out.println(prefix+line);
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
<file_sep>/README.md
spacegame-launcher
==================
The launcher for https://github.com/tiin57/spacegame
You can download a compiled version (possibly up-to-date) at http://tiin57.net/spacegame/launcher/spacegame_launcher.jar | bebabdb04495f400c6c4cc669be7cef46e65031f | [
"Markdown",
"Java"
] | 2 | Java | aldahick/spacegame-launcher | 2bae79dfeda0f0a968cc22c01016c523d7193b3d | 799fd21343d7608f8bf13198cbf77e1fb1b734ff |
refs/heads/master | <repo_name>David-Hinschberger/Configs-Settings<file_sep>/README.md
<h2>Config and Settings</h2>
Here is where I'll upload my preferences, settings files, etc.
Includes:
* bashrc
* vimrc
* zshrc
* hhkb keyboard layout
* bash script to install [onedark](https://github.com/joshdick/onedark.vim) vim theme
* bash script to switch audio input between my ODAC and gpu outputs.
<file_sep>/audio-switch
#!/bin/bash
cmd(){
pacmd list-sinks | grep -P -A1 "[^\*] index: (\d)" | grep -B1 -P "(name: .*hdmi|.*ODAC)" | head -n 1 | cut -f6 -d " "
}
port=$(cmd)
pacmd set-default-sink $port
pacmd list-sink-inputs | grep index | while read line
do
pacmd move-sink-input `echo $line | cut -f2 -d' '` $port
done
<file_sep>/onedark_install.sh
#!/bin/bash
git clone https://github.com/joshdick/onedark.vim.git
cd onedark.vim
cp -r autoload/ ~/.vim/
cp -r colors/ ~/.vim/
cd ../
rm -rf onedark.vim
<file_sep>/HHKB/keymap_main.c
/*
* WIP keymap
* Modified from hasu's keymap: https://github.com/tmk/tmk_keyboard/blob/master/keyboard/hhkb/keymap_hasu.c
*/
#include "keymap_common.h"
#ifdef KEYMAP_SECTION_ENABLE
const uint8_t keymaps[][MATRIX_ROWS][MATRIX_COLS] __attribute__ ((section (".keymap.keymaps"))) = {
#else
const uint8_t keymaps[][MATRIX_ROWS][MATRIX_COLS] PROGMEM = {
#endif
/* Layer 0: Normal Qwerty - Default
* ,-----------------------------------------------------------.
* |Esc| 1| 2| 3| 4| 5| 6| 7| 8| 9| 0| -| =| \| `|
* |-----------------------------------------------------------|
* |Tab | Q| W| E| R| T| Y| U| I| O| P| [| ]|Backs|
* |-----------------------------------------------------------|
* |Contro| A| S| D| F| G| H| J| K| L| ;| '| Enter |
* |-----------------------------------------------------------|
* |Shift | Z| X| C| V| B| N| M| ,| .| /| Shift | Fn0 |
* `-----------------------------------------------------------'
* |Gui|Alt | Space |Alt |Gui|
* `-------------------------------------------'
*/
[0] = \
KEYMAP(ESC, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, MINS,EQL, BSLS,GRV, \
TAB, Q, W, E, R, T, Y, U, I, O, P, LBRC,RBRC,BSPC, \
LCTL,A, S, D, F, G, H, J, K, L, SCLN, QUOT,ENT, \
LSFT, Z, X, C, V, B, N, M, COMM,DOT, SLSH, RSFT,FN0, \
LGUI,LALT, SPC, RALT, RGUI),
/* Layer 1: Placeholder
* ,-----------------------------------------------------------.
* |Esc| F1| F2| F3| F4| F5| F6| F7| F8| F9|F10|F11|F12|Ins|Del|
* |-----------------------------------------------------------|
* |Caps | | | | | | | |Psc|Slk|Pus|Up | |Backs|
* |-----------------------------------------------------------|
* |Contro|VoD|VoU|Mut| | | *| /|Hom|PgU|Lef|Rig|Enter |
* |-----------------------------------------------------------|
* |Shift | | | | | | +| -|End|PgD|Dow| T7 | |
* `-----------------------------------------------------------'
* |T2 |T3 | T4 |T5 | T6|
* `-------------------------------------------'
*/
[1] = \
KEYMAP(GRV, F1, F2, F3, F4, F5, F6, F7, F8, F9, F10, F11, F12, INS, DEL, \
CAPS,NO, NO, NO, NO, NO, NO, NO, PSCR,SLCK,PAUS, UP, NO, BSPC, \
LCTL,VOLD,VOLU,MUTE,NO, NO, PAST,PSLS,HOME,PGUP,LEFT,RGHT,ENT, \
LSFT,NO, NO, NO, NO, NO, PPLS,PMNS,END, PGDN,DOWN,FN7,TRNS, \
FN2, FN3, FN4, FN5,FN6),
/* Layer 2: Vi mode[Slash]
* ,-----------------------------------------------------------.
* |Esc| F1| F2| F3| F4| F5| F6| F7| F8| F9|F10|F11|F12|Ins|Del|
* |-----------------------------------------------------------|
* |Tab |Hom|PgD|Up |PgU|End|Hom|PgD|PgUlEnd| | | |Backs|
* |-----------------------------------------------------------|
* |Contro| |Lef|Dow|Rig| |Lef|Dow|Up |Rig| | |Return |
* |-----------------------------------------------------------|
* |Shift | | | | | |Hom|PgD|PgUlEnd| |Shift | |
* `-----------------------------------------------------------'
* |Gui|Alt | Space |Alt |Gui|
* `-------------------------------------------'
*/
[2] = \
KEYMAP(TRNS, TRNS, TRNS, TRNS, TRNS, TRNS, TRNS, TRNS, TRNS, TRNS, TRNS, TRNS, TRNS, TRNS, TRNS, \
TAB, HOME,PGDN,UP, PGUP,END, HOME,PGDN,PGUP,END, NO, NO, NO, BSPC, \
LCTL,NO, LEFT,DOWN,RGHT,NO, LEFT,DOWN,UP, RGHT,NO, NO, ENT, \
LSFT,NO, NO, NO, NO, NO, HOME,PGDN,PGUP,END, NO, RSFT,FN0, \
LGUI,LALT, SPC, RALT,RGUI),
/* Layer 3: Mouse mode(UHJK)
* ,-----------------------------------------------------------.
* |Esc| F1| F2| F3| F4| F5| F6| F7| F8| F9|F10|F11|F12|Ins|Del|
* |-----------------------------------------------------------|
* |Alt-T| | | | | |Mb1|McU|Mb2| | |Wbk|Wfr|Alt-T|
* |-----------------------------------------------------------|
* |Contro| | | | |MwU|McL|McD|McR| | | |Return |
* |-----------------------------------------------------------|
* |Shift | | | | |MwD| | | | | |Shift | |
* `-----------------------------------------------------------'
* |Gui |Alt | | | |
* `--------------------------------------------'
* Mc: Mouse Cursor / Mb: Mouse Button / Mw: Mouse Wheel
*/
[3] = \
KEYMAP(TRNS, TRNS, TRNS, TRNS, TRNS, TRNS, TRNS, TRNS, TRNS, TRNS, TRNS, TRNS, TRNS, TRNS, TRNS, \
FN8, NO, NO, NO, NO, NO, BTN1,MS_U, BTN2, NO, NO,FN9, FN10,FN8, \
LCTL, NO, NO, NO, NO, WH_U, MS_L, MS_D, MS_R, NO, NO, NO, ENT, \
LSFT,NO, NO, NO, NO, WH_D, NO, NO, NO, NO, NO, RSFT,FN0, \
LGUI,LALT, NO, RALT,RGUI),
/* Layer 4: Keypad
* ,-----------------------------------------------------------.
* |Esc| F1| F2| F3| F4| F5| F6| F7| F8| F9|F10|F11|F12|Ins|Del|
* |-----------------------------------------------------------|
* |Alt-T| | | | 7 | 8 | 9 | + | * | | UP| | |Backs|
* |-----------------------------------------------------------|
* |Contro| | | | 4 | 5 | 6 | - | / |Lef|Dow|Rig|Return |
* |-----------------------------------------------------------|
* |Shift | | | 0 | 1 | 2 | 3 | | | | |Shift | |
* `-----------------------------------------------------------'
* |Gui |Alt | Return | Alt |Gui|
* `--------------------------------------------'
*/
[4] = \
KEYMAP(TRNS, TRNS, TRNS, TRNS, TRNS, TRNS, TRNS, TRNS, TRNS, TRNS, TRNS, TRNS, TRNS, TRNS, TRNS, \
FN8, NO, NO, NO, 7, 8, 9, PPLS, PAST, NO, UP, NO, NO, BSPC, \
LCTL, NO, NO, NO, 4, 5, 6, PMNS,PSLS,LEFT,DOWN,RGHT, ENT, \
LSFT,NO, NO, 0, 1, 2, 3, NO, NO, NO ,NO, RSFT,FN0, \
LGUI,LALT, ENT, RALT,RGUI),
/* Layer 5: Dvorak
* ,-----------------------------------------------------------.
* |Esc| F1| F2| F3| F4| F5| F6| F7| F8| F9|F10|F11|F12|Ins|Del|
* |-----------------------------------------------------------|
* |Alt-T| '| ,| .| P| Y| F| G| C| R| L| /| =|Backs|
* |-----------------------------------------------------------|
* |Contro| A| O| E| U| I| D| H| T| N| S| -|Return |
* |-----------------------------------------------------------|
* |Shift | ;| Q| J| K| X| B| M| W| V| Z|Shift | |
* `-----------------------------------------------------------'
* |Gui |Alt | Return | Alt |Gui|
* `--------------------------------------------'
*/
[5] = \
KEYMAP(TRNS, TRNS, TRNS, TRNS, TRNS, TRNS, TRNS, TRNS, TRNS, TRNS, TRNS, TRNS, TRNS, TRNS, TRNS, \
TAB, QUOT, COMM, DOT, P, Y, F, G, C, R, L, SLSH,EQL,BSPC, \
LCTL,A, O, E, U, I, D, H, T, N, S, MINS, ENT, \
LSFT, SCLN, Q, J, K, X, B, M, W, V, Z, RSFT, FN0, \
LGUI,LALT, SPC, RALT, RGUI),
/* Layer 6: Dvorak copy [PLACEHOLDER]
* ,-----------------------------------------------------------.
* |Esc| F1| F2| F3| F4| F5| F6| F7| F8| F9|F10|F11|F12|Ins|Del|
* |-----------------------------------------------------------|
* |Alt-T| '| ,| .| P| Y| F| G| C| R| L| /| =|Backs|
* |-----------------------------------------------------------|
* |Contro| A| O| E| U| I| D| H| T| N| S| -|Return |
* |-----------------------------------------------------------|
* |Shift | ;| Q| J| K| X| B| M| W| V| Z|Shift | |
* `-----------------------------------------------------------'
* |Gui |Alt | Return | Alt |Gui|
* `--------------------------------------------'
*/
[6] = \
KEYMAP(TRNS, TRNS, TRNS, TRNS, TRNS, TRNS, TRNS, TRNS, TRNS, TRNS, TRNS, TRNS, TRNS, TRNS, TRNS, \
TAB, QUOT, COMM, DOT, P, Y, F, G, C, R, L, SLSH,EQL,BSPC, \
LCTL,A, O, E, U, I, D, H, T, N, S, MINS, ENT, \
LSFT, SCLN, Q, J, K, X, B, M, W, V, Z, RSFT, FN0, \
LGUI,LALT, SPC, RALT, RGUI),
/* Layer 7: Mess Around
* ,-----------------------------------------------------------.
* |Esc| F1| F2| F3| F4| F5| F6| F7| F8| F9|F10|F11|F12|Ins|Del|
* |-----------------------------------------------------------|
* |Alt-T| | | | 7 | 8 | 9 | + | * | | UP| | |Backs|
* |-----------------------------------------------------------|
* |Contro| | | | 4 | 5 | 6 | - | / |Lef|Dow|Rig|Return |
* |-----------------------------------------------------------|
* |Shift | | | 0 | 1 | 2 | 3 | | | | |Shift | |
* `-----------------------------------------------------------'
* |Gui |Alt | Return | Alt |Gui|
* `--------------------------------------------'
* Mc: Mouse Cursor / Mb: Mouse Button / Mw: Mouse Wheel
*/
[7] = \
KEYMAP(TRNS, TRNS, TRNS, TRNS, TRNS, TRNS, TRNS, TRNS, TRNS, TRNS, TRNS, TRNS, TRNS, TRNS, TRNS, \
TAB, FN12, COMM, DOT, P, Y, F, G, C, R, L, SLSH,EQL,BSPC, \
LCTL,A, O, E, U, I, D, H, T, N, S, MINS, ENT, \
LSFT, SCLN, Q, J, K, X, B, M, W, V, Z, RSFT, FN0, \
LGUI,LALT, FN11, RALT, RGUI),
/* Layer 8: HHKB mode[HHKB Fn] Modified to switch between layers
* ,-----------------------------------------------------------.
* |Esc| F1| F2| F3| F4| F5| F6| F7| F8| F9|F10|F11|F12|Ins|Del|
* |-----------------------------------------------------------|
* |Caps | | | | | | | |Psc|Slk|Pus|Up | |Backs|
* |-----------------------------------------------------------|
* |Contro|VoD|VoU|Mut| | | *| /|Hom|PgU|Lef|Rig|Enter |
* |-----------------------------------------------------------|
* |T1 | | | | | | +| -|End|PgD|Dow| T7 | |
* `-----------------------------------------------------------'
* |T2 |T3 | T4 |T5 | T6|
* `-------------------------------------------'
*/
[8] = \
KEYMAP(GRV, F1, F2, F3, F4, F5, F6, F7, F8, F9, F10, F11, F12, INS, DEL, \
CAPS,NO, NO, NO, NO, NO, NO, NO, PSCR,SLCK,PAUS, UP, NO, BSPC, \
LCTL,VOLD,VOLU,MUTE,NO, NO, PAST,PSLS,HOME,PGUP,LEFT,RGHT,ENT, \
FN1,NO, NO, NO, NO, NO, PPLS,PMNS,END, PGDN,DOWN,FN7,TRNS, \
FN2, FN3, FN4, FN5,FN6),
};
/* id for user defined functions */
enum function_id {
LSHIFT_LPAREN,
};
enum macro_id {
FORTNITE,
HELLO,
VOLUP,
ALT_TAB,
};
/*
* Fn action definition
*/
#ifdef KEYMAP_SECTION_ENABLE
const action_t fn_actions[] __attribute__ ((section (".keymap.fn_actions"))) = {
#else
const action_t fn_actions[] PROGMEM = {
#endif
[0] = ACTION_LAYER_MOMENTARY(8), // HHKB Layer
[1] = ACTION_LAYER_TOGGLE(1), // PLACEHOLDER
[2] = ACTION_LAYER_TOGGLE(2), // Vi Layer
[3] = ACTION_LAYER_TOGGLE(3), // Mouse Layer
[4] = ACTION_LAYER_TOGGLE(4), // Keypad Layer
[5] = ACTION_LAYER_TOGGLE(5), // Dvorak Layer
[6] = ACTION_LAYER_TOGGLE(6), // PLACEHOLDER Layer
[7] = ACTION_LAYER_TOGGLE(7), // Messaround Layer
[8] = ACTION_MACRO(ALT_TAB), // Application switching
[9] = ACTION_MODS_KEY(MOD_LALT, KC_LEFT),
[10] = ACTION_MODS_KEY(MOD_LALT, KC_RIGHT),
[11] = ACTION_MACRO(FORTNITE), // Fortnite !Land
[12] = ACTION_MACRO(HELLO), // Macro: say hello
// [x] = ACTION_LMOD_TAP_KEY(KC_LCTL, KC_BSPC), LControl with tap Backspace
// [x] = ACTION_LMOD_TAP_KEY(KC_LCTL, KC_ESC), // LControl with tap Esc
// [x] = ACTION_FUNCTION_TAP(LSHIFT_LPAREN), // Function: LShift with tap '('
// [x] = ACTION_MACRO(VOLUP), // Macro: media key
};
/*
* Macro definition
*/
const macro_t *action_get_macro(keyrecord_t *record, uint8_t id, uint8_t opt)
{
switch (id) {
case FORTNITE:
return (record->event.pressed ?
MACRO( D(LSHIFT), D(1), U(1), U(LSHIFT), T(L), T(A), T(N), T(D), T(ENTER), END) :
MACRO_NONE);
case HELLO:
return (record->event.pressed ?
MACRO( I(0), T(H), T(E), T(L), T(L), W(255), T(O), END ) :
MACRO_NONE );
case VOLUP:
return (record->event.pressed ?
MACRO( D(VOLU), U(VOLU), END ) :
MACRO_NONE );
case ALT_TAB:
return (record->event.pressed ?
MACRO( D(LALT), D(TAB), END ) :
MACRO( U(TAB), END ));
}
return MACRO_NONE;
}
/*
* user defined action function
*/
void action_function(keyrecord_t *record, uint8_t id, uint8_t opt)
{
if (record->event.pressed) dprint("P"); else dprint("R");
dprintf("%d", record->tap.count);
if (record->tap.interrupted) dprint("i");
dprint("\n");
switch (id) {
case LSHIFT_LPAREN:
// Shift parentheses example: LShft + tap '('
// http://stevelosh.com/blog/2012/10/a-modern-space-cadet/#shift-parentheses
// http://geekhack.org/index.php?topic=41989.msg1304899#msg1304899
if (record->event.pressed) {
if (record->tap.count > 0 && !record->tap.interrupted) {
if (record->tap.interrupted) {
dprint("tap interrupted\n");
register_mods(MOD_BIT(KC_LSHIFT));
}
} else {
register_mods(MOD_BIT(KC_LSHIFT));
}
} else {
if (record->tap.count > 0 && !(record->tap.interrupted)) {
add_weak_mods(MOD_BIT(KC_LSHIFT));
send_keyboard_report();
register_code(KC_9);
unregister_code(KC_9);
del_weak_mods(MOD_BIT(KC_LSHIFT));
send_keyboard_report();
record->tap.count = 0; // ad hoc: cancel tap
} else {
unregister_mods(MOD_BIT(KC_LSHIFT));
}
}
break;
}
}
| eb7da22fc52a9792b5d19c4aa835c9f9f4963d46 | [
"Markdown",
"C",
"Shell"
] | 4 | Markdown | David-Hinschberger/Configs-Settings | 670d7f26db5477bd461b0594b17a158deb21be11 | 916fbf517941c8f2305611a00b6bfdb5a1c115c0 |
refs/heads/master | <repo_name>median-man/learn-react-tdd<file_sep>/src/components/ProductList.jsx
import React from 'react';
import PropTypes from 'prop-types';
function ProductList(props) {
const { onProductSelect, filter } = props;
const productListItems = products => products
.filter(product => (props.filter.brand ? filter.brand === product.brand : true))
.map(product => (
<li key={product.id}>
<div
role="button"
tabIndex="0"
onClick={() => onProductSelect(product)}
onKeyPress={() => onProductSelect(product)}
>
{product.name} {product.brand}
</div>
</li>));
return <ul>{productListItems(props.products)}</ul>;
}
ProductList.propTypes = {
products: PropTypes.arrayOf(PropTypes.object).isRequired,
onProductSelect: PropTypes.func.isRequired,
filter: PropTypes.shape({ brand: PropTypes.string }),
};
ProductList.defaultProps = {
filter: {},
};
export default ProductList;
<file_sep>/src/App.test.jsx
import React from 'react';
import ReactDOM from 'react-dom';
import Adapter from 'enzyme-adapter-react-16';
import Enzyme, { shallow } from 'enzyme';
import ProductList from './components/ProductList';
import BrandSelector from './components/BrandSelector';
import App from './App';
Enzyme.configure({ adapter: new Adapter() });
let appWrapper;
let mockProducts;
beforeEach(() => {
appWrapper = shallow(<App />);
mockProducts = [
{ id: 1, name: 'AirMax 90', brand: 'Nike' },
{ id: 2, name: 'Yeezy', brand: 'Adidas' },
{ id: 3, name: 'Classic', brand: 'Reebok' },
];
appWrapper.setState({ products: mockProducts, currentBrand: '' });
});
function findProductList() {
return appWrapper.find(ProductList);
}
it('handleProductSelect() should add a product to state.selectedProducts', () => {
const input = mockProducts[0];
const expected = [input];
let handleProductSelect;
let selectedProducts;
const setUp = () => {
selectedProducts = () => appWrapper.state('selectedProducts');
({ handleProductSelect } = appWrapper.instance());
expect(selectedProducts()).toEqual([]);
};
setUp();
handleProductSelect(input);
expect(selectedProducts()).toEqual(expected);
});
it('handleBrandSelect() should set state.currentBrand', () => {
const expected = 'mockBrand';
const { handleBrandSelect } = appWrapper.instance();
handleBrandSelect(expected);
const actual = appWrapper.state('currentBrand');
expect(actual).toEqual(expected);
});
it('should render a `<ProductList />`', () => {
expect(findProductList().length).toEqual(1);
});
it('should set ProductList.props.products', () => {
appWrapper.setState({ products: mockProducts });
expect(findProductList().prop('products')).toEqual(mockProducts);
});
it('should set ProductList.props.onProductSelect', () => {
const expected = appWrapper.instance().handleProductSelect;
const actual = findProductList().prop('onProductSelect');
expect(actual).toBe(expected);
});
it('should set ProductList.props.filter', () => {
const expected = { brand: 'testBrand' };
appWrapper.setState({ currentBrand: 'testBrand' });
const actual = findProductList().prop('filter');
expect(actual).toEqual(expected);
});
it('should render the number of items in the cart', () => {
const expected = '2';
appWrapper.setState({ selectedProducts: [mockProducts[0], mockProducts[2]] });
const cartEl = appWrapper.find('.items-in-cart');
expect(cartEl.length).toEqual(1);
expect(cartEl.text()).toEqual(expect.stringContaining(expected));
});
describe('BrandSelector props set by render()', () => {
const findBrandSelector = () => appWrapper.find(BrandSelector);
it('should render a `<BrandSelector>', () => {
expect(findBrandSelector().length).toEqual(1);
});
it('should set BrandSelector.props.products', () => {
const actual = findBrandSelector().prop('products');
expect(actual).toEqual(mockProducts);
});
it('should set BrandSelector.props.onProductSelect', () => {
const expected = appWrapper.instance().handleBrandSelect;
const actual = findBrandSelector().prop('onBrandSelect');
expect(actual).toBe(expected);
});
});
it('should render without crashing', () => {
const div = document.createElement('div');
ReactDOM.render(<App />, div);
ReactDOM.unmountComponentAtNode(div);
});
<file_sep>/README.md
# Learn React TDD
This code is produced as a practice applying [TDD][wiki-tdd] to [React][react].
The code is wrtten as I follow [React + TDD = 💖][med-react-tdd], a post by [ADDM][med-addm] on [Medium][med].
## Tools Used
* [Jest][jest]
* [React][react]
* [Create React App][gh-create-react-app]
* [Enzyme][enzyme] (and correct [adapter package][enzyme-pkgs])
## Breif Description
Following the [post][med-react-tdd] by [ADDM][med-addm], this is an online shoe store application. A user may view a list of products, add products to the shopping cart, view the items in the cart, and filter products listed by brand.
<!-- links -->
[wiki-tdd]: https://en.wikipedia.org/wiki/Test-driven_development
[react]: https://reactjs.org/
[med-react-tdd]: https://medium.com/@admm/test-driven-development-in-react-is-easy-178c9c520f2f
[med-addm]: https://medium.com/@admm
[med]: https://medium.com/
[gh-create-react-app]: https://github.com/facebook/create-react-app
[jest]: https://facebook.github.io/jest/
[enzyme]: http://airbnb.io/enzyme/
[enzyme-pkgs]: https://github.com/airbnb/enzyme/tree/master/packages
<file_sep>/src/components/ProductList.test.jsx
import React from 'react';
import Adapter from 'enzyme-adapter-react-16';
import Enzyme, { shallow } from 'enzyme';
import ProductList from './ProductList';
describe('ProductList', () => {
Enzyme.configure({ adapter: new Adapter() });
let wrapper;
let mockProducts;
let productSelectFn;
beforeEach(() => {
mockProducts = [
{ id: 1, name: 'Mock Product 1', brand: 'MockBrandA' },
{ id: 2, name: 'Mock Product 2', brand: 'MockBrandB' },
{ id: 3, name: 'Mock Product 3', brand: 'MockBrandC' },
];
productSelectFn = jest.fn();
wrapper = shallow(<ProductList products={mockProducts} onProductSelect={productSelectFn} />);
});
afterEach(() => {
productSelectFn.mockReset();
});
function containsTextAt(text, index) {
const el = wrapper.find('li').at(index);
expect(el.contains(text)).toEqual(true);
}
it('should render a list of products as an unordered list', () => {
const expectedLength = mockProducts.length;
expect(wrapper.find('li').length).toEqual(expectedLength);
});
it('should display the product name in each `<li>` element', () => {
mockProducts.forEach(({ name }, index) => containsTextAt(name, index));
});
it('should display the brand name in each `<li>` element', () => {
mockProducts.forEach(({ brand }, index) => containsTextAt(brand, index));
});
describe('when props.filter.brand is is set', () => {
it('should render a filtered list of products', () => {
const excludedBrand = mockProducts[1].brand;
wrapper.setProps({ filter: { brand: mockProducts[0].brand } });
expect(wrapper.contains(excludedBrand)).toBeFalsy();
});
});
describe('props.onProductSelect()', () => {
let firstEl;
beforeEach(() => {
firstEl = wrapper.find('li').first().find('div');
expect(productSelectFn.mock.calls.length).toEqual(0);
});
function onProductSelectCalledWithExpectedArgs() {
expect(productSelectFn.mock.calls.length).toEqual(1);
expect(productSelectFn.mock.calls[0][0]).toEqual(mockProducts[0]);
}
it('should be called when a product `<div>` is clicked', () => {
firstEl.simulate('click');
onProductSelectCalledWithExpectedArgs();
});
it('should be called when `enter` key is pressed on a product `<div>`', () => {
firstEl.simulate('keypress', { key: 'Enter' });
onProductSelectCalledWithExpectedArgs();
});
});
});
<file_sep>/src/components/BrandSelector.jsx
import React from 'react';
import PropTypes from 'prop-types';
function BrandSelector(props) {
const onlyUnique = (item, index, array) => array.indexOf(item) === index;
const brands = products => products.map(product => product.brand).filter(onlyUnique);
return (
<select onChange={event => props.onBrandSelect(event.target.value)}>
{<option value="" />}
{brands(props.products)
.map(brand => <option key={brand} value={brand}>{brand}</option>)}
</select>
);
}
BrandSelector.propTypes = {
products: PropTypes.arrayOf(PropTypes.object).isRequired,
onBrandSelect: PropTypes.func.isRequired,
};
export default BrandSelector;
| c835a0d14a32303ad80841782e0fa4abd89d6934 | [
"JavaScript",
"Markdown"
] | 5 | JavaScript | median-man/learn-react-tdd | 643c41a687107afe49c2498c27b1cf3a78e4046d | b4a05b6d7386e112657fc7dfded51b8425056630 |
refs/heads/main | <file_sep># Geopt
<file_sep>import Rhino.Geometry as rg
"""
INPUTS:
OUTPUT:
"""
grid = []
for i in range(25):
for j in range(25):
grid.append(rg.Point3d(i,j,0))
a = grid
line = rg.Line(grid[0], grid[25])
length = line.Length
comment = 'this is a test'<file_sep>
# print('a')
a = input('Enter your Name:')
b = 'This is Python for Everybody'
def welcome_msg():
print('Hello:',' ', b)
welcome_msg()
| 68f6ca7c916e80f6f330fe75873c99882d5781fd | [
"Markdown",
"Python"
] | 3 | Markdown | sachin-dabas/AIA-Geopt | 571d2ce7370e284e2e9433b231e704c58cd595ea | 0b0234d3f5e6440be937d5131b443ddc009d433e |
refs/heads/master | <file_sep>import { Server } from 'http';
import { Socket } from 'socket.io';
import { Logger } from '@overnightjs/logger';
import { RoomManager } from './RoomManager';
import { ConnectType, ILoginCredential, SocketEvent } from '../network';
export class SocketServer {
private io: Server;
constructor(server: Server) {
this.io = require('socket.io')(server);
}
public start() {
this.io.on(SocketEvent.CONNECT, (socket: Socket) => {
RoomManager.getInstance().onSocketConnect(socket);
socket.on(SocketEvent.CLIENT_LOGIN, (creds: ILoginCredential) => SocketServer.onLogin(socket, creds));
Logger.Info(`[SocketServer] SocketIO Client Connected: ${socket.id}`);
});
}
private static onLogin(socket: Socket, creds: ILoginCredential) {
if (SocketServer.verifyCredential(creds)) {
switch (creds.type) {
case ConnectType.SCREEN:
RoomManager.getInstance().onRoomLogin(socket, creds);
break;
case ConnectType.CONTROLLER:
RoomManager.getInstance().onPlayerLogin(socket, creds);
break;
default:
Logger.Warn(`[RoomManager] Invalid login type ${creds.type}`);
socket.disconnect();
break;
}
} else {
Logger.Warn(`[RoomManager] Invalid login creds: ${creds}`);
socket.disconnect();
}
}
private static verifyCredential(creds: ILoginCredential): boolean {
return true;
}
}
<file_sep>/**
* Start the Express Web-Server
*
* created by <NAME> Apr 14, 2019
*/
import HomeEntertainmentServer from './HomeEntertainmentServer';
import { saveUser } from './store';
const server = new HomeEntertainmentServer(80);
if (!process.env.NODE_ENV || process.env.NODE_ENV !== 'production') {
saveUser({name: '微信用户', id: 'wechat1', avatar: '/avatar/wechat.png', cash: 1000});
}
server.start();
<file_sep>#!/usr/bin/env bash
git pull
docker container stop he
docker container rm he
docker container prune -f
docker image prune -f
docker build . --no-cache -t home-entertainment || exit 1
docker run -d --restart always -p 80:80 --name he -e WECHAT_APP -e WECHAT_TOKEN -e WECHAT_SECRET -e WECHAT_EKEY -e HE_PASSWORD -e NODE_ENV=production home-entertainment
<file_sep>import { Logger } from '@overnightjs/logger';
// @ts-ignore
import * as PokerSolver from 'pokersolver';
import { ICard, Poker } from '../../components/Poker';
import { StageSystem } from '../../components/StageSystem';
import { IGame } from '../../core/Game';
import { Player } from '../../core/Player';
import { IRoomConfig, Room } from '../../core/Room';
import { IInputAction } from '../../network';
import { ActStage } from './stages/ActStage';
import { DistributeStage } from './stages/DistributeStage';
import { EndStage } from './stages/EndStage';
import { FlipStage } from './stages/FlipStage';
import { GameOverStage } from './stages/GameOverStage';
import { ShowDownStage } from './stages/ShowDownStage';
import { StartStage } from './stages/StartStage';
import { PLAYER_FOLD, TexasHoldemPlayer, TexasHoldemRole } from './TexasHoldemPlayer';
export const STAGE_START = 'START';
export const STAGE_DISTRIBUTE = 'DISTRIBUTE';
export const STAGE_ACT = 'ACT';
export const STAGE_FLIP = 'FLIP';
export const STAGE_SHOWDOWN = 'SHOWDOWN';
export const STAGE_END = 'END';
export const STAGE_OVER = 'OVER';
export const SMALL_BLIND_BET = 5;
export enum TexasHoldemPlayerActionType {
PlayerFold = 'PlayerFold',
PlayerCheck = 'PlayerCheck',
PlayerCall = 'PlayerCall',
PlayerAllIn = 'PlayerAllIn',
PlayerRaise = 'PlayerRaise',
PlayerRaiseConfirm = 'PlayerRaiseConfirm',
}
interface ITexasHoldemGameState {
communityCards: ICard[];
countDown: number;
promotion: string;
stage: string;
highestBet: number;
}
export interface ITexasHoldemHandResult {
rank: number;
name: string;
description: string;
}
export class TexasHoldem implements IGame {
public communityCards: ICard[];
public players: { [id: string]: TexasHoldemPlayer };
public poker: Poker;
private readonly stageSystem: StageSystem<TexasHoldem>;
constructor(public room: Room) {
this.players = {};
this.poker = new Poker(1);
this.communityCards = [];
this.stageSystem = new StageSystem<TexasHoldem>(
this,
() => this.room.broadcastFullUpdate(),
() => this.room.broadcastFullUpdate(),
);
this.stageSystem.stages = {
[STAGE_START]: new StartStage(this, this.stageSystem),
[STAGE_ACT]: new ActStage(this, this.stageSystem),
[STAGE_DISTRIBUTE]: new DistributeStage(this, this.stageSystem),
[STAGE_FLIP]: new FlipStage(this, this.stageSystem),
[STAGE_SHOWDOWN]: new ShowDownStage(this, this.stageSystem),
[STAGE_END]: new EndStage(this, this.stageSystem),
[STAGE_OVER]: new GameOverStage(this, this.stageSystem),
};
this.stageSystem.currentStage = STAGE_START;
}
private static isValidAction(action: any): boolean {
if (typeof action.type === 'string') {
if (action.type in TexasHoldemPlayerActionType) {
if (action.type === TexasHoldemPlayerActionType.PlayerRaise) {
return typeof action.payload === 'number';
} else {
return true;
}
}
}
Logger.Warn(`[Texas Holdem] Receive invalid input action: ${action.type} ${action.payload}`);
return false;
}
public getRoomConfig(): IRoomConfig {
return {
tickFrequency: 1000,
numberOfPlayerAllow: 8,
gameName: 'TexasHoldem',
shareGamePlayerState: false,
numberOfPlayerRequired: 2,
};
}
public findWinnerBetween(players: TexasHoldemPlayer[]): TexasHoldemPlayer[] {
// From wiki: https://en.wikipedia.org/wiki/Texas_hold_%27em#Play_of_the_hand
// If the five community cards form the player's best hand,
// then the player is said to be playing the board and can only hope to split the pot,
// because each other player can also use the same five cards to construct the same hand.[10]
// Also From wiki: https://en.wikipedia.org/wiki/Kicker_(poker)
// A kicker, also called a side card,
// is a card in a poker hand that does not itself take part in determining the rank of the hand,
// but that may be used to break ties between hands of the same rank.[1][2]
// For example, the hand Q-Q-10-5-2 is ranked as a pair of queens.
// The 10, 5, and 2 are kickers. This hand would defeat any hand with no pair, or with a lower-ranking pair,
// and lose to any higher-ranking hand.
// But the kickers can be used to break ties between other hands that also have a pair of queens.
// For example, Q-Q-K-3-2 would win (because its K kicker outranks the 10),
// but Q-Q-10-4-3 would lose (because its 4 is outranked by the 5).
const playerInCompare = players.filter((player) => player.state !== PLAYER_FOLD);
const handWithPlayerReference = playerInCompare.map((p) => [p.getHandResult(), p]);
const winnerHands = PokerSolver.Hand.winners(handWithPlayerReference.map((h) => h[0]));
return handWithPlayerReference.filter((p) => winnerHands.includes(p[0])).map((p) => p[1]);
}
public calculateWinner() {
let remainingPlayers: TexasHoldemPlayer[] = this.getPlayerArray();
while (remainingPlayers.length > 1) {
let currentPot = 0;
remainingPlayers.sort((p1, p2) => p1.bet.getCashValue() - p2.bet.getCashValue());
const minValue = remainingPlayers[0].bet.getCashValue();
remainingPlayers.forEach((player) => {
const remainingCash = player.bet.removeChipValue(minValue);
currentPot += minValue;
// player will donate chip value tail to the pot
if (remainingCash > 0) {
currentPot += remainingCash;
}
});
const winners = this.findWinnerBetween(remainingPlayers);
const winnerPot = Math.floor(currentPot / winners.length);
winners.forEach((winner) => {
winner.win(winnerPot);
});
// winner pot tail will be win by the first winner
winners[0].win(currentPot - winnerPot * winners.length);
remainingPlayers = remainingPlayers.filter((p) => p.bet.getCashValue() > 0);
}
if (remainingPlayers.length === 1) {
remainingPlayers[0].giveBackUncalledBet();
}
}
public onPlayerEnter(player: Player): void {
const gamePlayer = new TexasHoldemPlayer(player.id, player.name, player.cash, this);
this.players[player.id] = gamePlayer;
player.gamePlayer = gamePlayer;
if (player.cash < SMALL_BLIND_BET * 2) {
Logger.Info(`[TexasHoldem] Player ${player.name} is coming with no chips, kicked`);
player.disconnect();
}
}
public onPlayerLeave(player: Player): void {
if (this.players[player.id].isDealer) {
const nextDealer = this.getPlayerArrayStartingAt(this.players[player.id], 1)[0];
nextDealer.isDealer = true;
}
if (this.stageSystem.currentStage === STAGE_ACT) {
const betStage = this.stageSystem.getCurrentStage() as ActStage;
if (!!betStage && betStage.getCurrentTurn() === player.gamePlayer) {
betStage.nextActPlayer();
}
}
player.cash = this.players[player.id].cash + this.players[player.id].chips.getCashValue();
// only player in game over stage can get back bet values
if (this.stageSystem.currentStage === STAGE_OVER) {
player.cash += this.players[player.id].bet.getCashValue();
}
player.saveUser();
delete this.players[player.id];
if (this.getPlayerArray().length === 1) {
this.stageSystem.changeStage(STAGE_OVER);
}
}
private getPromote(): string {
return this.stageSystem.getPromotion();
}
public getGameState(): ITexasHoldemGameState {
return {
communityCards: this.communityCards,
countDown: this.stageSystem.countDown,
stage: this.stageSystem.currentStage,
promotion: this.getPromote(),
highestBet: this.highestBet(),
};
}
public getPlayerArray(): TexasHoldemPlayer[] {
return Object.values(this.players);
}
public handlePlayerInput(player: Player, action: IInputAction): void {
if (!!TexasHoldem.isValidAction(action)) {
Logger.Info(`[Texas Holdem] Player Input Received ${player.name}: ${action.type} ${action.payload}`);
this.stageSystem.handlePlayerInput(player, action);
}
}
public end(): void {
this.stageSystem.endStage();
Logger.Info(`[Texas Holdem] Game End!`);
}
public tick(delta: number): void {
this.stageSystem.tick();
}
public start(): void {
Logger.Info(`[Texas Holdem] Game Start!`);
const randomDealerIndex = Math.floor(Math.random() * Math.floor(this.getPlayerArray().length - 1));
this.getPlayerArray()[randomDealerIndex].isDealer = true;
this.stageSystem.currentStage = STAGE_START;
this.stageSystem.startStage();
}
public getDealer(): TexasHoldemPlayer {
const dealer = this.getPlayerArray().find((p) => p.isDealer);
if (!dealer) {
throw new Error('Can not find dealer in game');
}
return dealer;
}
public lastReceiveCardPlayer(): TexasHoldemPlayer {
// last receive card player is dealer
return this.getDealer();
}
public firstActPlayer(): TexasHoldemPlayer {
// first Act player is the next of big blind
const bbIndex = this.getPlayerArray().findIndex((p) => p.role === TexasHoldemRole.BIG_BLIND);
if (bbIndex < 0) {
throw new Error('Can not find big blind in game');
}
const nextOfBigBlind = (bbIndex + 1) % this.getPlayerArray().length;
return this.getPlayerArray()[nextOfBigBlind];
}
public getPlayerArrayStartingAt(player: TexasHoldemPlayer | null, offset: number = 0): TexasHoldemPlayer[] {
if (!player) {
return this.getPlayerArray();
}
const startingPlayerIndex = this.getPlayerArray().indexOf(player);
if (startingPlayerIndex < 0) {
throw new Error('Can not find player in game');
}
const playerLength = this.getPlayerArray().length;
const startingIndex = (startingPlayerIndex + playerLength + (offset % playerLength)) % playerLength;
const players = [this.getPlayerArray()[startingIndex]];
players.push(...this.getPlayerArray().filter((p, index) => index > startingIndex));
players.push(...this.getPlayerArray().filter((p, index) => index < startingIndex));
return players;
}
public getCardDistributeSequence(): TexasHoldemPlayer[] {
return this.getPlayerArrayStartingAt(this.lastReceiveCardPlayer(), 1);
}
public highestBet(): number {
return Math.max(...this.getPlayerArray().map((p) => p.bet.getCashValue()));
}
public dispatchCardToCommunity() {
const card = this.poker.randomGet();
this.communityCards.push(card);
}
}
<file_sep>import {
TexasHoldem,
STAGE_ACT,
} from '../index';
import { ICard } from '../../../components/Poker';
import { Logger } from '@overnightjs/logger';
import { StageSystem, IStage } from '../../../components/StageSystem';
import { Player } from '../../../core/Player';
import { IInputAction } from '../../../network';
export const DISPATCH_CARD = '正在发牌';
export class DistributeStage implements IStage {
constructor(private game: TexasHoldem, private stageSystem: StageSystem<TexasHoldem>) {
}
public handlePlayerInput(player: Player, action: IInputAction): void {
return;
}
public stageStart(): void {
return;
}
public stageEnd(): void {
return;
}
public tick(): void {
const turn = this.game.lastReceiveCardPlayer().hand.length;
if (turn === 2) {
this.stageSystem.changeStage(STAGE_ACT);
return;
}
const player = this.game.getCardDistributeSequence().find((p) => p.hand.length === turn);
if (!!player) {
const card: ICard = this.game.poker.randomGet();
card.show = false;
player.hand.push(card);
Logger.Info(`[DistributeStage] Player receive card : ${player.name} ${card.suit} ${card.value}`);
}
}
public getPromotion(): string {
return DISPATCH_CARD;
}
public endCountDown(): void {
return;
}
}
<file_sep>import React from 'react';
import { Button, TextField } from '@material-ui/core';
import DialogTitle from '@material-ui/core/DialogTitle';
import Dialog from '@material-ui/core/Dialog';
import './App.css';
import { ServerAddress } from '../network';
import NameAndAvatar from '../components/NameAndAvatar';
const PasswordPrompt = (props) => {
const {onClose, ...other} = props;
let password = '';
const handleClose = () => {
onClose(password);
};
const valueChange = (value) => {
password = value.target.value;
};
return (
<Dialog aria-labelledby="simple-dialog-title" {...other}>
<DialogTitle id="simple-dialog-title">Please Enter Admin Password</DialogTitle>
<TextField
id="standard-password-input"
label="Password"
type="password"
onChange={valueChange}
margin="normal"
variant="outlined"
style={{margin: 15}}
/>
<Button color='primary' onClick={handleClose}>Submit</Button>
</Dialog>
);
};
class Admin extends React.Component {
token;
constructor(props) {
super(props);
this.state = {
open: true,
users: {}
};
this.token = '';
}
componentDidMount() {
}
passwordInput(value) {
this.token = value;
this.setState({open: false});
this.fetchData();
}
fetchData() {
fetch(ServerAddress + '/admin/list', {
headers: {
'authorization': this.token
},
})
.then(res => res.json())
.then(res => this.setState({users: res}))
.catch(e => {
console.log(e);
alert(e.toString())
});
}
handleDepositMoney(id, currentCash) {
fetch(ServerAddress + '/admin/modify', {
headers: {
'authorization': this.token,
'Content-Type': 'application/json'
},
method: 'POST',
body: JSON.stringify({[id]: {cash: currentCash + 1000}})
})
.then(() => this.fetchData())
.catch(e => {
console.log(e);
alert(e.toString())
});
}
handleWithdrawMoney(id, currentCash) {
let newCash = currentCash - 1000;
if (newCash < 0) {
newCash = 0;
}
fetch(ServerAddress + '/admin/modify', {
headers: {
'authorization': this.token,
'Content-Type': 'application/json'
},
method: 'POST',
body: JSON.stringify({[id]: {cash: newCash}})
})
.then(() => this.fetchData())
.catch(e => {
console.log(e);
alert(e.toString())
});
}
renderUsers(user) {
return (
<div style={{
display: 'flex',
flexDirection: 'row',
justifyContent: 'start',
width: '50vw',
borderBottomWidth: 2,
borderBottomStyle: 'solid',
borderColor: '#999'
}} key={user.id}>
<div style={{flex: 1, display: 'flex', alignItems: 'center'}}>
<NameAndAvatar name={user.name} avatar={user.avatar}/>
</div>
<p style={{marginRight: '5vw'}}>${user.cash}</p>
<div style={{
display:'flex',
justifyContent:'flex-end',
alignItems:'center',
flex:1
}}>
<Button variant='contained' color='primary' onClick={() => this.handleDepositMoney(user.id, user.cash)}>充值1000</Button>
<Button variant='contained' color='secondary' disabled={user.cash <= 0}
onClick={() => this.handleWithdrawMoney(user.id, user.cash)}>取款1000</Button>
</div>
</div>
)
}
render() {
return (
<div className="App">
<h1>系统管理</h1>
<div style={{display: 'flex', flexDirection: 'row', alignItems: 'center'}}>
<Button onClick={() => this.props.history.push('/')}>首页</Button>
<Button onClick={() => this.fetchData()}>刷新</Button>
</div>
<div style={{
display: 'flex',
flexDirection: 'column',
justifyContent: 'flex-start',
alignItems: 'center',
margin: '20vmin'
}}>
{
Object.values(this.state.users).map((user) => this.renderUsers(user))
}
</div>
<PasswordPrompt open={this.state.open} onClose={(p) => this.passwordInput(p)}/>
</div>
);
}
}
export default Admin;
<file_sep>import React from 'react';
import { createStore } from 'redux'
import { Provider } from 'react-redux';
import { reducer } from './reducer';
export const store = createStore(reducer);
export const HomeEntertainmentStore = (props) => {
return (
<Provider store={store}>
{props.children}
</Provider>
)
};
<file_sep>export * from './WechatController';
<file_sep>import { IBlackJackPlayerAction, BlackJack, STAGE_END } from '../index';
import { ICard } from '../../../components/Poker';
import { Logger } from '@overnightjs/logger';
import { StageSystem, IStage } from '../../../components/StageSystem';
import { Player } from '../../../core/Player';
import { IInputAction } from '../../../network';
const DEALER_TURN = '庄家操作';
export interface IPlayerPosition {
bet: number;
handValue: number;
}
export class DealStage implements IStage {
constructor(private game: BlackJack, private stageSystem: StageSystem<BlackJack>) {
}
public handlePlayerInput(player: Player, action: IInputAction): void {
return;
}
public stageStart(): void {
this.game.dealerHand.forEach((card: ICard) => card.show = true);
}
public stageEnd(): void {
}
public tick(): void {
const handleValue = BlackJack.handValue(this.game.dealerHand);
Logger.Info(`[DealStage] Dealer Hand Value: ${handleValue}`);
if (handleValue >= 21) {
Logger.Info(`[DealStage] Dealer Busted`);
this.stageSystem.changeStage(STAGE_END);
return;
}
if (handleValue >= 17) {
Logger.Info(`[DealStage] Dealer done hit`);
this.stageSystem.changeStage(STAGE_END);
} else {
const card: ICard = this.game.poker.randomGet();
Logger.Info(`[DealStage] Dealer receive card: ${card.value} ${card.suit}`);
this.game.dealerHand.push(card);
}
}
public getPromotion(): string {
return DEALER_TURN;
}
public endCountDown(): void {
}
}
<file_sep>import * as readline from 'readline';
import * as io from 'socket.io-client';
import Socket = SocketIOClient.Socket;
const playerNameBase = '电脑玩家';
const clients: { [id: string]: Socket } = {};
const clientData: { [id: string]: any } = {};
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
});
rl.question('How many player? ', (numberOfPlayers) => {
rl.prompt();
rl.on('line', (line) => {
const [action, player, type, payload] = line.split(' ');
if (!action) {
rl.prompt();
return;
}
const playerName = playerNameBase + player;
switch (action) {
case 'ready':
Object.values(clients).forEach((client) => {
client.emit('CLIENT_READY');
});
break;
case 'read':
if (!!player) {
console.log(JSON.stringify(clientData[playerName], null, 4));
}
break;
case 'connect':
for (let i = 0; i < parseInt(numberOfPlayers, 10); i++) {
const pn = playerNameBase + i;
clients[pn] = io('http://he.ddns.net');
clients[pn].on('connect', () => {
clients[pn].emit('CLIENT_LOGIN', {type: 1, name: pn, token: 111, data: '567'});
clients[pn].on('SERVER_UPDATE', (data: any) => {
clientData[pn] = data;
const p = data.players[pn];
// @ts-ignore
if (p.gamePlayerState.state === '正在行动') {
setTimeout(() => {
if (Math.random() < 0.95) {
if (Math.random() < 0.5) {
if (data.gameState.highestBet === p.gamePlayerState.betValue) {
clients[pn].emit('CLIENT_ACTION', {type: 'PlayerCheck'});
} else if (p.gamePlayerState.betValue + p.gamePlayerState.chipValue > data.gameState.highestBet) {
clients[pn].emit('CLIENT_ACTION', {type: 'PlayerCall'});
} else if (Math.random() < 0.9) {
clients[pn].emit('CLIENT_ACTION', {type: 'PlayerFold'});
} else {
clients[pn].emit('CLIENT_ACTION', {type: 'PlayerAllIn'});
}
} else if (
Math.random() < 0.3
&& (p.gamePlayerState.betValue + p.gamePlayerState.chipValue > data.gameState.highestBet + 25)
&& p.gamePlayerState.chips[2] > 0) {
clients[pn].emit('CLIENT_ACTION', {type: 'PlayerRaise', payload: 25});
clients[pn].emit('CLIENT_ACTION', {type: 'PlayerRaiseConfirm'});
} else {
clients[pn].emit('CLIENT_ACTION', {type: 'PlayerFold'});
}
} else {
clients[pn].emit('CLIENT_ACTION', {type: 'PlayerAllIn'});
}
}, Math.random() * 1000 + 500);
}
});
});
}
break;
case 'exit':
process.exit();
break;
case 'send':
if (!!player && !!type) {
clients[playerName].emit('CLIENT_ACTION', {type, payload: parseInt(payload, 10)});
}
break;
case 'allin':
Object.values(clients).forEach((client) => {
client.emit('CLIENT_ACTION', {type: 'PlayerAllIn'});
});
break;
}
rl.prompt();
});
});
<file_sep># HomeEntertainment
Home Entertainment system with Node and React
<file_sep>import { Room } from './Room';
import { Socket } from 'socket.io';
import { ILoginCredential, SocketEvent } from '../network';
import { Logger } from '@overnightjs/logger';
import { Player } from './Player';
export interface IRoomMapping {
[socketId: string]: Room;
}
export class RoomManager {
private readonly rooms: IRoomMapping;
private static roomManagerInstance: RoomManager;
constructor() {
this.rooms = {};
}
public onSocketConnect(socket: Socket) {
socket.on(SocketEvent.DISCONNECT, () => this.onDisconnect(socket));
}
public onPlayerLogin(socket: Socket, creds: ILoginCredential) {
const rm = Object.values(this.rooms).find((room) => room.getRoomName() === creds.data);
const player = new Player(creds.name, socket);
Logger.Info(`[RoomManager] Player Login: ${creds.name} -> ${creds.data}`);
if (!!rm) {
player.socket.on(SocketEvent.DISCONNECT, () => rm.onPlayerLeave(player));
rm.onPlayerLogin(player);
} else {
Logger.Warn(`[RoomManager] Cannot found room for: ${creds.data}`);
socket.disconnect();
}
}
public onRoomLogin(socket: Socket, creds: ILoginCredential) {
if (Object.values(this.rooms).find((r) => (r.getRoomName() === creds.name))) {
Logger.Warn('[RoomManager] Duplicate Room Creation Requested, kicked');
socket.disconnect();
return null;
}
try {
this.rooms[socket.id] = new Room(creds.data, creds.name, socket);
} catch (e) {
Logger.Warn(`[RoomManager] Failed to create room with game: ${e}`);
socket.disconnect();
return;
}
Logger.Info(`[RoomManager] New Room Created ${creds.name} : ${creds.data}`);
}
private onDisconnect(socket: Socket) {
const room = this.rooms[socket.id];
if (!!room) {
Logger.Info(`[RoomManger] Room socket disconnected, room closed`);
room.onRoomClose();
delete this.rooms[socket.id];
return;
}
Logger.Info(`[RoomManager] SocketIO Client Disconnected: ${socket.id}`);
}
public findRoomByPlayerId(playerId: string): Room | undefined {
return Object.values(this.rooms).find((room) => playerId in room.getPlayers());
}
public static getInstance(): RoomManager {
if (!RoomManager.roomManagerInstance) {
RoomManager.roomManagerInstance = new RoomManager();
}
return RoomManager.roomManagerInstance;
}
}
<file_sep>import { RoomManager } from '../../../core/RoomManager';
import { TexasHoldem, STAGE_START, SMALL_BLIND_BET, STAGE_OVER } from '../index';
import { Logger } from '@overnightjs/logger';
import { StageSystem, IStage } from '../../../components/StageSystem';
import { Player } from '../../../core/Player';
import { IInputAction } from '../../../network';
const ROUND_END = '本局结束,没有筹码的玩家被移除';
export class EndStage implements IStage {
private completeCalculation: boolean;
constructor(private game: TexasHoldem, private stageSystem: StageSystem<TexasHoldem>) {
this.completeCalculation = false;
}
public handlePlayerInput(player: Player, action: IInputAction): void {
return;
}
public stageStart(): void {
this.completeCalculation = false;
}
public stageEnd(): void {
return;
}
public tick(): void {
if (this.completeCalculation) {
const kickList = this.game.getPlayerArray().filter((p) => p.chips.getCashValue() + p.cash < SMALL_BLIND_BET * 2);
kickList.forEach((p) => {
Logger.Info(`[EndStage] Kick Player ${p.name} with no money!`);
this.game.room.getPlayers()[p.id].disconnect();
});
} else {
this.game.calculateWinner();
this.stageSystem.countDown = 10;
this.completeCalculation = true;
}
}
public getPromotion(): string {
return ROUND_END;
}
public endCountDown(): void {
if (this.game.getPlayerArray().length < 2) {
this.stageSystem.changeStage(STAGE_OVER);
} else {
this.stageSystem.changeStage(STAGE_START);
}
}
}
<file_sep>/**
* Example controller
*
* created by <NAME> Apr 14, 2019
*/
import {Request, Response, Router} from 'express';
import * as crypto from 'crypto';
import fetch from 'node-fetch';
import {readUser, saveUser} from '../store';
export class WechatController {
public router = Router();
private token: string = process.env.WECHAT_TOKEN || '';
constructor() {
this.router.get('/wechat/verify', (res, req) => this.verify(res, req));
this.router.get('/wechat/redirect', (res, req) => this.redirect(res, req));
}
private verify(req: Request, res: Response) {
if (this.checkToken(req.query.timestamp, req.query.nonce, req.query.signature)) {
res.end(req.query.echostr);
} else {
res.end('It is not from Wechat');
}
}
private redirect(req: Request, res: Response) {
const roomInformation = req.query.state || '';
const [room, gameName] = roomInformation.split('!');
if (!room || !gameName) {
res.send(req.query);
return;
}
const code = req.query.code;
if (!code) {
res.send(req.query);
return;
}
const getAccessCodeUrl = `https://api.weixin.qq.com/sns/oauth2/access_token?appid=${process.env.WECHAT_APP}&secret=${process.env.WECHAT_SECRET}&code=${code}&grant_type=authorization_code`;
fetch(getAccessCodeUrl)
.then((result) => result.json())
.then((data) => {
if (data.access_token) {
const getProfileUrl = `https://api.weixin.qq.com/sns/userinfo?access_token=${data.access_token}&openid=${data.openid}&lang=zh_CN`;
fetch(getProfileUrl)
.then((profileResult) => profileResult.json())
.then((profileData) => {
if (profileData.openid) {
let u = readUser(profileData.openid);
const cash = !!u ? u.cash : 1000;
u = {
name: profileData.nickname,
id: profileData.openid,
avatar: profileData.headimgurl,
cash,
};
saveUser(u);
res.redirect(`/controller/${room}/${gameName}?id=${u.id}`);
} else {
res.send(data);
}
}).catch((e) => {
res.send({error: e.toString(), data});
});
} else {
res.send(data);
}
}).catch((e) => {
res.send({error: e.toString(), step: 'get access token'});
});
}
private checkToken(timestamp: string, nonce: string, signature: string) {
const tmp = [this.token, timestamp, nonce].sort().join('');
const sign = crypto.createHash('sha1').update(tmp).digest('hex');
return sign === signature;
}
}
<file_sep>import { IGame } from '../core/Game';
import { Room } from '../core/Room';
import { BlackJack } from './BlackJack';
import {TexasHoldem} from './TexasHoldem';
export function gameFactory(gameType: string, room: Room): IGame {
switch (gameType) {
case 'BlackJack':
return new BlackJack(room);
case 'TexasHoldem':
return new TexasHoldem(room);
default:
throw new Error(`"${gameType}" is not a valid game type!`);
}
}
<file_sep>import { TexasHoldem, STAGE_DISTRIBUTE, SMALL_BLIND_BET } from '../index';
import { IStage, StageSystem } from '../../../components/StageSystem';
import { Player } from '../../../core/Player';
import { IInputAction } from '../../../network';
import { TexasHoldemRole } from '../TexasHoldemPlayer';
export const WAIT_START = '等待游戏开始...';
export class StartStage implements IStage {
constructor(private game: TexasHoldem, private stageSystem: StageSystem<TexasHoldem>) {
}
public handlePlayerInput(player: Player, action: IInputAction): void {
return;
}
public tick(): void {
return;
}
public stageStart(): void {
this.game.communityCards = [];
this.stageSystem.countDown = 5;
this.game.poker.reset();
const players = Object.values(this.game.players);
const lastDealerIndex = players.findIndex((p) => p.isDealer);
players.forEach((p) => p.roundReset());
// swap dealer and sb and bb
if (lastDealerIndex < 0) {
throw new Error('No Dealer existed, error!');
}
players[lastDealerIndex].role = TexasHoldemRole.NONE;
const nextDealerIndex = (lastDealerIndex + 1) % players.length;
players[nextDealerIndex].isDealer = true;
const nextSmallBlindIndex = (players.length > 2 ? nextDealerIndex + 1 : nextDealerIndex) % players.length;
const nextBigBlindIndex = (nextSmallBlindIndex + 1) % players.length;
players[nextSmallBlindIndex].setSmallBlind();
players[nextBigBlindIndex].setBigBlind();
}
public stageEnd(): void {
return;
}
public endCountDown(): void {
this.stageSystem.changeStage(STAGE_DISTRIBUTE);
}
public getPromotion(): string {
return WAIT_START;
}
}
<file_sep>#!/usr/bin/env bash
cd client && yarn build && cd ..
cd server && yarn build && cd ..
mkdir -p ./build/public ./build/build
cp -r client/build/* ./build/public/
cp -r server/build/* ./build/build/
cp server/package.json ./build/
cd build && yarn && yarn start
<file_sep>import React from 'react';
import { makeStyles } from '@material-ui/core/styles';
import Button from '@material-ui/core/Button';
import ButtonGroup from '@material-ui/core/ButtonGroup';
import ChipStack from '../../components/ChipStack';
import NameAndAvatar from "../../components/NameAndAvatar";
import {sendAction} from "../../network";
import {connect} from "react-redux";
const useStyles = makeStyles(theme => ({
container: {
display:'flex',
flex:1,
width:'100%',
flexDirection:'column',
alignItems:'center',
justifyContent:'center',
textAlign:'center',
backgroundColor: '#456e4a',
color:'white',
height:'100vh'
},
screen: {
flex:1,
width:'100%',
},
actionContainer: {
width:'100%',
height:'20vh'
},
chipStack: {
display:'flex',
width:'100%',
justifyContent: 'center',
alignItems:'center',
marginBottom:'10vh',
height:'20vh',
},
buttonGroup:{
height:'10vmax',
width: '100vw',
borderRadius: 0,
},
askButtonGroup:{
width:'50vw',
}
}));
function BlackJackController(props) {
const {remote, id} = props;
const styles = useStyles();
const addChip = (value) => {
if(gamePlayerStatus().betValue + value > 300){
alert("最高下注上限为300!");
}
sendAction({type: 'PlayerAddChip', payload: value});
};
const double = () => {
sendAction({type: 'PlayerDouble'});
};
const surrender = () => {
sendAction({type: 'PlayerSurrender'});
};
const bet = () => {
sendAction({type: 'PlayerBet'});
};
const hit = () => {
sendAction({type: 'PlayerHit'});
};
const stand = () => {
sendAction({type: 'PlayerStand'});
};
const playerStatus = () => {
return remote.players[id];
};
const gamePlayerStatus = () => {
return playerStatus().gamePlayerState;
};
const NoAction = () => {
return (<h4>当前没有可用操作</h4>);
};
const renderBet = () => {
return (
<ButtonGroup variant="contained" fullWidth color="primary" className={styles.buttonGroup}>
<Button onClick={bet}>确认</Button>
</ButtonGroup>
);
};
const renderAsk = () => {
return (
<ButtonGroup variant="contained" fullWidth color="primary" className={styles.buttonGroup}>
<Button onClick={hit}>要牌</Button>
<Button onClick={surrender} disabled={gamePlayerStatus().hand.length > 2}>投降</Button>
<Button onClick={double} disabled={gamePlayerStatus().betValue > gamePlayerStatus().chipValue || gamePlayerStatus().hand.length > 2}>双倍</Button>
<Button onClick={stand}>结束</Button>
</ButtonGroup>
);
};
const renderAction = () => {
if(remote.gameState.stage === 'BET' && gamePlayerStatus().state !== '已经下注'){
return renderBet();
}
if(remote.gameState.stage === 'ASK' && gamePlayerStatus().state === '正在要牌'){
return renderAsk();
}
return NoAction();
};
const ChipValue = [5,25,50,100];
const onStackClick = (index) => {
if(gamePlayerStatus().chips[index] > 0 && gamePlayerStatus().state === '正在下注') {
addChip(ChipValue[index]);
}
};
return (
<div className={styles.container}>
<div className={styles.screen}>
<NameAndAvatar name={playerStatus().name} avatar={playerStatus().avatar}/>
<h2>现金:{gamePlayerStatus().cash}</h2>
<h2>筹码:{gamePlayerStatus().chipValue}</h2>
<h4>{gamePlayerStatus().state}</h4>
</div>
<div className={styles.chipStack}>
<ChipStack chips={gamePlayerStatus().chips} onStackClick={onStackClick} />
</div>
<div className={styles.actionContainer}>
{renderAction()}
</div>
</div>
);
}
const mapState = (state) => ({
...state
});
export default connect(mapState)(BlackJackController);
<file_sep>export enum CardSuit {
DIAMONDS = 'DIAMONDS',
CLUBS = 'CLUBS',
HEARTS = 'HEARTS',
SPADES = 'SPADES',
}
export interface ICard {
suit: CardSuit;
value: number;
show: boolean;
}
export class Poker {
public usedCards: ICard[];
public cardPool: ICard[];
constructor(public numberOfSets: number) {
this.usedCards = [];
this.cardPool = [];
}
public reset() {
this.usedCards = [];
this.cardPool = [];
for (let set = 0; set < this.numberOfSets; set++) {
for (const suit in CardSuit) {
if (typeof suit === 'string') {
const eSuit = suit as CardSuit;
for (let value = 1; value < 14; value++) {
this.cardPool.push({suit: eSuit, value, show: true});
}
}
}
}
this.shuffle();
}
public card_left(): number {
return this.cardPool.length;
}
public randomGet(): ICard {
if (this.card_left() <= 0) {
throw new Error('[Poker] Card Stack is empty');
}
const card = this.cardPool.pop() as ICard;
this.usedCards.push(card);
return card;
}
public shuffle() {
for (let i = this.cardPool.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
const temp = this.cardPool[i];
this.cardPool[i] = this.cardPool[j];
this.cardPool[j] = temp;
}
}
public static cardToString(card: ICard): string {
let str = '';
switch (card.value) {
case 1:
str = 'A';
break;
case 10:
str = 'T';
break;
case 11:
str = 'J';
break;
case 12:
str = 'Q';
break;
case 13:
str = 'K';
break;
default:
str = card.value.toString();
break;
}
str += card.suit[0].toLowerCase();
return str;
}
}
<file_sep>import { Player } from './Player';
import { IInputAction } from '../network';
import { IRoomConfig } from './Room';
export interface IGame {
getRoomConfig(): IRoomConfig;
getGameState(): any;
onPlayerEnter(player: Player): void;
onPlayerLeave(player: Player): void;
handlePlayerInput(player: Player, action: IInputAction): void;
start(): void;
end(): void;
tick(delta: number): void;
}
<file_sep>import React from 'react';
import Typography from '@material-ui/core/Typography';
import { makeStyles } from '@material-ui/core';
import Avatar from '@material-ui/core/Avatar';
import { Textfit } from 'react-textfit';
const useStyles = makeStyles(theme => ({
container: {
display: 'flex',
justifyContent: 'center',
alignItems: 'center',
flexDirection: 'column',
},
nameContainer: {
display: 'flex',
flexDirection: 'row',
justifyContent: 'center',
alignItems: 'center',
}
}));
export default function NameAndAvatar(props) {
const styles = useStyles();
const {name, avatar, textStyle, description} = props;
const aUrl = avatar || '/avatar/default.png';
return (
<div className={styles.container}>
<div className={styles.nameContainer}>
<Avatar src={aUrl} alt={name} style={{margin: 8}}/>
<Textfit mode={'single'} forceSingleModeWidth={false}>
<Typography variant={'h5'} style={textStyle}>{name}</Typography>
</Textfit>
</div>
<Typography variant={'h6'} style={textStyle}>{description}</Typography>
</div>
);
}
<file_sep>/**
* Example controller
*
* created by <NAME> Apr 14, 2019
*/
import {Request, Response, Router} from 'express';
import {getStore, IUserInfo, readUser, saveUser} from '../store';
export class AdminController {
public router = Router();
private token: string | undefined = process.env.NODE_ENV === 'production' ? process.env.HE_PASSWORD : '<PASSWORD>';
constructor() {
this.router.get('/admin/list', (res, req) => this.list(res, req));
this.router.post('/admin/modify', (res, req) => this.modify(res, req));
}
private list(req: Request, res: Response) {
if (this.checkToken(req.headers.authorization)) {
res.header('Access-Control-Allow-Origin', '*');
res.end(JSON.stringify(getStore()));
} else {
res.status(403).send({message: 'Wrong Password', req: req.headers});
}
}
private modify(req: Request, res: Response) {
if (this.checkToken(req.headers.authorization)) {
const returnData: { [id: string]: IUserInfo } = {};
Object.keys(req.body).forEach((userId) => {
const usr = readUser(userId);
if (!!usr) {
Object.assign(usr, req.body[userId]);
saveUser(usr);
returnData[userId] = usr;
}
});
res.header('Access-Control-Allow-Origin', '*');
res.end(JSON.stringify(returnData));
} else {
res.status(403).send({message: 'Wrong Password', req: req.headers});
}
}
private checkToken(password: string | string[] | undefined): boolean {
if (typeof password !== 'string' || !this.token) {
return false;
}
return password === this.token;
}
}
<file_sep>import React, { useState } from 'react';
import { makeStyles } from '@material-ui/core/styles';
import Button from '@material-ui/core/Button';
import ButtonGroup from '@material-ui/core/ButtonGroup';
import ChipStack from '../../components/ChipStack';
import NameAndAvatar from '../../components/NameAndAvatar';
import { sendAction } from '../../network';
import { connect } from 'react-redux';
import CardStack from '../../components/CardStack';
import posed from 'react-pose';
import { tween } from 'popmotion';
const useStyles = makeStyles(theme => ({
container: {
display: 'flex',
flex: 1,
width: '100%',
flexDirection: 'column',
alignItems: 'center',
justifyContent: 'center',
textAlign: 'center',
backgroundColor: '#456e4a',
color: 'white',
height: '100vh'
},
screen: {
flex: 1,
width: '100%',
},
actionContainer: {
width: '100%',
},
chipStack: {
display: 'flex',
width: '100%',
justifyContent: 'center',
alignItems: 'center',
marginBottom: '15vh',
},
buttonGroup: {
height: '10vmax',
width: '100vw',
borderRadius: 0,
},
askButtonGroup: {
width: '50vw',
},
cardCoverContainer: {
position: 'relative',
overflow: 'hidden',
display: 'flex'
},
cardCover: {
position: 'absolute',
top: 0,
right: 0,
bottom: 0,
left: 0,
backgroundColor: '#456e4a',
zIndex: 100,
display: 'flex',
justifyContent: 'center',
alignItems: 'center',
}
}));
const CardCover = posed.div({
draggable: 'y',
dragBounds: {top: 0},
dragEnd: {
y: 0,
transition: tween
}
});
function TexasHoldemController(props) {
const {remote, id} = props;
const styles = useStyles();
const [isRaising, setIsRaising] = useState(false);
const fold = () => {
sendAction({type: 'PlayerFold'});
};
const check = () => {
sendAction({type: 'PlayerCheck'});
};
const call = () => {
sendAction({type: 'PlayerCall'});
};
const allIn = () => {
sendAction({type: 'PlayerAllIn'});
};
const raise = (value) => {
sendAction({type: 'PlayerRaise', payload: value});
};
const raiseConfirm = () => {
sendAction({type: 'PlayerRaiseConfirm'});
setIsRaising(false);
};
const playerStatus = () => {
return remote.players[id];
};
const gamePlayerStatus = () => {
return playerStatus().gamePlayerState;
};
const NoAction = () => {
return (<h4>当前没有可用操作</h4>);
};
const renderRaise = () => {
return (
<ButtonGroup variant="contained" fullWidth color="primary" className={styles.buttonGroup}>
<Button onClick={raiseConfirm}>确认</Button>
</ButtonGroup>
);
};
const renderAct = () => {
return (
<ButtonGroup variant="contained" fullWidth color="primary" className={styles.buttonGroup}>
<Button onClick={fold}>弃牌</Button>
{
gamePlayerStatus().betValue < remote.gameState.highestBet
&& gamePlayerStatus().betValue + gamePlayerStatus().chipValue >= remote.gameState.highestBet
&& <Button onClick={call}>跟注(+{remote.gameState.highestBet - gamePlayerStatus().betValue})</Button>
}
{
gamePlayerStatus().betValue + gamePlayerStatus().chipValue - remote.gameState.highestBet >= 5 &&
<Button onClick={() => {
setIsRaising(true);
}}>加注</Button>
}
<Button onClick={allIn}>全压!</Button>
{
gamePlayerStatus().betValue >= remote.gameState.highestBet && <Button onClick={check}>结束</Button>
}
</ButtonGroup>
);
};
const renderAction = () => {
if (['正在行动', '玩家加注'].includes(gamePlayerStatus().state)) {
return isRaising ? renderRaise() : renderAct();
} else {
return NoAction();
}
};
const ChipValue = [5, 25, 50, 100];
const onStackClick = (index) => {
if (gamePlayerStatus().chips[index] > 0 && isRaising) {
raise(ChipValue[index]);
}
};
const backCard = [];
gamePlayerStatus().hand.forEach((card) => {
card.show = true;
backCard.push({value: 1, suit: 'Clubs', show: false});
});
return (
<div className={styles.container}>
<div className={styles.screen}>
<NameAndAvatar name={playerStatus().name} avatar={playerStatus().avatar}/>
<h2>现金:{gamePlayerStatus().cash}</h2>
<h2>筹码:{gamePlayerStatus().chipValue}</h2>
<h4>{gamePlayerStatus().state}</h4>
<div className={styles.cardCoverContainer}>
<CardStack cards={gamePlayerStatus().hand} display={'full'}
description={gamePlayerStatus().handResult} height={'30vh'}/>
<CardCover className={styles.cardCover}>
<CardStack cards={backCard} display={'full'}
description={'下滑查看手牌'} height={'30vh'}/>
</CardCover>
</div>
</div>
<div className={styles.chipStack}>
<ChipStack chips={gamePlayerStatus().chips} onStackClick={onStackClick}/>
</div>
<div className={styles.actionContainer}>
{renderAction()}
</div>
</div>
);
}
const mapState = (state) => ({
...state
});
export default connect(mapState)(TexasHoldemController);
<file_sep>import { BlackJackPlayer } from './components/BlackJackPlayer';
import { IGame } from '../../core/Game';
import { Player } from '../../core/Player';
import { IRoomConfig, Room } from '../../core/Room';
import { ICard, Poker } from '../../components/Poker';
import { Logger } from '@overnightjs/logger';
import { StartStage } from './stages/StartStage';
import { BetStage } from './stages/BetStage';
import { DealStage } from './stages/DealStage';
import { AskStage } from './stages/AskStage';
import { EndStage } from './stages/EndStage';
import { DistributeStage } from './stages/DistributeStage';
import { StageSystem } from '../../components/StageSystem';
import { IInputAction } from '../../network';
export const STAGE_START = 'START';
export const STAGE_BET = 'BET';
export const STAGE_DISTRIBUTE = 'DISTRIBUTE';
export const STAGE_ASK = 'ASK';
export const STAGE_DEAL = 'DEAL';
export const STAGE_END = 'END';
export enum BlackJackPlayerActionType {
PlayerBet = 'PlayerBet',
PlayerStand = 'PlayerStand',
PlayerHit = 'PlayerHit',
PlayerAddChip = 'PlayerAddChip',
PlayerSurrender = 'PlayerSurrender',
PlayerDouble = 'PlayerDouble',
}
export interface IBlackJackPlayerAction {
type: BlackJackPlayerActionType;
data: any;
}
interface IBlackJackGameState {
dealHand: ICard[];
dealValue: number;
countDown: number;
promotion: string;
playerTurn: number;
cardLeft: number;
stage: string;
}
export class BlackJack implements IGame {
public dealerHand: ICard[];
public players: { [id: string]: BlackJackPlayer };
public playing: boolean;
public poker: Poker;
public playerTurn: number;
private readonly stageSystem: StageSystem<BlackJack>;
constructor(public room: Room) {
this.playing = false;
this.players = {};
this.poker = new Poker(6);
this.dealerHand = [];
this.playerTurn = 0;
this.stageSystem = new StageSystem<BlackJack>(
this,
() => this.room.broadcastFullUpdate(),
() => this.room.broadcastFullUpdate(),
);
this.stageSystem.stages = {
[STAGE_START]: new StartStage(this, this.stageSystem),
[STAGE_BET]: new BetStage(this, this.stageSystem),
[STAGE_DISTRIBUTE]: new DistributeStage(this, this.stageSystem),
[STAGE_ASK]: new AskStage(this, this.stageSystem),
[STAGE_DEAL]: new DealStage(this, this.stageSystem),
[STAGE_END]: new EndStage(this, this.stageSystem),
};
this.stageSystem.currentStage = STAGE_START;
}
private static isValidAction(action: any): boolean {
if (typeof action.type === 'string') {
if (action.type in BlackJackPlayerActionType) {
if (action.type === BlackJackPlayerActionType.PlayerAddChip) {
return typeof action.payload === 'number';
} else {
return true;
}
}
}
Logger.Warn(`[Black Jack] Receive invalid input action: ${action.type} ${action.payload}`);
return false;
}
public getRoomConfig(): IRoomConfig {
return {
tickFrequency: 1000,
numberOfPlayerAllow: 5,
gameName: 'BlackJack',
shareGamePlayerState: false,
numberOfPlayerRequired: 1,
};
}
public static handValue(cards: ICard[], withHidden: boolean = false): number {
let valueWithoutAce = 0;
let numberOfAce = 0;
cards.forEach((card) => {
if (!card.show && !withHidden) {
return;
}
if (card.value === 1) {
numberOfAce++;
} else {
valueWithoutAce += card.value > 10 ? 10 : card.value;
}
});
if (numberOfAce === 0) {
return valueWithoutAce;
}
const possibleValueWithAce = [];
for (let i = 0; i <= numberOfAce; i++) {
const valueAs1 = i;
const valueAs11 = (numberOfAce - i) * 11;
possibleValueWithAce.push(valueWithoutAce + valueAs11 + valueAs1);
}
possibleValueWithAce.sort((a, b) => a - b);
const smallestPossibleValue = possibleValueWithAce[0];
while (possibleValueWithAce.length > 0) {
const finalValue = possibleValueWithAce.pop() || 0;
if (finalValue <= 21) {
return finalValue;
}
}
return smallestPossibleValue;
}
public onPlayerEnter(player: Player): void {
const gamePlayer = new BlackJackPlayer(player.id, player.name, player.cash);
this.players[player.id] = gamePlayer;
player.gamePlayer = gamePlayer;
}
public onPlayerLeave(player: Player): void {
if (this.stageSystem.currentStage === STAGE_ASK) {
const askStage = this.stageSystem.getCurrentStage() as AskStage;
if (!!askStage && askStage.getCurrentTurn() === player.id) {
askStage.nextBetPlayer();
}
}
player.cash = this.players[player.id].cash + this.players[player.id].chips.getCashValue();
player.saveUser();
delete this.players[player.id];
}
private getPromote(): string {
return this.stageSystem.getPromotion();
}
public getGameState(): IBlackJackGameState {
return {
dealHand: this.dealerHand,
dealValue: BlackJack.handValue(this.dealerHand),
countDown: this.stageSystem.countDown,
stage: this.stageSystem.currentStage,
playerTurn: this.playerTurn,
promotion: this.getPromote(),
cardLeft: this.poker.card_left(),
};
}
public handlePlayerInput(player: Player, action: IInputAction): void {
if (!!BlackJack.isValidAction(action)) {
Logger.Info(`[BlackJack] Player Input Received ${player.name}: ${action.type} ${action.payload}`);
this.stageSystem.handlePlayerInput(player, action);
}
}
public end(): void {
this.stageSystem.endStage();
Logger.Info(`[BlackJack] Game End!`);
}
public isPlaying(): boolean {
return this.playing;
}
public tick(delta: number): void {
this.stageSystem.tick();
}
public start(): void {
Logger.Info(`[BlackJack] Game Start!`);
this.playing = true;
this.stageSystem.currentStage = STAGE_START;
this.stageSystem.startStage();
}
}
<file_sep>export enum SocketEvent {
SERVER_FULL_STATE_UPDATE = 'SERVER_UPDATE',
SERVER_ACTION = 'SERVER_ACTION',
CLIENT_ACTION = 'CLIENT_ACTION',
CLIENT_LOGIN = 'CLIENT_LOGIN',
CLIENT_READY = 'CLIENT_READY',
DISCONNECT = 'disconnect',
CONNECT = 'connect',
NOTIFICATION = 'NOTIFICATION',
}
export enum ConnectType {
SCREEN,
CONTROLLER,
}
export enum NotificationType {
SUCCESS,
INFO,
WARNING,
ERROR,
}
export interface INotification {
type: NotificationType;
message: string;
}
export interface ILoginCredential {
name: string;
token: string;
type: ConnectType;
data: string;
}
export interface IInputAction {
type: string;
payload: any;
}
<file_sep>import React from 'react';
import Modal from '@material-ui/core/Modal';
import { ServerAddress, WechatRedirectUrl } from '../network';
import { makeStyles } from '@material-ui/core/styles';
import Typography from '@material-ui/core/Typography';
import QRCode from 'qrcode.react';
import ListItemIcon from '@material-ui/core/ListItemIcon';
import ListItem from '@material-ui/core/ListItem';
import List from '@material-ui/core/List';
import ListItemText from '@material-ui/core/ListItemText';
import DoneIcon from '@material-ui/icons/Done';
import ErrorIcon from '@material-ui/icons/Error';
import CircularProgress from '@material-ui/core/CircularProgress';
import CloseIcon from '@material-ui/icons/Close';
import IconButton from '@material-ui/core/IconButton';
import ListItemAvatar from '@material-ui/core/ListItemAvatar';
import Avatar from '@material-ui/core/Avatar';
function getModalStyle() {
return {
top: `${50}%`,
left: `${50}%`,
transform: `translate(-${50}%, -${50}%)`,
justifyContent: 'center',
alignItems: 'center',
flexDirection: 'column',
display: 'flex',
};
}
const useStyles = makeStyles(theme => ({
paper: {
position: 'absolute',
width: '70vh',
backgroundColor: theme.palette.background.paper,
boxShadow: theme.shadows[5],
padding: theme.spacing(4),
outline: 'none',
},
root: {
justifyContent: 'center',
alignItems: 'center'
},
list: {
alignItems: 'center',
width: '80%'
},
button: {
position: 'absolute',
right: 0,
top: 0
},
avatar: {
width: '10vw',
height: '10vw',
margin: 10,
}
}));
function generateList(players) {
return Object.values(players).map((p) => (
<ListItem key={p.name}>
<ListItemAvatar>
<Avatar src={p.avatar} alt={p.name}/>
</ListItemAvatar>
<ListItemText
primary={p.name}
color='primary'
/>
<ListItemIcon>
{p.ready ? <DoneIcon color='primary'/> : <ErrorIcon color="error"/>}
</ListItemIcon>
</ListItem>
))
}
export default function RoomStatusModal(props) {
const {remote, back, connected, gameName, roomName} = props;
const {name, players, maxPlayerNumber, minPlayerNumber} = remote;
const classes = useStyles();
const connectionString = process.env.NODE_ENV === 'development' ? ServerAddress + '/controller/' + name + '/' + gameName : `${WechatRedirectUrl}${roomName}!${gameName}`;
const [modalStyle] = React.useState(getModalStyle);
return (
<Modal open={true}>
{connected ?
<div style={modalStyle} className={classes.paper}>
<IconButton className={classes.button} aria-label="Delete" onClick={() => back()}>
<CloseIcon style={{color: 'black'}}/>
</IconButton>
<Typography variant="h4" id="modal-title" style={{color: 'black', textAlign: 'center'}}>
{roomName}
</Typography>
<QRCode value={connectionString} size={258} includeMargin={true}/>
<span>微信扫码加入</span>
{process.env.NODE_ENV === 'development' &&
<a href={connectionString} target='_blank'>{connectionString}</a>}
<Typography variant="h5" id="modal-title" style={{color: Object.keys(players).length >= minPlayerNumber ? 'green' : 'black', textAlign: 'center'}}>
Player: {Object.keys(players).length}/[{minPlayerNumber}-{maxPlayerNumber}]
</Typography>
<List className={classes.list}>
{generateList(players)}
</List>
</div>
:
<div style={modalStyle} className={classes.paper}>
<h2 style={{display: 'flex', alignItems: 'center', justifyItems: 'center'}}><CircularProgress
style={{marginRight: '5vh'}} color="secondary"/>正在连接服务器</h2>
</div>
}
</Modal>
);
}
<file_sep>import React from 'react';
import { isMobile } from 'react-device-detect';
const styles = {
chip: {
height: isMobile ? '10vh' : '6vh',
}
};
export const allChipResource = () => {
const images = [];
let fileName = `/chips/chip_5.png`;
images.push(fileName);
fileName = `/chips/chip_25.png`;
images.push(fileName);
fileName = `/chips/chip_50.png`;
images.push(fileName);
fileName = `/chips/chip_100.png`;
images.push(fileName);
const audios = [];
audios.push('/sounds/chipsStack4.wav');
audios.push('/sounds/chipsStack2.wav');
return {images, audios};
};
export class Chip extends React.PureComponent {
componentDidMount() {
const audio = new Audio('/sounds/chipsStack4.wav');
const r = audio.play();
r.catch((e) => {
console.log(e);
});
}
componentWillUnmount() {
const audio = new Audio('/sounds/chipsStack2.wav');
const r = audio.play();
}
render() {
const {value} = this.props;
return (
<div>
<img src={`/chips/chip_${value}.png`} alt={`chip_${value}.png`} style={styles.chip}/>
</div>
)
}
}
export default Chip;
<file_sep>import { BlackJack, BlackJackPlayerActionType, IBlackJackPlayerAction, STAGE_DEAL, STAGE_END } from '../index';
import { BlackJackPlayer, BUSTED } from '../components/BlackJackPlayer';
import { ICard } from '../../../components/Poker';
import { Logger } from '@overnightjs/logger';
import { IInputAction, NotificationType } from '../../../network';
import { StageSystem, IStage } from '../../../components/StageSystem';
import { Player } from '../../../core/Player';
export const PLAYER_TURN = '等待 {0} 要牌';
export const DISPATCH_CARD = '等待发牌';
export class AskStage implements IStage {
private turn: string;
constructor(private game: BlackJack, private stageSystem: StageSystem<BlackJack>) {
this.turn = '';
}
public handlePlayerInput(player: Player, action: IInputAction): void {
const playerIndex = player.id;
if (playerIndex !== this.turn) {
Logger.Warn(`[AskStage] Receive action from wrong player: ${playerIndex} ${this.turn}`);
return;
}
const gamePlayer = player.gamePlayer as BlackJackPlayer;
if (!gamePlayer) {
return;
}
switch (action.type) {
case BlackJackPlayerActionType.PlayerStand:
Logger.Info(`[AskStage] Player ${player.name} : ${playerIndex} Stand`);
this.nextBetPlayer();
break;
case BlackJackPlayerActionType.PlayerHit:
Logger.Info(`[AskStage] Player ${player.name} : ${playerIndex} Hit`);
const card: ICard = this.game.poker.randomGet();
gamePlayer.receiveCard(card, false);
Logger.Info(`[AskStage] Player ${player.name} : ${playerIndex} Receive Card ${card.suit} ${card.value}`);
if (!gamePlayer.canAsk()) {
if (gamePlayer.state === BUSTED) {
gamePlayer.lost();
}
Logger.Info(`[AskStage] Player ${player.name} ${gamePlayer.state}`);
this.nextBetPlayer();
}
break;
case BlackJackPlayerActionType.PlayerDouble:
if (gamePlayer.hand.length === 2 && gamePlayer.double()) {
Logger.Info(`[AskStage] Player ${player.name} : ${playerIndex} Double`);
const c: ICard = this.game.poker.randomGet();
gamePlayer.receiveCard(c, false);
if (gamePlayer.state === BUSTED) {
gamePlayer.lost();
}
Logger.Info(`[AskStage] Player ${player.name} : ${playerIndex} Receive Card for double ${c.suit} ${c.value}`);
this.nextBetPlayer();
} else {
if (gamePlayer.hand.length > 2) {
this.game.room.sendPlayerNotification(playerIndex, NotificationType.WARNING, '要牌后无法加倍');
Logger.Info(`[AskStage] Player ${player.name} : ${playerIndex} can not double after hit`);
} else {
this.game.room.sendPlayerNotification(playerIndex, NotificationType.WARNING, '没有足够的钱加倍!');
Logger.Info(`[AskStage] Player ${player.name} : ${playerIndex} can not double`);
}
}
break;
case BlackJackPlayerActionType.PlayerSurrender:
if (gamePlayer.hand.length === 2) {
Logger.Info(`[AskStage] Player ${player.name} : ${playerIndex} Surrender`);
gamePlayer.surrender();
this.nextBetPlayer();
} else {
this.game.room.sendPlayerNotification(playerIndex, NotificationType.WARNING, '要牌后不能投降!');
Logger.Info(`[AskStage] Player ${player.name} : ${playerIndex} can not surrender after hit`);
}
break;
default:
Logger.Warn(`Unrecognized action ${action.type}`);
break;
}
}
public stageStart(): void {
this.turn = '';
this.nextBetPlayer();
}
public stageEnd(): void {
return;
}
public tick(): void {
return;
}
public getPromotion(): string {
if (!!this.game.players[this.turn]) {
const player: BlackJackPlayer = this.game.players[this.turn];
return PLAYER_TURN.replace('{0}', player.name);
}
return DISPATCH_CARD;
}
public endCountDown(): void {
return;
}
public getCurrentTurn(): string {
return this.turn;
}
public nextBetPlayer(): void {
Logger.Info(`[AskStage] Next Bet Player`);
if (!!this.game.players[this.turn]) {
this.game.players[this.turn].offTurn();
}
const nextTurnPlayer: BlackJackPlayer | undefined = Object.values(this.game.players).find((p) => p.canAsk());
if (!!nextTurnPlayer) {
this.game.players[nextTurnPlayer.id].onTurn();
this.turn = nextTurnPlayer.id;
Logger.Info(`[AskStage] Next Bet Player : ${nextTurnPlayer.name}`);
} else {
if (Object.values(this.game.players).every((p) => p.inFinalState())) {
Logger.Info(`[AskStage]All bet player busted or black jacked!`);
this.stageSystem.changeStage(STAGE_END);
} else {
Logger.Info(`[AskStage]All bet player complete round!`);
this.stageSystem.changeStage(STAGE_DEAL);
}
}
}
}
<file_sep>import { Logger } from '@overnightjs/logger';
import { IStage, StageSystem } from '../../../components/StageSystem';
import { Player } from '../../../core/Player';
import { IInputAction } from '../../../network';
import { TexasHoldemPlayerActionType, STAGE_END, STAGE_FLIP, STAGE_SHOWDOWN, TexasHoldem } from '../index';
import { ALL_IN, BET_RAISE, TexasHoldemPlayer, WAIT_ACT, WAIT_GAME, WAIT_OTHER } from '../TexasHoldemPlayer';
export const START_BET = '等待 {0} 行动';
export class ActStage implements IStage {
public turnPlayer: TexasHoldemPlayer | null;
constructor(private game: TexasHoldem, private stageSystem: StageSystem<TexasHoldem>) {
this.turnPlayer = null;
}
public handlePlayerInput(player: Player, action: IInputAction): void {
const gamePlayer = player.gamePlayer as TexasHoldemPlayer;
if (!gamePlayer || this.turnPlayer !== gamePlayer || !gamePlayer.canAct()) {
return;
}
switch (action.type) {
case TexasHoldemPlayerActionType.PlayerFold:
Logger.Info(`[ActStage] Player ${player.name} Fold`);
gamePlayer.fold();
this.nextActPlayer();
break;
case TexasHoldemPlayerActionType.PlayerCall:
if (gamePlayer.canCall()) {
Logger.Info(`[ActStage] Player ${player.name} Call`);
gamePlayer.call();
this.nextActPlayer();
}
break;
case TexasHoldemPlayerActionType.PlayerAllIn:
if (gamePlayer.canAllIn()) {
Logger.Info(`[ActStage] Player ${player.name} All in`);
gamePlayer.allIn();
this.nextActPlayer();
}
break;
case TexasHoldemPlayerActionType.PlayerCheck:
if (gamePlayer.canCheck()) {
Logger.Info(`[ActStage] Player ${player.name} Check`);
this.nextActPlayer();
}
break;
case TexasHoldemPlayerActionType.PlayerRaise:
if (gamePlayer.canRaise()) {
Logger.Info(`[ActStage] Player ${player.name} Raise ${action.payload}`);
gamePlayer.raiseChip(action.payload);
if (gamePlayer.state === ALL_IN) {
Logger.Info(`[ActStage] Player ${player.name} Raise all chips, turn to ALL IN`);
this.nextActPlayer();
}
}
break;
case TexasHoldemPlayerActionType.PlayerRaiseConfirm:
if (gamePlayer.state === BET_RAISE) {
Logger.Info(`[ActStage] Player ${player.name} Raise Confirm`);
gamePlayer.confirmRaise();
this.nextActPlayer();
}
break;
default:
Logger.Warn(`Unrecognized action ${action.type}`);
break;
}
}
public stageStart(): void {
this.game.getPlayerArray().forEach((p) => {
if (p.canAct()) {
p.state = WAIT_ACT;
}
});
this.turnPlayer = this.game.firstActPlayer();
this.nextActPlayer();
return;
}
public stageEnd(): void {
this.turnPlayer = null;
return;
}
public tick(): void {
return;
}
public endCountDown(): void {
return;
}
public getPromotion(): string {
return START_BET.replace('{0}', this.turnPlayer ? this.turnPlayer.name : '');
}
public getCurrentTurn(): TexasHoldemPlayer | null {
return this.turnPlayer;
}
public resetToWaitAct() {
this.game.getPlayerArray().forEach((p) => {
if (p.canAct() && p.bet.getCashValue() < this.game.highestBet()) {
p.state = WAIT_ACT;
}
});
}
public nextActPlayer(): void {
this.turnPlayer && this.turnPlayer.offTurn();
this.resetToWaitAct();
if (this.game.getPlayerArray().filter((p) => p.inGame()).length === 1) {
Logger.Info(`[ActStage] Only 1 player left, end game!`);
this.stageSystem.changeStage(STAGE_END);
return;
}
const nextTurnPlayer: TexasHoldemPlayer | undefined = this.game.getPlayerArrayStartingAt(this.turnPlayer).find((p) => p.shouldAct());
if (!!nextTurnPlayer) {
nextTurnPlayer.onTurn();
this.turnPlayer = nextTurnPlayer;
Logger.Info(`[ActStage] Next Act Player : ${nextTurnPlayer.name}`);
} else {
if (this.game.getPlayerArray().filter((p) => p.canAct()).length < 2 || this.game.communityCards.length === 5) {
this.stageSystem.changeStage(STAGE_SHOWDOWN);
Logger.Info(`[ActStage] All player ALL IN or complete dispatching card, go to show down!`);
} else {
this.stageSystem.changeStage(STAGE_FLIP);
Logger.Info(`[ActStage] Have 2 more player in game, go to flip!`);
}
}
}
}
<file_sep>import { BlackJack, BlackJackPlayerActionType, IBlackJackPlayerAction, STAGE_DISTRIBUTE } from '../index';
import { Logger } from '@overnightjs/logger';
import { StageSystem, IStage } from '../../../components/StageSystem';
import { Player } from '../../../core/Player';
import { IInputAction } from '../../../network';
export const START_BET = '请下注';
export const BET_MAXIMUM = 300;
export class BetStage implements IStage {
constructor(private game: BlackJack, private stageSystem: StageSystem<BlackJack>) {
}
public handlePlayerInput(player: Player, action: IInputAction): void {
const playerIndex = player.id;
if (action.type === BlackJackPlayerActionType.PlayerAddChip) {
if (action.payload > 0 && this.game.players[playerIndex].canBet() && this.game.players[playerIndex].bet.getCashValue() + action.payload <= BET_MAXIMUM) {
this.game.players[playerIndex].addBet(action.payload);
Logger.Info(`[BetStage]Player ${this.game.players[playerIndex].name} add bet ${action.payload}`);
}
return;
}
if (action.type === BlackJackPlayerActionType.PlayerBet) {
if (this.game.players[playerIndex].bet.getCashValue() === 0) {
Logger.Info(`[BetStage]Player ${this.game.players[playerIndex].name} can not confirm bet if no chip added`);
return;
}
this.game.players[playerIndex].completeBet();
Logger.Info(`[BetStage]Player ${this.game.players[playerIndex].name} confirm bet`);
if (Object.values(this.game.players).every((p) => p.isCompleteBet() || !p.haveChip())) {
Logger.Info(`[BetStage]All player bet!`);
this.stageSystem.changeStage(STAGE_DISTRIBUTE);
}
}
}
public stageStart(): void {
Object.values(this.game.players).forEach((p) => p.startBet());
return;
}
public stageEnd(): void {
return;
}
public tick(): void {
return;
}
public endCountDown(): void {
return;
}
public getPromotion(): string {
return START_BET;
}
}
<file_sep>import { TexasHoldem, STAGE_ACT } from '../index';
import { IStage, StageSystem } from '../../../components/StageSystem';
import { Player } from '../../../core/Player';
import { IInputAction } from '../../../network';
export const DISPATCHING_COMMUNITY_CARD = '正在发公共牌';
enum FlipStep {
FLOP,
TURN,
RIVER,
}
export class FlipStage implements IStage {
private flipStep: FlipStep;
constructor(private game: TexasHoldem, private stageSystem: StageSystem<TexasHoldem>) {
this.flipStep = FlipStep.FLOP;
}
public handlePlayerInput(player: Player, action: IInputAction): void {
return;
}
public tick(): void {
let endLength = 3;
if (this.flipStep === FlipStep.TURN) {
endLength = 4;
}
if (this.flipStep === FlipStep.RIVER) {
endLength = 5;
}
if (this.game.communityCards.length < endLength) {
this.game.dispatchCardToCommunity();
} else {
this.backToActStage();
}
}
public stageStart(): void {
switch (this.game.communityCards.length) {
case 0:
this.flipStep = FlipStep.FLOP;
break;
case 3:
this.flipStep = FlipStep.TURN;
break;
case 4:
this.flipStep = FlipStep.RIVER;
break;
default:
throw new Error('Invalid flip step: can only enter this stage with community cards = 0,3,4');
}
}
public stageEnd(): void {
return;
}
public backToActStage() {
this.stageSystem.changeStage(STAGE_ACT);
}
public endCountDown(): void {
return;
}
public getPromotion(): string {
return DISPATCHING_COMMUNITY_CARD;
}
}
<file_sep>import React from 'react';
export const allPokerCardResource = () => {
const images = [];
for (let i = 1; i < 13; i++) {
for (let s of ['clubs', 'diamonds', 'spades', 'hearts']) {
const fileName = `/cards/${i}_of_${s.toLowerCase()}.svg`;
images.push(fileName)
}
}
images.push('/cards/back.svg');
images.push('/cards/black_joker.svg');
images.push('/cards/red_joker.svg');
const audios = [];
audios.push('/sounds/cardSlide1.wav');
audios.push('/sounds/cardSlide3.wav');
return {images, audios};
};
export class PokerCard extends React.PureComponent {
componentDidMount() {
const audio = new Audio('/sounds/cardSlide1.wav');
audio.play().catch((e) => console.log(e));
}
//
// componentWillReceiveProps(nextProps, nextContext) {
// if(this.props.show !== nextProps.show){
// this.setState({poseState: 'exit'});
// setTimeout(()=>{
// this.setState({poseState: 'enter'});
// },300)
// }
// }
//
componentWillUnmount() {
const audio = new Audio('/sounds/cardSlide3.wav');
audio.play().catch((e) => console.log(e));
}
render() {
const {suit, value, show, height} = this.props;
const finalHeight = height || '23vh';
const fileName = show ? `${value}_of_${suit.toLowerCase()}` : 'back';
return (
<div>
<img src={`/cards/${fileName}.svg`} alt={fileName} style={{height: finalHeight}}/>
</div>
)
}
}
export default PokerCard;
<file_sep>import React from 'react';
import { connect } from 'react-redux'
import RoomStatusModal from '../components/RoomStatusModal';
import { connectToServer, addSocketListener, disconnectServer } from '../network';
import { toggleFullScreen, setFullScreen } from '../store/actions';
import AppBar from '@material-ui/core/AppBar';
import Toolbar from '@material-ui/core/Toolbar';
import Typography from '@material-ui/core/Typography';
import Fullscreen from 'react-full-screen';
import CloseIcon from '@material-ui/icons/Close';
import IconButton from '@material-ui/core/IconButton';
import FullScreenIcon from '@material-ui/icons/Fullscreen';
import { GameList, PrecacheAssets } from '../games';
import Preload from 'react-preload';
import CircularProgress from '@material-ui/core/CircularProgress';
import posed from 'react-pose';
const soundToLoad = (game) => (
<audio preload="auto">
{
PrecacheAssets[game].audios.map((audio) => <source src={audio} key={audio}/>)
}
</audio>
);
const loadingIndicator = (
<div style={
{
display: 'flex',
height: '100vh',
alignItems: 'center',
justifyContent: 'center',
color: 'white',
}
}>
<CircularProgress style={{marginRight: '5vh'}} color="primary"/>
<h2>正在载入资源...</h2>
</div>
);
const AnimatedAppBar = posed.div({
show: {
y: 0,
zIndex: 99999,
},
hide: {
y: -50,
zIndex: 99999,
}
});
class Room extends React.Component {
constructor(props) {
super(props);
this.state = {
shouldHide: false,
};
this.lastAct = +new Date();
}
componentDidMount() {
const {game} = this.props.match.params;
const roomName = localStorage.getItem('HE-room-name');
connectToServer({type: 0, name: roomName, data: game, token: 111});
addSocketListener('disconnect', () => {
this.props.history.push('/');
});
this.tickHandler = setInterval(() => {
const thisActTime = +new Date();
if (thisActTime - this.lastAct > 3000) {
this.setState({
shouldHide: true
})
}
}, 1000);
document.onmousemove = () => {
this.lastAct = +new Date();
this.setState({
shouldHide: false
});
}
}
back = () => {
this.props.history.push('/');
};
componentWillUnmount() {
document.onmousemove = null;
disconnectServer();
}
render() {
const roomName = localStorage.getItem('HE-room-name');
const {game} = this.props.match.params;
const GameContent = GameList[game];
return (
<Fullscreen
enabled={this.props.fullScreen}
onChange={isFull => this.props.setFullScreen(isFull)}
onLeave={this.back}
>
<div className='room-container' style={{cursor: this.state.shouldHide ? 'none' : 'default'}}>
<AnimatedAppBar pose={this.state.shouldHide ? 'hide' : 'show'}>
<AppBar position="fixed" color="primary"
style={{
justifyContent: 'center',
height: this.props.fullScreen ? 25 : 50,
zIndex: 99999
}}>
<Toolbar>
<Typography variant="h6" color="inherit" style={{flex: 1}}>
{`${roomName} - ${game}`}
</Typography>
<IconButton aria-label="Full Screen" onClick={this.props.toggleFullScreen}>
<FullScreenIcon style={{color: 'white'}}/>
</IconButton>
<IconButton aria-label="Back" onClick={this.back}>
<CloseIcon style={{color: 'white'}}/>
</IconButton>
</Toolbar>
</AppBar>
</AnimatedAppBar>
<div className='room-game'>
<Preload
loadingIndicator={loadingIndicator}
images={PrecacheAssets[game].images}
>
{
this.props.remote.isStarted ?
<GameContent/>
:
<RoomStatusModal
roomName={roomName}
gameName={game}
back={this.back}
connected={this.props.connected}
remote={this.props.remote}/>
}
</Preload>
{soundToLoad(game)}
</div>
</div>
</Fullscreen>
)
}
}
const mapState = (state) => ({
...state
});
const mapDispatch = dispatch => ({
toggleFullScreen: () => dispatch(toggleFullScreen()),
setFullScreen: (v) => dispatch(setFullScreen(v)),
});
export default connect(mapState, mapDispatch)(Room);
<file_sep>/**
* Server file for Home Entertainment Server
*
* created by <NAME>
*/
import { WebServer } from './core/WebServer';
import { SocketServer } from './core/SocketServer';
import * as path from 'path';
class HomeEntertainmentServer {
public static readonly PORT: number = 8080;
private readonly io: SocketServer;
private readonly web: WebServer;
constructor(private readonly port?: number) {
this.web = new WebServer(path.join(__dirname, '..', 'public'));
this.io = new SocketServer(this.web.getServer());
}
public start(): void {
this.web.start(this.port || +HomeEntertainmentServer.PORT);
this.io.start();
}
}
export default HomeEntertainmentServer;
<file_sep>import { BlackJack, STAGE_BET } from '../index';
import { IStage, StageSystem } from '../../../components/StageSystem';
import { Player } from '../../../core/Player';
import { IInputAction } from '../../../network';
export const WAIT_START = '等待游戏开始...';
export class StartStage implements IStage {
constructor(private game: BlackJack, private stageSystem: StageSystem<BlackJack>) {
}
public handlePlayerInput(player: Player, action: IInputAction): void {
return;
}
public tick(): void {
return;
}
public stageStart(): void {
this.game.dealerHand = [];
this.stageSystem.countDown = 5;
this.game.playerTurn = 0;
Object.values(this.game.players).map((p) => p.roundReset());
if (this.game.poker.card_left() < 25) {
this.game.poker.reset();
}
}
public stageEnd(): void {
return;
}
public endCountDown(): void {
this.stageSystem.changeStage(STAGE_BET);
}
public getPromotion(): string {
return WAIT_START;
}
}
<file_sep>import { IInputAction } from '../../../network';
import { StageSystem, IStage } from '../../../components/StageSystem';
import { Player } from '../../../core/Player';
import { STAGE_END, TexasHoldem } from '../index';
import { DISPATCHING_COMMUNITY_CARD } from './FlipStage';
export const PLAYER_FLIP = '正在翻牌';
export class ShowDownStage implements IStage {
constructor(private game: TexasHoldem, private stageSystem: StageSystem<TexasHoldem>) {
}
public handlePlayerInput(player: Player, action: IInputAction): void {
return;
}
public stageStart(): void {
return;
}
public stageEnd(): void {
return;
}
public tick(): void {
if (this.game.communityCards.length < 5) {
this.game.dispatchCardToCommunity();
return;
}
const flipPlayer = this.game.getPlayerArrayStartingAt(this.game.getDealer(), 1).find((p) => p.shouldShow());
if (!!flipPlayer) {
if (flipPlayer.hand[0].show) {
flipPlayer.hand[1].show = true;
} else {
flipPlayer.hand[0].show = true;
}
} else {
this.stageSystem.changeStage(STAGE_END);
}
}
public getPromotion(): string {
return this.game.communityCards.length < 5 ? DISPATCHING_COMMUNITY_CARD : PLAYER_FLIP;
}
public endCountDown(): void {
return;
}
}
<file_sep>FROM node
RUN apt-get update && apt-get upgrade -y && npm install -g yarn
WORKDIR /build
COPY . /build
# build dependency
RUN mkdir -p /app/public /app/build
RUN cd client && yarn
RUN cd server && yarn && cp package.json /app && cd /app && yarn
# build app
RUN cd client && yarn build && cp -r ./build/* /app/public/
RUN cd server && yarn test && yarn build && cp -r ./build/* /app/build/
EXPOSE 80
WORKDIR /app
CMD npm start
<file_sep>import { Socket } from 'socket.io';
import { SocketEvent } from '../network';
import { saveUser, readUser } from '../store';
export interface IPlayerState {
name: string;
id: string;
ready: boolean;
cash: number;
avatar: string;
gamePlayerState: any;
}
export interface IGamePlayer {
getGamePlayerState(): any;
}
export class Player {
private _ready: boolean;
private _name: string;
private _avatar: string;
private _cash: number;
private _gamePlayer: IGamePlayer | null;
constructor(private _id: string, private _socket: Socket) {
const userInfo = readUser(this.id);
if (!!userInfo) {
this._name = userInfo.name;
this._avatar = userInfo.avatar;
this._cash = userInfo.cash;
} else {
this._name = _id;
this._avatar = '/avatar/default.png';
this._cash = 1000;
}
this._gamePlayer = null;
this._ready = false;
}
get gamePlayer(): IGamePlayer | null {
return this._gamePlayer;
}
set gamePlayer(value: IGamePlayer | null) {
this._gamePlayer = value;
}
get ready(): boolean {
return this._ready;
}
set ready(value: boolean) {
this._ready = value;
}
get name(): string {
return this._name;
}
set name(value: string) {
this._name = value;
}
get avatar(): string {
return this._avatar;
}
set avatar(value: string) {
this._avatar = value;
}
get cash(): number {
return this._cash;
}
set cash(value: number) {
this._cash = value;
}
get id(): string {
return this._id;
}
get socket(): SocketIO.Socket {
return this._socket;
}
public send(type: SocketEvent, data: any) {
this.socket.emit(type, data);
}
public getState(): IPlayerState {
return {
name: this.name,
id: this.id,
ready: this.ready,
avatar: this.avatar,
cash: this.cash,
gamePlayerState: this._gamePlayer && this._gamePlayer.getGamePlayerState() || {},
};
}
public disconnect() {
this.socket.disconnect();
}
public saveUser() {
saveUser({id: this.id, name: this.name, avatar: this.avatar, cash: this.cash});
}
}
<file_sep>import React from 'react';
import {makeStyles} from '@material-ui/core/styles';
import Player from './Player';
import Typography from '@material-ui/core/Typography';
import CardStack from "../../components/CardStack";
import Sound from 'react-sound';
import PromotionAndCountdown from "../../components/PromotionAndCountdown";
import PokerCard from "../../components/PokerCard";
import {connect} from "react-redux";
const useStyles = makeStyles(theme => ({
container: {
display: 'flex',
position: 'float',
flexDirection: 'column',
justifyContent: 'space-around',
alignItems: 'center',
height: '100vh',
backgroundColor: '#456e4a'
},
dealerContainer: {
paddingTop: '5vh',
height:'27vh',
justifyContent: 'center',
alignItems: 'center',
justifyItems: 'center',
width: '50%',
display: 'flex',
flexDirection: ' row',
},
boardContainer: {
flex: 1,
flexGrow: 1,
width: '100%',
},
playerContainer: {
width: '100%',
height: '55vh',
display: 'flex',
flexDirection: 'row',
justifyContent: 'space-around'
},
remainingCardsContainer: {
display:'flex',
justifyContent:'center',
alignItems:'center',
position: 'absolute',
top:'7vh',
right:'5vh',
textAlign: 'center',
color: 'white'
}
}));
function BlackJack(props) {
const {remote} = props;
const {gameState, players} = remote;
const styles = useStyles();
return (
<div className={styles.container}>
<div className={styles.remainingCardsContainer}>
<PokerCard value={1} suit={'clubs'} show={false} />
<h1 styles={{margin:10}}> X {gameState.cardLeft}</h1>
</div>
<div className={styles.dealerContainer}>
<Typography variant="h3" id="modal-title" style={{color: 'white', marginRight: '20%'}}>
{gameState.dealValue !== 0 && gameState.dealValue} {gameState.dealValue > 21 && "庄家爆牌!"} {gameState.dealValue === 21 && "庄家 Black Jack!"}
</Typography>
<CardStack cards={gameState.dealHand}/>
</div>
<div className={styles.boardContainer}>
<PromotionAndCountdown promotion={gameState.promotion} countDown={gameState.countDown}/>
</div>
<div className={styles.playerContainer}>
{
Object.values(players).map((player) => (<Player player={player} key={player.id}/>))
}
</div>
<Sound
url={'/music/card-game.mp3'}
loop
autoPlay='autoplay'
volume={40}
autoLoad
playStatus={Sound.status.PLAYING}
/>
</div>
)
}
const mapState = (state) => ({
...state
});
export default connect(mapState)(BlackJack);
<file_sep>import { ALL } from 'tslint/lib/rules/completedDocsRule';
import { ICard, Poker } from '../../components/Poker';
import { ChipStack, IChipStack } from '../../components/ChipStack';
import { IGamePlayer } from '../../core/Player';
// @ts-ignore
import * as PokerSolver from 'pokersolver';
import { PLAYER_EVEN } from '../BlackJack/components/BlackJackPlayer';
import { SMALL_BLIND_BET, TexasHoldem } from './index';
// START GAME STATE
export const WAIT_GAME = '等待开始';
// BET STATE
export const WAIT_ACT = '等待行动';
export const IN_ACT = '正在行动';
export const BET_RAISE = '玩家加注';
export const WAIT_OTHER = '等待其他玩家';
export const ALL_IN = '玩家全压';
// END STATE
export const PLAYER_WIN = '玩家获胜!';
export const PLAYER_FOLD = '玩家弃牌';
export enum TexasHoldemRole {
BIG_BLIND = 'BIG_BLIND',
SMALL_BLIND = 'SMALL_BLIND',
NONE = 'NONE',
}
export interface ITexasHoldemPlayerState {
hand: ICard[];
handResult: string;
name: string;
cash: number;
bet: IChipStack;
betValue: number;
chips: IChipStack;
chipValue: number;
state: string;
id: string;
role: TexasHoldemRole;
isDealer: boolean;
}
export class TexasHoldemPlayer implements IGamePlayer {
public hand: ICard[];
public bet: ChipStack;
public chips: ChipStack;
public state: string;
public cash: number;
public role: TexasHoldemRole;
public isDealer: boolean;
constructor(public id: string, public name: string, chipsValues: number, private game: TexasHoldem) {
this.hand = [];
// 5 25 50 100
this.bet = new ChipStack([0, 0, 0, 0], false);
this.chips = new ChipStack();
this.state = WAIT_GAME;
this.cash = this.chips.evenChip(chipsValues);
this.role = TexasHoldemRole.NONE;
this.isDealer = false;
}
public addBet(cashValue: number) {
const res = this.chips.removeChipValue(cashValue);
if (res < 0) {
return;
}
this.cash += res;
this.bet.addChipValue(cashValue);
}
// BET STAGE ACTIONS
public onTurn() {
this.state = IN_ACT;
}
public offTurn() {
if (this.state === IN_ACT) {
this.state = WAIT_OTHER;
}
}
public check() {
this.state = WAIT_OTHER;
}
public call() {
const highestBet = this.game.highestBet();
const callValue = highestBet - this.bet.getCashValue();
const remaining = this.chips.removeChipValue(callValue);
if (remaining < 0) {
return;
}
this.cash += remaining;
this.bet.removeAllChips();
const betRemain = this.bet.addChipValue(highestBet);
if (betRemain > 0) {
return;
}
this.state = this.chips.getCashValue() === 0 ? ALL_IN : WAIT_OTHER;
}
public fold() {
this.state = PLAYER_FOLD;
}
public allIn() {
this.state = ALL_IN;
this.bet.addChipValue(this.chips.getCashValue());
this.chips.removeAllChips();
}
public raiseChip(chip: number) {
const highestBet = this.game.highestBet();
if (this.chips.removeChip(chip)) {
this.bet.addChip(chip);
} else {
return;
}
const valueRemainingToCall = highestBet - this.bet.getCashValue();
if (valueRemainingToCall > 0) {
this.cash += this.chips.removeChipValue(valueRemainingToCall);
this.bet.addChipValue(valueRemainingToCall);
}
this.state = this.chips.getCashValue() === 0 ? ALL_IN : BET_RAISE;
}
public confirmRaise() {
this.state = WAIT_OTHER;
}
public win(chipValue: number) {
this.state = PLAYER_WIN;
this.cash += this.chips.addChipValue(chipValue);
}
public setSmallBlind() {
this.role = TexasHoldemRole.SMALL_BLIND;
this.addBet(SMALL_BLIND_BET);
}
public setBigBlind() {
this.role = TexasHoldemRole.BIG_BLIND;
this.addBet(SMALL_BLIND_BET * 2);
}
public giveBackUncalledBet() {
this.cash += this.chips.addChipValue(this.bet.getCashValue());
this.bet.removeAllChips();
}
// OTHER ACTIONS
public roundReset() {
this.hand = [];
this.bet.removeAllChips();
this.state = WAIT_GAME;
this.cash = this.chips.evenChip(this.cash);
this.isDealer = false;
this.role = TexasHoldemRole.NONE;
}
public getGamePlayerState(): ITexasHoldemPlayerState {
return {
id: this.id,
hand: this.hand,
name: this.name,
cash: this.cash,
chips: this.chips.getStack(),
chipValue: this.chips.getCashValue(),
bet: this.bet.getStack(),
betValue: this.bet.getCashValue(),
state: this.state,
handResult: this.hand.length === 2 && this.getHandResult().name,
role: this.role,
isDealer: this.isDealer,
};
}
public getHandResult(): PokerSolver.Hand {
const cards = this.game.communityCards.map((card) => Poker.cardToString(card));
this.hand.forEach((card) => cards.push(Poker.cardToString(card)));
return PokerSolver.Hand.solve(cards);
}
// state condition
public canRaise(): boolean {
return (this.chips.getCashValue() + this.bet.getCashValue() - this.game.highestBet()) > SMALL_BLIND_BET;
}
public canCall(): boolean {
return (this.chips.getCashValue() + this.bet.getCashValue()) >= this.game.highestBet();
}
public canAllIn(): boolean {
return true; // player always can ALL IN
}
public canCheck(): boolean {
return this.bet.getCashValue() === this.game.highestBet();
}
public shouldAct(): boolean {
return this.state === WAIT_ACT;
}
public canAct(): boolean {
return ![ALL_IN, PLAYER_FOLD].includes(this.state);
}
public shouldShow(): boolean {
return this.state !== PLAYER_FOLD && this.hand.length === 2 && this.hand.some((card) => !card.show);
}
public inGame(): boolean {
return [WAIT_ACT, WAIT_OTHER, ALL_IN].includes(this.state);
}
}
<file_sep>import { ICard } from '../../../components/Poker';
import { BlackJack } from '../index';
import { ChipStack, IChipStack, CHIP_VALUES } from '../../../components/ChipStack';
import { Logger } from '@overnightjs/logger';
import { IGamePlayer } from '../../../core/Player';
// START GAME STATE
export const WAIT_BET = '等待下注';
// BET STATE
export const BET_TURN = '正在下注';
export const NOT_ENOUGH_MONEY = '筹码不足';
export const ALREADY_BET = '已经下注';
// ASK STATE : begin
export const WAIT_ASK = '等待要牌';
export const ASK_TURN = '正在要牌';
export const PLAYER_DOUBLE = '双倍下注';
export const WAIT_OTHER = '等待其他玩家';
export const BUSTED = '爆牌';
export const BLACK_JACK = '21点!';
export const INITIAL_BLACK_JACK = '21点!';
// END STATE
export const PLAYER_WIN = '玩家获胜!';
export const PLAYER_SURRENDER = '玩家投降';
export const PLAYER_LOST = '庄家获胜';
export const PLAYER_EVEN = '平局';
export const PLAYER_QUIT = '玩家退出';
export interface IBlackJackPlayerState {
hand: ICard[];
name: string;
handValue: number;
cash: number;
bet: IChipStack;
betValue: number;
chips: IChipStack;
chipValue: number;
state: string;
id: string;
}
export class BlackJackPlayer implements IGamePlayer {
public hand: ICard[];
public bet: ChipStack;
public chips: ChipStack;
public state: string;
public cash: number;
constructor(public id: string, public name: string, chipsValues: number) {
this.hand = [];
// 5 25 50 100
this.bet = new ChipStack([0, 0, 0, 0], false);
this.chips = new ChipStack();
this.state = WAIT_BET;
this.cash = this.chips.evenChip(chipsValues);
}
// DISTRIBUTE STAGE ACTION
public startDistribute() {
this.state = this.inRound() ? WAIT_ASK : WAIT_OTHER;
}
// ASK STAGE ACTIONS
public onTurn() {
this.state = ASK_TURN;
}
public offTurn() {
if (this.state === ASK_TURN) {
this.state = WAIT_OTHER;
}
}
public double(): boolean {
if (this.chips.getCashValue() >= this.bet.getCashValue()) {
const betValue = this.bet.getCashValue();
const remaining = this.chips.removeChipValue(betValue);
if (remaining < 0) {
return false;
} else {
this.bet.addChipValue(betValue);
this.cash += remaining;
this.state = PLAYER_DOUBLE;
return true;
}
} else {
return false;
}
}
public receiveCard(card: ICard, isInitial: boolean = false) {
if (!this.canReceiveCard()) {
return;
}
this.hand.push(card);
const handValue = BlackJack.handValue(this.hand);
if (handValue === 21) {
this.state = isInitial ? INITIAL_BLACK_JACK : BLACK_JACK;
} else if (handValue > 21) {
this.state = BUSTED;
}
}
// END STAGE ACTIONS
public win(rate: number = 1) {
if (this.inRound() && !this.inFinalState()) {
const betValue = this.bet.getCashValue();
this.bet.removeAllChips();
this.cash += this.chips.evenChip(betValue * rate + betValue);
this.state = PLAYER_WIN;
}
}
public surrender() {
if (this.inRound() && !this.inFinalState()) {
const betValue = this.bet.getCashValue();
this.cash += this.chips.addChipValue(betValue / 2);
this.bet.removeAllChips();
this.state = PLAYER_SURRENDER;
}
}
public even() {
if (this.inRound() && !this.inFinalState()) {
this.cash += this.chips.addChipValue(this.bet.getCashValue());
this.bet.removeAllChips();
this.state = PLAYER_EVEN;
}
}
public lost() {
if (this.inRound() && !this.inFinalState()) {
this.bet.removeAllChips();
this.cash += this.chips.evenChip();
this.state = PLAYER_LOST;
}
}
// BET STAGE ACTION
public addBet(bet: number) {
if (this.state !== BET_TURN) {
return;
}
if (!CHIP_VALUES.includes(bet)) {
Logger.Warn(`Player add invalid bet ${bet}`);
return;
}
if (this.chips.removeChip(bet)) {
this.bet.addChip(bet);
return;
} else {
Logger.Warn(`Player dont have enough chips to bet`);
this.state = NOT_ENOUGH_MONEY;
}
}
public startBet() {
this.state = BET_TURN;
}
public completeBet() {
this.state = ALREADY_BET;
}
// OTHER ACTIONS
public roundReset() {
this.hand = [];
this.bet.removeAllChips();
this.state = WAIT_BET;
this.cash = this.chips.evenChip(this.cash);
}
public canBet(): boolean {
return [BET_TURN, NOT_ENOUGH_MONEY].includes(this.state);
}
public inFinalState(): boolean {
return [PLAYER_WIN, PLAYER_LOST, PLAYER_EVEN, PLAYER_SURRENDER].includes(this.state) || !this.inRound();
}
public inRound(): boolean {
return this.bet.getCashValue() > 0;
}
public isCompleteBet(): boolean {
return [ALREADY_BET].includes(this.state);
}
public haveChip(): boolean {
return this.chips.getCashValue() > 0;
}
public canReceiveCard(): boolean {
return this.inRound();
}
public canAsk(): boolean {
return this.inRound() && [WAIT_ASK, ASK_TURN].includes(this.state);
}
public getGamePlayerState(): IBlackJackPlayerState {
return {
id: this.id,
hand: this.hand,
name: this.name,
cash: this.cash,
chips: this.chips.getStack(),
chipValue: this.chips.getCashValue(),
handValue: BlackJack.handValue(this.hand),
bet: this.bet.getStack(),
betValue: this.bet.getCashValue(),
state: this.state,
};
}
}
<file_sep>import { Player } from '../core/Player';
import { IInputAction } from '../network';
export interface IStage {
stageStart(): void;
stageEnd(): void;
tick(): void;
getPromotion(): string;
endCountDown(): void;
handlePlayerInput(player: Player, action: IInputAction): void;
}
export interface IStageMapping {
[stageName: string]: IStage;
}
export class StageSystem<T> {
private _stages: IStageMapping;
private _countDown: number;
private _currentStage: string;
constructor(
private _game: T,
private onStageStart: (stageName: string) => void,
private onStageEnd: (stageName: string) => void,
) {
this._stages = {};
this._countDown = -1;
this._currentStage = '';
}
get stages(): IStageMapping {
return this._stages;
}
set stages(value: IStageMapping) {
this._stages = value;
}
get countDown(): number {
return this._countDown;
}
set countDown(value: number) {
this._countDown = value;
}
get currentStage(): string {
return this._currentStage;
}
set currentStage(value: string) {
if (value in this.stages) {
this._currentStage = value;
}
}
public changeStage(newStageName: string) {
if (newStageName in this.stages) {
this.endStage();
this.currentStage = newStageName;
this.startStage();
}
}
public startStage() {
if (this.inValidStage()) {
this.getCurrentStage().stageStart();
this.onStageStart(this.currentStage);
}
}
public endStage() {
if (this.inValidStage()) {
this.getCurrentStage().stageEnd();
this.countDown = -1;
this.onStageEnd(this.currentStage);
}
}
public getCurrentStage(): IStage {
return this.stages[this.currentStage];
}
public tick() {
if (this.inValidStage()) {
this.getCurrentStage().tick();
if (this.countDown > 0) {
this.countDown -= 1;
} else if (this.countDown === 0) {
this.countDown = -1;
this.getCurrentStage().endCountDown();
}
}
}
public getPromotion(): string {
if (this.inValidStage()) {
return this.getCurrentStage().getPromotion();
} else {
return '';
}
}
public inValidStage(): boolean {
return this.currentStage in this.stages;
}
public handlePlayerInput(player: Player, action: IInputAction) {
this.getCurrentStage().handlePlayerInput(player, action);
}
}
<file_sep>import {
BlackJack,
STAGE_ASK,
STAGE_END,
} from '../index';
import { INITIAL_BLACK_JACK } from '../components/BlackJackPlayer';
import { ICard } from '../../../components/Poker';
import { Logger } from '@overnightjs/logger';
import { StageSystem, IStage } from '../../../components/StageSystem';
import { Player } from '../../../core/Player';
import { IInputAction } from '../../../network';
export const DISPATCH_CARD = '正在发牌';
export class DistributeStage implements IStage {
constructor(private game: BlackJack, private stageSystem: StageSystem<BlackJack>) {
}
public handlePlayerInput(player: Player, action: IInputAction): void {
return;
}
public stageStart(): void {
Object.values(this.game.players).forEach((p) => p.startDistribute());
}
public stageEnd(): void {
return;
}
public tick(): void {
const turn = this.game.dealerHand.length;
if (turn === 2) {
if (Object.values(this.game.players).every((p) => p.inFinalState())) {
Logger.Info(`[DistributeStage]All bet player win!`);
this.stageSystem.changeStage(STAGE_END);
} else {
Logger.Info(`[DistributeStage]All bet player complete round!`);
this.stageSystem.changeStage(STAGE_ASK);
}
return;
}
const player = Object.values(this.game.players).find((p) => p.hand.length === turn && p.inRound());
if (!!player) {
const card: ICard = this.game.poker.randomGet();
player.receiveCard(card, true);
Logger.Info(`[DistributeStage]Player receive card : ${player.name} ${card.suit} ${card.value}`);
} else {
const card: ICard = this.game.poker.randomGet();
this.game.dealerHand.push(card);
Logger.Info(`[DistributeStage] Dealer receive card : ${card.suit} ${card.value}`);
if (this.game.dealerHand.length === 2) {
card.show = false;
if (BlackJack.handValue(this.game.dealerHand, true) === 21) {
this.game.dealerHand.forEach((c: ICard) => c.show = true);
this.stageSystem.changeStage(STAGE_END);
} else {
Object.values(this.game.players).forEach((p) => {
if (p.state === INITIAL_BLACK_JACK) {
p.win(1.5);
Logger.Info(`[DistributeStage] Player Initial BlackJack!!! : ${p.name}`);
}
});
}
}
}
}
public getPromotion(): string {
return DISPATCH_CARD;
}
public endCountDown(): void {
return;
}
}
<file_sep>import { ICard, Poker } from '../components/Poker';
import { IPlayerState, Player } from './Player';
import { IGame } from './Game';
import { IInputAction, NotificationType, SocketEvent } from '../network';
import { Socket } from 'socket.io';
import { gameFactory } from '../games';
import { Logger } from '@overnightjs/logger';
import Timeout = NodeJS.Timeout;
import * as _ from 'lodash';
export interface IRoomConfig {
tickFrequency: number;
numberOfPlayerAllow: number;
gameName: string;
shareGamePlayerState: boolean;
numberOfPlayerRequired: number;
}
export interface IFullRoomState {
name: string;
game: string;
players: IPlayerStateMapping;
gameState: any;
config: IRoomConfig;
maxPlayerNumber: number;
minPlayerNumber: number;
isStarted: boolean;
}
export interface IPlayerMapping {
[id: string]: Player;
}
export interface IPlayerStateMapping {
[id: string]: IPlayerState;
}
export class Room {
private readonly players: IPlayerMapping;
private game: IGame;
private prevFullState: IFullRoomState | null;
private readonly config: IRoomConfig;
private tickHandle: Timeout | null;
private lastTickTime: number;
private isStarted: boolean;
constructor(private gameType: string, private roomName: string, private socket: Socket) {
this.players = {};
this.game = gameFactory(gameType, this);
this.config = this.game.getRoomConfig();
this.prevFullState = null;
this.tickHandle = null;
this.lastTickTime = +new Date();
this.isStarted = false;
this.broadcastFullUpdate();
}
public getRoomId(): string {
return this.socket.id;
}
public getRoomName(): string {
return this.roomName;
}
public onPlayerLogin(player: Player) {
if (this.isStarted || this.config.numberOfPlayerAllow < Object.keys(this.players).length) {
Logger.Warn(`[Room] Cannot join new player as room reach maximum occupancy`);
player.disconnect();
return;
}
if (!!Object.values(this.players).find((p) => p.name === player.name)) {
Logger.Warn(`[Room] Player ${player.name} is already entered, can not rejoin!`);
player.disconnect();
return;
}
Logger.Info(`[Room]New Player Join Room ${player.name} -> ${this.roomName}`);
this.players[player.id] = player;
this.bindEvent(player);
this.game.onPlayerEnter(player);
this.broadcastFullUpdate();
}
private isAllReady(): boolean {
return Object.values(this.players).every((p) => p.ready) && Object.keys(this.players).length > 0;
}
private bindEvent(player: Player) {
player.socket.on(SocketEvent.CLIENT_ACTION, (action: IInputAction) => {
Logger.Info(`[Room]Player Action Received ${player.name} : ${action}`);
this.game.handlePlayerInput(player, action);
this.broadcastFullUpdate();
});
player.socket.on(SocketEvent.CLIENT_READY, () => {
player.ready = true;
Logger.Info(`[Room]Player Ready ${player.name}`);
if (this.isAllReady() && Object.keys(this.players).length >= this.config.numberOfPlayerRequired && !this.isStarted) {
this.startGame();
}
this.broadcastFullUpdate();
});
}
public onRoomClose() {
this.endGame();
Object.values(this.players).forEach((p) => p.disconnect());
}
public startGame() {
this.game.start();
if (!!this.tickHandle) {
clearInterval(this.tickHandle);
}
this.isStarted = true;
this.tickHandle = setInterval(() => this.tick(), this.config.tickFrequency);
this.broadcastFullUpdate();
}
public tick() {
const thisTickTime = +new Date();
this.lastTickTime = thisTickTime;
this.game.tick(thisTickTime - this.lastTickTime);
this.broadcastFullUpdate();
}
public endGame() {
if (!!this.tickHandle) {
clearInterval(this.tickHandle);
}
this.game.end();
this.broadcastFullUpdate();
}
public onPlayerLeave(player: Player) {
if (player.id in this.players) {
Logger.Info(`[Room]Player Leave ${player.name}`);
this.game.onPlayerLeave(player);
delete this.players[player.id];
if (Object.keys(this.players).length === 0 && this.isStarted) {
this.socket.disconnect();
Logger.Info(`[Room]All player Leave, kick room socket!`);
return;
}
this.broadcastFullUpdate();
} else {
Logger.Warn(`[Room] Player Leave : User ${player.getState()} is not belongs to ${this.getRoomName()}`);
}
}
public getPlayerStates(): IPlayerStateMapping {
const res: IPlayerStateMapping = {};
Object.values(this.players).forEach((p) => {
res[p.id] = p.getState();
});
return res;
}
public getFullRoomState(): IFullRoomState {
return {
name: this.roomName,
game: this.config.gameName,
players: this.getPlayerStates(),
gameState: this.game.getGameState(),
maxPlayerNumber: this.config.numberOfPlayerAllow,
minPlayerNumber: this.config.numberOfPlayerRequired,
isStarted: this.isStarted,
config: this.config,
};
}
public getPlayerRoomState(playerId: string): IFullRoomState {
const state = this.getFullRoomState();
if (!this.config.shareGamePlayerState) {
Object.values(state.players).forEach((player) => {
if (player.id !== playerId) {
player.gamePlayerState = {};
}
});
}
return state;
}
public broadcastFullUpdate() {
const state = this.getFullRoomState();
if (_.isEqual(this.prevFullState, state)) {
return;
}
this.socket.emit(SocketEvent.SERVER_FULL_STATE_UPDATE, state);
Object.values(this.players).forEach((player) => {
const playerState = this.getPlayerRoomState(player.id);
player.send(SocketEvent.SERVER_FULL_STATE_UPDATE, playerState);
});
// clone state in case prevFullState was modified during game tick
this.prevFullState = _.cloneDeep(state);
}
public sendScreenAction(action: IInputAction) {
this.socket.emit(SocketEvent.SERVER_ACTION, action);
}
public sendScreenNotification(type: NotificationType, message: string) {
this.socket.emit(SocketEvent.NOTIFICATION, {type, message});
}
public sendPlayerNotification(playerId: string, type: NotificationType, message: string) {
if (!!this.players[playerId]) {
this.players[playerId].socket.emit(SocketEvent.NOTIFICATION, {type, message});
}
}
public getPlayers(): IPlayerMapping {
return this.players;
}
}
<file_sep>import 'mocha';
import {expect} from 'chai';
describe('Room', () => {
it('should create room', () => {
expect(1).to.eql(1);
});
});
<file_sep>const store: { [id: string]: any } = {};
export interface IUserInfo {
id: string;
name: string;
avatar: string;
cash: number;
}
export function save(id: string, data: any) {
store[id] = data;
}
export function read(id: string): any {
if (id in store) {
return store[id];
}
return null;
}
export function saveUser(user: IUserInfo) {
save(user.id, user);
}
export function readUser(id: string): IUserInfo | null {
return read(id);
}
export function getStore(){
return store;
}
<file_sep>import { BlackJack, STAGE_START } from '../index';
import { Logger } from '@overnightjs/logger';
import { ICard } from '../../../components/Poker';
import { StageSystem, IStage } from '../../../components/StageSystem';
import { Player } from '../../../core/Player';
import { IInputAction } from '../../../network';
const ROUND_END = '本局结束';
export class EndStage implements IStage {
private completeCalculation: boolean;
constructor(private game: BlackJack, private stageSystem: StageSystem<BlackJack>) {
this.completeCalculation = false;
}
public handlePlayerInput(player: Player, action: IInputAction): void {
return;
}
public stageStart(): void {
this.completeCalculation = false;
}
public stageEnd(): void {
return;
}
public tick(): void {
if (this.completeCalculation) {
return;
}
this.game.dealerHand.forEach((c: ICard) => c.show = true);
const dealerValue = BlackJack.handValue(this.game.dealerHand);
const player = Object.values(this.game.players).find((p) => !p.inFinalState());
if (!!player) {
const playerPosition = {bet: player.bet, handValue: BlackJack.handValue(player.hand)};
Logger.Info(`[EndStage] Player ${player.name} : ${playerPosition.handValue} vs dealer ${dealerValue}`);
if (dealerValue > 21) {
player.win();
return;
}
if (dealerValue < playerPosition.handValue) {
player.win();
return;
} else if (playerPosition.handValue === dealerValue) {
player.even();
} else {
player.lost();
}
} else {
this.stageSystem.countDown = 5;
this.completeCalculation = true;
Logger.Info(`[EndStage] Calculation Done!`);
}
}
public getPromotion(): string {
return ROUND_END;
}
public endCountDown(): void {
this.stageSystem.changeStage(STAGE_START);
}
}
<file_sep>import * as express from 'express';
import { Server } from 'http';
import * as bodyParser from 'body-parser';
import { WechatController } from '../controllers';
import { AdminController } from '../controllers/AdminController';
import { Logger } from '@overnightjs/logger';
export class WebServer {
private readonly app: express.Application;
private readonly server: Server;
constructor(staticPath: string) {
this.app = express();
this.server = require('http').Server(this.app);
const cors = require('cors');
this.app.options('*', cors({allowedHeaders: ['authorization', 'Content-Type']}));
this.app.use(bodyParser.json());
this.app.use(express.static(staticPath));
const wechat = new WechatController();
this.app.use('/', wechat.router);
const admin = new AdminController();
this.app.use('/', admin.router);
this.app.get('*', (req, res) => {
res.sendFile(`${staticPath}/index.html`);
});
}
public start(port: number) {
this.server.listen(port, () => {
Logger.Info(`Running server on port ${port}`);
});
}
public getServer(): Server {
return this.server;
}
}
<file_sep>import React from 'react';
import { makeStyles } from '@material-ui/core/styles';
import Player from './Player';
import Typography from '@material-ui/core/Typography';
import CardStack from '../../components/CardStack';
import Sound from 'react-sound';
import PromotionAndCountdown from '../../components/PromotionAndCountdown';
import PokerCard from '../../components/PokerCard';
import { connect } from 'react-redux';
const useStyles = makeStyles(theme => ({
container: {
paddingTop:'1vh',
display: 'flex',
flexDirection: 'column',
justifyContent: 'space-around',
alignItems: 'center',
height: '100vh',
backgroundColor: '#456e4a'
},
rowContainer: {
display: 'flex',
flexDirection: 'row',
flex: 1,
width: '100vw',
marginTop:'1vh',
marginBottom:'1vh',
},
middleContainer: {
flex: 2,
display:'flex',
width: '100vw',
flexDirection: 'row',
},
boardContainer: {
flex: 1,
},
playerContainer: {
width: '100%',
height: '30vh',
display: 'flex',
flexDirection: 'row',
justifyContent: 'space-around'
},
playerContainerColumn: {
flexDirection: 'column',
width:'20vw',
display: 'flex',
justifyContent: 'center',
alignItems:'center',
marginLeft:'1vw',
marginRight:'1vw',
}
}));
function TexasHoldem(props) {
const {remote} = props;
const {gameState, players} = remote;
const styles = useStyles();
const playerArray = Object.values(players);
const playerMap = {
topPlayers:[],
rightPlayers:[],
bottomPlayers:[],
leftPlayers:[],
};
// top right bottom left
let pushNumber = [0,0,0,0] ;
switch (playerArray.length) {
case 2:
pushNumber = [1,0,1,0];
break;
case 3:
pushNumber = [1,1,1,0];
break;
case 4:
pushNumber = [1,1,1,1];
break;
case 5:
pushNumber = [2,1,1,1];
break;
case 6:
pushNumber = [2,1,2,1];
break;
case 7:
pushNumber = [3,1,2,1];
break;
case 8:
pushNumber = [3,1,3,1];
break;
}
playerMap.topPlayers.push(...playerArray.splice(0,pushNumber[0]));
playerMap.rightPlayers.push(...playerArray.splice(0,pushNumber[1]));
playerMap.bottomPlayers.push(...playerArray.splice(0,pushNumber[2]));
playerMap.bottomPlayers.reverse();
playerMap.leftPlayers.push(...playerArray.splice(0,pushNumber[3]));
return (
<div className={styles.container}>
<div className={styles.rowContainer}>
<div className={styles.playerContainer} style={{alignItems:'flex-end'}}>
{
Object.values(playerMap.topPlayers).map((player) => (<Player player={player} key={player.id} reverse={true}/>))
}
</div>
</div>
<div className={[styles.middleContainer]}>
<div className={[styles.playerContainerColumn]} style={{alignItems:'flex-end'}}>
{
Object.values(playerMap.leftPlayers).map((player) => (<Player player={player} key={player.id} vertical/>))
}
</div>
<div className={styles.boardContainer}>
<PromotionAndCountdown promotion={gameState.promotion} countDown={gameState.countDown}/>
<CardStack cards={gameState.communityCards} display={'full'}/>
</div>
<div className={[styles.playerContainerColumn]} style={{alignItems:'flex-start'}}>
{
Object.values(playerMap.rightPlayers).map((player) => (<Player player={player} key={player.id} vertical/>))
}
</div>
</div>
<div className={styles.rowContainer}>
<div className={styles.playerContainer}>
{
Object.values(playerMap.bottomPlayers).map((player) => (<Player player={player} key={player.id}/>))
}
</div>
</div>
<Sound
url={'/music/card-game.mp3'}
loop
autoPlay='autoplay'
volume={40}
autoLoad
playStatus={Sound.status.PLAYING}
/>
</div>
)
}
const mapState = (state) => ({
...state
});
export default connect(mapState)(TexasHoldem);
<file_sep>export const RESET_STATE = 'RESET_STATE';
export const FULL_REMOTE_UPDATE = 'FULL_REMOTE_UPDATE';
export const SET_CONNECTED = 'SET_CONNECTED';
export const SET_FULLSCREEN = 'SET_FULLSCREEN';
export const TOGGLE_FULLSCREEN = 'TOGGLE_FULLSCREEN';
export const resetState = () => ({
type: RESET_STATE
});
export const fullRemoteUpdate = (remote) => ({
type: FULL_REMOTE_UPDATE,
remote
});
export const setConnected = (connected) => ({
type: SET_CONNECTED,
connected
});
export const setFullScreen = (fullScreen) => ({
type: SET_FULLSCREEN,
fullScreen
});
export const toggleFullScreen = () => ({
type: TOGGLE_FULLSCREEN,
});
<file_sep>import { TexasHoldem, STAGE_DISTRIBUTE, SMALL_BLIND_BET } from '../index';
import { IStage, StageSystem } from '../../../components/StageSystem';
import { Player } from '../../../core/Player';
import { IInputAction } from '../../../network';
export const GAME_OVER = '游戏结束, {0} 获胜!';
export class GameOverStage implements IStage {
constructor(private game: TexasHoldem, private stageSystem: StageSystem<TexasHoldem>) {
}
public handlePlayerInput(player: Player, action: IInputAction): void {
return;
}
public tick(): void {
return;
}
public stageStart(): void {
return;
}
public stageEnd(): void {
return;
}
public endCountDown(): void {
return;
}
public getPromotion(): string {
return GAME_OVER.replace('{0}', this.game.getPlayerArray()[0] && this.game.getPlayerArray()[0].name);
}
}
<file_sep>import React from 'react';
import Button from '@material-ui/core/Button';
import Input from '@material-ui/core/Input';
import './Controller.css';
import DoneIcon from '@material-ui/icons/Done';
import ErrorIcon from '@material-ui/icons/Error';
import { sendReady } from '../network';
import ListItemIcon from '@material-ui/core/ListItemIcon';
import ListItem from '@material-ui/core/ListItem';
import List from '@material-ui/core/List';
import ListItemText from '@material-ui/core/ListItemText';
import { ControllerList } from '../games';
import ListItemAvatar from '@material-ui/core/ListItemAvatar';
import Avatar from '@material-ui/core/Avatar';
import * as queryString from 'query-string'
import { connect } from 'react-redux';
import { connectToServer } from '../network';
class Controller extends React.Component {
playerName;
constructor(props) {
super(props);
}
generateList = (players) => {
return Object.values(players).map((p) => (
<ListItem key={p.name}>
<ListItemAvatar>
<Avatar src={p.avatar} alt={p.name}/>
</ListItemAvatar>
<ListItemText
primary={p.name}
/>
<ListItemIcon>
{p.ready ? <DoneIcon color='primary'/> : <ErrorIcon color="error"/>}
</ListItemIcon>
</ListItem>
))
};
componentDidMount() {
this.playerName = localStorage.getItem('HE-player-name') || '';
const values = queryString.parse(this.props.location.search);
if (!!values.id) {
const {room} = this.props.match.params;
this.id = values.id;
this.connect(values.id, room);
}
}
valueChange = (value) => {
this.playerName = value.target.value;
localStorage.setItem('HE-player-name', value.target.value);
};
connect = (name, room) => {
connectToServer({type: 1, name: name, data: room, token: 111});
};
onEnterClick = () => {
if (!this.playerName) {
alert('玩家名称不能为空!');
return;
}
const {room} = this.props.match.params;
this.id = this.playerName;
this.connect(this.playerName, room);
};
onReady = () => {
sendReady();
};
renderGame = () => {
const {game} = this.props.match.params;
const GameController = ControllerList[game];
return <GameController id={this.id}/>;
};
renderForm = () => {
const values = queryString.parse(this.props.location.search);
if (!!values.id) {
return (
<div className="Controller">
<div className="player-input-container">
<h1>错误</h1>
<h2>无法以微信登录模式加入游戏</h2>
</div>
<Button className="player-input-button" variant="contained" color="primary"
onClick={() => window.location.reload()}>刷新</Button>
</div>
);
} else {
const defaultName = localStorage.getItem('HE-player-name') || '';
const {room, game} = this.props.match.params;
return (
<div className="Controller">
<div className="player-input-container">
<h1>{room} : {game}</h1>
<div className='player-input'>
<h2>玩家名称</h2>
<Input
defaultValue={defaultName}
onChange={this.valueChange}
className='input'
/></div>
</div>
<Button className="player-input-button" variant="contained" color="primary"
onClick={this.onEnterClick}>开始</Button>
</div>
);
}
};
renderLogin = () => {
return (
this.props.connected ?
<div className="Controller">
<div className="player-ready-container">
<h1>准备</h1>
<List className='controller-player-list'>
{this.generateList(this.props.remote.players)}
</List>
</div>
<Button className="player-input-button" variant="contained" color="primary"
onClick={this.onReady}>就绪</Button>
</div>
:
this.renderForm()
);
};
render() {
return (
<div>
{
this.props.remote.isStarted ?
this.renderGame()
:
this.renderLogin()
}
</div>
);
}
}
const mapState = (state) => ({
...state
});
export default connect(mapState)(Controller);
<file_sep>import React from 'react';
import Typography from '@material-ui/core/Typography';
export default class PromotionAndCountdown extends React.PureComponent {
componentWillReceiveProps(nextProps, nextContext) {
if (nextProps.countDown >= 0 && nextProps.countDown !== this.props.countDown) {
const audio = new Audio('/sounds/tick.mp3');
const r = audio.play();
}
}
render() {
const {promotion, countDown} = this.props;
return (
<React.Fragment>
<Typography variant="h3" id="modal-title" style={{color: 'white', textAlign: 'center'}}>
{promotion}
</Typography>
<Typography
variant="h3"
id="modal-title"
style={{color: 'white', textAlign: 'center', margin: '2vh'}}
>
{countDown >= 0 && countDown}
</Typography>
</React.Fragment>
);
}
}
<file_sep>export type IChipStack = [number, number, number, number];
export const CHIP_REFERENCE: { [value: number]: number } = {
5: 0,
25: 1,
50: 2,
100: 3,
};
export const CHIP_VALUES = [5, 25, 50, 100];
export const MAXIMUM_NUMBER_OF_CHIPS = 10;
export class ChipStack {
constructor(private stack: IChipStack = [0, 0, 0, 0], private sortChipFromLeft: boolean = true) {
}
public getCashValue(): number {
let totalValue = 0;
this.stack.forEach((numberOfChip, index) => {
totalValue += numberOfChip * CHIP_VALUES[index];
});
return totalValue;
}
public getStack(): IChipStack {
return this.stack;
}
public getNumberOfChip(value: number) {
if (value in CHIP_REFERENCE) {
return this.stack[CHIP_REFERENCE[value]];
} else {
return -1;
}
}
public removeAllChips() {
this.stack = [0, 0, 0, 0];
}
public addChip(value: number) {
if (value in CHIP_REFERENCE) {
this.stack[CHIP_REFERENCE[value]] += 1;
return;
}
}
public removeChip(value: number): boolean {
if (value in CHIP_REFERENCE && this.stack[CHIP_REFERENCE[value]] > 0) {
this.stack[CHIP_REFERENCE[value]] -= 1;
return true;
}
return false;
}
public addChipValue(value: number): number {
return this.evenChip(value);
}
public removeChipValue(value: number): number {
if (this.getCashValue() < value) {
return -1;
}
return this.evenChip(-value);
}
public evenChip(extraCash: number = 0): number {
let remainingCashValue = this.getCashValue() + extraCash;
// Get more greater value chips as possible
if (this.sortChipFromLeft) {
for (let index = 0; index < CHIP_VALUES.length; index++) {
const numberOfChip = Math.floor(remainingCashValue / CHIP_VALUES[index]);
if (numberOfChip > MAXIMUM_NUMBER_OF_CHIPS) {
this.stack[index] = MAXIMUM_NUMBER_OF_CHIPS;
} else {
this.stack[index] = numberOfChip;
}
remainingCashValue -= CHIP_VALUES[index] * this.stack[index];
}
} else {
for (let index = CHIP_VALUES.length - 1; index >= 0; index--) {
const numberOfChip = Math.floor(remainingCashValue / CHIP_VALUES[index]);
if (numberOfChip > MAXIMUM_NUMBER_OF_CHIPS) {
this.stack[index] = MAXIMUM_NUMBER_OF_CHIPS;
} else {
this.stack[index] = numberOfChip;
}
remainingCashValue -= CHIP_VALUES[index] * this.stack[index];
}
}
return remainingCashValue;
}
}
| 3bd7d2d818d24c3e6fd184bcc6c3abdea288cf76 | [
"JavaScript",
"Markdown",
"TypeScript",
"Dockerfile",
"Shell"
] | 54 | TypeScript | huangwc94/HomeEntertainment | 19d59e4e479754614495842c64c47f0d0955041b | 682f1ab884780a36e36a3634e5e73239f1019134 |
refs/heads/master | <repo_name>vnduy01/Unify-React<file_sep>/src/components/ProductService/ProductService.js
import React, { Component } from 'react';
export default class ProductService extends Component {
render() {
return (
<div className="row margin-bottom-60">
<div className="col-md-4 product-service md-margin-bottom-30">
<div className="product-service-heading">
<i className="fa fa-truck" />
</div>
<div className="product-service-in">
<h3>Free Delivery</h3>
<p>Integer mattis lacinia felis vel molestie. Ut eu euismod erat, tincidunt pulvinar semper veliUt porta, leo...</p>
<a href="#">+Read More</a>
</div>
</div>
<div className="col-md-4 product-service md-margin-bottom-30">
<div className="product-service-heading">
<i className="icon-earphones-alt" />
</div>
<div className="product-service-in">
<h3>Customer Service</h3>
<p>Integer mattis lacinia felis vel molestie. Ut eu euismod erat, tincidunt pulvinar semper veliUt porta, leo...</p>
<a href="#">+Read More</a>
</div>
</div>
<div className="col-md-4 product-service">
<div className="product-service-heading">
<i className="icon-refresh" />
</div>
<div className="product-service-in">
<h3>Free Returns</h3>
<p>Integer mattis lacinia felis vel molestie. Ut eu euismod erat, tincidunt pulvinar semper veliUt porta, leo...</p>
<a href="#">+Read More</a>
</div>
</div>
</div>
);
}
}<file_sep>/src/components/Sponsors/Sponsors.js
import React, { Component } from 'react';
export default class Sponsors extends Component {
render() {
return (
<div className="container content">
<div className="heading heading-v1 margin-bottom-40">
<h2>Sponsors</h2>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed odio elit, ultrices vel cursus sed, placerat ut leo. Phasellus in magna erat. Etiam gravida convallis augue non tincidunt. Nunc lobortis dapibus neque quis lacinia. Nam dapibus tellus sit amet odio venenatis</p>
</div>
<ul className="list-inline owl-slider-v2">
<li className="item first-child">
<img src="assets/img/clients/07.png" alt />
</li>
<li className="item">
<img src="assets/img/clients/08.png" alt />
</li>
<li className="item">
<img src="assets/img/clients/10.png" alt />
</li>
<li className="item">
<img src="assets/img/clients/11.png" alt />
</li>
<li className="item">
<img src="assets/img/clients/09.png" alt />
</li>
<li className="item">
<img src="assets/img/clients/12.png" alt />
</li>
<li className="item">
<img src="assets/img/clients/07.png" alt />
</li>
<li className="item">
<img src="assets/img/clients/08.png" alt />
</li>
<li className="item">
<img src="assets/img/clients/09.png" alt />
</li>
<li className="item">
<img src="assets/img/clients/10.png" alt />
</li>
<li className="item">
<img src="assets/img/clients/11.png" alt />
</li>
<li className="item">
<img src="assets/img/clients/12.png" alt />
</li>
</ul>{/*/end owl-carousel*/}
</div>
);
}
}
<file_sep>/src/components/Illustrationv5/Illustrationv5.js
import React, { Component } from 'react';
export default class Illustrationv5 extends Component {
render() {
return (
<div className="row illustration-v4 margin-bottom-40">
<div className="col-md-4">
<div className="heading heading-v1 margin-bottom-20">
<h2>Top Rated</h2>
</div>
<div className="thumb-product">
<img className="thumb-product-img" src="assets/img/thumb/08.jpg" alt />
<div className="thumb-product-in">
<h4><a href="shop-ui-inner.html">Yuketen</a> – <a href="shop-ui-inner.html">Derby Shoe</a></h4>
<span className="thumb-product-type">Footwear - Oxfords</span>
</div>
<ul className="list-inline overflow-h">
<li className="thumb-product-price line-through">$75.00</li>
<li className="thumb-product-price">$65.00</li>
<li className="thumb-product-purchase"><a href="#"><i className="fa fa-shopping-cart" /></a> | <a href="#"><i className="fa fa-heart" /></a></li>
</ul>
</div>
<div className="thumb-product">
<img className="thumb-product-img" src="assets/img/thumb/09.jpg" alt />
<div className="thumb-product-in">
<h4><a href="shop-ui-inner.html">Yuketen</a> – <a href="shop-ui-inner.html">Derby Shoe</a></h4>
<span className="thumb-product-type">Footwear - Oxfords</span>
</div>
<ul className="list-inline overflow-h">
<li className="thumb-product-price">$75.00</li>
<li className="thumb-product-purchase"><a href="#"><i className="fa fa-shopping-cart" /></a> | <a href="#"><i className="fa fa-heart" /></a></li>
</ul>
</div>
<div className="thumb-product">
<img className="thumb-product-img" src="assets/img/thumb/03.jpg" alt />
<div className="thumb-product-in">
<h4><a href="shop-ui-inner.html">Yuketen</a> – <a href="shop-ui-inner.html">Derby Shoe</a></h4>
<span className="thumb-product-type">Footwear - Oxfords</span>
</div>
<ul className="list-inline overflow-h">
<li className="thumb-product-price">$75.00</li>
<li className="thumb-product-purchase"><a href="#"><i className="fa fa-shopping-cart" /></a> | <a href="#"><i className="fa fa-heart" /></a></li>
</ul>
</div>
</div>
<div className="col-md-4">
<div className="heading heading-v1 margin-bottom-20">
<h2>Best Sellers</h2>
</div>
<div className="thumb-product">
<img className="thumb-product-img" src="assets/img/thumb/02.jpg" alt />
<div className="thumb-product-in">
<h4><a href="shop-ui-inner.html">Yuketen</a> – <a href="shop-ui-inner.html">Derby Shoe</a></h4>
<span className="thumb-product-type">Footwear - Oxfords</span>
</div>
<ul className="list-inline overflow-h">
<li className="thumb-product-price">$75.00</li>
<li className="thumb-product-purchase"><a href="#"><i className="fa fa-shopping-cart" /></a> | <a href="#"><i className="fa fa-heart" /></a></li>
</ul>
</div>
<div className="thumb-product">
<img className="thumb-product-img" src="assets/img/thumb/10.jpg" alt />
<div className="thumb-product-in">
<h4><a href="shop-ui-inner.html">Yuketen</a> – <a href="shop-ui-inner.html">Derby Shoe</a></h4>
<span className="thumb-product-type">Footwear - Oxfords</span>
</div>
<ul className="list-inline overflow-h">
<li className="thumb-product-price">$75.00</li>
<li className="thumb-product-purchase"><a href="#"><i className="fa fa-shopping-cart" /></a> | <a href="#"><i className="fa fa-heart" /></a></li>
</ul>
</div>
<div className="thumb-product">
<img className="thumb-product-img" src="assets/img/thumb/06.jpg" alt />
<div className="thumb-product-in">
<h4><a href="shop-ui-inner.html">Yuketen</a> – <a href="shop-ui-inner.html">Derby Shoe</a></h4>
<span className="thumb-product-type">Footwear - Oxfords</span>
</div>
<ul className="list-inline overflow-h">
<li className="thumb-product-price line-through">$75.00</li>
<li className="thumb-product-price">$65.00</li>
<li className="thumb-product-purchase"><a href="#"><i className="fa fa-shopping-cart" /></a> | <a href="#"><i className="fa fa-heart" /></a></li>
</ul>
</div>
</div>
<div className="col-md-4 padding">
<div className="heading heading-v1 margin-bottom-20">
<h2>Sale Items</h2>
</div>
<div className="thumb-product">
<img className="thumb-product-img" src="assets/img/thumb/07.jpg" alt />
<div className="thumb-product-in">
<h4><a href="shop-ui-inner.html">Yuketen</a> – <a href="shop-ui-inner.html">Derby Shoe</a></h4>
<span className="thumb-product-type">Footwear - Oxfords</span>
</div>
<ul className="list-inline overflow-h">
<li className="thumb-product-price line-through">$75.00</li>
<li className="thumb-product-price">$65.00</li>
<li className="thumb-product-purchase"><a href="#"><i className="fa fa-shopping-cart" /></a> | <a href="#"><i className="fa fa-heart" /></a></li>
</ul>
</div>
<div className="thumb-product">
<img className="thumb-product-img" src="assets/img/thumb/04.jpg" alt />
<div className="thumb-product-in">
<h4><a href="shop-ui-inner.html">Yuketen</a> – <a href="shop-ui-inner.html">Derby Shoe</a></h4>
<span className="thumb-product-type">Footwear - Oxfords</span>
</div>
<ul className="list-inline overflow-h">
<li className="thumb-product-price">$75.00</li>
<li className="thumb-product-purchase"><a href="#"><i className="fa fa-shopping-cart" /></a> | <a href="#"><i className="fa fa-heart" /></a></li>
</ul>
</div>
<div className="thumb-product">
<img className="thumb-product-img" src="assets/img/thumb/05.jpg" alt />
<div className="thumb-product-in">
<h4><a href="shop-ui-inner.html">Yuketen</a> – <a href="shop-ui-inner.html">Derby Shoe</a></h4>
<span className="thumb-product-type">Footwear - Oxfords</span>
</div>
<ul className="list-inline overflow-h">
<li className="thumb-product-price">$75.00</li>
<li className="thumb-product-purchase"><a href="#"><i className="fa fa-shopping-cart" /></a> | <a href="#"><i className="fa fa-heart" /></a></li>
</ul>
</div>
</div>
</div>
);
}
}
<file_sep>/src/views/Home.js
import React, { Component } from 'react';
import { BrowserRouter, Route, Link } from "react-router-dom";
import Slider from '../components/Slider/Slider';
import SaleBanner from '../components/Banner/SaleBanner';
import ProductItem from '../components/Item/ProductItem';
import CategoryItem from '../components/Item/CategoryItem';
import CollectionBanner from '../components/Banner/CollectionBanner';
import TwitterBlock from '../components/TwitterBlock/TwitterBlock';
import ProductService from '../components/ProductService/ProductService';
import Illustrationv5 from '../components/Illustrationv5/Illustrationv5';
import Sponsors from '../components/Sponsors/Sponsors';
export default class Home extends Component {
render() {
const categories = [
{
name: "Men",
amount: "450"
},
{
name: "Men1",
amount: "450"
},
{
name: "Men2",
amount: "450"
},
];
const products = [
{
name: "name1",
gender: "man",
category: "cate1",
price: "300$"
},
{
name: "name2",
gender: "man",
category: "cate2",
price: "300$"
},
{
name: "name3",
gender: "man",
category: "cate3",
price: "300$"
},
{
name: "name4",
gender: "man",
category: "cate4",
price: "300$"
},
{
name: "name5",
gender: "man",
category: "cate5",
price: "300$"
},
];
return (
<BrowserRouter>
<div>
<div className="wrapper">
<Slider />
<div className="container content-md">
<SaleBanner />
<div className="heading heading-v1 ymargin-bottom-20">
<h2>Featured products</h2>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed odio elit, ultrices vel cursus sed, placerat ut leo. Phasellus in magna erat. Etiam gravida convallis augue non tincidunt. Nunc lobortis dapibus neque quis lacinia. Nam dapibus tellus sit amet odio venenatis</p>
</div>
<div className="illustration-v2 margin-bottom-60">
<div className="customNavigation margin-bottom-25">
<a className="owl-btn prev rounded-x"><i className="fa fa-angle-left" /></a>
<a className="owl-btn next rounded-x"><i className="fa fa-angle-right" /></a>
</div>
<ul className="list-inline owl-slider">
{products.map((product, index) => {
return (
<div key={index}>
<ProductItem product={product} />
</div>
)
})}
</ul>
</div>
<div className="row margin-bottom-50">
{categories.map((category, index) => {
return (
<div key={index}>
<CategoryItem category={category} />
</div>
)
})}
</div>
<div className="heading heading-v1 margin-bottom-40">
<h2>Latest products</h2>
</div>
<div className="illustration-v2 margin-bottom-60">
<div className="customNavigation margin-bottom-25">
<a className="owl-btn prev rounded-x"><i className="fa fa-angle-left" /></a>
<a className="owl-btn next rounded-x"><i className="fa fa-angle-right" /></a>
</div>
<ul className="list-inline owl-slider">
{products.map((product, index) => {
return (
<div key={index}>
<ProductItem product={product} />
</div>
)
})}
</ul>
</div>
</div>
<TwitterBlock />
<div className="container">
<ProductService />
<Illustrationv5 />
</div>
<CollectionBanner />
<Sponsors />
</div>
</div>
</BrowserRouter>
)
}
}<file_sep>/src/components/Slider/Slider.js
import React, { Component } from 'react';
export default class Slider extends Component {
render() {
return (
<div className="tp-banner-container">
<div className="tp-banner">
<ul>
{/* SLIDE */}
<li className="revolution-mch-1" data-transition="fade" data-slotamount={5} data-masterspeed={1000} data-title="Slide 1">
{/* MAIN IMAGE */}
<img src="assets/img/1.jpg" alt="darkblurbg" data-bgfit="cover" data-bgposition="left top" data-bgrepeat="no-repeat" />
<div className="tp-caption revolution-ch1 sft start" data-x="center" data-hoffset={0} data-y={100} data-speed={1500} data-start={500} data-easing="Back.easeInOut" data-endeasing="Power1.easeIn" data-endspeed={300}>
The New <br />
<strong>Collection</strong><br />
is here
</div>
{/* LAYER */}
<div className="tp-caption sft" data-x="center" data-hoffset={0} data-y={380} data-speed={1600} data-start={1800} data-easing="Power4.easeOut" data-endspeed={300} data-endeasing="Power1.easeIn" data-captionhidden="off" style={{zIndex: 6}}>
<a href="#" className="btn-u btn-brd btn-brd-hover btn-u-light">Shop Now</a>
</div>
</li>
{/* END SLIDE */}
{/* SLIDE */}
<li className="revolution-mch-1" data-transition="fade" data-slotamount={5} data-masterspeed={1000} data-title="Slide 2">
{/* MAIN IMAGE */}
<img src="assets/img/5.jpg" alt="darkblurbg" data-bgfit="cover" data-bgposition="left top" data-bgrepeat="no-repeat" />
<div className="tp-caption revolution-ch3 sft start" data-x="center" data-hoffset={0} data-y={140} data-speed={1500} data-start={500} data-easing="Back.easeInOut" data-endeasing="Power1.easeIn" data-endspeed={300}>
Latest <strong>Fashion</strong> Trends
</div>
{/* LAYER */}
<div className="tp-caption revolution-ch4 sft" data-x="center" data-hoffset={-14} data-y={210} data-speed={1400} data-start={2000} data-easing="Power4.easeOut" data-endspeed={300} data-endeasing="Power1.easeIn" data-captionhidden="off" style={{zIndex: 6}}>
Cras non dui et quam auctor pretium.<br />
Aenean enim tortr, tempus et iteus m
</div>
{/* LAYER */}
<div className="tp-caption sft" data-x="center" data-hoffset={0} data-y={300} data-speed={1600} data-start={1800} data-easing="Power4.easeOut" data-endspeed={300} data-endeasing="Power1.easeIn" data-captionhidden="off" style={{zIndex: 6}}>
<a href="#" className="btn-u btn-brd btn-brd-hover btn-u-light">Shop Now</a>
</div>
</li>
{/* END SLIDE */}
{/* SLIDE */}
<li className="revolution-mch-1" data-transition="fade" data-slotamount={5} data-masterspeed={1000} data-title="Slide 3">
{/* MAIN IMAGE */}
<img src="assets/img/3.jpg" alt="darkblurbg" data-bgfit="cover" data-bgposition="right top" data-bgrepeat="no-repeat" />
<div className="tp-caption revolution-ch3 sft start" data-x="right" data-hoffset={5} data-y={130} data-speed={1500} data-start={500} data-easing="Back.easeInOut" data-endeasing="Power1.easeIn" data-endspeed={300}>
<strong>Luxury</strong> Watches
</div>
{/* LAYER */}
<div className="tp-caption revolution-ch4 sft" data-x="right" data-hoffset={0} data-y={210} data-speed={1400} data-start={2000} data-easing="Power4.easeOut" data-endspeed={300} data-endeasing="Power1.easeIn" data-captionhidden="off" style={{zIndex: 6}}>
lectus. Cras non dui et quam auctor.<br />
Aenean enim tortor, tempus et im
</div>
{/* LAYER */}
<div className="tp-caption sft" data-x="right" data-hoffset={0} data-y={300} data-speed={1600} data-start={2800} data-easing="Power4.easeOut" data-endspeed={300} data-endeasing="Power1.easeIn" data-captionhidden="off" style={{zIndex: 6}}>
<a href="#" className="btn-u btn-brd btn-brd-hover btn-u-light">Shop Now</a>
</div>
</li>
{/* END SLIDE */}
{/* SLIDE */}
<li className="revolution-mch-1" data-transition="fade" data-slotamount={5} data-masterspeed={1000} data-title="Slide 4">
{/* MAIN IMAGE */}
<img src="assets/img/2.jpg" alt="darkblurbg" data-bgfit="cover" data-bgposition="left top" data-bgrepeat="no-repeat" />
<div className="tp-caption revolution-ch1 sft start" data-x="center" data-hoffset={0} data-y={100} data-speed={1500} data-start={500} data-easing="Back.easeInOut" data-endeasing="Power1.easeIn" data-endspeed={300}>
Girl's Accesories
</div>
{/* LAYER */}
<div className="tp-caption revolution-ch2 sft" data-x="center" data-hoffset={0} data-y={280} data-speed={1400} data-start={2000} data-easing="Power4.easeOut" data-endspeed={300} data-endeasing="Power1.easeIn" data-captionhidden="off" style={{zIndex: 6}}>
Super Promo
</div>
{/* LAYER */}
<div className="tp-caption sft" data-x="center" data-hoffset={0} data-y={370} data-speed={1600} data-start={2800} data-easing="Power4.easeOut" data-endspeed={300} data-endeasing="Power1.easeIn" data-captionhidden="off" style={{zIndex: 6}}>
<a href="#" className="btn-u btn-brd btn-brd-hover btn-u-light">View More</a>
<a href="#" className="btn-u btn-brd btn-brd-hover btn-u-light">Shop Now</a>
</div>
</li>
{/* END SLIDE */}
{/* SLIDE */}
<li className="revolution-mch-1" data-transition="fade" data-slotamount={5} data-masterspeed={1000} data-title="Slide 5">
{/* MAIN IMAGE */}
<img src="assets/img/4.jpg" alt="darkblurbg" data-bgfit="cover" data-bgposition="right top" data-bgrepeat="no-repeat" />
<div className="tp-caption revolution-ch5 sft start" data-x="right" data-hoffset={5} data-y={130} data-speed={1500} data-start={500} data-easing="Back.easeInOut" data-endeasing="Power1.easeIn" data-endspeed={300}>
<strong>Jeans</strong> Collection
</div>
{/* LAYER */}
<div className="tp-caption revolution-ch4 sft" data-x="right" data-hoffset={-14} data-y={210} data-speed={1400} data-start={2000} data-easing="Power4.easeOut" data-endspeed={300} data-endeasing="Power1.easeIn" data-captionhidden="off" style={{zIndex: 6}}>
Cras non dui et quam auctor pretium.<br />
Aenean enim tortr, tempus et iteus m
</div>
{/* LAYER */}
<div className="tp-caption sft" data-x="right" data-hoffset={0} data-y={300} data-speed={1600} data-start={2800} data-easing="Power4.easeOut" data-endspeed={300} data-endeasing="Power1.easeIn" data-captionhidden="off" style={{zIndex: 6}}>
<a href="#" className="btn-u btn-brd btn-brd-hover btn-u-light">Shop Now</a>
</div>
</li>
{/* END SLIDE */}
</ul>
<div className="tp-bannertimer tp-bottom" />
</div>
</div>
);
}
}<file_sep>/src/layouts/Header.js
import React, { Component } from 'react';
import { BrowserRouter,Route,Link } from "react-router-dom";
export default class Header extends Component {
render() {
return (
<div className="header-v5 header-static">
{/* Topbar v3 */}
{/* End Topbar v3 */}
{/* Navbar */}
<div className="navbar navbar-default mega-menu" role="navigation">
<div className="container">
{/* Brand and toggle get grouped for better mobile display */}
<div className="navbar-header">
<button type="button" className="navbar-toggle" data-toggle="collapse" data-target=".navbar-responsive-collapse">
<span className="sr-only">Toggle navigation</span>
<span className="icon-bar" />
<span className="icon-bar" />
<span className="icon-bar" />
</button>
<a href="/"className="navbar-brand" >
<img id="logo-header" src="assets/img/logo.png" alt="Logo" />
</a>
</div>
{/* Shopping Cart */}
<div className="shop-badge badge-icons pull-right">
<a href="#"><i className="fa fa-shopping-cart" /></a>
<span className="badge badge-sea rounded-x">3</span>
<div className="badge-open">
<ul className="list-unstyled mCustomScrollbar" data-mcs-theme="minimal-dark">
<li>
<img src="assets/img/thumb/05.jpg" alt />
<button type="button" className="close">×</button>
<div className="overflow-h">
<span>Black Glasses</span>
<small>1 x $400.00</small>
</div>
</li>
<li>
<img src="assets/img/thumb/02.jpg" alt />
<button type="button" className="close">×</button>
<div className="overflow-h">
<span>Black Glasses</span>
<small>1 x $400.00</small>
</div>
</li>
<li>
<img src="assets/img/thumb/03.jpg" alt />
<button type="button" className="close">×</button>
<div className="overflow-h">
<span>Black Glasses</span>
<small>1 x $400.00</small>
</div>
</li>
</ul>
<div className="subtotal">
<div className="overflow-h margin-bottom-10">
<span>Subtotal</span>
<span className="pull-right subtotal-cost">$1200.00</span>
</div>
<div className="row">
<div className="col-xs-6">
<a href="shop-ui-inner.html" className="btn-u btn-brd btn-brd-hover btn-u-sea-shop btn-block">View Cart</a>
</div>
<div className="col-xs-6">
<a href="shop-ui-add-to-cart.html" className="btn-u btn-u-sea-shop btn-block">Checkout</a>
</div>
</div>
</div>
</div>
</div>
{/* End Shopping Cart */}
{/* Collect the nav links, forms, and other content for toggling */}
<div className="collapse navbar-collapse navbar-responsive-collapse">
{/* Nav Menu */}
<ul className="nav navbar-nav">
{/* Pages */}
<li className="dropdown active">
<a href="javascript:void(0);" className="dropdown-toggle" data-hover="dropdown" data-toggle="dropdown">
Pages
</a>
<ul className="dropdown-menu">
<li className="active"><a href="index.html">Shop UI</a></li>
<li><Link to="shop-ui-inner.html">Product Details</Link></li>
<li><Link to="/products">Product List</Link></li>
<li><a href="shop-ui-add-to-cart.html">Checkout</a></li>
</ul>
</li>
{/* End Pages */}
{/* Promotion */}
<li className="dropdown">
<a href="javascript:void(0);" className="dropdown-toggle" data-hover="dropdown" data-toggle="dropdown">
Promotion
</a>
<ul className="dropdown-menu">
<li className="dropdown-submenu">
<a href="javascript:void(0);">Jeans</a>
<ul className="dropdown-menu">
<li><a href="#">Skinny Jeans</a></li>
<li><a href="#">Bootcut Jeans</a></li>
<li><a href="#">Straight Cut Jeans</a></li>
</ul>
</li>
<li className="dropdown-submenu">
<a href="javascript:void(0);">Shoes</a>
<ul className="dropdown-menu">
<li><a href="#">Sandals</a></li>
<li><a href="#">Heels</a></li>
</ul>
</li>
</ul>
</li>
{/* End Promotion */}
{/* Gifts */}
<li className="dropdown mega-menu-fullwidth">
<a href="javascript:void(0);" className="dropdown-toggle" data-hover="dropdown" data-toggle="dropdown">
Gifts
</a>
<ul className="dropdown-menu">
<li>
<div className="mega-menu-content">
<div className="container">
<div className="row">
<div className="col-md-3 col-sm-12 col-xs-12 md-margin-bottom-30">
<h3 className="mega-menu-heading">Pellentes que nec diam lectus</h3>
<p>Proin pulvinar libero quis auctor pharet ra. Aenean fermentum met us orci, sedf eugiat augue pulvina r vitae. Nulla dolor nisl, molestie nec aliquam vitae, gravida sodals dolor...</p>
<button type="button" className="btn-u btn-u-dark">Read More</button>
</div>
<div className="col-md-3 col-sm-4 col-xs-4 md-margin-bottom-30">
<a href="#"><img className="product-offers img-responsive" src="assets/img/blog/01.jpg" alt /></a>
</div>
<div className="col-md-3 col-sm-4 col-xs-4 sm-margin-bottom-30">
<a href="#"><img className="product-offers img-responsive" src="assets/img/blog/02.jpg" alt /></a>
</div>
<div className="col-md-3 col-sm-4 col-xs-4">
<a href="#"><img className="product-offers img-responsive" src="assets/img/blog/03.jpg" alt /></a>
</div>
</div>{/*/end row*/}
</div>{/*/end container*/}
</div>{/*/end mega menu content*/}
</li>
</ul>{/*/end dropdown-menu*/}
</li>
{/* End Gifts */}
{/* Clothes */}
<li className="dropdown">
<a href="javascript:void(0);" className="dropdown-toggle" data-hover="dropdown" data-toggle="dropdown" data-delay={1000}>
Clothes
</a>
<ul className="dropdown-menu">
<li><a href="#">Jeans</a></li>
<li><a href="#">T-shirts</a></li>
<li><a href="#">Shorts</a></li>
</ul>
</li>
{/* End Clothes */}
{/* Main Demo */}
{/* Main Demo */}
</ul>
{/* End Nav Menu */}
</div>
</div>
</div>
{/* End Navbar */}
</div>
);
}
}<file_sep>/src/views/ProductDetails.js
import React, {Component} from 'react';
import Panel from '../components/Panel/Panel'
export default class ProductDetails extends Component {
render() {
return(
<div>
<Panel/>
</div>
)
}
}
<file_sep>/src/components/Item/ProductItem.js
import React, { Component } from 'react';
import propTypes from 'prop-types';
export default class ProductItem extends Component {
render() {
const {product} = this.props;
return (
<li className="item">
<div className="product-img">
<a href="shop-ui-inner.html"><img className="full-width img-responsive" src="assets/img/blog/09.jpg" alt /></a>
<a className="product-review" href="shop-ui-inner.html">Quick review</a>
<a className="add-to-cart" href="#"><i className="fa fa-shopping-cart" />Add to cart</a>
</div>
<div className="product-description product-description-brd">
<div className="overflow-h margin-bottom-5">
<div className="pull-left">
<h4 className="title-price"><a href="shop-ui-inner.html">{product.name}</a></h4>
<span className="gender text-uppercase">{product.gender}</span>
<span className="gender">{product.category}</span>
</div>
<div className="product-price">
<span className="title-price">{product.price}</span>
</div>
</div>
<ul className="list-inline product-ratings">
<li><i className="rating-selected fa fa-star" /></li>
<li><i className="rating-selected fa fa-star" /></li>
<li><i className="rating-selected fa fa-star" /></li>
<li><i className="rating fa fa-star" /></li>
<li><i className="rating fa fa-star" /></li>
<li className="like-icon"><a data-original-title="Add to wishlist" data-toggle="tooltip" data-placement="left" className="tooltips" href="#"><i className="fa fa-heart" /></a></li>
</ul>
</div>
</li>
);
}
}
ProductItem.propTypes = {
product: propTypes.object
}
ProductItem.defaultProps = {
product: {
name: "name4",
gender: "man",
category: "cate4",
price: "300$"
}
}
<file_sep>/src/components/Banner/SaleBanner.js
import React, { Component } from 'react';
export default class SaleBanner extends Component {
render() {
const salebanner = [
1, 2
];
return (
<div className="row margin-bottom-60">
{salebanner.map((salebanner,index) =>
<div class="col-md-6 md-margin-bottom-30">
<div class="overflow-h">
<div class="illustration-v1 illustration-img1">
<div class="illustration-bg">
<div class="illustration-ads ad-details-v1">
<h3>SUMMER <strong>SALE</strong> 30% - 60% <strong>off</strong></h3>
<a class="btn-u btn-brd btn-brd-hover btn-u-light" href="#">Shop Now</a>
</div>
</div>
</div>
</div>
</div>
)}
</div>
);
}
}
<file_sep>/src/components/Item/CategoryItem.js
import React, { Component } from 'react';
import propTypes from 'prop-types';
export default class CategoryItem extends Component {
render() {
const {category} = this.props;
return (
<div className="col-md-4 md-margin-bottom-30">
<div className="overflow-h">
<a className="illustration-v3 illustration-img1" href="#">
<span className="illustration-bg">
<span className="illustration-ads">
<span className="illustration-v3-category">
<span className="product-category">{category.name}</span>
<span className="product-amount">{category.amount}</span>
</span>
</span>
</span>
</a>
</div>
</div>
);
}
}
CategoryItem.propTypes = {
category: propTypes.object
}
CategoryItem.defaultProps = {
category: {
name: "Men",
amount: "56 Items"
}
}
<file_sep>/src/components/TwitterBlock/TwitterBlock.js
import React, { Component } from 'react';
export default class TwitterBlock extends Component {
render() {
return (
<div className="parallaxBg twitter-block margin-bottom-60">
<div className="container">
<div className="heading heading-v1 margin-bottom-20">
<h2>Latest Tweets</h2>
</div>
<div id="carousel-example-generic-v5" className="carousel slide" data-ride="carousel">
{/* Indicators */}
<ol className="carousel-indicators">
<li className="active rounded-x" data-target="#carousel-example-generic-v5" data-slide-to={0} />
<li className="rounded-x" data-target="#carousel-example-generic-v5" data-slide-to={1} />
<li className="rounded-x" data-target="#carousel-example-generic-v5" data-slide-to={2} />
</ol>
<div className="carousel-inner">
<div className="item active">
<p>Unify has reached 10000 plus sales and we just want to thank you to our all customers for being part of the Unify Template success <a href="http://bit.ly/1c0UN3Y">http://bit.ly/1c0UN3Y</a></p><p>
</p><p><a href="https://twitter.com/htmlstream">@htmlstream</a></p>
<ul className="list-inline twitter-icons">
<li><a href="#"><i className="fa fa-reply" /></a></li>
<li><a href="#"><i className="fa fa-retweet" /></a></li>
<li><a href="#"><i className="fa fa-star" /></a></li>
</ul>
</div>
<div className="item">
<p>the majority have suffered #alteration in some form, by injected humour, or randomised words which don't look even slightly believable. If you are going to use a passage of Lorem Ipsum</p>
<p><a href="https://twitter.com/htmlstream">@twbootstrap</a></p>
<ul className="list-inline twitter-icons">
<li><a href="#"><i className="fa fa-reply" /></a></li>
<li><a href="#"><i className="fa fa-retweet" /></a></li>
<li><a href="#"><i className="fa fa-star" /></a></li>
</ul>
</div>
<div className="item">
<p>New 100% Free Stock Photos. Every. Single. Day. Everything you need for your creative projects. <a href="#">http://publicdomainarchive.com</a></p>
<p><a href="https://twitter.com/htmlstream">@wrapbootstrap</a></p>
<ul className="list-inline twitter-icons">
<li><a href="#"><i className="fa fa-reply" /></a></li>
<li><a href="#"><i className="fa fa-retweet" /></a></li>
<li><a href="#"><i className="fa fa-star" /></a></li>
</ul>
</div>
</div>
<div className="carousel-arrow">
<a className="left carousel-control" href="#carousel-example-generic-v5" data-slide="prev">
<i className="fa fa-angle-left" />
</a>
<a className="right carousel-control" href="#carousel-example-generic-v5" data-slide="next">
<i className="fa fa-angle-right" />
</a>
</div>
</div>
</div>
</div>
);
}
}
| 41d1d8312a9e791cc8555461c39fda90a88ca32c | [
"JavaScript"
] | 11 | JavaScript | vnduy01/Unify-React | 69c05b6e01d58626cc6444916bf294aec88ac45e | 4ab5b280f022f725eb30a2a45b5430a2684bfac0 |
refs/heads/master | <file_sep>//
// GameScene.swift
// Platform Souls
//
// Created by Alumnoids on 24/04/18.
// Copyright © 2018 Alumnoids. All rights reserved.
//
import SpriteKit
import GameplayKit
class GameScene: SKScene {
private var label : SKLabelNode?
private var spinnyNode : SKShapeNode?
var isRight : Bool = false
var isLeft : Bool = false
var thePlayer:SKSpriteNode = SKSpriteNode()
let swipeRightRec = UISwipeGestureRecognizer()
let swipeLeftRec = UISwipeGestureRecognizer()
let tapRec = UITapGestureRecognizer()
override func didMove(to view: SKView) {
tapRec.numberOfTouchesRequired = 2
tapRec.numberOfTapsRequired = 3
swipeRightRec.addTarget(self, action: #selector(GameScene.swipedRight) )
swipeRightRec.direction = .right
self.view!.addGestureRecognizer(swipeRightRec)
swipeLeftRec.addTarget(self, action: #selector(GameScene.swipedLeft) )
swipeLeftRec.direction = .left
self.view!.addGestureRecognizer(swipeLeftRec)
if let somePlayer:SKSpriteNode = self.childNode(withName: "Dude") as? SKSpriteNode {
thePlayer = somePlayer
thePlayer.physicsBody?.isDynamic = true
}
}
//Esto detecta los gestos
@objc func tappedView() {
print("THREE TAPS")
}
@objc func swipedRight() {
print("right")
}
@objc func swipedLeft() {
print("left")
}
override func update(_ currentTime: TimeInterval) {
}
//lo que hace que se pueda mover el personaje
func touchDown(atPoint pos : CGPoint) {
print("touched \( pos.x)")
print("touched \( pos.y)")
var wait:SKAction = SKAction.wait(forDuration: 0.01)
//let walkAnimation:SKAction = SKAction(named: "TEST")
var moveAction:SKAction
if (pos.x < self.size.width/2){
isLeft = true
moveAction = SKAction.moveBy(x: -30, y: 0, duration: 0.5)
print("Left")
thePlayer.run(moveAction)
}
if(pos.x > self.size.width/2){
moveAction = SKAction.moveBy(x: 30, y: 0, duration: 0.5)
isRight = true
print("Right")
thePlayer.run(moveAction)
}
if (pos.x < self.size.width/2 || pos.y < self.size.width/2){
isLeft = true
moveAction = SKAction.moveBy(x: -30, y: 20, duration: 0.5)
wait = SKAction.wait(forDuration: 0.7)
print("Left Up")
thePlayer.run(moveAction)
thePlayer.run(wait)
}
if(pos.x > self.size.width/2 || pos.y < self.size.width/2){
moveAction = SKAction.moveBy(x: 30, y: 20, duration: 0.5)
wait = SKAction.wait(forDuration: 0.7)
isRight = true
print("Right Up")
thePlayer.run(moveAction)
thePlayer.run(wait)
}
}
func touchMoved(toPoint pos : CGPoint) {
}
func touchUp(atPoint pos : CGPoint) {
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
for t in touches { self.touchDown(atPoint: t.location(in: self)) }
}
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
for t in touches { self.touchMoved(toPoint: t.location(in: self)) }
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
for t in touches { self.touchUp(atPoint: t.location(in: self)) }
}
override func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent?) {
for t in touches { self.touchUp(atPoint: t.location(in: self)) }
}
}
| 534ab7857ec4a3a456e08991761a3c737b641f67 | [
"Swift"
] | 1 | Swift | HoasdAS/PlatSouls | 4f050d96509b5004784260602dd013aba114a7f5 | 66c203cca0b4a6d14df230995736d6e2748f5a70 |
refs/heads/master | <file_sep>#include "protocol.h"
struct message * create_message(enum message_type type, char * text, char * error_text);
void delete_message(struct message * msg);
<file_sep>#include <string.h>
#include <stdlib.h>
#include "message.h"
#include "protocol.h"
struct message * create_message(enum message_type type, char * text, char * error_text){
struct message * message = (struct message *)malloc(sizeof(struct message));
message->text = malloc(strlen(text) * sizeof(char));
message->error_text = malloc(strlen(error_text) * sizeof(char));
message->type = type;
strcpy(message->text, text);
strcpy(message->error_text, error_text);
return message;
}
void delete_message(struct message * message){
if(message){
if(message->text)
free(message->text);
if(message->error_text)
free(message->error_text);
free(message);
}
}
<file_sep>#include "event_handler.h"
event_handler* create_acceptor(int fd, reactor* r);
<file_sep>#include "protocol.h"
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <sys/ioctl.h>
#include <net/if.h>
#include <net/if_arp.h>
#include <string.h>
#include <stdint.h>
#include <ifaddrs.h>
#include <stdio.h>
#define BUFOR_SIZE 1000
int server_fd;
static int send_bytes(int fd, const char* msg, size_t len)
{
int result = -1;
if (write(fd, &len, sizeof(size_t)) > 0)
if (write(fd, msg, len) == len)
result = 0;
return result;
}
int send_ack_nack(int fd, char is_error, const char* error_msg)
{
char* msg = "1.0";
size_t len = 3;
if (is_error) {
len = strlen(error_msg) + 4;
msg = malloc((len + 1) * sizeof(char));
strcpy(msg, "1.1.");
strcpy(msg+4, error_msg);
}
return send_bytes(fd, msg, len);
}
struct message* receive_message(int fd)
{
size_t len = 0;
char* msg = 0;
struct message* m = 0;
if (read(fd, &len, sizeof(size_t)) < 1)
return 0;
msg = malloc(len * sizeof(char));
if (read(fd, msg, len) != len) {
return 0;
}
m = malloc(sizeof(struct message));
m->text = 0;
m->error_text = 0;
switch (msg[0]) {
case '1':
m->type = INTERFACES_LIST;
break;
case '2':
default:
free(m);
m = 0;
}
free(msg);
return m;
}
int get_interface_status(const int fd, const char * name, char * buf){
struct ifreq ifr;
strcpy(ifr.ifr_name, name);
if(0 > ioctl(fd, SIOCGIFFLAGS, &ifr)){
printf("ioctl error (SIOCGIFFLAGS): \'%s\'\n", strerror(errno));
return -1;
}
if(ifr.ifr_flags & IFF_UP)
strcpy(buf, "UP");
else
strcpy(buf, "DOWN");
return 0;
}
int get_interface_mac_address(const int fd, const char * name, char * buf){
int i = 0;
char part[4];
struct ifreq ifr;
strcpy(ifr.ifr_name, name);
if(0 > ioctl(fd, SIOCGIFHWADDR, &ifr)){
printf("ioctl error (SIOCGIFHWADDR): \'%s\'\n", strerror(errno));
return -1;
}
buf[0] = '\0';
for(i = 0; i < 6; ++i){
sprintf(part, "%hhx:", (unsigned char)ifr.ifr_hwaddr.sa_data[i]);
strcat(buf, part);
}
buf[strlen(buf) - 1] = '\0';
return 0;
}
int get_interface_ipv4(const int fd, const char * name, char * buf){
struct ifreq ifr;
ifr.ifr_addr.sa_family = AF_INET;
strcpy(ifr.ifr_name, name);
if(0 > ioctl(fd, SIOCGIFADDR, &ifr)){
printf("ioctl error (SIOCGIFADDR): \'%s\'\n", strerror(errno));
return -1;
}
strcpy(buf, inet_ntoa(((struct sockaddr_in *) &ifr.ifr_addr)->sin_addr));
return 0;
}
int get_interface_ipv6(const int fd, const char * name, char * buf){
struct ifaddrs * addrs, * interface;
struct sockaddr_in6 *s6;
if(getifaddrs(&addrs)){
printf("getifaddrs error: \'%s\'\n", strerror(errno));
return -1;
}
for(interface = addrs; interface != NULL; interface = interface->ifa_next){
if(!strcmp(name, interface->ifa_name)){
if(interface->ifa_addr->sa_family == AF_INET6){
s6 = (struct sockaddr_in6 *)(interface->ifa_addr);
if(NULL == inet_ntop(interface->ifa_addr->sa_family, (void *)&(s6->sin6_addr), buf, 100)){
printf("inet_ntop error: \'%s\'\n", strerror(errno));
}
}
}
}
return 0;
}
int get_interface_netmask(const int fd, const char * name, char * buf){
struct ifreq ifr;
if (0 > ioctl(fd, SIOCGIFNETMASK, &ifr)){
printf("SIOCGIFNETMASK\n");
return -1;
}
strcpy(buf, inet_ntoa(((struct sockaddr_in *)&ifr.ifr_addr)->sin_addr));
return 0;
}
int get_interface_info(const int fd, const char * name, char * buf){
char status[5], mac[18], ipv4[16], netmask[16], ipv6[100];
get_interface_status(fd, name, status);
get_interface_mac_address(fd, name, mac);
get_interface_ipv4(fd, name, ipv4);
get_interface_netmask(fd, name, netmask);
get_interface_ipv6(fd, name, ipv6);
sprintf(buf, "%s, %s, %s, %s, %s",status, mac, ipv4, netmask, ipv6);
return 0;
}
int get_network_interfaces(const int fd, char * buf)
{
int i = 0;
unsigned int MAX_INTERFACES = 128;
struct ifreq ifr[MAX_INTERFACES];
struct ifconf config;
config.ifc_len = MAX_INTERFACES * sizeof(struct ifreq);
config.ifc_buf = (char *)ifr;
//ioctl modify ifconf.ifc_len to amount of interfaces * sizeof structure
if(0 > ioctl(fd, SIOCGIFCONF, (char *)&config)){
printf("ioctl error (SIOCGIFCONF): \'%s\'\n", strerror(errno));
return -1;
}
for(i = 0; i < config.ifc_len / (sizeof(struct ifreq)); ++i){
strcat(buf, ifr[i].ifr_name);
strcat(buf, "\n");
}
return 0;
}
int set_mac_address(const int fd, const char * name, const char * mac){
struct ifreq ifr;
memset(&ifr, 0, sizeof(ifr));
strcpy(ifr.ifr_name, name);
sscanf(mac, "%hhx:%hhx:%hhx:%hhx:%hhx:%hhx" ,
&ifr.ifr_hwaddr.sa_data[0],
&ifr.ifr_hwaddr.sa_data[1],
&ifr.ifr_hwaddr.sa_data[2],
&ifr.ifr_hwaddr.sa_data[3],
&ifr.ifr_hwaddr.sa_data[4],
&ifr.ifr_hwaddr.sa_data[5]);
ifr.ifr_hwaddr.sa_family = ARPHRD_ETHER;
if(0 > ioctl(fd, SIOCSIFHWADDR, &ifr)){
printf("ioctl error (SIOCSIFHWADDR): \'%s\'\n", strerror(errno));
return -1;
}
return 0;
}
int set_ipv4_address(const int fd, const char * name, const char * ipv4){
struct ifreq ifr;
memset(&ifr, 0, sizeof(ifr));
strcpy(ifr.ifr_name, name);
ifr.ifr_addr.sa_family = AF_INET;
if(0 == inet_aton(ipv4, &((struct sockaddr_in *) &ifr.ifr_addr)->sin_addr)){
printf("inet_aton error. Invalid ip address\n");
return -1;
}
if(0 > ioctl(fd, SIOCSIFADDR, &ifr)){
printf("ioctl error (SIOCSIWADDR): \'%s\'\n", strerror(errno));
return -1;
}
return 0;
}
int set_netmask_address(const int fd, const char * name, const char * netmask){
struct ifreq ifr;
memset(&ifr, 0, sizeof(ifr));
strcpy(ifr.ifr_name, name);
ifr.ifr_addr.sa_family = AF_INET;
if(0 == inet_aton(netmask, &((struct sockaddr_in *) &ifr.ifr_addr)->sin_addr)){
printf("inet_aton error. Invalid netmask address\n");
return -1;
}
if(0 > ioctl(fd, SIOCSIFNETMASK, &ifr)){
printf("ioctl error (SIOCSIFNETMASK): \'%s\'\n", strerror(errno));
return -1;
}
return 0;
}
int send_network_interfaces(const int fd){
char message[BUFOR_SIZE];
char interfaces[BUFOR_SIZE];
size_t length = 2;
strcpy(message, "1.");
strcpy(interfaces, "");
if(0 > get_network_interfaces(fd, interfaces)){
return -1;
}
length += strlen(interfaces);
strcat(message, interfaces);
return send_bytes(fd, message, length);
}
/*int main(){
//Server config init
int server_fd = socket (PF_INET, SOCK_STREAM, 0), client_fd;
struct sockaddr_in server_address, client_address;
socklen_t client_length;
//ifreq config
char buf[1000];
if(0 > server_fd){
printf("socket error: \'%s\'\n", strerror(errno));
return -1;
}
server_address.sin_family = AF_INET;
server_address.sin_addr.s_addr = inet_addr("10.0.2.15");
server_address.sin_port = htons(9865);
if(0 > bind(server_fd, (struct sockaddr*)&server_address, sizeof (server_address))){
printf("bind error: \'%s\'\n", strerror(errno));
return -1;
}
if(0 > listen (server_fd, 1)){
printf("listen error: \'%s\'\n", strerror(errno));
return -1;
}
if (0 > (client_fd = accept(server_fd, (struct sockaddr *)&client_address, &client_length))){
printf("accept error: \'%s\'\n", strerror(errno));
return -1;
}
set_netmask_address(server_fd, "eth0", "255.0.0.0");
//set_ipv4_address(server_fd, "eth0", "10.0.2.15");
//set_mac_address(server_fd, "eth0", "08:00:27:c0:4c:85");
//get_network_interfaces(server_fd, buf);
get_interface_info(server_fd, "eth0", buf);
write(client_fd, buf, sizeof(buf));
close(client_fd);
close(server_fd);
}*/
<file_sep>#ifndef PROTOCOL_H
#define PROTOCOL_H
#include <stdlib.h>
enum message_type {
INTERFACES_LIST = 1,
INTERFACE_INFO,
SET_MAC,
SET_IP,
SET_NETMASK
};
struct message {
enum message_type type;
char* text;
char* error_text;
};
int send_ack_nack(int fd, char is_error, const char* error_msg);
struct message* receive_message(int fd);
int get_interface_status(const int fd, const char * name, char * buf);
int get_interface_mac_address(const int fd, const char * name, char * buf);
int get_interface_ipv4(const int fd, const char * name, char * buf);
int get_interface_ipv6(const int fd, const char * name, char * buf);
int get_interface_netmask(const int fd, const char * name, char * buf);
int get_interface_info(const int fd, const char * name, char * buf);
int get_network_interfaces(const int fd, char * buf);
int set_mac_address(const int fd, const char * name, const char * mac);
int set_ipv4_address(const int fd, const char * name, const char * ipv4);
int set_netmask_address(const int fd, const char * name, const char * netmask);
int send_network_interfaces(const int fd);
#endif
<file_sep>#include <sys/socket.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <netinet/in.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#define DEFAULT_PORT 9865
#define LOOPBACK "127.0.0.1"
int main(int argc, char ** argv){
int server_fd = socket (PF_INET, SOCK_STREAM, 0);
struct sockaddr_in server_address, client_address;
char buf[1000];
if(0 > server_fd){
printf("Creating socket error");
return -1;
}
server_address.sin_family = AF_INET;
if(3 == argc){
server_address.sin_addr.s_addr = inet_addr(argv[1]);
server_address.sin_port = htons(atoi(argv[2]));
}
else if(2 == argc){
server_address.sin_addr.s_addr = inet_addr(argv[1]);
server_address.sin_port = htons(DEFAULT_PORT);
}
else{
server_address.sin_addr.s_addr = inet_addr(LOOPBACK);
server_address.sin_port = htons(DEFAULT_PORT);
}
if(0 > connect(server_fd, (struct sockaddr *)& server_address, sizeof(server_address))){
printf("Connect error\n");
return -1;
}
char * msg = "1.";
size_t len = strlen(msg);
write(server_fd, &len, sizeof(size_t));
write(server_fd, msg, sizeof(msg));
msg = malloc(1000);
read(server_fd, &len, sizeof(size_t));
read(server_fd, msg, len);
printf("%s\n", msg);
//while(1){
//wypisanie menu mozliwosci, i wybor opcji
//read(server_fd, buf, sizeof(buf));
//printf("%s\n", buf);
//}
close(server_fd);
}
<file_sep>#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <sys/epoll.h>
#include <arpa/inet.h>
#include <errno.h>
#include "reactor.h"
#include "acceptor_eh.h"
#include "client_eh.h"
extern errno;
extern int server_fd;
int init_server(int* s, int* e);
int main(int argc, const char *argv[])
{
int srv_fd = -1;
int epoll_fd = -1;
reactor* r = 0;
event_handler* seh = 0;
if (init_server(&srv_fd, &epoll_fd) != 0)
return 1;
server_fd = srv_fd;
r = create_reactor(epoll_fd);
seh = create_acceptor(srv_fd, r);
r->add_eh(r, seh);
r->event_loop(r);
return 0;
}
int init_server(int* s, int* e)
{
int srv_fd = -1;
int epoll_fd = -1;
struct sockaddr_in srv_addr;
struct epoll_event ee;
memset(&srv_addr, 0, sizeof(struct sockaddr_in));
memset(&ee, 0, sizeof(e));
srv_fd = socket(AF_INET, SOCK_STREAM | SOCK_NONBLOCK, 0);
if (srv_fd < 0) {
printf("Cannot create socket\n");
return 1;
}
srv_addr.sin_family = AF_INET;
srv_addr.sin_addr.s_addr = htonl(INADDR_ANY);
srv_addr.sin_port = htons(5557);
if (bind(srv_fd, (struct sockaddr*) &srv_addr, sizeof(srv_addr)) < 0) {
printf("Cannot bind socket\n");
close(srv_fd);
return 1;
}
if (listen(srv_fd, 1) < 0) {
printf("Cannot listen\n");
close(srv_fd);
return 1;
}
epoll_fd = epoll_create(MAX_USERS + 1);
if (epoll_fd < 0) {
printf("Cannot create epoll\n");
close(srv_fd);
return 1;
}
ee.events = EPOLLIN;
ee.data.fd = srv_fd;
if (epoll_ctl(epoll_fd, EPOLL_CTL_ADD, srv_fd, &ee) < 0) {
printf("Cannot add server socket to epoll\n");
close(epoll_fd);
close(srv_fd);
return 1;
}
*s = srv_fd;
*e = epoll_fd;
return 0;
}
<file_sep>#include "event_handler.h"
event_handler* create_client_eh(int fd, reactor* r);
<file_sep>#include "client_eh.h"
#include "protocol.h"
#include "reactor.h"
#include "message.h"
#include <string.h>
#include <sys/epoll.h>
#include <stdio.h>
static int handle_client_message(event_handler* self, struct message* m)
{
int fd = self->fd;
int result = -1;
switch (m->type) {
case INTERFACES_LIST:
result = send_network_interfaces(fd);
break;
default:
break;
}
delete_message(m);
return result;
}
static void serve_client(event_handler* self, uint32_t e)
{
int result = -1;
struct message* m = 0;
if (e & EPOLLIN) {
m = receive_message(self->fd);
if (m)
result = handle_client_message(self, m);
}
if (result < 0) {
self->r->rm_eh(self->r, self->fd);
}
}
event_handler* create_client_eh(int fd, reactor* r)
{
event_handler* eh = malloc(sizeof(event_handler));
eh->fd = fd;
eh->r = r;
eh->handle_event = &serve_client;
return eh;
}
| 5452dec77c352f8183317f3d814e61567323e898 | [
"C"
] | 9 | C | kalvyy/Advanced_Linux_Programming | d654da61aa01e1e20e8a53760a7fb7b3d392542f | bc59cef764d3232257b499a0f8d5b2d90cd6b893 |
refs/heads/master | <repo_name>ntsoftware/sara<file_sep>/env.sh
# run command "source env.sh" to setup command-line environment
PATH=$PWD/usr/bin:$PWD/usr/sox-14.4.1:$PATH
export PATH
DYLD_LIBRARY_PATH=$PWD/usr/lib:$DYLD_LIBRARY_PATH
export DYLD_LIBRARY_PATH
MANPATH=$PWD/usr/share/man:$MANPATH
export MANPATH
<file_sep>/test/test_reco.cpp
#include "gtest/gtest.h"
#include <pocketsphinx.h>
TEST(test_reco, test_reco) {
ps_decoder_t *ps;
cmd_ln_t *config;
config = cmd_ln_init(NULL, ps_args(), TRUE,
"-hmm", MODELDIR "/hmm/fr/lium_french_f0",
"-lm", MODELDIR "/lm/fr/french3g62K.lm.dmp",
"-dict", MODELDIR "/lm/fr/frenchWords62K.dic",
"-fwdtree", "yes",
"-fwdflat", "yes",
"-bestpath", "yes",
"-input_endian", "little",
"-samprate", "16000", NULL);
ASSERT_TRUE(config != NULL);
ps = ps_init(config);
ASSERT_TRUE(ps != NULL);
ps_free(ps);
cmd_ln_free_r(config);
}
<file_sep>/setup.sh
#!/bin/bash
USR_DIR=$PWD/usr
BUILD_DIR=$PWD/build
SPHINXBASE_DIR=$PWD/build/sphinxbase-0.8
POCKETSPHINX_DIR=$PWD/build/pocketsphinx-0.8
function clean {
rm -rf $BUILD_DIR $USR_DIR
}
function get {
if [ ! -f `basename $1` ]
then
curl -L -O $1
fi
}
function setup_libraries {
# download and extract third-party libraries
mkdir -p $BUILD_DIR
pushd $BUILD_DIR
get http://download.sourceforge.net/project/cmusphinx/sphinxbase/0.8/sphinxbase-0.8.tar.gz
get http://download.sourceforge.net/project/cmusphinx/pocketsphinx/0.8/pocketsphinx-0.8.tar.gz
tar xvf sphinxbase-0.8.tar.gz
tar xvf pocketsphinx-0.8.tar.gz
popd
# configure and build sphinxbase library
pushd $SPHINXBASE_DIR
./configure --prefix=$USR_DIR && make && make install
popd
# configure and build pocketsphinx library
pushd $POCKETSPHINX_DIR
./configure --prefix=$USR_DIR --with-sphinxbase=$SPHINXBASE_DIR && make && make install
popd
}
function setup_acoustic_model {
# download French acoustic model
mkdir -p $USR_DIR/share/pocketsphinx/model/hmm/fr
pushd $USR_DIR/share/pocketsphinx/model/hmm/fr
get http://download.sourceforge.net/project/cmusphinx/Acoustic%20and%20Language%20Models/French%20F0%20Broadcast%20News%20Acoustic%20Model/lium_french_f0.tar.gz
get http://download.sourceforge.net/project/cmusphinx/Acoustic%20and%20Language%20Models/French%20F2%20Telephone%20Acoustic%20Model/lium_french_f2.tar.gz
tar xvf lium_french_f0.tar.gz
tar xvf lium_french_f2.tar.gz
popd
}
function setup_language_model {
# download French language model
mkdir -p $USR_DIR/share/pocketsphinx/model/lm/fr
pushd $USR_DIR/share/pocketsphinx/model/lm/fr
for i in fr-phone.lm.dmp french3g62K.lm.dmp frenchWords62K.dic
do
get http://download.sourceforge.net/project/cmusphinx/Acoustic%20and%20Language%20Models/French%20Language%20Model/$i
done
popd
}
function setup_sox {
# download and extract sox
mkdir -p $USR_DIR
pushd $USR_DIR
get http://download.sourceforge.net/project/sox/sox/14.4.1/sox-14.4.1-macosx.zip
unzip sox-14.4.1-macosx.zip
popd
}
setup_libraries
setup_acoustic_model
setup_language_model
setup_sox
echo "Setup done. Run command \"source env.sh\""
| 3665f4753d305df802a21f5424df2d05703f7179 | [
"C++",
"Shell"
] | 3 | Shell | ntsoftware/sara | 8e5cff76b05ffee502697e6cc81fb5216ca7624a | a00df91cd9f759f3b49550d4ea41bee44122ace8 |
refs/heads/main | <file_sep># NWN .NET Barebone Template #
This is a minimal implementation of NWNEE using the bare beamdog image
<file_sep># Pull Dotnet image to build the project
FROM mcr.microsoft.com/dotnet/sdk:5.0 AS build
ADD ./src/services /Build
WORKDIR /Build/HelloWorld
RUN dotnet publish -c Release -o out
# Build the final NWN server image
FROM nwndotnet/anvil:b48cf825
COPY --from=build /Build/HelloWorld/out /nwn/anvil/Plugins/HelloWorld/
<file_sep># NWNXee Barebone Template #
This is a minimal implementation of NWNXEE.
<file_sep># NWN .NET Barebone Template #
This is a minimal implementation of NWNXEE DotNet using the [NWN.Core](https://github.com/nwn-dotnet/NWN.Core) library. It is intended for those who would like to build their own implementations from the ground up. See documentation in comments of Main.cs.
### Credits ###
* Barebone implementation by [Wytchwood](https://github.com/Wytchwood)
* Forked from [Urothis](https://github.com/urothis)' nwn-dotnet-module-template
* Originally forked from: [nwnstuff/nwn-csharp](https://github.com/nwnstuff/nwn-csharp/)
<file_sep># Pull Dotnet image to build the project
FROM mcr.microsoft.com/dotnet/sdk:5.0 AS build
WORKDIR /Build
ADD ./src .
RUN dotnet publish -c Release
# Build the final NWN server image
FROM nwnxee/unified:2450a81
COPY --from=build /Build/bin/Release/net5.0/publish /nwn/data/data/
<file_sep># NWN .NET Barebone Template #
This is a minimal implementation of an Anvil project.
<file_sep>using System;
using NWN.Core;
namespace NWN
{
public class ServerCore
{
public static int Bootstrap(IntPtr intPtr, int length)
{
CoreGameManager coreGameManager = new CoreGameManager();
coreGameManager.OnSignal += OnSignal;
coreGameManager.OnRunScript += OnRunScript;
coreGameManager.OnServerLoop += OnServerLoop;
return NWNCore.Init(intPtr, length, coreGameManager);
}
private static void OnRunScript(string scriptName, uint objectSelf, out int scriptHandleResult) {
// This switch statement illustrates how the template prompts individual script calls. Most
// implementations will split this logic into a Dictionary or other sensible arrangement. Note that
// a script does not need to be in the module for its name to be assigned. Many DotNET modules
// have no .nss or .ncs files at all. Note that script names must always be shorter than 16
// characters by an internal engine limitation.
switch (scriptName)
{
// An ordinary script. No return value set.
case "x2_mod_def_load":
Console.WriteLine("Module started.");
break;
// A conditional script. Return value set appropriately.
case "chk_is_male":
scriptHandleResult = NWScript.GetGender(NWScript.GetPCSpeaker()) == 0 ? 1 : 0;
break;
}
// default return value
scriptHandleResult = -1;
}
private static void OnSignal(string signal)
{
switch (signal)
{
case "ON_MODULE_LOAD_FINISH":
break;
case "ON_DESTROY_SERVER":
break;
}
}
private static void OnServerLoop(ulong frame)
{
}
}
}
| b24419d7960c445a6e2a38644fc1c12b8057fc66 | [
"Markdown",
"C#",
"Dockerfile"
] | 7 | Markdown | nwn-dotnet/nwn-dotnet-barebone-template | 51e59355983f8812afc1a2b698046517fe1a1b01 | 3fe776fa1dcbb7b998700100fa0c8063273c0f89 |
refs/heads/master | <repo_name>Gonzik28/food<file_sep>/src/test/java/BotTest.java
import org.junit.Test;
import java.util.Calendar;
import java.util.Date;
import static org.junit.Assert.*;
public class BotTest {
@Test
public void test() {
Date date = new Date();
Calendar c = Calendar.getInstance();
c.setTime(date);
int dayOfWeek = c.get(Calendar.DAY_OF_WEEK) - 1;
String foodOfTheDay = null;
switch (dayOfWeek) {
case 1:
foodOfTheDay = "Тайская еда";
break;
case 2:
foodOfTheDay = "Барбекю-бургер";
break;
case 3:
foodOfTheDay = "Индийская кухня";
break;
case 4:
foodOfTheDay = "Пицца";
break;
case 5:
foodOfTheDay = "Китайская еда";
break;
case 6:
foodOfTheDay = "Хлопья";
break;
case 7:
foodOfTheDay = "Побалуй себя";
break;
}
System.out.println(foodOfTheDay);
}
} | ba194c2cae6c61185fb16eba0aab681769f2638c | [
"Java"
] | 1 | Java | Gonzik28/food | 762fdf2c5574cea224206614383522c56421bff3 | 686984f6b56c2ebfc64378367a16a9ac6ddd96bf |
refs/heads/master | <file_sep>import { Body, Controller, Get, Post, Res } from '@nestjs/common';
import { BoardingsService } from './boardings.service';
import { Response } from 'express';
import { CheckBoardingDto } from './dto/check-boarding.dto';
import { ApiOperation, ApiResponse, ApiTags } from '@nestjs/swagger';
import { User } from '../users/user.schema';
@ApiTags('boarding')
@Controller('/boarding')
export class BoardingsController {
constructor(private boardingsService: BoardingsService) {}
@Get()
async getAll() {
return this.boardingsService.getAllBoardings();
}
@ApiOperation({
summary: 'Generate barcode for user by id',
})
@ApiResponse({
status: 201,
description: 'Image file represented as string of binary data',
})
@Post('/gen')
async generateCodeForUser(@Body('id') id: string, @Res() res: Response) {
const image = await this.boardingsService.generateCodeForUser(id);
res.contentType('image/png').send(image);
}
@ApiOperation({
summary: 'Check user invite by id and invite code (same as invite id)',
})
@ApiResponse({
status: 201,
description: 'Check was succeed',
type: User,
})
@Post('/check')
async validateInviteCode(@Body() boardingDto: CheckBoardingDto) {
return this.boardingsService.validateCode(boardingDto);
}
}
<file_sep>import { Module } from '@nestjs/common';
import { importsProviders } from './imports.providers';
@Module({
providers: [...importsProviders],
exports: [...importsProviders],
})
export class ImportsModule {}
<file_sep>import { Injectable } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { User, UserDocument } from './user.schema';
import { Model } from 'mongoose';
import { CreateUserDto } from './dto/user.dto';
@Injectable()
export class UsersService {
constructor(@InjectModel(User.name) private userModel: Model<UserDocument>) {}
async getAllUsers() {
return this.userModel.find().exec();
}
async createUser(dto: CreateUserDto) {
return this.userModel.create(dto);
}
async createMockUsers() {
const names = [
'<NAME>',
'<NAME>',
'<NAME>',
'<NAME>',
'<NAME>',
'<NAME>',
];
for (const name of names) {
await this.userModel.create({
name,
distance: Math.floor(Math.random() * 10000),
hours: Math.floor(Math.random() * 1000),
});
}
return this.getAllUsers();
}
}
<file_sep>version: '3.7'
networks:
web-watcher:
driver: bridge
volumes:
backend:
mongo:
services:
mongo:
image: 'mongo:latest'
container_name: mongo
volumes:
- mongo:/data/db
networks:
- web-watcher
ports:
- 27017:27017
command: --serviceExecutor adaptive --wiredTigerCacheSizeGB 1.5 --bind_ip mongo --noauth
backend:
build:
context: ./
volumes:
- type: bind
source: ./
target: /opt/app
consistency: cached
depends_on:
- mongo
ports:
- 3000:3000
networks:
- web-watcher
<file_sep>import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';
import { Document } from 'mongoose';
import { ApiProperty } from '@nestjs/swagger';
export type UserDocument = User & Document;
@Schema()
export class User {
@ApiProperty({
example: '<NAME>',
description: 'User name',
})
@Prop({ required: true })
name: string;
@ApiProperty({
example: 1234,
description: 'Amount distance in km',
})
@Prop()
distance: number;
@ApiProperty({
example: 100,
description: 'Amount flight hours',
})
@Prop()
hours: number;
}
export const UserSchema = SchemaFactory.createForClass(User);
<file_sep>import {
ConnectedSocket,
SubscribeMessage,
WebSocketGateway,
WebSocketServer,
OnGatewayDisconnect,
} from '@nestjs/websockets';
import { Server, Socket } from 'socket.io';
import { InjectModel } from '@nestjs/mongoose';
import { User, UserDocument } from '../../users/user.schema';
import { Model } from 'mongoose';
@WebSocketGateway()
export class EventsGateway implements OnGatewayDisconnect {
@WebSocketServer()
private server: Server;
private interval: NodeJS.Timeout;
private toSendIndex: number;
private readonly statisticsClients: Socket[];
private readonly lastCheckedClients: Socket[];
constructor(
@InjectModel(User.name)
private readonly userModel: Model<UserDocument>,
) {
this.statisticsClients = [];
this.lastCheckedClients = [];
}
sendLastChecked(user: User) {
for (const client of this.lastCheckedClients) {
if (!client.disconnected) {
client.emit('boarding', user);
}
}
}
@SubscribeMessage('boarding')
async handleBoardingEvent(@ConnectedSocket() client: Socket) {
this.lastCheckedClients.push(client);
}
@SubscribeMessage('map')
async handleMapEvent(@ConnectedSocket() client: Socket) {
clearInterval(this.interval);
this.statisticsClients.push(client);
const emitNextUser = async () => {
const users = await this.userModel.find().exec();
if (this.toSendIndex == null || this.toSendIndex >= users.length) {
this.toSendIndex = 0;
}
const user = users[this.toSendIndex];
for (const client of this.statisticsClients) {
if (!client.disconnected) {
client.emit('userStatistics', user);
}
}
this.toSendIndex++;
};
await emitNextUser();
this.interval = setInterval(() => emitNextUser(), 10000);
}
handleDisconnect() {
clearInterval(this.interval);
}
}
<file_sep>FROM node:14
WORKDIR /opt/app
CMD ["npm", "run", "start:dev"]
<file_sep>import { ApiProperty } from '@nestjs/swagger';
export class CheckBoardingDto {
@ApiProperty({
example: '607c418e12acd66fa792a451',
})
readonly id: string;
@ApiProperty({
example: '607c418e12acd66fa792a123',
})
readonly code: string;
}
<file_sep>import { Module } from '@nestjs/common';
import { EventsGateway } from './events.gateway';
import { MongooseModule } from '@nestjs/mongoose';
import { User, UserSchema } from '../../users/user.schema';
@Module({
imports: [
MongooseModule.forFeature([{ name: User.name, schema: UserSchema }]),
],
providers: [EventsGateway],
exports: [EventsGateway],
})
export class EventsModule {}
<file_sep>import { Module } from '@nestjs/common';
import { MongooseModule } from '@nestjs/mongoose';
import { BoardingsController } from './boardings.controller';
import { BoardingsService } from './boardings.service';
import { Boarding, BoardingSchema } from './boarding.schema';
import { ImportsModule } from './imports/imports.module';
import { User, UserSchema } from '../users/user.schema';
import { EventsModule } from './events/events.module';
@Module({
imports: [
MongooseModule.forFeature([
{ name: Boarding.name, schema: BoardingSchema },
{ name: User.name, schema: UserSchema },
]),
ImportsModule,
EventsModule,
],
controllers: [BoardingsController],
providers: [BoardingsService],
})
export class BoardingsModule {}
<file_sep>import { HttpException, Inject, Injectable } from '@nestjs/common';
import { BarcodeGenerator, Imports } from './imports/types';
import { CheckBoardingDto } from './dto/check-boarding.dto';
import { InjectModel } from '@nestjs/mongoose';
import { Boarding, BoardingDocument } from './boarding.schema';
import { Model } from 'mongoose';
import { User, UserDocument } from '../users/user.schema';
import { EventsGateway } from './events/events.gateway';
@Injectable()
export class BoardingsService {
constructor(
@Inject(Imports.BARCODE_MODULE)
private readonly barcodeModule: BarcodeGenerator,
@InjectModel(Boarding.name)
private readonly boardingModel: Model<BoardingDocument>,
@InjectModel(User.name)
private readonly userModel: Model<UserDocument>,
private readonly eventsGateway: EventsGateway,
) {}
async getAllBoardings() {
return this.boardingModel.find().populate('user').exec();
}
async generateCodeForUser(id: string) {
const user = await this.userModel.findById(id);
if (!user) {
throw new HttpException("User doesn't exist", 404);
}
let doc = await this.boardingModel.findOne({
user: user.id,
});
if (!doc) {
doc = await this.boardingModel.create({
user: user.id,
});
}
return this.barcodeModule.toBuffer({
bcid: 'code128',
text: doc.id,
scale: 3,
height: 15,
includetext: true,
textxalign: 'center',
});
}
async validateCode(boardingDto: CheckBoardingDto) {
const doc = await this.boardingModel
.findOne({
_id: boardingDto.code,
user: boardingDto.id,
})
.populate('user')
.exec();
if (!doc) {
throw new HttpException('Not valid!', 409);
}
this.eventsGateway.sendLastChecked(doc.user as UserDocument);
return doc.user;
}
}
<file_sep>import bwip from 'bwip-js';
export type BarcodeGenerator = typeof bwip;
export enum Imports {
BARCODE_MODULE = 'BARCODE_MODULE',
}
<file_sep>import { ApiProperty } from '@nestjs/swagger';
export class CreateUserDto {
@ApiProperty({
example: '<NAME>',
description: 'User name',
})
readonly name: string;
@ApiProperty({
example: 1234,
description: 'Amount distance in km',
})
readonly distance: string;
@ApiProperty({
example: 100,
description: 'Amount flight hours',
})
readonly hours: number;
}
<file_sep>import { Body, Controller, Get, Post } from '@nestjs/common';
import { UsersService } from './users.service';
import { CreateUserDto } from './dto/user.dto';
import { ApiOperation, ApiResponse, ApiTags } from '@nestjs/swagger';
import { User } from './user.schema';
@ApiTags('users')
@Controller('/users')
export class UsersController {
constructor(private readonly usersService: UsersService) {}
@ApiOperation({
summary: 'Get all users',
})
@Get()
getAll() {
return this.usersService.getAllUsers();
}
@ApiOperation({
summary: 'Create user',
})
@ApiResponse({
status: 201,
description: 'User created',
type: User,
})
@Post()
create(@Body() dto: CreateUserDto) {
return this.usersService.createUser(dto);
}
@ApiOperation({
summary: 'Create mock data',
})
@Get('/mock')
createMockUsers() {
return this.usersService.createMockUsers();
}
}
<file_sep>import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';
import { Document, Types } from 'mongoose';
import { User } from '../users/user.schema';
export type BoardingDocument = Boarding & Document;
@Schema()
export class Boarding {
@Prop()
code: string;
@Prop({ type: User, ref: 'User' })
user: Types._ObjectId | User;
}
export const BoardingSchema = SchemaFactory.createForClass(Boarding);
<file_sep>import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { MongooseModule } from '@nestjs/mongoose';
import { UsersModule } from './users/users.module';
import { ConfigModule } from '@nestjs/config';
import { BoardingsModule } from './boardings/boardings.module';
import { ServeStaticModule } from '@nestjs/serve-static';
import * as path from 'path';
@Module({
imports: [
ConfigModule.forRoot({
envFilePath: `.${process.env.NODE_ENV}.env`,
}),
ServeStaticModule.forRoot({
rootPath: path.join(__dirname, '..', 'client'),
}),
MongooseModule.forRoot(
`mongodb://${process.env.DB_HOST}:${process.env.DB_PORT}/${process.env.DB_NAME}`,
),
UsersModule,
BoardingsModule,
],
controllers: [AppController],
providers: [AppService],
})
export class AppModule {}
<file_sep>import * as bwip from 'bwip-js';
import { Imports } from './types';
export const importsProviders = [
{
provide: Imports.BARCODE_MODULE,
useFactory: () => bwip,
},
];
| d76a6bda73e723b8f70fc89483352d71879d5a03 | [
"TypeScript",
"YAML",
"Dockerfile"
] | 17 | TypeScript | breeeew/nestjs-training | 9dcc9b11348edb538ea44a71690f40c9d0970e65 | fde8ce44a10bb4517a0e8e792d19a9b6c3a024e6 |
refs/heads/master | <file_sep># Changelog - sscg
### 0.0.4
__Changes__
- deply: fix GH_TOKEN for travis
__Contributors__
- mh-cbon
Released by mh-cbon, Thu 03 Nov 2016 -
[see the diff](https://github.com/mh-cbon/sscg/compare/0.0.3...0.0.4#diff)
______________
### 0.0.3
__Changes__
- deploy: fix travis release key
__Contributors__
- mh-cbon
Released by mh-cbon, Thu 03 Nov 2016 -
[see the diff](https://github.com/mh-cbon/sscg/compare/0.0.2...0.0.3#diff)
______________
### 0.0.2
__Changes__
- deploy: fix typos in both appveyor / travis files
__Contributors__
- mh-cbon
Released by mh-cbon, Thu 03 Nov 2016 -
[see the diff](https://github.com/mh-cbon/sscg/compare/0.0.1...0.0.2#diff)
______________
### 0.0.1
__Changes__
- init
__Contributors__
- mh-cbon
Released by mh-cbon, Thu 03 Nov 2016 -
[see the diff](https://github.com/mh-cbon/sscg/compare/cb711a8af9bc509445bd8330519900534835b17f...0.0.1#diff)
______________
<file_sep>#!/bin/sh
rm -fr test/
go run main.go --host example.org --out test
(openssl x509 -in test/cert.pem -text -noout | grep "DNS:example.org" && echo "OK") || exit 1
(openssl x509 -in test/cert.pem -text -noout | grep "Issuer: O=Acme Co" && echo "OK") || exit 1
(openssl x509 -in test/cert.pem -text -noout | grep "Subject: O=Acme Co" && echo "OK") || exit 1
echo "test passed!"
<file_sep># sscg
Generate self signed certificate
## Usage
```sh
sscg - 0.0.0
Generate self signed certificate.
-ca
whether this cert should be its own Certificate Authority
-duration duration
Duration that certificate is valid for (default 8760h0m0s)
-ecdsa-curve string
ECDSA curve to use to generate a key. Valid values are P224, P256, P384, P521
-h
-help
Get help
-host string
Comma-separated hostnames and IPs to generate a certificate for
-out string
Output put directory (default ".")
-rsa-bits int
Size of RSA key to generate. Ignored if --ecdsa-curve is set (default 2048)
-start-date string
Creation date formatted as Jan 1 15:04:05 2011
-v
-version
Get version
```
__Examples__
```sh
sscg --host dev.example.org
sscg --help
sscg --version
```
## Install
Pick an msi package [here](https://github.com/mh-cbon/sscg/releases)!
__chocolatey__
```sh
choco install sscg
```
__deb/rpm repositories__
```sh
wget -O - https://raw.githubusercontent.com/mh-cbon/latest/master/source.sh \
| GH=mh-cbon/sscg sh -xe
# or
curl -L https://raw.githubusercontent.com/mh-cbon/latest/master/source.sh \
| GH=mh-cbon/sscg sh -xe
```
__deb/rpm packages__
```sh
curl -L https://raw.githubusercontent.com/mh-cbon/latest/master/install.sh \
| GH=mh-cbon/sscg sh -xe
# or
wget -q -O - --no-check-certificate \
https://raw.githubusercontent.com/mh-cbon/latest/master/install.sh \
| GH=mh-cbon/sscg sh -xe
```
__go__
```sh
mkdir -p $GOPATH/src/github.com/mh-cbon
cd $GOPATH/src/github.com/mh-cbon
git clone https://github.com/mh-cbon/sscg.git
cd sscg
glide install
go install
```
## Credits
Orignal code taken from https://golang.org/src/crypto/tls/generate_cert.go and re-packed.
| 35ad6ef143410715e83b22dbbb1aa831f17b928c | [
"Markdown",
"Shell"
] | 3 | Markdown | mh-cbon/sscg | f97240581cace21693174543d560961554b461a0 | 45cfc29a1ca1ee62fe605ccdfe8c8af86362b772 |
refs/heads/master | <file_sep>import {HttpHeaders} from '@angular/common/http';
export const filesUrl = '/files';
export const serviceRunnerUrl = '/services/run';
export const userUrl = '/adminapi';
export const batchUrl = '/services/batch';
export const serviceUrl = '/api/data';
export const headers = new HttpHeaders().set('Content-Type', 'application/json');
<file_sep>import { BrowserModule } from '@angular/platform-browser';
import { NgModule, NO_ERRORS_SCHEMA } from '@angular/core';
import { AppComponent } from './app.component';
import {ServicecategoryService} from './service/servicecategory.service';
import {BrowserAnimationsModule} from '@angular/platform-browser/animations';
import {HttpClientModule} from '@angular/common/http';
import {MDBBootstrapModule} from 'angular-bootstrap-md';
import { CarouselModule, WavesModule } from 'angular-bootstrap-md';
import {ButtonModule} from 'primeng/button';
import {SafeHtml} from './service/safe.html.pipe';
import {RouterModule} from '@angular/router';
import {appRouting} from './app.routing';
import {NgxPageScrollModule} from 'ngx-page-scroll';
@NgModule({
declarations: [
AppComponent,
SafeHtml
],
imports: [
BrowserModule,
HttpClientModule,
ButtonModule,
CarouselModule,
WavesModule,
MDBBootstrapModule.forRoot(),
BrowserAnimationsModule,
NgxPageScrollModule,
RouterModule,
appRouting
],
providers: [ServicecategoryService, SafeHtml],
bootstrap: [AppComponent],
schemas: [ NO_ERRORS_SCHEMA ],
exports: [SafeHtml]
})
export class AppModule { }
<file_sep>import {Service} from './Service';
export class ServiceCategory {
constructor(public id: string,
public name: string,
public description: string,
public shortDescription: string,
public catchyPhrase: string,
public services: Service[],
public imageFile: string) {
}
}
<file_sep>export class Contactperson {
constructor(public id: string,
public lsfId: string,
public name: string,
public email: string,
public phone: string,
public room: string) {
}
}
<file_sep>import {Contactperson} from './Contactperson';
export class Service {
constructor(public id: string,
public title: string,
public description: string,
public shortDescription: string,
public catchyPhrase: string,
public targetedAudience: string[],
public audienceLevel: string[],
public contactpersons: Contactperson[],
public serviceCategory: string,
public requirements: string,
public activeService: Boolean,
public imageFile: string,
public href: string) {
}
}
<file_sep>export class ActiveSlide {
constructor(public direction: string,
public relatedTarget: number) {
}
}
<file_sep>import {Injectable} from '@angular/core';
import {Observable} from 'rxjs/Observable';
import {HttpClient} from '@angular/common/http';
import {ServiceCategory} from '../model/ServiceCategory';
import * as appGlobals from '../app.globals';
@Injectable()
export class ServicecategoryService {
private serviceUrl = appGlobals.serviceUrl + '/servicecategory';
constructor (private http: HttpClient) {}
getAll(): Observable<ServiceCategory[]> {
return this.http.get<ServiceCategory[]>(this.serviceUrl + '/all');
}
getFiltered(filterTarget: string, filterAudience: string): Observable<ServiceCategory[]> {
console.log('retrieving filtered categories with ' + filterTarget + ' and ' + filterAudience);
return this.http.get<ServiceCategory[]>(this.serviceUrl + '/filtered?filterTarget=' + filterTarget + '&filterAudience=' + filterAudience);
}
}
<file_sep>import {Component, OnInit} from '@angular/core';
import {ServicecategoryService} from './service/servicecategory.service';
import {ServiceCategory} from './model/ServiceCategory';
import {ActiveSlide} from './model/ActiveSlide';
import {ActivatedRoute, Params, Router} from '@angular/router';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
// providers: []
})
export class AppComponent implements OnInit {
serviceCategories: ServiceCategory[];
activeSlide: ActiveSlide;
activeCategory: ServiceCategory;
filterTargetedAudience: string;
filterAudienceLevel: string;
constructor( private servicecategoryService: ServicecategoryService,
private router: Router,
private route: ActivatedRoute) {
}
ngOnInit() {
this.route.queryParams.subscribe((params: Params) => {
if (params['filterTarget'] !== undefined) {
this.filterTargetedAudience = params['filterTarget'].trim();
console.log('read target filter ' + this.filterTargetedAudience);
} else {
this.filterTargetedAudience = '';
}
if (params['filterAudience'] !== undefined) {
this.filterAudienceLevel = params['filterAudience'].trim();
console.log('read audience filter ' + this.filterAudienceLevel);
} else {
this.filterAudienceLevel = '';
}
this.servicecategoryService.getFiltered(this.filterTargetedAudience, this.filterAudienceLevel).subscribe(
data => {
this.serviceCategories = data;
this.activeSlide = new ActiveSlide('', 0);
this.activeCategory = this.serviceCategories[this.activeSlide.relatedTarget];
}
);
});
}
goToserviceList() {
window.location.href = '#serviceList?filterTarget=' + this.filterTargetedAudience + '&filterAudience=' + this.filterAudienceLevel;
}
activeSlideChange() {
this.activeCategory = this.serviceCategories[this.activeSlide.relatedTarget];
}
}
| 71bee35d2dd7f5fb491de9cc1e3c55bf067c40bf | [
"TypeScript"
] | 8 | TypeScript | ETspielberg/viewer-web | 9ee97c6c489f8b003ce13ed884c1f62db872dfca | 5390ce9b7d62c8059f8d35519e02efadc9f22b9f |
refs/heads/master | <file_sep>from kivy.app import App
from kivy.uix.widget import Widget
from kivy.graphics import *
from kivy.clock import Clock
import math
class MyWidget(Widget):
points = [[200,200],[200,300],[300,300],[300,200],[200,200]]
affine = [[1,0,0],[0,1,0],[50,50,1]]
count = 0;
orig = [0,0]
def __init__(self, **kwargs):
super(MyWidget, self).__init__(**kwargs)
self.bind(pos=self.update_canvas)
self.bind(size=self.update_canvas)
self.update_canvas()
Clock.schedule_interval(self.rotcall, 0.02)
def update_canvas(self, *args):
self.canvas.clear()
with self.canvas:
Color(0.5, 0.5, 0.5, 0.5)
xarr = self.affine[0]
yarr = self.affine[1]
t = self.affine[2]
xp = [xarr[0]*p[0] + yarr[0]*p[1] + t[0] + self.orig[0] for p in self.points]
yp = [xarr[1]*p[0] + yarr[1]*p[1] + t[1] + self.orig[1] for p in self.points]
points_to_draw = [[xp[i],yp[i]] for i in range(len(self.points))]
self.count += 1;
print self.count, self.affine
Line(points=tuple([i for a in points_to_draw for i in a]))
Color(0.9, 0.9, 0.9, 1)
Line(points=tuple([i for a in self.points for i in a]))
def apply_to_affine(self, mat):
self.affine = [[sum([self.affine[i][k]*mat[k][j] for k in range(3)]) for j in range(3)] for i in range(3)]
def rotate(self, deg):
cosr = math.cos(deg*math.pi/180)
sinr = math.sin(deg*math.pi/180)
self.apply_to_affine(([cosr, sinr, 0],[-sinr, cosr, 0],[0,0,1]))
def translate(self, tx, ty):
self.apply_to_affine([[1,0,0],[0, 1, 0],[tx, ty, 1]])
def scale(self, s):
self.apply_to_affine([[s,0,0],[0,s,0],[0,0,1]])
def translate_orig(self, tx, ty):
self.orig[0] = tx
self.orig[1] = ty
def rotcall(self, dt):
self.translate(-250-self.orig[0],-250-self.orig[1])
self.rotate(5)
self.translate(250+self.orig[0],250+self.orig[1])
# self.apply_to_affine([[1,0,0],[0, 1, 0],[-250, -250, 1]])
# self.apply_to_affine([[0.984807753,0.173648178,0],[-0.173648178, 0.984807753, 0],[0, 0, 1]])
# self.apply_to_affine([[1,0,0],[0, 1, 0],[250, 250, 1]])
# self.translate_orig(50*math.cos(self.count*0.1),50*math.sin(self.count*0.1))
self.translate(-200-self.orig[0],-200-self.orig[1])
self.rotate(3)
self.translate(200+self.orig[0],200+self.orig[1])
self.update_canvas()
class MyApp(App):
def build(self):
return MyWidget()
MyApp().run()
| b5d33e88ce1b48529162e03ea5b9f5452e07d65d | [
"Python"
] | 1 | Python | nantunest/pyaffinetransf | c0849ae9a16f5392cb4cff4cbaa42351dec684af | ec9396e31966d8a227de0e0771ef8962f6d38562 |
refs/heads/master | <repo_name>Chyngyz1009/J2hw3<file_sep>/src/com/company/BankAccount.java
package com.company;
public class BankAccount {
private double amount;
public double getAmount() {
return amount;
}
public void deposit(double sum) {
amount = amount + sum;
System.out.println("Вы положили " + sum);
}
public void withDraw(int sum) throws LimitException {
if (sum > amount) {
throw new LimitException("Недостаточно средств ", getAmount());
}
amount = amount - sum;
System.out.println("Вы сняли " + sum);
}
}
| 4429e25f744886c4dcc31b7ce66a3a7278336b81 | [
"Java"
] | 1 | Java | Chyngyz1009/J2hw3 | c22be9bff68b40aa0eea0370a8bc69e949a03471 | 318a10ee9c6202b80c4e15a4028a1fea9005244f |
refs/heads/master | <repo_name>gastonfeng/1kw<file_sep>/README.md
# 1kw
历史项目开源:1KW正弦波逆变器
项目年份:2001
<file_sep>/program/main.c
/**********************************************
* Filename: main.c
* Project: 2k1.pjt
* Product name: 1kW sin waveform inverter
***********************************************
*
* Author: <NAME>
* Date: 2001.01.22
* Compiled Using CC5Xfree package
*
**********************************************/
#define OPEN_LOOP
//#define FEEDBACK
#define F50Hz
//#define F60Hz
#include <16C73A.H>
#include <int16cxx.H>
//#include "spwmtab.C"
#define SPWMCOUNT 29
bit intflag,neg,front,change;
unsigned char index;
#pragma bit PWMHR @ 7.0
#pragma bit PWMLL @ 7.1 //CCP2
#pragma bit PWMLR @ 7.2 //CCP1
#pragma bit PWMHL @ 7.3
#pragma bit LED_POWER @ 6.4
#pragma bit LED_LVD @ 6.5
#pragma bit LED_PROTECT @ 6.6
#pragma bit LED_WORK @ 6.7
unsigned char SPWMTAB(unsigned char tabindex);
unsigned char PEIRODTAB(unsigned char tabindex);
#pragma origin = 4
interrupt int_server( void)
{
int_save_registers // W, STATUS (and PCLATH)
intflag=1;
PR2=PEIRODTAB(index);
if(TMR2IF){
if(neg){
CCPR1L=SPWMTAB(index);
if(change){
PWMHR=0;
CCP2CON=0;
CCP1CON=0xc;
PWMHL=1;
change=0;
}
if(front){
if(index==SPWMCOUNT){
front=0;
}
else index++;
}
else{
if(index==0){
front=1;
neg=0;
change=1;
//PWMHL=0;
//CCP1CON=0;
//CCP2CON=0xc;
//PWMHR=1;
}
else index--;
}
}
else{
CCPR2L=SPWMTAB(index);
if(change){
PWMHL=0;
CCP1CON=0;
CCP2CON=0xc;
PWMHR=1;
change=0;
}
if(front){
if(index==SPWMCOUNT){
front=0;
}
else index++;
}
else{
if(index==0){
front=1;
neg=1;
change=1;
//PWMHR=0;
//CCP2CON=0;
//CCP1CON=0xc;
//PWMHL=1;
}
else index--;
}
}
TMR2IF=0;
}
int_restore_registers // W, STATUS (and PCLATH)
}
//***********************************************
// SPWM DATA TAB
// Generate by SPWMGEN V1.0
// Author:Fengjiantao
// http://fjt.yeah.net
// Email:<EMAIL>
// Carrier Index:120
// Modulation Index:80
// Pluse number:167
// MODE:µ¥¼«ÐÔ
//************************************************
unsigned char SPWMTAB(unsigned char tabindex)
{
PCL+=W;
return 3;
return 10;
return 17;
return 24;
return 31;
return 37;
return 44;
return 51;
return 57;
return 63;
return 69;
return 75;
return 81;
return 86;
return 91;
return 96;
return 101;
return 105;
return 110;
return 113;
return 117;
return 120;
return 123;
return 125;
return 128;
return 129;
return 131;
return 132;
return 133;
return 133;
}
unsigned char PEIRODTAB(unsigned char tabindex)
{
PCL+=W;
return 166;
return 170;
return 170;
return 170;
return 170;
return 170;
return 170;
return 170;
return 170;
return 170;
return 170;
return 169;
return 169;
return 169;
return 169;
return 169;
return 169;
return 169;
return 169;
return 168;
return 168;
return 168;
return 168;
return 168;
return 168;
return 167;
return 167;
return 167;
return 167;
return 167;
}
void main(void)
{
// PORT CONFIGRATION
TRISB=0xf;
PORTC=0;
TRISC=0xf0;
// PWM OUTPUT CONFIGRATION
neg=0;
front=1;
index=0;
CCPR1L=0;
CCPR2L=0;
PR2=0xa6; //PERIORD
// CCP1CON=0xc;
CCP2CON=0xc;
TMR2IE=1;
T2CON=4;
PEIE=1;
GIE=1;
while(1);
}
<file_sep>/reference/PWM99.c
/* 输出128*128个数据到T3.c中 */
#include "stdio.h"
#include "math.h"
const double pi=3.141592654;
int c,i,k,m,p,n,u,v,w,x,y,z,b[129],pp;
double t=0.000000;
double r,s,s1,f,g,j,l,q,a[100];
double sum=0.000000;
int test(double q);
int table(int v);
FILE *fp; /* 设文件指针 */
main()
{
fp=fopen("T3.c","a+"); /* 打开文件T3.c,并将结果存入该文件 */
if((fp=fopen("T3.c","a+"))==NULL)
printf("error");
n=0; /* n 代表第几条曲线 */
q=1.000000; /* q:0.666666--1 */
while (n<=130) /* 128 条曲线 */
{
printf("n=%d\n",n);
if(n>128) /* n>128的结果舍去不要 */
fprintf(fp,"n=%d ",n);
test(q);
q=q-0.0026041666; /* 将q分成128份,每分0.0026041666 */
n++;
}
fclose(fp); /* 程序结束后关闭文件 */
}
test(double q)
{
p=0,u=1,x=0,z=1,pp=0;
for(w=0;w<128;w++) /* 将一条正弦曲线分成128分 */
{
for (k=0;k<156;k++) /* 每分占 156.25us */
{
for(i=1;i<=100;i++) /* 利用富氏分解公式计算某一时刻的三角波值 */
{
l=(i%2==0)? -1.000000:1.000000;
j=l/((i*2-1)*(i*2-1));
f=j*sin(40000*(2*i-1)*pi*t);
f=8.33670275*f/(pi*pi);
sum=sum+f;
}
for(m=0;m<=127;m++) /* 计算某一时刻的正弦值 */
{
if(t>=(m*0.00015625)&&t<=((m+1)*0.00015625))
{s=q*sin(100*pi*m*0.00015625);break;}
}
if(s>sum) /* 正弦值大于三角值则存入数组 */
{
a[p]=t;
p++;
u=0; /* 标志数组存放的是本次计算结果 */
}
else
{
if(u==0)
{
p--;
r=a[p]-a[0]; /* 计算出脉宽时间值 */
r=r*1000000;
v=r*128/47; /* 将时间值乘1000000并折算成移位数,并取整 */
pp++;
if(pp==2) /* 取第二个脉宽值的移位数 */
table(v); /* 将移位数转化为高位地址 */
u++;
}
p=0;
}
t=t+0.000001;
sum=0;
}
pp=0;
x++;
if(x%16==0) /* 16个数据一行 */
{ printf("\n");
fprintf(fp,"\nDCB "); }
if((w!=0)&&(w%4==0)) /* 时间校准 */
t=t+0.000001;
z=1.000000;
}
t=0;
return 0;
}
table(int v) /* 将移位数转化为对应的高位地址 */
{
int b[129];
int e;
int d=0x00;
int ka=0x00;
if((ferror(fp)!=0)||(feof(fp)!=0))
{printf("error");
fprintf(fp,"error");}
for(e=1;e<=128;e++) /* 将移位数转化为对应的高位地址 */
b[e]=d++;
if((b[v]==0x0a)||(b[v]==0x0b)||(b[v]==0x0c)||(b[v]==0x0d)||(b[v]==0x0e)||(b[v]=
=0x0f))
fprintf(fp,"%x",ka); /* a,b,c,d,e,f前加0 */
fprintf(fp,"%xH,",b[v]);
return 0;
}
<file_sep>/program/15kHz.C
//***********************************************
// SPWM DATA TAB
// Generate by SPWMGEN V1.0
// Author:Fengjiantao
// http://fjt.yeah.net
// Email:<EMAIL>
// Carrier Index:300
// Modulation Index:80
// Pluse number:67
// MODE:µ¥¼«ÐÔ
//************************************************
unsigned char SPWMTAB(unsigned char tabindex)
{
PCL+=W;
return 0;
return 1;
return 2;
return 3;
return 5;
return 6;
return 7;
return 8;
return 9;
return 10;
return 11;
return 12;
return 13;
return 14;
return 16;
return 17;
return 18;
return 19;
return 20;
return 21;
return 22;
return 23;
return 24;
return 25;
return 26;
return 27;
return 28;
return 29;
return 30;
return 31;
return 31;
return 32;
return 33;
return 34;
return 35;
return 36;
return 37;
return 37;
return 38;
return 39;
return 40;
return 40;
return 41;
return 42;
return 43;
return 43;
return 44;
return 44;
return 45;
return 46;
return 46;
return 47;
return 47;
return 48;
return 48;
return 49;
return 49;
return 50;
return 50;
return 50;
return 51;
return 51;
return 51;
return 52;
return 52;
return 52;
return 52;
return 52;
return 53;
return 53;
return 53;
return 53;
return 53;
return 53;
return 53;
return 53;
return 53;
return 53;
return 53;
return 53;
return 53;
return 53;
return 52;
return 52;
return 52;
return 52;
return 52;
return 51;
return 51;
return 51;
return 50;
return 50;
return 50;
return 49;
return 49;
return 48;
return 48;
return 47;
return 47;
return 46;
return 46;
return 45;
return 44;
return 44;
return 43;
return 43;
return 42;
return 41;
return 40;
return 40;
return 39;
return 38;
return 37;
return 37;
return 36;
return 35;
return 34;
return 33;
return 32;
return 31;
return 31;
return 30;
return 29;
return 28;
return 27;
return 26;
return 25;
return 24;
return 23;
return 22;
return 21;
return 20;
return 19;
return 18;
return 17;
return 16;
return 14;
return 13;
return 12;
return 11;
return 10;
return 9;
return 8;
return 7;
return 6;
return 5;
return 3;
return 2;
return 1;
return 0;
}
unsigned char PERIODTAB(unsigned char tabindex)
{
PCL+=W;
return 67;
return 67;
return 67;
return 67;
return 67;
return 67;
return 67;
return 67;
return 67;
return 67;
return 67;
return 67;
return 67;
return 67;
return 67;
return 67;
return 67;
return 67;
return 67;
return 67;
return 67;
return 67;
return 67;
return 67;
return 67;
return 67;
return 67;
return 67;
return 67;
return 67;
return 67;
return 67;
return 67;
return 67;
return 67;
return 67;
return 67;
return 67;
return 67;
return 67;
return 67;
return 67;
return 67;
return 67;
return 67;
return 67;
return 67;
return 67;
return 67;
return 67;
return 67;
return 67;
return 67;
return 67;
return 67;
return 67;
return 67;
return 67;
return 67;
return 67;
return 67;
return 67;
return 67;
return 67;
return 67;
return 67;
return 67;
return 67;
return 67;
return 67;
return 67;
return 67;
return 67;
return 67;
return 67;
}
<file_sep>/program/SPWMTAB.C
//***********************************************
// SPWM DATA TAB
// Generate by SPWMGEN V1.0
// Author:Fengjiantao
// http://fjt.yeah.net
// Email:<EMAIL>
// Carrier Index:120
// Modulation Index:80
// Pluse number:167
// MODE:µ¥¼«ÐÔ
//************************************************
unsigned char SPWMTAB(unsigned char tabindex)
{
PCL+=W;
return 3;
return 10;
return 17;
return 24;
return 31;
return 37;
return 44;
return 51;
return 57;
return 63;
return 69;
return 75;
return 81;
return 86;
return 91;
return 96;
return 101;
return 105;
return 110;
return 113;
return 117;
return 120;
return 123;
return 125;
return 128;
return 129;
return 131;
return 132;
return 133;
return 133;
}
unsigned char PERIODTAB(unsigned char tabindex)
{
PCL+=W;
return 166;
return 170;
return 170;
return 170;
return 170;
return 170;
return 170;
return 170;
return 170;
return 170;
return 170;
return 169;
return 169;
return 169;
return 169;
return 169;
return 169;
return 169;
return 169;
return 168;
return 168;
return 168;
return 168;
return 168;
return 168;
return 167;
return 167;
return 167;
return 167;
return 167;
}
| 2e43a97e547fa1a0c1d5cd2d15a5f070a68f64ea | [
"Markdown",
"C"
] | 5 | Markdown | gastonfeng/1kw | 8b3fb0bfa8e4d4581c1af1f246b0f8ec4d35c17b | c3d3ac4160dbb15d437462a6a4a0997e01e9eb64 |
refs/heads/master | <repo_name>csechols38/invoice-masters<file_sep>/subGroup.js
function subGroup(index) {
var selected = document.getElementById('selected').value;
var par = document.getElementById('proo'+index).value;
var squeerryString = "?selected="+selected+"&par="+par;
http.open("GET", "product.php" +
squeerryString, true);
http.onreadystatechange = srgeetHttpRess;
http.send(null);
}
function srgeetHttpRess() {
if (http.readyState == 4) {
reeess = http.responseText; // These following lines get the response and update the page
document.getElementById('getme').innerHTML = reeess;
}
}
function getXHTTP() {
var xhttp;
try { // The following "try" blocks get the XMLHTTP object for various browsers…
xhttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
xhttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e2) {
// This block handles Mozilla/Firefox browsers...
try {
xhttp = new XMLHttpRequest();
} catch (e3) {
xhttp = false;
}
}
}
return xhttp; // Return the XMLHTTP object
}
var http = getXHTTP(); // This executes when the page first loads.
<file_sep>/allReady.js
function savePage() {
var page = document.getElementById('page').value;
var inv= document.getElementById('inv').value;
var sqsuerryString = "?page="+page+"&inv="+inv;
http.open("GET", "copy.php" +
sqsuerryString, true);
http.onreadystatechange = ssrgetHttpRess;
http.send(null);
}
function ssrgetHttpRess() {
if (http.readyState == 4) {
sreess = http.responseText; // These following lines get the response and update the page
document.getElementById('div1').innerHTML = sreess;
}
}
function getXHTTP() {
var xhttp;
try { // The following "try" blocks get the XMLHTTP object for various browsers…
xhttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
xhttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e2) {
// This block handles Mozilla/Firefox browsers...
try {
xhttp = new XMLHttpRequest();
} catch (e3) {
xhttp = false;
}
}
}
return xhttp; // Return the XMLHTTP object
}
var http = getXHTTP(); // This executes when the page first loads.
<file_sep>/111.php
<?
$html = file_get_contents('http://invoice-masters.com/getContents.php?invvid=74&id=1');
$fp = fopen('pdf/name.html', 'w+');
fwrite($fp, $html);
fclose($fp);
if($fp) {
system("wkhtmltopdf http://invoice-masters.com/pdf/name.html pdf/shibby.pdf 2>&1");
header("Locationhttp://invoice-masters.com/pdf/shibby.pdf");
}
?><file_sep>/Addd.js
function Addd(index) {
var r=confirm("Would You like to add this item into your inventory?");
if (r==true)
{
var name = document.getElementById("name").value;
var d = document.getElementById("desc1").value;
var p = document.getElementById("bob").value;
var gr = document.getElementById("group1").value;
var pl = document.getElementById("bobl").value;
var wholesale = document.getElementById("wholesale").value;
var nn = document.getElementById('number'+index).value;
var quan = document.getElementById('quan').value;
var cream = document.getElementById('invid'+index).value;
var creames = document.getElementById('invidd').value;
var addItem = "?name="+name+"&d="+d+"&p="+p+"&pl="+pl+"&nn="+nn+"&quan="+quan+"&cream="+cream+"&wholesale="+wholesale+"&creames="+creames+"&gr="+gr;
http.open("GET", "product.php" +
addItem, true);
http.onreadystatechange = rgetHttpRes;
http.send(null);
}
else {
var n = document.getElementById("name").value;
var d = document.getElementById("desc1").value;
var p = document.getElementById("bob").value;
var pl = document.getElementById("bobl").value;
var nn = document.getElementById('number'+index).value;
var quan = document.getElementById('quan').value;
var cream = document.getElementById('invid'+index).value;
var wholesale = document.getElementById('wholesale').value;
var creames = document.getElementById('invidd').value;
var addItem = "?n="+n+"&d="+d+"&p="+p+"&pl="+pl+"&nn="+nn+"&quan="+quan+"&cream="+cream+"&wholesale="+wholesale+"&creames="+creames;
http.open("GET", "product.php" +
addItem, true);
var index = http.myCustomValue;
http.myCustomValue = index;
http.onreadystatechange = rgetHttpRes;
http.send(null);
}
}
function rgetHttpRes() {
if (http.readyState == 4) {
rees = http.responseText; // These following lines get the response and update the page
var index = http.myCustomValue;
document.getElementById('prohidden'+index).innerHTML = rees;
}
}
function getXHTTP() {
var xhttp;
try { // The following "try" blocks get the XMLHTTP object for various browsers…
xhttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
xhttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e2) {
// This block handles Mozilla/Firefox browsers...
try {
xhttp = new XMLHttpRequest();
} catch (e3) {
xhttp = false;
}
}
}
return xhttp; // Return the XMLHTTP object
}
var http = getXHTTP(); // This executes when the page first loads.
<file_sep>/delete.php
<?php
include('database_connection.php');
session_start();
$data = $_GET['cancle'];
$id = $_GET['cancle'];
$hag = "DELETE FROM `invoices` WHERE `invid`='".$id."' AND `midd` = '".$_SESSION['id']."' ";
$poop = mysqli_query($dbc, $hag);
if(!$poop) {
die(mysqli_error($dbc));
}
$cock = "DELETE FROM `dataa` WHERE `invid` = '".$id."' AND `midd` = '".$_SESSION['id']."' ";
$KK = mysqli_query($dbc, $cock);
if(!$KK) {
die(mysqli_error($dbc));
}
$cocka = "DELETE FROM `customers` WHERE `invoice` = '".$id."' AND `mid` = '".$_SESSION['id']."' ";
$KKa = mysqli_query($dbc, $cocka);
if(!$KKa) {
die(mysqli_error($dbc));
}
else {
echo 'Invoice Number <span style="color:blue;">'.$id.'</span> Not saved';
}
?><file_sep>/jobPhp1.php
<?php
include('database_connection.php');
session_start();
if(isset($_GET['submit'])) {
$poop = array_values($_GET);
$gg = count($poop);
for($i=1; $i<11; $i++){
$jparts[$i] = mysql_real_escape_string($_GET['jparts'.$i.'']);
}
for($k=1; $k<11; $k++) {
$Jparts[$i] = mysql_real_escape_string($_GET['Jparts'.$k.'']);
}
for($l=1; $l<6; $l++) {
$jlabor1[$l] = mysql_real_escape_string($_GET['jlabor'.$l.'']);
}
for($g=1; $g<6; $g++) {
$Jlabor[$g] = mysql_real_escape_string($_GET['Jlabor'.$g.'']);
}
$Jdesc = mysql_real_escape_string($_GET['Jdesc']);
$mid = $_SESSION['id'];
$name = mysql_real_escape_string($_GET['Jname']);
$group =mysql_real_escape_string($_GET['Jgroup']);
if(isset($_GET['Jwhole'])) {
$whole = mysql_real_escape_string($_GET['Jwhole']);
}
if(isset($_GET['MIDD'])) {
$gay = "SELECT * FROM `jobs` WHERE `midd` = '".$_SESSION['id']."' AND `midd` ='".$_GET['MIDD']."'";
$hh = mysqli_query($dbc, $gay);
if(!$hh) {
die(mysqli_error($dbc));
}
else {
$tits ="UPDATE `jobs` SET `Jwhole`='$whole', `group`='$group', Jname= '$name', midd= '$mid', Jdesc='$Jdesc', jpart1='$jparts1', jpart2='$jparts2', jpart3='$jparts3', jpart4='$jparts4', jpart5='$jparts5', jpart6='$jparts6', jpart7='$jparts7', jpart8='$jparts8', jpart9='$jparts9', jpart10='$jparts10', Jparts1='$Jparts1', Jparts2='$Jparts2', Jparts3='$Jparts3', Jparts4='$Jparts4', Jparts5='$Jparts5', Jparts6='$Jparts6', Jparts7='$Jparts7', Jparts8='$Jparts8', Jparts9='$Jparts9', Jparts10='$Jparts10', jjlabor1='$jlabor1', jjlabor2='$jlabor2', jjlabor3='$jlabor3', jjlabor4='$jlabor4', jjlabor5='$jlabor5', Jlabor1='$Jlabor1', Jlabor2='$Jlabor2', Jlabor3='$Jlabor3', Jlabor4='$Jlabor4', Jlabor5='$Jlabor5' WHERE `job num` ='".$_GET['MIDD']."'";
$tit = mysqli_query($dbc, $tits);
if(!$tit) {
die(mysqli_error($dbc));
}
else {
echo 'Thanks Your jobb has been added!<br/><a href="members.php">Back</a>';
}
}
if(!isset($_GET['MIDD'])) {
$gay = "SELECT * FROM `jobs` WHERE `midd` = '".$_SESSION['id']."' ORDER BY `job num` DESC LIMIT 1";
$hh = mysqli_query($dbc, $gay);
if(!$hh) {
die(mysqli_error($dbc));
}
$ho = mysqli_fetch_array($hh);
$jobnum = $ho['job num'];
$group =mysql_real_escape_string($_GET['Jgroup']);
$tits ="UPDATE `jobs` SET `Jwhole`='$whole', `group`='$group', Jname= '$name', midd= '$mid', Jdesc='$Jdesc', jpart1='$jparts1', jpart2='$jparts2', jpart3='$jparts3', jpart4='$jparts4', jpart5='$jparts5', jpart6='$jparts6', jpart7='$jparts7', jpart8='$jparts8', jpart9='$jparts9', jpart10='$jparts10', Jparts1='$Jparts1', Jparts2='$Jparts2', Jparts3='$Jparts3', Jparts4='$Jparts4', Jparts5='$Jparts5', Jparts6='$Jparts6', Jparts7='$Jparts7', Jparts8='$Jparts8', Jparts9='$Jparts9', Jparts10='$Jparts10', jjlabor1='$jlabor1', jjlabor2='$jlabor2', jjlabor3='$jlabor3', jjlabor4='$jlabor4', jjlabor5='$jlabor5', Jlabor1='$Jlabor1', Jlabor2='$Jlabor2', Jlabor3='$Jlabor3', Jlabor4='$Jlabor4', Jlabor5='$Jlabor5' WHERE `job num` ='$jobnum'";
$tit = mysqli_query($dbc, $tits);
if(!$tit) {
die(mysqli_error($dbc));
}
else {
echo '<div style="color:red; font-weight:bold; padding-top:100px;">Thanks Your jobb has been added!<br/><a href="members.php">Back</a></div>';
}
}
}
}
?><file_sep>/index.js
$(document).ready(function() {
$(".slide").show();
$(".cslide").click(function() {
$(".slide").slideToggle("slow")
.show();
$("#less").html(' <div class="nav">Login:</div><br/><form action="index.php" method="GET" id="form">\
<label class="loginlbl">Username:</label>\
<input type="text" name="usr" id="usr"/><br/><br/>\
<label class="loginlbll">Password:</label>\
<input type="password" id="pass" name="pass"/><br/>\
<input type="submit" name="submit" id="submit" value="login"/>\
</form>');
$("#less").css("background", "#c7dbff");
});
});
$(document).ready(function() {
$("#cAslide").click(function() {
$(".slide").slideToggle("slow");
$.ajax({
url:"register.php",
success:function(result) {
$("#less").html(result);
},
});
});
});
function aboutUs(index) {
$("#about").css("float", "left")
.css("max-width", "400px;");
if(index == 1) {
data ="1="+ 1;
}
if(index == 2) {
data="2="+2;
}
if(index == 3) {
data="3="+3;
}
if(index == 4) {
data="4="+4;
}
if(index == 5) {
data="5="+5
}
if(index == 6) {
data="6="+6
}
if(index == 7) {
data="7="+7
}
if(index == 8) {
data="8="+8
}
if(index == 9) {
data="9="+9
}
if(index == 10) {
data="10="+10
}
if(index == 11) {
data="11="+11
}
$.ajax ({
url:"aboutUs.php",
data:data,
success:function(result) {
$(".about").html(result);
},
});
}<file_sep>/img/poop_files/slideForm.js
$(document).ready(function() {
$("#invform").click(function() {
$("#left").slideToggle("fast");
$("#invtable").slideToggle("slow");
});
});
$(function() {
var state = true;
$( "#cinfo" ).click(function() {
if ( state ) {
$("#ctable").slideDown("slow")
.css("z-index", "1");
$("#center").css("opacity", "0.3");
$("#left").css("opacity", "0.3");
$("body").css("background", "silver");
} else {
$("#ctable").slideUp("slow");
$("#center").css("opacity", "1.0");
$("#left").css("opacity", "1.0");
$("body").css("background", "white");
}
state = !state;
});
});
<file_sep>/Text.php
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
<script src="http://thebestbangforyourbuck.tk/gist/jquery/lib/jquery.js"></script>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.9.2/themes/base/jquery-ui.css" />
<script src="http://code.jquery.com/jquery-1.8.3.js"></script>
<script src="http://code.jquery.com/ui/1.9.2/jquery-ui.js"></script>
<script>
function myF() {
$("#hidden").show();
}
</script>
<style>
#hidden {
display:none;
}
</style>
</head>
<body>
<div id="pp" onClick="myF(); return false">email</div>
<div id="hidden">
<form action="<?$PHP_SELF?>" method="POST">
<label for="to">To:</label><input type="text" name="to" />
<label for="from">To:</label><input type="text" name="from" />
<input type="submit" name="submit" value="submit"/>
</form>
</div>
<?
if(isset($_POST['submit'])) {
$subject = "Soeztosell.com invoice registration\r\n";
$message = 'New Email';
$headers = "From: <EMAIL>\r\n".
"Reply-To: <EMAIL>\r\n"
."Return-Path: <EMAIL>\r\n";
$tits = mail($_POST['to'],$subject,$message,$headers);
if($tits) {
echo 'Sent';
}
}
?>
</body>
</html>
<file_sep>/upInventory.js
$(".blend").click(function() {
var index = $("#hippie").text();
$(".blend").blur(doThis(index))
return false;
});
});
function doThis(index) {
var find = document.getElementById('tname').value;
var squerryString = "?find="+find;
http.open("GET", "one.php" +
squerryString, true);
http.onreadystatechange = srgetHttpRess;
http.send(null);
}
function srgetHttpRess() {
if (http.readyState == 4) {
reess = http.responseText; // These following lines get the response and update the page
document.getElementById('hello').innerHTML = reess;
}
}
function getXHTTP() {
var xhttp;
try { // The following "try" blocks get the XMLHTTP object for various browsers…
xhttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
xhttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e2) {
// This block handles Mozilla/Firefox browsers...
try {
xhttp = new XMLHttpRequest();
} catch (e3) {
xhttp = false;
}
}
}
return xhttp; // Return the XMLHTTP object
}
var http = getXHTTP(); // This executes when the page first loads.
<file_sep>/shib.php
<?php
include('database_connection.php');
///////////////////////////////
class Test {
function proccess($table, $data, $sess){
$this->table = $table;
$this->data = $data;
$this->sess = $sess;
}
function gather() {
$con = "SELECT * FROM ".$this->table." WHERE ".$this->data." = ".$this->sess."";
// Make the connection:
$dbc = @mysqli_connect(DATABASE_HOST, DATABASE_USER, DATABASE_PASSWORD,
DATABASE_NAME);
$query = mysqli_query($dbc, $con);
if(!$query) die(mysqli_error($dbc));
while($jeep = mysqli_fetch_array($query)) {
$array[] = array(
$this->id[]=$jeep['id'],
$this->name[]=$jeep['name'],
$this->amount[]=$jeep['amount'],
$this->desc[]=$jeep['desc'],
$this->price[]=$jeep['price'],
$this->altname[]=$jeep['altname'],
$this->group[]=$jeep['group'],
$this->midd[]=$jeep['midd'],
$this->lprice[]=$jeep['lprice'],
$this->yprice[]=$jeep['yprice'],
$this->vendor[]=$jeep['vendor']
);
}
return $array;
}
function map() {
$keys = $this->gather();
$count = count($keys);
foreach($keys as $value) {
$dick[] = $value;
}
$b =0;
foreach($dick as $shib) {
$b++;
print_r($shib);
}
}
}
$new = new Test;
$new->proccess('inventory', 'midd', '1');
$new->gather();
$new->map();
?><file_sep>/jobPhp.php
<?php
include('database_connection.php');
session_start();
if(isset($_GET['submit'])) {
$poop = array_values($_GET);
$gg = count($poop);
for($m=1; $m<11; $m++) {
$Jquan[$m] = mysql_real_escape_string($_GET['Jquan'.$m.'']);
}
for($i=1; $i<11; $i++){
$jparts[$i] = mysql_real_escape_string($_GET['jparts'.$i.'']);
}
for($k=1; $k<11; $k++) {
$Jparts[$k] = mysql_real_escape_string($_GET['Jparts'.$k.'']);
}
for($l=1; $l<6; $l++) {
$jlabor[$l] = mysql_real_escape_string($_GET['jlabor'.$l.'']);
}
for($g=1; $g<6; $g++) {
$Jlabor[$g] = mysql_real_escape_string($_GET['Jlabor'.$g.'']);
}
for($j=1; $j<11; $j++) {
$cock[$j]= 'jparts'.$j.'';
}
for($jd=1; $jd<11; $jd++) {
$cockk[$jd]= 'Jpart'.$jd.'';
}
for($jfd=1; $jfd<6; $jfd++) {
$cockkk[$jfd]= 'Jlabor'.$jfd.'';
}
for($jjfd=1; $jjfd<6; $jjfd++) {
$cockkkk[$jjfd]= 'jjlabor'.$jjfd.'';
}
for($jjfdd=1; $jjfdd<11; $jjfdd++) {
$cocK[$jjfdd]= 'Jquan'.$jjfdd.'';
}
$Jdesc = mysql_real_escape_string($_GET['Jdesc']);
$mid = $_SESSION['id'];
$name = mysql_real_escape_string($_GET['Jname']);
$group =mysql_real_escape_string($_GET['Jgroup']);
if(isset($_GET['Jwhole'])) {
$whole = mysql_real_escape_string($_GET['Jwhole']);
}
$tits = implode(", ", $cock);
if(isset($_GET['MIDD'])) {
$gay = "SELECT * FROM `jobs` WHERE `midd` = '".$_SESSION['id']."' AND `job num` ='".$_GET['MIDD']."'";
$hh = mysqli_query($dbc, $gay);
if(!$hh) {
die(mysqli_error($dbc));
}
$ff = mysqli_fetch_array($hh);
for($k=1; $k<11; $k++) {
$titss ="UPDATE `jobs` SET `Jwhole`='$whole', `group`='$group', Jname= '$name', midd= '$mid', Jdesc='$Jdesc', $cock[$k] = '$jparts[$k]', $cockk[$k] = '$Jparts[$k]', $cocK[$k] = '$Jquan[$k]'WHERE `midd` = '".$_SESSION['id']."' AND `job num`='".$ff['job num']."'";
$cc = mysqli_query($dbc, $titss);
if(!$cc) die(mysqli_error($dbc));
}
for($kg=1; $kg<6; $kg++) {
$titses ="UPDATE `jobs` SET $cockkk[$kg] = '$Jlabor[$kg]', $cockkkk[$kg] = '$jlabor[$kg]' WHERE `midd` = '".$_SESSION['id']."' AND `job num`='".$ff['job num']."'";
$cec = mysqli_query($dbc, $titses);
if(!$cec) die(mysqli_error($dbc));
}
echo '<div style="color:red; font-weight:bold; padding-top:100px;">Thanks Your jobb has been added!<br/><a href="members.php">Back</a></div>';
}
if(!isset($_GET['MIDD'])) {
$gay = "SELECT * FROM `jobs` WHERE `midd` = '".$_SESSION['id']."' ORDER BY `job num` DESC LIMIT 1";
$hh = mysqli_query($dbc, $gay);
if(!$hh) {
die(mysqli_error($dbc));
}
$ho = mysqli_fetch_array($hh);
$jobnum = $ho['job num'] + 1;
$group =mysql_real_escape_string($_GET['Jgroup']);
for($k=1; $k<11; $k++) {
$tits ="UPDATE `jobs` SET `Jwhole`='$whole', `group`='$group', Jname= '$name', midd= '$mid', Jdesc='$Jdesc', $cock[$k] = '$jparts[$k]', $cockk[$k] = '$Jparts[$k]', $cocK[$k] = '$Jquan[$k]' WHERE `midd` = '".$_SESSION['id']."' AND `job num`='".$ho['job num']."'";
$cc = mysqli_query($dbc, $tits);
if(!$cc) die(mysqli_error($dbc));
}
for($kg=1; $kg<6; $kg++) {
$titses ="UPDATE `jobs` SET $cockkk[$kg] = '$Jlabor[$kg]', $cockkkk[$kg] = '$jlabor[$kg]' WHERE `midd` = '".$_SESSION['id']."' AND `job num`='".$ho['job num']."'";
$cec = mysqli_query($dbc, $titses);
if(!$cec) die(mysqli_error($dbc));
}
echo '<div style="color:red; font-weight:bold; padding-top:100px;">Thanks Your jobb has been added!<br/><a href="members.php">Back</a></div>';
}
}
?>
<file_sep>/class.php
<?php
class Style {
var $text;
var $alink;
var $vlink;
var $link;
var $bgcol;
var $face;
var $size;
var $align;
var $valign;
function Style ($text="#000000",$alink="#AA00AA",
$vlink="#AA00AA",$link="#3333FF",
$bgcol="#999999",$face="Book Antiqua",$size=3,$align="CENTER",$valign="TOP") {
$this->text=$text;
$this->alink=$alink;
$this->vlink=$vlink;
$this->link=$link;
$this->bgcol=$bgcol;
$this->face=$face;
$this->size=$size;
$this->align=$align;
$this->valign=$valign;
}
Function Set($varname,$value) {
$this->$varname=$value;
}
function Body() {
PRINT "<BODY BGCOLOR=\"$this->bgcol\" ".
"TEXT=\"$this->text\" ".
"LINK=\"$this->link\" VLINK=\"$this->vlink\" ".
"ALINK=\"$this->alink\"><FONT ".
"FACE=\"$this->face\" SIZE=$this->size>\n";
}
function TDOut ($message=" ",$colspan=1) {
PRINT "<TD COLSPAN=$colspan BGCOLOR=\"$this->bgcol\" ".
"ALIGN=\"$this->align\" VALIGN=\"$this->valign\">";
$this->TextOut($message);
PRINT "</TD>\n";
}
}
$Theader= new Style;
$Theader->Set('text','#0000FF');
$Theader->Set('bgcol','#000000');
$Basic = new Style;
$Basic->Body();
?>
<TABLE>
<TR>
<?php
$Theader->TDOut("Name",2);
$Theader->TDOut("Location",3);
?>
</TR>
<tr>
<?php
$Theader->TDOut("Last");
$Theader->TDOut("First");
$Theader->TDOut("City");
$Theader->TDOut("State/Province");
$Theader->TDOut("Country");
?>
</tr>
?><file_sep>/saveMe.js
function saveIt() {
var pif = document.getElementById('pif').value;
var totsale = document.getElementById('totall').value;
var profits = document.getElementById('grosstotal').value;
var saveinv = document.getElementById('saveinv').value;
var partstot = document.getElementById('partstot').value;
var wholesa = document.getElementById('wholesa').value;
var taxes = document.getElementById('taxes').value;
var labor = document.getElementById('labors').value;
var dates = document.getElementById('dateinv').value;
var squerryStrinng = "?pif="+pif+"&totsale="+totsale+"&profits="+profits+"&saveinv="+saveinv+"&partstot="+partstot+"&taxes="+taxes+"&labor="+labor+"&dates="+dates+"&wholesa="+wholesa;
http.open("GET", "product.php" +
squerryStrinng, true);
http.onreadystatechange = srgetHtttpRess;
http.send(null);
}
function srgetHtttpRess() {
if (http.readyState == 4) {
rteess = http.responseText; // These following lines get the response and update the page
document.getElementById('div1').innerHTML = rteess;
}
}
function getXHTTP() {
var xhttp;
try { // The following "try" blocks get the XMLHTTP object for various browsers…
xhttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
xhttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e2) {
// This block handles Mozilla/Firefox browsers...
try {
xhttp = new XMLHttpRequest();
} catch (e3) {
xhttp = false;
}
}
}
return xhttp; // Return the XMLHTTP object
}
var http = getXHTTP(); // This executes when the page first loads.
<file_sep>/getName.js
function savePage() {
var name = window.prompt("Enter a customer name or title.");
var cachefile = document.getElementById('cachefile').value;
var invid = document.getElementById('invid').value;
var queryString = "?name="+name+"&cachefile="+cachefile+"&invid="+invid;
http.open("GET", "invoices.php" +
queryString, true);
http.onreadystatechange = getHttpRes;
http.send(null);
}
function getHttpRes() {
if (http.readyState == 4) {
res = http.responseText; // These following lines get the response and update the page
document.getElementById('info').innerHTML = res;
}
}
function getXHTTP() {
var xhttp;
try { // The following "try" blocks get the XMLHTTP object for various browsers…
xhttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
xhttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e2) {
// This block handles Mozilla/Firefox browsers...
try {
xhttp = new XMLHttpRequest();
} catch (e3) {
xhttp = false;
}
}
}
return xhttp; // Return the XMLHTTP object
}
var http = getXHTTP(); // This executes when the page first loads.
<file_sep>/emaila.php
<?
system("wkhtmltopdf http://invoice-masters.com/pdf/".$name.".php pdf/".$name.".pdf ");
?>
<file_sep>/Text.html
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
<script src="http://thebestbangforyourbuck.tk/gist/jquery/lib/jquery.js"></script>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.9.2/themes/base/jquery-ui.css" />
<script src="http://code.jquery.com/jquery-1.8.3.js"></script>
<script src="http://code.jquery.com/ui/1.9.2/jquery-ui.js"></script>
<script>
function myF() {
$("#pp").hide();
}
</script>
</head>
<body>
<div id="pp" onClick="myF(); return false">email</div>
<div id="hidden">
<form action="<?$PHP_SELF?>" method="POST">
<label for="to">To:</label><input type="text" name="to" />
<label for="from">To:</label><input type="text" name="from" />
</form>
</body>
</html>
<p>A new website has been created to help people that own a small business and need a program to manage it. Invoice-masters.com has tons of great features that help you to get organized. Here is just a few of the awesome features you get for free:<br>
<li>Inventory Management</li><br>
Insert your parts / items into your own personal database which allows you to have faster invoicing, organization, see profits made, and keep track of what items are selling best.<br>
<li>Customer Management</li><br>
Store all of your customers online, in one place. Access any of your customers and invoices from anywhere that you have INTERNET!<br>
<li>Invoicing</li><br>
Invoice-masters has a built-in invoicing system allowing you to customize your invoices. Once your done with an invoice, directly email it to your customer in PDF format or to view online.
All your invoices are stored online for you to view, print, and email at your convenience. <br>
<li>Day Planner</li><br>
Plan your months as you go with their events / reminders function.<br>
<li>Vendor Management</li><br>
<li>Store all your vendor information and see which vendors give you the best price on your parts / items.<br>
Invoice-masters.com is 100% free to use. Their is no hidden fees down the road. Give it a try today!</li></p>
<file_sep>/drag.js
$(document).ready(function() {
$("#info").bind("hover",function() {
$(".callback").click(function() {
$(".editcall").show();
});
});
});
function editCall() {
var invid = $("#saveinv").attr('value');
var data = "invid="+invid;
$.ajax({
url:"customer.php",
data:data,
success:function(result) {
$(".callback").html(result);
},
});
}
function sParts(index) {
$(".hPP"+index).slideToggle("slow");
$("#clozze"+index).hide();
}
function slideSearch(index) {
$("#searchS"+index).slideToggle("slow");
}<file_sep>/Register.php
<?
include('database_connection.php');
session_start();
$usr = mysql_real_escape_string($_GET['usr']);
$pass = mysql_real_escape_string($_GET['pass']);
$bname = mysql_real_escape_string($_GET['Bname']);
$email = mysql_real_escape_string($_GET['email']);
$RRE = "SELECT * FROM members WHERE usr ='$usr'";
$check = mysqli_query($dbc, $RRE);
if(!$check) die(mysqli_error($dbc));
$checkk = mysqli_num_rows($check);
if($checkk > 0){
die('That Username is already Taken');
}
else {
// Make sure the email address is available:
$query_verify_email = "SELECT * FROM members WHERE email ='$email'";
$result_verify_email = mysqli_query($dbc, $query_verify_email);
if (!$result_verify_email) {
die(' Database Error Occured ');
}
if (mysqli_num_rows($result_verify_email) == 1) {
die('That E-mail has already been registered');
}
if (mysqli_num_rows($result_verify_email) == 0) { // IF no previous user is using this email .
$activation = md5(uniqid(rand(), true));
$query_insert_user = "INSERT INTO `members` ( `usr`, `email`, `pass`, `activation`, `Bname`) VALUES ( '$usr', '$email', '$pass', '$activation', '$bname')";
$result_insert_user = mysqli_query($dbc, $query_insert_user);
if (!$result_insert_user) {
die(mysqli_error($dbc));
}
if (mysqli_affected_rows($dbc) == 1) { //If the Insert Query was successfull.
// Send the email:
$subject = "Invoice-Masters invoicing registration\r\n";
$message = 'http://invoice-masters.com/activate.php?email=' . urlencode($email) . "&key=$activation";
$header = "From:<EMAIL>\r\n";
$header .= "Reply-To:<EMAIL>\r\n";
$header .= "Return-Path:<EMAIL>\r\n";
$poop = mail($email,$subject,$message,$header);
if(!$poop) {
die(mysqli_error($dbc));
}
else {
echo 'Thank You, An e-mail has been sent to <span style="color:blue;">'.$email.'</span>, If you dont recieve the e-mail in 3 minutes please check your junk mail!';
}
}
}
}
?>
<file_sep>/menu.php
<?php
function callMenu() {
?>
<ul id="menu">
<li>
<a href="#">Background</a>
<ul>
<li>
<a href="#">Color</a>
<ul>
<li><a href="#" class="blue">Blue</a></li>
<li><a href="#" class="silver">Silver</a></li>
</ul>
</li>
<li>
<a href="#">Width</a>
<ul>
<li><a href="#" class="plus1">+5px</a></li>
<li><a href="#">+10px</a></li>
</ul>
</li>
<li>
<a href="#">Height</a>
<ul>
<li><a href="#" class="hmin10">-10px</a></li>
<li><a href="#" class="hmin20">-20px</a></li>
<li><a href="#" class="hmin30">-30px</a></li>
<li><a href="#" class="hplus10">+10px</a></li>
<li><a href="#" class="hplus20">+20px</a></li>
</ul>
</li>
</ul>
<li>
<a href="#">Fonts</a>
<ul>
<li>
<a href="#">Colors</a>
<ul>
<li>
<a href="#">Parents</a>
<ul>
<li style="color:blue;"><a href="#" onclick="fSilver('blue'); return false;">Blue</a></li>
<li style="color:red;"><a href="#" onclick="fSilver('red'); return false;">Red</a></li>
<li style="color:green;"><a href="#" onclick="fSilver('green'); return false;">Green</a></li>
<li style="color:yellow;"><a href="#" onclick="fSilver('yellow'); return false;">Yellow</a></li>
<li style="color:orange;"><a href="#" onclick="fSilver('orange'); return false;">Orange</a></li>
<li style="color:teal;"><a href="#" onclick="fSilver('teal'); return false;">Teal</a></li>
<li style="color:silver;"><a href="#" onclick="fSilver('silver'); return false;">Silver</a></li>
</ul>
</li>
<li>
<a href="#">Children</a>
<ul class="cchild">
<li style="color:blue;" class="cblue"><a href="#" onclick="fChildren('blue'); return false;" onmouseover="fChildrenH('blue'); return false;">Blue</a></li>
<li style="color:red;" class="cred"><a href="#" onclick="fChildren('red'); return false;" onmouseover="fChildrenH('red'); return false;">Red</a></li>
<li style="color:green;" class="cgreen"><a href="#" onclick="fChildren('green'); return false;" onmouseover="fChildrenH('green'); return false;">Green</a></li>
<li style="color:yellow;" class="cyellow"><a href="#" onclick="fChildren('yellow'); return false;" onmouseover="fChildrenH('yellow'); return false;">Yellow</a></li>
<li style="color:orange;" class="corange"><a href="#" onclick="fChildren('orange'); return false;" onmouseover="fChildrenH('orange'); return false;">Orange</a></li>
<li style="color:teal;" class="cteal"><a href="#" onclick="fChildren('teal'); return false;" onmouseover="fChildrenH('teal'); return false;">Teal</a></li>
<li style="color:silver;" class="csilver"><a href="#" onclick="fChildren('silver'); return false;" onmouseover="fChildrenH('silver'); return false;">Silver</a></li>
</ul>
</li>
</ul>
<li>
<a href="#">Style/Type</a>
<ul>
<li>
<a href="#">Parents</a>
<ul>
<li style="font-wieght:bold;"><a href="#" class="wbold">Bold</a></li>
<li><a href="#" class="witalic">Italic</a></li>
<li><a href="#" class="wnormall">Normall</a></li>
</ul>
</li>
<li>
<a href="#">Children</a>
<ul>
<li style="font-wieght:bold;"><a href="#" class="wbold">Bold</a></li>
<li><a href="#" class="witalic">Italic</a></li>
<li><a href="#" class="wnormall">Normall</a></li>
</ul>
</li>
</ul>
</li>
</ul>
<li>
<a href="#">Tables</a>
<ul>
<li>
<a href="#">Background</a>
<ul>
<li style="border:1px solid blue; background:blue;"><a href="#" class="bblue">Blue</a></li>
<li style="border:1px solid red; background:red;"><a href="#" class="bred">Red</a></li>
<li style="border:1px solid orange; background:orange;"><a href="#" class="borange">Orange</a></li>
<li style="border:1px solid pink; background:pink;"><a href="#" class="bpink">Pink</a></li>
<li style="border:1px solid silver; background:silver;"><a href="#" class="bsilver">Silver</a></li>
<li style="border:1px solid green; background:green;"><a href="#" class="bgreen">Green</a></li>
</ul>
</li>
<li>
<a href="#">Borders</a>
<ul>
<li style="border:1px solid orange; background:orange;"><a href="#" class="boorange">Orange</a></li>
<li style="border:1px solid red; background:red;"><a href="#" class="bored">Red</a></li>
<li style="border:1px solid silver; background:silver;"><a href="#" class="bosilver">Silver</a></li>
<li style="border:1px solid pink; background:pink;"><a href="#" class="bopink">Pink</a></li>
</ul>
</li>
</ul>
</li>
</li>
</ul>
</body>
</html>
<?php
}
function infO() {
$dbc = mysqli_connect("localhost", "root", "honda388", "invoice");
$hobo = "SELECT * FROM `members` WHERE `id` = '".$_SESSION['id']."' ";
$res = mysqli_query($dbc, $hobo);
if(!$res) {
die(mysqli_error($dbc));
}
while($ll = mysqli_fetch_array($res)) {
?>
<tr valign="top">
<td id="upload">
%<input type="text" name="tax" id="tax" size="5" value="<?echo($ll['tax']);?>"/>
<label class="uplbl">Your tax rate:</label><br/>
<input type="text" name="company" id="company" value="<?echo($ll['Bname']);?>" />
<label class="uplbl"> Company name:</label><br/>
<input type="text" id="cphone" name="cphone" value="<?echo($ll['phone']);?>"/>
<label class="uplbl" >Company Phone # :</label><br/>
<input typ="text" name="cfax" id="cfax" value="<?echo($ll['fax']); ?>" />
<label class="uplbl">Company Fax # : </label><br/>
<input type="text" id="caddr" name="caddr" value="<?echo($ll['addr']);?>" />
<label class="uplbl">Company Address:<label><br/>
<input type="text" id="cslogan" name="cslogan" value="<?echo($ll['slogan']);?>" />
<label class="uplbl">Company Slogan:<label><br/>
<label class="uplbl">Disclaimer:</label><br/>
<textarea cols="30" rows="15" id="cdisc" name="cdisc" WRAP="VIRTUAL"><?echo($ll['disclaimer'])?></textarea><br/>
<input type="submit" name="submit" value="submit" id="sendcForm" onClick="sendcForm(); return false;"/><br/><br/>
<span class="xline">______________________________________________________________</span><br/><br/>
<label class="uplbl"> Upload Your company logo:</label><br/>
<form action="img.php" method="POST" enctype="multipart/form-data">
<input type="file" name="image"/><br/>
<label class="updd">Update your information first!</label>
<input type="hidden" name="time" id="time" value="<? echo(time());?>" />
<input type="hidden" name="page" id="page" value="<? echo(time());?>" />
<input type="hidden" name="ip" id="ip" value="<? echo($_SERVER['REMOTE_ADDR']);?>" />
<input type="hidden" name="image"/>
<input name="Submit" type="submit" value="Upload image"/>
</form>
</td>
</tr>
<?
}
}
?>
<file_sep>/home.php
<?php
include('database_connection.php');
session_start();
// get date from calender {
$change = str_replace('-', '/', date('m-d-Y'));
$two1 = strtotime($change);
$get = "SELECT * FROM events WHERE `midd` = '".$_SESSION['id']."' AND date='$two1'";
$got = mysqli_query($dbc, $get);
echo '<div class="overU">'.date('M-d-y h:i:s').'</div>';
$kk ="SELECT * FROM `invoices` WHERE `midd` = '".$_SESSION['id']."' ORDER BY `date` ASC ";
//end
$ff = mysqli_query($dbc, $kk);
$kk ="SELECT SUM(profits) AS overall FROM `invoices` WHERE `midd` = '".$_SESSION['id']."' AND `date` LIKE '%".(date('M'))."%'";
$kkk ="SELECT SUM(baldue) AS overalle FROM `invoices` WHERE `midd` = '".$_SESSION['id']."' AND `date` LIKE '%".(date('M'))."%'";
$ll = mysqli_query($dbc, $kk);
$jj = mysqli_query($dbc, $kkk);
$oj = mysqli_fetch_array($jj);
if(!$ll) {
die(mysqli_error($dbc));
}
$oo = mysqli_fetch_array($ll);
$what = $oo['overall'] - $oj['overalle'];
$fin = number_format($what, 2);
$finn = number_format($oj['overalle'], 2);
echo '<table class="overit" align="right">';//table for showing total profits
echo '<tr valign="top"><td>';
echo '<span class="eventg"><div class="ievent">Profits</div></span><br/>';
echo '<div><span class="newclass">'.date('M-Y').':</span><span class="nclass"> $'.$fin.'</span></div>';
echo '<div><span style="color:red; font-eight:bold;">Pending Balances:</span> $'.$finn.'</div>';
echo '</td></tr></table>';//end
$gun="SELECT * FROM inventory WHERE midd = '".$_SESSION['id']."'";
$gu = mysqli_query($dbc, $gun);
$g = mysqli_num_rows($gu);
echo '<table class="overitt" align="right">';//table for showing total profits
echo '<tr valign="top"><td>';
echo '<span class="eventg"><div class="ievent">Inventory</div></span>';
echo '<div class="over">'.$g.' - Items\'s in your inventory</div>';
$guun="SELECT * FROM inventory WHERE midd = '".$_SESSION['id']."' AND amount < '4'";
$guu = mysqli_query($dbc, $guun);
$count = mysqli_num_rows($guu);
echo '<div style="color:red; font-weight:bold;">You have:<span style="color:blue;"> '.$count.'</span> - Items\'s Low on inventory </div>';
while($gur = mysqli_fetch_array($guu)) {
echo '<div class="events"><span class="over">Product:</span> <span class="dif">'.$gur['name'].'</span><div class="rightinv">Quantity:'.$gur['amount'].'</div></div>';
}
echo '</td></tr></table>';//end
//date
echo '<div id="dateslide">';
echo '<div id="dateP"></div>';
echo '</div>';
echo '<div id="homePage">';
echo '<span class="eventg"><div class="ievent">Todays Events / Reminders:</div></span>';
echo '<ul id="ulevent">';
while($rees = mysqli_fetch_array($got)) {
$gdate = date('m-d-Y', $rees['date']);
echo '<div class="heventdate">'.$gdate.'<br/>';
echo '<span class="hevents">'.$rees['event'].'</span></div>';
}
echo '</ul>';
echo '</div>';
//end
$fag ="SELECT `invid` FROM `invoices` WHERE(`midd` = '".$_SESSION['id']."')ORDER BY invid DESC LIMIT 1";
$di ="SELECT `invid` FROM `invoices` WHERE(`baldue` > '0.00' AND `midd` ='".$_SESSION['id']."')";
$dii = mysqli_query($dbc, $di);
$fun = mysqli_query($dbc, $fag);
$num = mysqli_num_rows($dii);
echo '<div id="ahomePage1">';
echo '<ul id="homePage1"><span class="eventg"><div class="ievent">Invoices</div></span>';
$shib = mysqli_fetch_object($fun);
if($num > 0) {
echo '<li class="ievent">Invoices created:';
echo '<span class="dif">'.$shib->invid.'</span></li>';
}
echo '<li class="ievent" id="homenice">Pending balences:';
echo '<span class="dif">'.$num.'</span></li>';
$fart ="SELECT * FROM `invoices` WHERE(`baldue` > '0.00' AND `midd` = '".$_SESSION['id']."')";
$tard = mysqli_query($dbc, $fart);
while($jip = mysqli_fetch_array($tard)) {
$card = "SELECT `name` FROM customers WHERE invoice ='".$jip['invid']."' AND `mid`='".$_SESSION['id']."'";
$wild = mysqli_query($dbc, $card);
$ret = mysqli_fetch_object($wild);
echo '<p class="pending"><span class="dif">Invoice #'.$jip['invid'].':</span><span class="diff">';
echo '<a href="getContents.php?invvid='.$jip['invid'].'&id='.$_SESSION['id'].'">'.$ret->name.' - </a><br/>- Balance Due: $'.$jip['baldue'].'</span></p>';
}
echo '</ul>';
echo '</div>';
//end events
?>
<file_sep>/seemyBill.php
<?php
include('database_connection.php');
$invnum = $_GET['invvid'];
$custid=$_GET['id'];
$code = $_GET['code'];
$check ="SELECT * FROM `invoices` WHERE `invid`='$invnum' AND `midd`='$custid' AND `code`='$code'";
$cred = mysqli_query($dbc, $check);
if(!$cred) die(mysqli_error($dbc));
$check_cred = mysqli_num_rows($cred);
if($check_cred != 0) {
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w
3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<head>
<html xmlns="http://www.w3.org/1999/xhtml">
<title>Members Area</title>
<META http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<META http-equiv="Content-language" content="us-en" />
<title></title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
<script src="http://thebestbangforyourbuck.tk/gist/jquery/lib/jquery.js"></script>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.9.2/themes/base/jquery-ui.css" />
<script src="http://code.jquery.com/jquery-1.8.3.js"></script>
<script src="http://code.jquery.com/ui/1.9.2/jquery-ui.js"></script>
<script src="seemyBill.js"></script>
<meta content="text/css">
<link rel="stylesheet" type="text/ css" href="Cust1.css"></link>
<STYLE type="text/css" MEDIA="screen, projection">
<!--
@import url(Cust1.css);
-->
</STYLE>
<?php if(isset($_GET['id'])) {
$tom = "SELECT * FROM `members` WHERE `id` = '".$_GET['id']."'";
$delo = mysqli_query($dbc, $tom);
if(!$delo) die(mysqli_error($dbc));
$fart = mysqli_fetch_array($delo);
}
?>
<script>
function printInv() {
$("#print").hide();
window.print();
}
</script>
</head>
<body>
<a style="float:right;" id="print" href="#" onclick="printInv(); return false;">print</a>
<div id="slide"></div>
<div id="slides"></div>
<table id="center" align="center">
<tr valign="top">
<td id="centertd">
<div id="info">
<table id="invoice" align="left">
<tr valign="top">
<td>
<?php if(!$fart['img'] == '0'){ echo '<img class="img" src="http://invoice-masters.com/img/'.$fart['img'].'" height="200" width="250"/>';}?>
</td>
</tr>
</table><br/>
<table align="right" id="contact">
<tr valign="top">
<td id="con" class="colorr">
<span class="bname"><?echo($fart['Bname']);?></span><br/>
<span class="con">Phone:</span> <?echo($fart['phone']);?><br/>
<span class="con">Fax:</span> <?echo($fart['fax']);?><br/>
<span class="con">Address:</span> <?echo($fart['addr']);?><br/>
</td>
</tr>
</table><br/>
<table align="center" id="custable" class="colorr">
<tr valign="top">
<td id="icusttd" class="colorr">
<?php
$get = "SELECT `cust` FROM `invoices` WHERE `invid` = '".$_GET['invvid']."' AND `midd` = '".$_GET['id']."'";
$cget = mysqli_query($dbc, $get);
$gett = mysqli_fetch_object($cget);
echo($gett->cust);
?>
</td>
</tr>
</table><br/>
<div class="linee"><?echo($fart['slogan']);?>
</div>
<div class="line">
<div id="sel1" value="sel1" class="zzselect" onClick="selectProduct(1); return false;">Select Item</div><div id="enter1" class="zzenter" onClick="inputFeild(1); return false;" value="sel1">Enter An Item</div>
<?php
$get = "SELECT * FROM `invoices` WHERE `invid`='".$_GET['invvid']."' AND `midd` = '".$_GET['id']."' ";
$p ="SELECT * FROM `dataa` WHERE `invid`='".$_GET['invvid']."' AND `midd` = '".$_GET['id']."'";
$poop = mysqli_query($dbc, $get);
$ppoop = mysqli_query($dbc, $p);
while($vv = mysqli_fetch_array($ppoop)) {
$get = "SELECT * FROM `invoices` WHERE `invid`='".$_GET['invvid']."' AND `midd` = '".$_GET['id']."' ";
$p ="SELECT * FROM `dataa` WHERE `invid`='".$_GET['invvid']."' AND `midd` = '".$_GET['id']."' ";
$poop = mysqli_query($dbc, $get);
$ppoop = mysqli_query($dbc, $p);
while($vv = mysqli_fetch_array($ppoop)) {
for($i=1; $i<=12; $i++) {
if($vv['data'.$i.''] !='') {
echo '<div id="prohidden'.$i.'" class="sel1">'.$vv['data'.$i.''].'</div>';
echo '<input type="hidden" name="invid" id="invid1" value="'.$_GET['invvid'].'" />';
echo '<input type="hidden" name="pro'.$i.'" id="pro'.$i.'" value="'.$i.'"/>';
}
}
}
}
?>
</div>
<?php
$get_total = "SELECT `total` FROM `invoices` WHERE `midd`='".$_GET['id']."' AND `invid`='".$_GET['invvid']."'";
$got = mysqli_query($dbc, $get_total);
if(!$got) { die(mysqli_error($dbc)); }
else {
$num = mysqli_num_rows($got);
if($num > 0) {
$res = mysqli_fetch_object($got);
echo '<div id="div1">'.$res->total.'</div>';
}
else {
?>
<div id="div1">
</div>
<?php
}
}
?>
<div id="aroundFooter">
<button id="sub-button" class="button" name="sub-button" value="<?echo($_GET['id']);?>" onClick="Add(); return false;">Total</button><br/><br/><div id="total">
</div>
<div id="notes">
<input type="button" name="txt-button" id="txt-button" class="button" onClick="txt(); return false;" value="Okay" />
<span class="special">Special Notes:</span><br/>
<?php $ff = "SELECT * FROM `invoices` WHERE `midd` = '".$_GET['id']."' AND `invid` = '".$_GET['invvid']."' ";
$fag = mysqli_query($dbc, $ff);
if(!$fag) {
die(mysqli_error($dbc));
}
$tits = mysqli_fetch_array($fag);
if($tits['special'] =='') {
?>
<div id="asnotes">
<textarea cols="90" rows="6" WRAP="VIRTUAL" class="button" id="snotes">
</textarea>
</div>
<?
}
else {
echo ''.$tits['special'].'';
}
?>
</div>
<table align="left">
<tr valign="top">
<td >
<label id="disc">Disclaimer:
</label><br/>
<?php $go = "SELECT * FROM `members` WHERE `id`='".$_GET['id']."' ";
$get = mysqli_query($dbc, $go);
while($res = mysqli_fetch_array($get)) {
echo '<div id="ddisc" class="colorr">'.$res['disclaimer'].'</div><br/>';
}
?>
</td>
</tr>
</table>
<table style="float:left;">
<tr valing="top">
<td>
<input type="button" name="ready-button" id="ready" onClick="allReady(); return false;" class="button" value="Print"/>
</td>
<td>
<div id="sign">
<span style="color:red;" class="custsign">Customer Signiture[ X ]
</span>____________________________________
</div>
</td>
</tr>
</table>
<?php
$date = new DateTime('');
$date->add(new DateInterval('P0Y0M3DT0H0M0S'));
$date1 = $date->format('M-d-y') ."\n";
?>
<input type="hidden" id="dateinv" value="<?echo($date1);?>"/>
<input type="hidden" id="sid" value="<?echo($fart['id']);?>"/>
<input type="hidden" value="<?echo($_GET['invvid']);?>" id="saveinv" />
</div>
</body>
</html>
<?php
}
?>
<file_sep>/copy.php
<?php
include('database_connection.php');
ob_start();
session_start();
// Create a stream
$opts = array(
'http'=>array(
'method'=>"GET",
'header'=>"Accept-language: en\r\n",
)
);
$fileurll = 'img/page.php';
$fh = fopen($fileurll, "w");
$context = stream_context_create($opts);
// Open the file using the HTTP headers set above
$file = file_get_contents('http://invoice.com/'.$_GET['cachefile'].'', false, $context);
fwrite($fh, $file) or die(mysql_error());
fclose($fh);
?>
<file_sep>/img/poop_files/submitForm.js
function submitInv() {
var namee = document.getElementById('namee').value;
var altname = document.getElementById('altname').value;
var amount = document.getElementById('amount').value;
var price = document.getElementById('price').value;
var yprice = document.getElementById('yprice').value;
var desc = document.getElementById('desc').value;
var group = document.getElementById('group').value;
var midd = document.getElementById('midd').value;
var vendor = document.getElementById('vendor').value;
var labor = document.getElementById('labor').value;
var queryString = "?namee="+namee+"&altname="+altname+"&amount="+amount+"&price="+price+"&yprice="+yprice+"&desc="+desc+"&group="+group+"&midd="+midd+"&vendor="+vendor+"&labor="+labor;
http.open("GET", "query.php" +
queryString, true);
http.onreadystatechange = getHttpRes;
http.send(null);
}
function submitForm() {
var name = document.getElementById('name').value;
if(name == '') {
$("#hid").show();
document.getElementById('hid').focus();
}
else {
var lastname = document.getElementById('lastname').value;
var phone = document.getElementById('phone').value;
var wphone = document.getElementById('wphone').value;
var mid = document.getElementById('mid').value;
var date = document.getElementById('date').value;
var addr = document.getElementById('addr').value;
var email = document.getElementById('email').value;
var queryString = "?name="+name+"&lastname="+lastname+"&phone="+phone+"&wphone="+wphone+"&mid="+mid+"&date="+date+"&addr="+addr+"&email="+email;
http.open("GET", "query.php" +
queryString, true);
http.onreadystatechange = getHttpRes;
http.send(null);
}
}
function getHttpRes() {
if (http.readyState == 4) {
res = http.responseText; // These following lines get the response and update the page
document.getElementById('info').innerHTML = res;
}
}
function getXHTTP() {
var xhttp;
try { // The following "try" blocks get the XMLHTTP object for various browsers…
xhttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
xhttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e2) {
// This block handles Mozilla/Firefox browsers...
try {
xhttp = new XMLHttpRequest();
} catch (e3) {
xhttp = false;
}
}
}
return xhttp; // Return the XMLHTTP object
}
var http = getXHTTP(); // This executes when the page first loads.
<file_sep>/animate.js
function showInput() {
$(".hide_input").slideToggle("slow");
$(".hide_input").animate({left: "+850"}, "fast");
}
function showInputt() {
$(".hide_input").slideToggle("slow");
$(".hide_input").animate({left: "+850"}, "fast");
}
function date() {
}
<file_sep>/upInv.js
function showMe(index) {
$("#upinv"+index).show();
$("#delete"+index).show();
}
function slideInv(index) {
$(".ainvto").animate({opacity:"0.3"}, 600);
$(".DDgroup"+index).slideToggle("slow");
$("#invto"+index).removeClass('inventory').addClass('active');
$("#ainvto"+index).animate({opacity:"1.0"}, 600);
}
function deleteInv(index) {
var dat = "index="+index;
$.ajax({
url:"customer.php",
data:dat,
success:function(result) {
$(".invnum"+index).html(result);
},
});
}
function upInv(index) {
var tname = document.getElementById('tname'+index).value;
var taname = document.getElementById('taname'+index).value;
var tamount = document.getElementById('tamount'+index).value;
var tprice = document.getElementById('tprice'+index).value;
var tgroup = document.getElementById('tgroup'+index).value;
var tdesc = document.getElementById('tdesc'+index).value;
var typrice = document.getElementById('typrice'+index).value;
var tvendor = document.getElementById('tvendor'+index).value;
var tlabor = document.getElementById('tlabor'+index).value;
var squerrySstring = "?tname="+tname+"&taname="+taname+"&tamount="+tamount+"&tprice="+tprice+"&tgroup="+tgroup+"&tdesc="+tdesc+"&index="+index+"&typrice="+typrice+"&tvendor="+tvendor+"&tlabor="+tlabor;
http.open("GET", "customer.php" +
squerrySstring, true);
http.onreadystatechange = srgetHttpResss;
http.myCustomValue = index;
http.send(null);
$("#upinv"+index).hide();
}
function deleteMe(index) {
var dtname = document.getElementById('tname'+index).value;
var taname = document.getElementById('taname'+index).value;
var tamount = document.getElementById('tamount'+index).value;
var tprice = document.getElementById('tprice'+index).value;
var squerrySstring = "?dtname="+dtname+"&taname="+taname+"&tamount="+tamount+"&tprice="+tprice+"&index="+index;
http.open("GET", "customer.php" +
squerrySstring, true);
http.onreadystatechange = srgetHttpResss;
http.myCustomValue = index;
http.send(null);
$("#delete"+index).hide();
}
function srgetHttpResss() {
if (http.readyState == 4) {
reesss = http.responseText; // These following lines get the response and update the page
var index = http.myCustomValue;
document.getElementById('ppp').innerHTML = reesss;
}
}
function getXHTTP() {
var xhttp;
try { // The following "try" blocks get the XMLHTTP object for various browsers…
xhttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
xhttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e2) {
// This block handles Mozilla/Firefox browsers...
try {
xhttp = new XMLHttpRequest();
} catch (e3) {
xhttp = false;
}
}
}
return xhttp; // Return the XMLHTTP object
}
var http = getXHTTP(); // This executes when the page first loads.
<file_sep>/customer.php
<?
include('database_connection.php');
session_start();
ob_start();
?>
<? if(isset($_GET['id'])) {
//edit my jobs
$tran = "SELECT * FROM `jobs` WHERE `midd` = '".$_SESSION['id']."'";
$trans = mysqli_query($dbc, $tran);
if(!$trans) {
die(mysqli_error($dbc));
}
$check = mysqli_num_rows($trans);
if($check == 0) {
echo '<div style="color:red; font-weight:bold; text-align:center;">You have no jobs added yet. Click the "jobs" button above to create your first job!</div>';
}
else {
echo '<div class="invhead">Edit My Jobs</div>';
echo '<ul id="ajobs">';
while($res = mysqli_fetch_array($trans)) {
echo '<li span class="myJ" onClick="showMyJob('.$res['job num'].'); return false;">'.$res['Jname'].'';
echo '<input type="hidden" id="jobs'.$res['job num'].'" value="'.$res['job num'].'"/></li>';
}
echo '</ul>';
echo '<form id="bigtits" action="jobPhp.php" method="get">';
}
}
if(isset($_GET['jobNum'])) {
$trany = "SELECT * FROM `jobs` WHERE `midd` = '".$_SESSION['id']."' AND `job num` = '".$_GET['jobNum']."' ";
$transy = mysqli_query($dbc, $trany);
if(!$transy) {
die(mysqli_error($dbc));
}
while($ss = mysqli_fetch_array($transy)) {
$ll =$ss['job num'];
?>
<p class="pedit" style="color:red; text-align:center;"><span style="font-size:18px; font-weight:bold; color:blue;">** Edit My Jobs **</span><br/> Fill out the form bellow, When you are done: use the <span style="color:blue; text-transform:italic; text-decoration:italic;">Total Button</span>
to add up the total of the job and save your prices. Make sure you enter in a whole-sale price first so you will know how much money you will be making off the job. Don't click Add Job untill you have clicked Total.</p>
<table align="left" id="Jobtable" style="padding-top:10px;">
<tr valign="top">
<td id="Jmain" style="float:left">
<div id="formright" style="float:right;">
<input type="hidden" name="MIDD" id="MIDD" value="<?echo($ll);?>"/>
<label class="lblss">Job Name:</label><br/>
<input type="text" id="Jname" name="Jname" value="<?echo($ss['Jname']);?>" /><br/>
<label class="lblss">Job Group:</label><br/>
<input type="text" id="Jgroup" name="Jgroup" value="<?echo($ss['group']);?>"/><br/>
<label class="lblss">Job description:</label><br/>
<input type="text" id="Jdesc" name="Jdesc" value="<?echo($ss['Jdesc']);?>"/><br/>
<label class="lblss">Job Wholesale:</label><br/>
$<input type="text" id="Jwhole<?echo($ll);?>" size="7" name="Jwhole" value="<?echo($ss['Jwhole']);?>"/><br/>
<label type="text" class="lblss">Tax:</label><br/>
<?echo($_SESSION['tax']);?>%<br/>
</td>
<td id="par">
<div id="formright" style="float:right;">
<?
for($i=1; $i<11; $i++) {
echo '<label class="lbls">Parts Item #1:</label><br/>';
echo '<input type="text" id="Jquan'.$i.''.$ll.'" name="Jquan'.$i.'" value="'.$ss['Jquan'.$i.''].'" size="1">';
echo '$<input type="text" id="jparts'.$i.''.$ll.'" name="jparts'.$i.'" value="'.$ss['jparts'.$i.''].'" size="5">';
echo '<input type="text" id="Jparts'.$i.'" name="Jparts'.$i.'" value="'.$ss['Jpart'.$i.''].'"/><br/>';
}
?>
</td>
<td style="float:right; padding-bottom:210px;" id="lab">
<label class="lbls">Labor #1:</label><br/>
$<input type="text" id="jlabor1<?echo($ll);?>" name="jlabor1" value="<?echo($ss['jjlabor1']);?>" size="5">
<input type="text" id="Jlabor1" name="Jlabor1" value="<?echo($ss['Jlabor1']);?>" /><br/>
<label class="lbls">Labor #2:</label><br/>
$<input type="text" id="jlabor2<?echo($ll);?>" name="jlabor2" value="<?echo($ss['jjlabor2']);?>" size="5">
<input type="text" id="Jlabor2" name="Jlabor2" value="<?echo($ss['Jlabor2']);?>" /><br/>
<label class="lbls">Labor #3:</label><br/>
$<input type="text" id="jlabor3<?echo($ll);?>" name="jlabor3" value="<?echo($ss['jjlabor3']);?>" size="5">
<input type="text" id="Jlabor3" name="Jlabor3" value="<?echo($ss['Jlabor3']);?>" /><br/>
<label class="lbls">Labor #4:</label><br/>
$<input type="text" id="jlabor4<?echo($ll);?>" name="jlabor4" value="<?echo($ss['jjlabor4']);?>" size="5">
<input type="text" id="Jlabor4" name="Jlabor4" value="<?echo($ss['Jlabor4']);?>" /><br/>
<label class="lbls">Labor #5:</label><br/>
$<input type="text" id="jlabor5<?echo($ll);?>" name="jlabor5" value="<?echo($ss['jjlabor5']);?>" size="5">
<input type="text" id="Jlabor5" name="Jlabor5" value="<?echo($ss['Jlabor5']);?>" /><br/><br/>
<div id="Jstotals"></div>
<input type="submit" id="Jsend" value="Update" name="submit"/>
</div>
</form>
<input type="submit" id="Jadd" value="Update Total" onClick="addjForm(<?echo($ss['job num']);?>); return false"/><br/><br/>
<input type="submit" id="del" value="Delete" onClick="addDelete(<?echo($ss['job num']);?>); return false"/><br/><br/>
</tr>
</td>
</table>
<?
//endedit
}
}
//customer callback from members.php
if(isset($_GET['iddd'])) {
$dis = "SELECT DISTINCT name FROM customers WHERE mid='".$_SESSION['id']."'";
$dist = mysqli_query($dbc, $dis);
if(!$dist) die(mysqli_error($dbc));
$nuum = mysqli_num_rows($dist);
if($nuum == 0) {
echo '<div style="color:red; font-weight:bold; text-align:center;">You have no customers yet! Click the invoice button to the left to start your first invoice and save your first customer.</div>';
}
$i=1;
echo '<div id="customer">My Customers</div>';
while($car = mysqli_fetch_array($dist)) {
$get = "SELECT * FROM `customers` WHERE `mid` = '".$_SESSION['id']."' AND `name` = '".$car['name']."' ORDER by `name` ASC ";
$result = mysqli_query($dbc, $get);
$count = mysqli_num_rows($result);
$custt = mysqli_fetch_array($result);
echo '<div class="acustslide">';
echo '<span class="custslide"><span class="namesC">Customer:</span> <span class="hcustn">'.$car['name'].'</span></span>';
echo '<span class="custslide"><span class="namesC">Lastname:</span><span class="hcustn">'.$custt['lastname'].'</span></span>';
echo '<div class="counti"><span id="hcust'.$i.'" onclick="showCust('.$i.'); return false;"><span class="namesC">'.$count.' invoice(s) <input type="button" class="viewinv" value="view"/></span></div><br/>';
echo '</div>';
echo '<table class="idddtable" id="hhcust'.$i.'" align="left"><tr valign="top">';
$geet = "SELECT * FROM `customers` WHERE `mid` = '".$_SESSION['id']."' AND `name` = '".$car['name']."' ORDER by `name` ASC ";
$reesult = mysqli_query($dbc, $geet);
while($cust = mysqli_fetch_array($reesult)) {
$grab ="SELECT `code` FROM `invoices` WHERE `midd`='".$cust['mid']."' AND `invid`='".$cust['invoice']."'";
$crap=mysqli_query($dbc, $grab); if(!$grab) die(mysqli_error($dbc));
$code=mysqli_fetch_object($crap);
echo '<tr valign="top"><td><span class="names'.$cust['id'].'" class="names">Customer:</span><br/><input type="text" id="tnaame'.$cust['id'].'" size="12" onClick="showMee('.$cust['id'].'); return false;" class="blend" value="'.$cust['name'].'"/></td><td>';
echo '<span class="names">Last Name:</span><br/><input type="text" id="tlast'.$cust['id'].'" size="12" onClick="showMee('.$cust['id'].'); return false;" class="blend" value="'.$cust['lastname'].'"/></td>';
echo '<td><span class="names">Phone:</span><br/><input type="text" id="tphone'.$cust['id'].'" size="12" onClick="showMee('.$cust['id'].'); return false;" class="blend" value="'.$cust['phone'].'"/></td>';
echo '<td><span class="names">Work Phone:</span><br/><input type="text" id="twphone'.$cust['id'].'" size="12" onClick="showMee('.$cust['id'].'); return false;" class="blend" value="'.$cust['wphone'].'"/> </td>';
echo '<td><span class="names">Address:</span><br/><input type="text" id="taddr'.$cust['id'].'" size="12" onClick="showMee('.$cust['id'].'); return false;" class="blend" value="'.$cust['addr'].'"/> </td>';
echo '<td><span class="names">Date:</span><br/><input type="text" id="tdate'.$cust['id'].'" size="12" onClick="showMee('.$cust['id'].'); return false;" class="blend" value="'.$cust['date'].'"/></td>';
echo '<td><span class="names">Email:</span><br/><input type="text" id="temail'.$cust['id'].'" size="12" onClick="showMee('.$cust['id'].'); return false;" class="blend" value="'.$cust['email'].'" /></td>';
echo '<input type="hidden" name="inv#" id="Cinv'.$cust['id'].'" value="'.$cust['invoice'].'" />';
echo '<td><a href="#" class="hidebutton" name="upCust" id="upCust'.$cust['id'].'" onclick="upCust('.$cust['id'].'); return false;">Update</a><br/><a href="#" class="hidebutton" name="delete" id="Cdelete'.$cust['id'].'" onclick="CdeleteMe('.$cust['id'].'); return false;">Delete</a></td>';
echo '<td><span class="names">Invoice#'.$cust['invoice'].'</span><br/><form action="getContents.php" method="GET">';
echo '<input type="hidden" id="id" value="'.$_SESSION['id'].'" name="id"/><input type="hidden" value="'.$code->code.'" name="code"/><input type="hidden" name="invvid" value="'.$cust['invoice'].'"/><input type="submit" name="Submit" value="view" id="submit"/></form></td></tr>';
}
echo '</tr></table></span>';
$i++;
}
}
//end
//inventory callback from members.php
if(isset($_GET['idddd'])) {
$chump = "SELECT distinct `group` FROM `inventory` WHERE `midd` ='".$_SESSION['id']."'";
$chimp = mysqli_query($dbc, $chump);
if(!$chimp) die(mysqli_error($dbc));
echo '<div class="invhead">My Inventory</div>';
echo '<label class="dif">Search:</label><input type="text" id="Sinventory"/><input type="submit" value="Go" onClick="sInventory(); return false;"/><br/><br/>';//searchme.js
$i=1;
echo '<div id="inva"><div class="albl">Groups</div></div>';
while($hu = mysqli_fetch_array($chimp)) {
if($hu['group'] != '') {
$get = "SELECT * FROM `inventory` WHERE `midd`='".$_SESSION['id']."' AND `group`='".$hu['group']."'";
$result = mysqli_query($dbc, $get); if(!$result) die(mysqli_error($dbc));
echo '<div class="ainvto" id="ainvto'.$i.'"><div class="inventory" id="invto'.$i.'" onClick="slideInv('.$i.'); return false;">'.$hu['group'].'</div></div>';
$s = 1;
while($cust = mysqli_fetch_array($result)) {
echo '<div class="DDgroup'.$i.'" id="Dgroup">';
echo '<div class="ainventable">';
echo '<table class="inventable" align="center">';
echo '<div id="ppp"></div>';
echo '<tr valign="top">';
echo '<td><span class="names" id=hippie">Name:<br/></span><input type="text" id="tname'.$cust['id'].'" onClick="showMe('.$cust['id'].'); return false;" value="'.$cust['name'].'" class="blend" size="9"/></td><td><span class="names">Part Number:<br/></span><input type="text" onClick="showMe('.$cust['id'].'); return false;" id="taname'.$cust['id'].'" value="'.$cust['altname'].'" class="blend" size="12" /></td>';
echo '<td><span class="names">Quantity:<br/></span><input type="text" onClick="showMe('.$cust['id'].'); return false;" id="tamount'.$cust['id'].'" value="'.$cust['amount'].'" class="blend" size="9"/></td>';
echo '<td><span class="names">Retail:<br/></span>$<input onClick="showMe('.$cust['id'].'); return false;" type="text" id="tprice'.$cust['id'].'" value="'.$cust['price'].'" class="blend" size="6"/></td>';
echo '<td><span class="names">Labor:<br/></span>$<input onClick="showMe('.$cust['id'].'); return false;" type="text" id="tlabor'.$cust['id'].'" value="'.$cust['lprice'].'" class="blend" size="6"/></td>';
echo '<td><span class="names">Wholesale:<br/></span>$<input onClick="showMe('.$cust['id'].'); return false;" type="text" id="typrice'.$cust['id'].'" value="'.$cust['yprice'].'" class="blend" size="6"/></td>';
echo '<td><span class="names">Vendor:<br/></span><input onClick="showMe('.$cust['id'].'); return false;" type="text" id="tvendor'.$cust['id'].'" value="'.$cust['vendor'].'" class="blend" size="8"/></td>';
echo '<td><span class="names">Group:<br/></span><input type="text" id="tgroup'.$cust['id'].'" onClick="showMe('.$cust['id'].'); return false;" value="'.$cust['group'].'" class="blend" size="9" /></td>';
echo '<td><span class="names">Description:<br/></span><input type="text" onClick="showMe('.$cust['id'].'); return false;" id="tdesc'.$cust['id'].'" value="'.$cust['desc'].'" class="blend" size="10" /></td>';
echo '<td><a href="#" class="hidebutton" name="upCust" id="upinv'.$cust['id'].'" onclick="upInv('.$cust['id'].'); return false;">Update</a><br/>';
echo '<a href="#" class="hidebutton" name="delete" id="delete'.$cust['id'].'" onclick="deleteMe('.$cust['id'].'); return false;">Delete</a></td>';
echo '</tr></table>';
echo '</div>';
echo '</div>';
$s++;
}
$i++;
}
echo '</div>';
}
}
//end
//update inventory items
if(isset($_GET['tname'])) {
$name = $_GET['tname'];
$taname = $_GET['taname'];
$tamount = $_GET['tamount'];
$tprice = $_GET['tprice'];
$tgroup = $_GET['tgroup'];
$tdesc = $_GET['tdesc'];
$index = $_GET['index'];
$yprice = $_GET['typrice'];
$vendor = $_GET['tvendor'];
$tlabor = $_GET['tlabor'];
$insert = "UPDATE `inventory` SET `name` = '".mysql_real_escape_string($name)."', `altname` = '".mysql_real_escape_string($taname)."', `amount` = '".mysql_real_escape_string($tamount)."', `price` = '".mysql_real_escape_string($tprice)."', `group` = '".mysql_real_escape_string($tgroup)."', `desc` = '".mysql_real_escape_string($tdesc)."', `yprice` ='".mysql_real_escape_string($yprice)."', `vendor` ='".mysql_real_escape_string($vendor)."', `lprice`='".mysql_real_escape_string($tlabor)."' WHERE `id` = '".mysql_real_escape_string($index)."'";
$inser = mysqli_query($dbc, $insert);
if(!$inser) {
echo 'Failed';
}
else {
echo 'Updated';
}
}
//end
//delete inventory
if(isset($_GET['dtname'])) {
$name = $_GET['dtname'];
$taname = $_GET['taname'];
$tamount = $_GET['tamount'];
$tprice = $_GET['tprice'];
$index = $_GET['index'];
$del = "DELETE FROM `inventory` WHERE `name` = '".$name."' AND `altname` = '".$taname."' AND `amount` = '".$tamount."' AND `price` = '".$tprice."' AND `midd` = '".$_SESSION['id']."'";
$delete=mysqli_query($dbc, $del);
if(!$delete) {
die(mysqli_error($dbc));
}
else {
echo 'Deleted';
}
}
//end
//delete customer && invoice
if(isset($_GET['Ftnaame'])) {
$naame = $_GET['Ftnaame'];
$tlast = $_GET['tlast'];
$tphone = $_GET['tphone'];
$twphone = $_GET['twphone'];
$taddr = $_GET['taddr'];
$tdate = $_GET['tdate'];
$temail = $_GET['temail'];
$index = $_GET['index'];
$invid = $_GET['Cinv'];
$insert = "DELETE FROM `customers` WHERE `invoice` ='".$invid."' AND `mid` = '".$_SESSION['id']."'";
$inser = mysqli_query($dbc, $insert);
if(!$inser) {
die(mysqli_error($dbc));
}
else {
$remove = "DELETE FROM `invoices` WHERE `midd` = '".$_SESSION['id']."' AND `invid` = '".$invid."'";
$done = mysqli_query($dbc, $remove);
if(!$done) {
die(mysqli_error($dbc));
}
$removeD = "DELETE FROM `dataa` WHERE `midd` = '".$_SESSION['id']."' AND `invid` = '".$invid."'";
$doneD = mysqli_query($dbc, $removeD);
if(!$doneD) {
die(mysqli_error($dbc));
}
else {
echo '<span stlye="color:blue;">Deleted</span>';
}
}
}
//end
if(isset($_GET['index'])) {
$invid = $_GET['index'];
$insert = "DELETE FROM `customers` WHERE `invoice` ='".$invid."' AND `mid` = '".$_SESSION['id']."'";
$inser = mysqli_query($dbc, $insert);
if(!$inser) {
die(mysqli_error($dbc));
}
else {
$remove = "DELETE FROM `invoices` WHERE `midd` = '".$_SESSION['id']."' AND `invid` = '".$invid."'";
$done = mysqli_query($dbc, $remove);
if(!$done) {
die(mysqli_error($dbc));
}
$removeD = "DELETE FROM `dataa` WHERE `midd` = '".$_SESSION['id']."' AND `invid` = '".$invid."'";
$doneD = mysqli_query($dbc, $removeD);
if(!$doneD) {
die(mysqli_error($dbc));
}
else {
echo '<span stlye="color:red;">Deleted</span>';
}
}
}
//delete invoice if they which ** from invoices callback ** upinv.js
//
//update customer info
if(isset($_GET['tnaame'])) {
$naame = $_GET['tnaame'];
$tlast = $_GET['tlast'];
$tphone = $_GET['tphone'];
$twphone = $_GET['twphone'];
$taddr = $_GET['taddr'];
$tdate = $_GET['tdate'];
$temail = $_GET['temail'];
$index = $_GET['index'];
$insert = "UPDATE `customers` SET `name` = '".mysql_real_escape_string($naame)."', `lastname` = '".mysql_real_escape_string($tlast)."', `phone` = '".mysql_real_escape_string($tphone)."', `wphone` = '".mysql_real_escape_string($twphone)."', `addr` = '".mysql_real_escape_string($taddr)."', `date` = '".mysql_real_escape_string($tdate)."', `email` = '".mysql_real_escape_string($temail)."' WHERE `id` = '".mysql_real_escape_string($index)."'";
$inser = mysqli_query($dbc, $insert);
if(!$inser) {
die(mysqli_error($dbc));
}
else {
echo 'Updated';
}
}
//end
//invoices callback for viewing
if(isset($_GET['inv'])) {
$get = "SELECT * FROM `invoices` WHERE `midd` = '".$_SESSION['id']."' ORDER BY `invid` DESC";
$result = mysqli_query($dbc, $get);
$nuum = mysqli_num_rows($result);
if($nuum == 0) {
echo '<div style="color:red; font-weight:bold; text-align:center;">You have no invoices yet! Click the invoice button on the left to create your first invoice!</div>';
}
if($result) {
echo '<div class="invhead">Invoices</div>';
echo '<table id="idddtable" align="left">';
echo '<tr valign="top"><td class="invlist"><span class="namesI">Customer:</td>';
echo '<td class="invlist"><span class="namesI">Total:</td>';
echo '<td class="invlist"><span class="namesI">Balance Due:</td>';
echo '<td class="invlist"><span class="namesI">Deposit:</td>';
echo '<td class="invlist"><span class="namesI">Date:</td>';
echo '<td class="invlist"><span class="namesI">Invoice #:</td>';
while($cust = mysqli_fetch_array($result)) {
if($cust['date'] != '' AND $cust['cust'] != '') { //if the invoie is not blank show
$HH = "SELECT * FROM `customers` WHERE `mid` = '".$_SESSION['id']."' AND `invoice` = '".$cust['invid']."'";
$hh = mysqli_query($dbc, $HH);
$ff = mysqli_fetch_array($hh);
$gg = number_format($cust['baldue'], 2);
echo '<tr valign="top"><td class="moreiddd" id="moreiddd'.$cust['invid'].'" onclick="showCustomer('.$cust['invid'].'); return false;">'.$ff['name'].'</td>';
echo '<td class="idddtd">$'.$cust['totsale'].'</td>';
if($gg > 0.00) {
echo '<td style="color:red; background-color:#99F195; font-size:14px; text-align:center;"><span style="font-size:15px; font-weight:bold;"> $'.$gg.'</span></td>';
}
else {
echo '<td class="idddtd">$'.$gg.'</td>';
}
if($cust['deposit'] == '') {
echo '<td class="idddtd">$0.00</td>';
}
else {
echo '<td class="idddtd">$'.$cust['deposit'].'</td>';
}
echo '<td class="idddtd"><span style="color:blue; font-size:14px;">'.$ff['date'].'</span></td>';
echo '<td class="idddtd"><span class="names">#'.$cust['invid'].'</span><br/>';
echo '<div class="aclick"><a href="getContents.php?invvid='.$cust['invid'].'&id='.$_SESSION['id'].'&code='.$cust['code'].'">View</a> |';
echo ' <a href="#" class="invnum'.$cust['invid'].'" onClick="deleteInv('.$cust['invid'].'); return false;">Delete</a> |';
echo ' <a href="#" class="invsnotes" id="aainv'.$cust['invid'].'" onclick="sinvNotes('.$cust['invid'].'); return false;">Comment</a></div></td>';
echo '<td class="invnotes" id="invsnotes'.$cust['invid'].'"><label>Write a Note / Comment.</label><br/><textarea class="invtnotes'.$cust['invid'].'" cols="15" rows="6" WRAP="VIRTUAL">'.$cust['comments'].'</textarea><input type="button" onclick="sinvNotes('.$cust['invid'].'); return false;" value="send"/></td></tr>';
}
}
echo '</table>';
}
}
//end
if(isset($_GET['profits'])) {
echo '<div class="invhead">My Profits</div>';
$Jan ="SELECT SUM(profits) AS Jtot FROM `invoices` WHERE `midd` ='".$_SESSION['id']."' AND `date` LIKE '%".('jan')."%'";
$how = "SELECT * FROM `invoices` WHERE `midd` ='".$_SESSION['id']."' AND `date` LIKE '%".(date('M'))."%'";
$tod ="SELECT SUM(profits) AS today FROM `invoices` WHERE `midd` = '".$_SESSION['id']."' AND `date` LIKE '%".(date('M-d-y'))."%'";
$kkk ="SELECT SUM(baldue) AS overalle FROM `invoices` WHERE `midd` = '".$_SESSION['id']."' AND `date` LIKE '%".(date('M'))."%'";
$jj = mysqli_query($dbc, $tod);
$fin = mysqli_query($dbc, $kkk);
$find = mysqli_fetch_array($fin);
$finn = number_format($find['overalle'], 2);
$toda = mysqli_query($dbc, $tod);
$todayy = mysqli_fetch_array($toda);
$today = number_format($todayy['today'], 2);
$res = mysqli_query($dbc, $how);
$result = mysqli_num_rows($res);
$Janu = mysqli_query($dbc, $Jan); if(!$Janu) die(mysqli_error($dbc));
echo '<ul id="ulprof">';
echo '<li class="itemp">January-2013:</span><br/>';
while($FUCK = mysqli_fetch_array($Janu)) {
$fin = number_format($FUCK['Jtot'], 2);
echo '<span class="itemn">- $'.$fin.'</span><br/>';
echo '<span class="itemn">- Balances Pending: $'.$finn.'</span><br/>';
echo '<span class="itemn">- Today: $'.$today.'</span><br/>';
echo '<span class="itemn">- Invoices Created: '.$result.'</span>';
}
echo '</li>';
echo '<li class="itemp">February</li>';
echo '<li class="itemp">March</li>';
echo '<li class="itemp">Aprill</li>';
echo '<li class="itemp">May</li>';
echo '<li class="itemp">June</li>';
echo '<li class="itemp">July</li>';
echo '<li class="itemp">August</li>';
echo '<li class="itemp">September</li>';
echo '<li class="itemp">October</li>';
echo '<li class="itemp">November</li>';
echo '<li class="itemp">December</li>';
echo '</ul>';
}
// my vendors
if(isset($_GET['vendors'])) {
echo '<div class="invhead">My Vendors</div>';
$id = $_SESSION['id'];
$ven = "SELECT distinct `vendor` FROM `inventory` WHERE `midd` ='$id'";
$vend = mysqli_query($dbc, $ven);
if(!$vend) {
die(mysqli_error($dbc));
}
$nuum = mysqli_num_rows($vend);
if($nuum < 1) {
echo '<div style="color:red; font-weight:bold; text-align:center;">You have no vendors yet! Type in your vendors when you add inventory!</div>';
}
$i=1;
while($cust = mysqli_fetch_array($vend)) {
echo '<div class="invhead'.$i.'" id="invhead" onCLick="showVen('.$i.'); return false;">'.$cust['vendor'].'</div>';
echo '<div class="vvdiv" id="vvid'.$i.'">';
$tits = "SELECT * FROM `inventory` WHERE `vendor` = '".$cust['vendor']."' AND midd = '".$_SESSION['id']."'";
$fag = mysqli_query($dbc, $tits);
while($rr = mysqli_fetch_array($fag)) {
$tits1 = "SELECT * FROM `inventory` WHERE `vendor` != '".$rr['vendor']."' AND `name` = '".$rr['name']."'";
$fag1 = mysqli_query($dbc, $tits1);
if(!$fag1) die(mysqli_error($dbc));
$rows = mysqli_num_rows($fag1);
$col = mysqli_fetch_array($fag1);
$pro = $rr['price'] - $rr['yprice'];
$prof = number_format($pro, 2);
if($rows != 0 ) {
echo '<table align="left" style="float:right; width:520px;" class="vendordata"><tr valign="top" class="match">';
echo '<td class="floater"><span class="namesV">Vendor:</span><br/>'.$col['vendor'].'</td>';
echo '<td><span class="namesV">Product:</span><br/>'.$col['name'].'</td>';
echo '<td><span class="namesV">Part #:</span><br/>'.$rr['altname'].'</td>';
echo '<td><span class="namesV">Retail:</span><br/>$'.$rr['price'].'</td>';
echo '<td><span class="namesV">Wholesale:</span><br/>$'.$rr['yprice'].'</td></tr>';
echo '</tr></table>';
}
echo '<table class="vendordata" ><tr valign="top">';
echo '<td class="Vdata"><span class="names">Product:</span><br/>'.$rr['name'].'</td>';
echo '<td><span class="names">Part #:</span><br/>'.$rr['altname'].'</td>';
echo '<td><span class="names">Retail:</span><br/>$'.$rr['price'].'</td>';
echo '<td><span class="names">Wholesale:</span><br/>$'.$rr['yprice'].'</td>';
echo '<td><span class="names">Profit:</span><br/>$'.$prof.'</td></tr>';
echo '</table>';
}
echo '</div>';
$i++;
}
}
//end
if(isset($_GET['tits'])) {
$tits1 = "SELECT * FROM `inventory` WHERE `group` = '".$_GET['tits']."' AND `midd`='".$_SESSION['id']."'";
$fag1 = mysqli_query($dbc, $tits1);
if(!$fag1) die(mysqli_error($dbc));
echo '<table align="center" id="jizztable">';
while($col = mysqli_fetch_array($fag1)) {
echo '<tr><td class="Jtd"><span class="namesS">Item:</span> '.$col['name'].'<br/>';
echo '<span class="names">Price:</span> $'.$col['price'].'<br/>';
echo '<span class="names">Wholesale:</span> $'.$col['yprice'].'<br/>';
echo '<span class="names">Description:</span> '.$col['desc'].'<br/></td></tr>';
}
echo '</table>';
}
//produts hover file jizzEm.js
if(isset($_GET['titss'])) {
$tits1 = "SELECT * FROM `inventory` WHERE `id`='".$_GET['titss']."'";
$fag1 = mysqli_query($dbc, $tits1);
if(!$fag1) {
die(mysqli_error($dbc));
}
echo '<table align="center" id="jizztable">';
echo '<div class="closepop" onclick="closePop(); return false;">[close]</div>';
while($col = mysqli_fetch_array($fag1)) {
echo '<tr><td class="Jtd"><span class="JOB">Item: '.$col['name'].'</span><br/>';
echo '<span class="namesS">Price:</span> $'.$col['price'].'<br/>';
echo '<span class="namesS">Labor:</span> $'.$col['lprice'].'<br/>';
echo '<span class="namesS">Wholesale:</span> $'.$col['yprice'].'<br/>';
echo '<span class="namesS">Description:</span> '.$col['desc'].'<br/></td></tr>';
}
echo '</table><br/>';
}
//end
// get jobs hover file:jizzEm.js
if(isset($_GET['job'])) {
$tits1 = "SELECT * FROM `jobs` WHERE `job num`='".$_GET['job']."' AND `midd`='".$_SESSION['id']."'";
$fag1 = mysqli_query($dbc, $tits1);
if(!$fag1) {
die(mysqli_error($dbc));
}
echo '<table align="center" id="jizztable">';
echo '<div class="closepop" onclick="closePop(); return false;">[close]</div>';
while($col = mysqli_fetch_array($fag1)) {
echo '<tr><td class="Jtd"><span class="JOB">Job: '.$col['Jname'].'</span><br/>';
echo '<span class="namesS">Price: $'.$col['Jtotal'].'</span><br/>';
echo '<span class="namesS">Wholesale: $'.$col['Jwhole'].'</span><br/>';
echo '<span class="namesS">Description: '.$col['Jdesc'].'</span><br/>';
for($i=1; $i<=10; $i++) {
if($col['Jpart'.$i.''] != '' && $col['jparts'.$i.''] !='0.00') {
echo '<span class="partsS">Part #'.$i.': '.$col['Jpart'.$i.''].'</span> <br/>';
echo '<span class="pricesS">Price: $'.$col['jparts'.$i.''].'</span><br/>';
}
}
for($b=1; $b<6; $b++) {
if($col['Jlabor'.$b.''] != '' && $col['jjlabor'.$b.''] !='') {
echo '<span class="lpartsS">Labor #'.$b.': '.$col['Jlabor'.$b.''].'</span> <br/>';
echo '<span class="lpricesS">Price: $'.$col['jjlabor'.$b.''].'</span><br/>';
}
}
echo '</td></tr>';
}
echo '</table><br/>';
}
// edit invoice ** customer information
if(isset($_GET['invid'])) {
?>
<form action="" method="GET" id="custform">
<input type="text" name="iname" id="iname" onClick="runTime(); return false;"/>
<label class="lbl">Customer Name:</label><br/>
<span id="getauto">
<input type="text" name="ilast name" id="ilastname"/>
<label class="lbl">Last Name:</label><br/>
<input type="text" name="iphone" id="iphone"/>
<label class="lbl">Phone:</label><br/>
<input type="text" name="iwphone" id="iwphone"/>
<label class="lbl">Work Phone:</label><br/>
<input type="text" name="iaddr" id="iaddr"/>
<label class="lbl">Address</label><br/>
<input type="text" name="iemail" id="iemail"/>
<label class="lbl">E-mail</label><br/>
</span>
<input type="hidden" name="imid" id="imid" value="<? echo($_SESSION['id']);?>"/>
<input type="hidden" name="invidd" id="invidd" value="<?$_GET['invid']?>" />
<input type="hidden" name="idate" id="idate" value=""/>
<input type="submit" name="submit" id="icust-submit" onclick="iSubmitForm(<?echo($_GET['invid']);?>); return false;" value="submit"/>
</form>
<?
}
//end
//upcoming events
if(isset($_GET['events'])) {
$get ="SELECT * FROM events WHERE midd = '".$_SESSION['id']."'";
$got = mysqli_query($dbc, $get);
$amount = mysqli_num_rows($got);
if(!$got) die(mysqli_error($dbc));
$cock ="SELECT DISTINCT date FROM events WHERE midd = '".$_SESSION['id']."'";
$gg = mysqli_query($dbc, $cock);
if(!$gg) die(mysqli_error($dbc));
if($amount == 0) {
echo '<div class="invhead">You have no events for today.</div>';
}
else {
echo '<div class="invhead">My Events / Reminders.</div>';
}
echo '<div id="atitle"><div id="aup">Upcoming Events / Reminders</div><div id="addE">Ad Event / Reminder</div></div><br/>';
echo '<table id="upcome" alig="left">';
echo '<tr valign="top">';
echo '<td id="upcoming">';
while($jj = mysqli_fetch_array($gg)) {
$rees = mysqli_fetch_array($got);
$date = $jj['date'];//change date format
$one = date( 'm-d-Y', $jj['date']);
$gdate = str_replace('-', '/', date('m-d-Y'));
$two = strtotime($gdate);
if($date > $two){
echo '<li class="upcoming" onClick="getEvent('.$rees['id'].'); return false;">'.$one.'</li>';
}
}
echo '</td></tr></table>';
$gdaate = str_replace('-', '/', date('m-d-Y'));
$twoo = strtotime($gdaate);
$geet ="SELECT * FROM events WHERE midd = '".$_SESSION['id']."' ORDER BY date ASC LIMIT 1";
$geg = mysqli_query($dbc, $geet);
if(!$geg) die(mysqli_error($dbc));
$how = mysqli_fetch_array($geg);
if($twoo > $how['date']) {
echo '<a style="padding-left:350px;" href="#" onClick="getEvent(010); return false;" >View past Events / Reminders</a>';
}
//end
//add event
echo '<table id="addevent" align="center">';
echo '<tr valign="top">';
echo '<td id="apickdate">';
echo '<label class="eventlbl">Reminder:</label><br/>';
echo '<textarea cols="40" rows="3" id="event" wrap="virtual"></textarea><br/>';
echo '<label class="eventlbl">Date:</label><br/>';
echo '<input type="text" id="datepicker" onmouseover="datePicker(); return false;"/>';
echo '<input type="submit" id="send-event" value="Set" onclick="setEvent(); return false";/>';
echo '<div class="done"></div>';
echo '</td></tr></table><br/>';
$geet ="SELECT * FROM events WHERE midd = '".$_SESSION['id']."' AND `date`='$twoo' ";
$goot = mysqli_query($dbc, $geet);
echo '<table id="eventbl" align="left">';
echo '<tr valign="top"><td class="event">My Events / Reminders:</td></tr><br/>';
while($rees = mysqli_fetch_array($goot)) {
$onee = date( 'm-d-Y', $rees['date']);
echo '<tr valign="top">';
echo '<td class="events">'.$rees['event'].'';
echo '<div class="eventdate">'.$onee.'</div></td>';
echo '</tr>';
}
echo '</table>';
echo '<div id="titsm"></div>';
}
//end
//insert event into database
if(isset($_GET['event'])) {
$event = mysql_real_escape_string($_GET['event']);
$date = strtotime($_GET['date']);
$select = "SELECT `id` FROM `events` WHERE `midd` = '".$_SESSION['id']."' ORDER BY `id` DESC LIMIT 1";
$for = mysqli_query($dbc, $select);
$ob = mysqli_fetch_object($for);
$row = mysqli_num_rows($for);
if($row == 0) {
$fuck = 1;
}
else {
$fuck = $ob->id + 1;
}
$go ="INSERT INTO events(midd, event, date, id) VALUES ('".$_SESSION['id']."', '$event', '$date', '$fuck')";
$result = mysqli_query($dbc, $go);
if(!$go) {
die(mysqli_error($dbc));
}
else {
echo 'Your event has been added';
}
}
if(isset($_GET['eventId'])) {
$event = $_GET['eventId'];
if($event == 010) {
$gdaate = str_replace('-', '/', date('m-d-Y'));
$twoo = strtotime($gdaate);
$geet ="SELECT * FROM events WHERE midd = '".$_SESSION['id']."' AND `date` < '$twoo' ORDER BY date DESC";
$geg = mysqli_query($dbc, $geet);
if(!$geg) die(mysqli_error($dbc));
echo '<table align="center"><tr valign="top"><td class="event">Previous Events / Reminders</td></tr><br/>';
while($sa = mysqli_fetch_array($geg)) {
echo '<tr><td class="events">'.$sa['event'].'</td>';
$haha = date('m-d-Y', $sa['date']);
echo '<td><div class="eventdate">'.$haha.'</div></td></tr>';
}
echo '</table>';
}
else {
$food ="SELECT * FROM `events` WHERE `midd` = '".$_SESSION['id']."' AND `id` = '".$_GET['eventId']."' LIMIT 1";
$doo = mysqli_query($dbc, $food);
if(!$doo) {
die(mysqli_error($dbc));
}
else {
echo '<tr valign="top"><td class="event">Upcoming Events / Reminders</td></tr><br/>';
$pro = mysqli_fetch_array($doo);
$haha = date('m-d-Y', $pro['date']);
echo '<td class="events">'.$pro['event'].'';
echo '<div class="eventdate">'.$haha.'</div></td>';
}
}
}
//end
?><file_sep>/img/members.php_files/cSetting.js
function sendcForm() {
var company = document.getElementById('company').value;
var ctax = document.getElementById('tax').value;
var cphone = document.getElementById('cphone').value;
var cfax = document.getElementById('cfax').value;
var caddr = document.getElementById('caddr').value;
var discs = document.getElementById('cdisc').value;
var queryStriing = "?company="+company+"&ctax="+ctax+"&cphone="+cphone+"&cfax="+cfax+"&caddr="+caddr+"&discs="+discs;
http.open("GET", "settings.php" +
queryStriing, true);
http.onreadystatechange = getHttpiRes;
http.send(null);
}
function getHttpiRes() {
if (http.readyState == 4) {
ires = http.responseText; // These following lines get the response and update the page
document.getElementById('ctable').innerHTML = ires;
}
}
function getXHTTP() {
var xhttp;
try { // The following "try" blocks get the XMLHTTP object for various browsers…
xhttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
xhttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e2) {
// This block handles Mozilla/Firefox browsers...
try {
xhttp = new XMLHttpRequest();
} catch (e3) {
xhttp = false;
}
}
}
return xhttp; // Return the XMLHTTP object
}
var http = getXHTTP(); // This executes when the page first loads.
<file_sep>/email1.php
<?php
include('database_connection.php');
session_start();
//function for when user clicks email.. We show them inputs to send email
if(isset($_GET['num'])) {
echo '<input type="hidden" id="inum" value="'.$_GET['num'].'"/>';
echo '<input type="hidden" id="isid" value="'.$_GET['sid'].'"/>';
echo '<table align="center" id="emailtbl">';
echo '<tr valign="top"><td>';
echo '<img id="loadGif" src="img/load.gif"/>';
echo '<label for="to" class="to">To:</label><br/> <input type="text" name="to" id="to"/><br/>';
echo '<label for="for" class="to">From:</label><br/> <input type="text" name="from" id="from" title="Your Reply-To E-mail Address"/>';
echo '<label for="comments" class="to">Message/Comments</label><textarea cols="30" rows="10" name="commentsI" id="commentsI"></textarea>';
echo '<input type="button" name="submit" value="Send" onClick="sendEmail(); return false;"/>';
echo '<input type="button" id="b-close" onClick="bClose(); return false;" value="close"></button>';
echo '</td></tr></table>';
}
//end
if(isset($_GET['invoice'])) {
$GET ="SELECT * FROM invoices WHERE(`invid` = '".$_GET['invoice']."' AND `midd` ='".$_GET['usrid']."')";
$tits = "SELECT * FROM `customers` WHERE(`invoice` = '".$_GET['invoice']."' AND `mid` = '".$_GET['usrid']."')";
$res = mysqli_query($dbc, $GET);
if(!$res) {
die(mysqli_error($dbc));
}
$rees = mysqli_query($dbc, $tits);
if(!$rees) die(mysqli_error($dbc));
else {
$bitch = "SELECT * FROM `members` WHERE(`id` ='".$_GET['usrid']."')";
$bi = mysqli_query($dbc, $bitch);
if(!$bi) die(mysqli_error($dbc));
$mem = mysqli_fetch_array($bi);
$cust = mysqli_fetch_array($rees);
$inv = mysqli_fetch_array($res);
$code = $inv['code'];
$email = $_GET['to'];
$member = $mem['usr'];
$com = mysql_real_escape_string($_GET['mess']);
$name = $cust['name'];
$Cname = $cust['name'];
$to = $_GET['to'];
$from = $_GET['from'];
$invoice = $inv['invid'];
$invn = $cust['mid'];
// We creat a pdf && send email--------------------------------
$html = file_get_contents('http://invoice-masters.com/seemyBill.php?invvid='.$invoice.'&id='.$invn.'&code='.$code.'');
$name =''.$cust['name'].''.$cust['invoice'].'';
$fp = fopen('pdf/'.$name.'.php', 'w+');
fwrite($fp, $html);
fclose($fp);
if($fp) {
system("wkhtmltopdf http://invoice-masters.com/pdf/".$name.".php pdf/".$name.".pdf ");
$done = system('echo " '.$com.''."\r\n".'See your attatchment or view your invoice here: http://invoice-masters.com/seemyBill.php?invvid='.$invoice.'&id='.$invn.'&code='.$code.' "| mutt -s "Invoice for: '.$Cname.', From: '.$mem['Bname'].'" '.$to.' -c '.$from.' -a /opt/lampp/htdocs/invoice/pdf/'.$name.'.pdf');
echo 'Your E-mail has been sent!';
}
}
}
?><file_sep>/invoices1.php
<?php
session_start();
if(isset($_GET['idd'])) {
include('database_connection.php');
$got = "SELECT * FROM `invoices` WHERE `midd` ='".$_SESSION['id']."' ORDER BY `invid` DESC LIMIT 1 ";
$gp = mysqli_query($dbc, $got);
$hd = mysqli_fetch_array($gp);
$row = mysqli_num_rows($gp);
if($row == 0) {
$poke = "INSERT INTO `invoices` (`invid`, `midd`) VALUES ('1', '".$_SESSION['id']."')";
$mon = mysqli_query($dbc, $poke);
}
if($row != 0) {
$cream = $hd['invid'] + 1;
$pokey = "INSERT INTO `invoices` (`invid`, `midd`) VALUES ('".$cream."', '".$_SESSION['id']."')";
$cocka = mysqli_query($dbc, $pokey);
if($cocka){
$goty = "SELECT * FROM `invoices` WHERE `midd` ='".$_SESSION['id']."' ORDER BY `invid` DESC LIMIT 1 ";
$hh = mysqli_query($dbc, $goty);
$jy = mysqli_fetch_array($hh);
}
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w
3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Members Area</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
<script src="http://thebestbangforyourbuck.tk/gist/jquery/lib/jquery.js"></script>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.9.2/themes/base/jquery-ui.css" />
<script src="http://code.jquery.com/jquery-1.8.3.js"></script>
<script src="http://code.jquery.com/ui/1.9.2/jquery-ui.js"></script>
<script src="http://invoiceit.tk/cust.js"></script>
<script src="http://invoiceit.tk/submitForm.js"></script>
<script src="http://invoiceit.tk/selectProduct.js"></script>
<script src="http://invoiceit.tk/selectPro.js"></script>
<script src="http://invoiceit.tk/add.js"></script>
<script src="http://invoiceit.tk/enterItem.js"></script>
<script src="http://invoiceit.tk/Addd.js"></script>
<script src="http://invoiceit.tk/drag.js"></script>
<script src="http://invoiceit.tk/iSubmitForm.js"></script>
<script src="http://invoiceit.tk/sendComment.js"></script>
<script src="http://invoiceit.tk/allReady1.js"></script>
<script src="http://invoiceit.tk/upInv.js"></script>
<script src="http://invoiceit.tk/slideForm.js"></script>
<script src="http://invoiceit.tk/cSetting.js"></script>
<meta content="text/css">
<link rel="stylesheet" type="text/ css" href="http://invoiceit.tk/members.css"></link>
<STYLE type="text/css" MEDIA="screen, projection">
<!--
@import url(http://invoiceit.tk/members.css);
-->
</STYLE>
<style></style>
</head>
<body>
<form action="getContents.php" method="POST">
<table id="invoice" align="left">
<tr valign="top">
<td>
<? if(!$_SESSION['img'] == '0'){ echo '<img class="img" src="img/'.$_SESSION['img'].'" height="200" width="250"/>';}?>
</td>
</tr>
</table>
<table align="right" id="contact">
<tr valign="top">
<td id="con">
<span class="con">Phone:</span> <?echo($_SESSION['phone']);?><br/>
<span class="con">Fax:</span> <?echo($_SESSION['fax']);?><br/>
<span class="con">Address:</span> <?echo($_SESSION['addr']);?><br/>
</td>
</tr>
</table>
<table align="left" id="custable">
<tr valign="top">
<td>
<td id="icusttd">
<form action="" method="GET" id="custform">
<input type="text" name="iname" id="iname"/>
<label class="lbl">Customer Name:</label><br/>
<input type="text" name="ilast name" id="ilastname"/>
<label class="lbl">Last Name:</label><br/>
<input type="text" name="iphone" id="iphone"/>
<label class="lbl">Phone:</label><br/>
<input type="text" name="iwphone" id="iwphone"/>
<label class="lbl">Work Phone:</label><br/>
<input type="text" name="iaddr" id="iaddr"/>
<label class="lbl">Address</label><br/>
<input type="text" name="iemail" id="iemail"/>
<label class="lbl">E-mail</label><br/>
<input type="hidden" name="imid" id="imid" value="<? echo($_SESSION['id']);?>"/>
<input type="hidden" name="invid" id="invid" value="<?echo($cream);?>" />
<input type="hidden" name="idate" id="idate" value=""/>
<input type="submit" name="submit" id="icust-submit" onclick="iSubmitForm(); return false;" value="submit"/>
</form>
</td>
</tr>
</table>
<span class="line">________________________________________________________________________________________________________________________</span><br/><br/>
<table id="zztable" align="center">
<div id="sel1" value="sel1" class="zzselect" onClick="selectProduct(1); return false;">Select Item</div><div id="enter1" class="zzenter" onClick="inputFeild(1); return false;" value="sel1">Enter An Item</div>
<div id="prohidden1" class="sel1"></div>
<input type="hidden" name="pro1" id="pro1" value="1"/>
<input type="hidden" name="invid" id="invid1" value="<?echo($cream);?>" />
</table>
<span class="linee">________________________________________________________________________________________________________________________</span><br/><br/>
<div id="div1"></div>
<button id="sub-button" class="button" name="sub-button" value="<?echo($_SESSION['id']);?>" onClick="Add(); return false;">Total</button><br/><br/><div id="total">
</div>
<div id="notes">
<input type="button" name="txt-button" id="txt-button" class="button" onClick="txt(); return false;" value="Okay" /></span>
<span class="special">Special Notes:<br/>
<span id="asnotes"><textarea cols="112" rows="6" WRAP="VIRTUAL" id="snotes"></textarea>
</span>
<table align="left">
<tr valign="top">
<td><label id="disc">Disclaimer:</label><br/>
<? $go = "SELECT * FROM `members` WHERE `id`='".$_SESSION['id']."' ";
$get = mysqli_query($dbc, $go);
while($res = mysqli_fetch_array($get)) {
echo '<div id="ddisc">'.$res['disclaimer'].'</div><br/>';
}
?>
</td>
</tr>
</table>
<br/>
<div id="aready"><input type="button" name="ready-button" id="ready" onClick="allReady(); return false;" class="button" value="Print"/></div><br/>
</form>
</body>
</html>
<?php
}
?>
<file_sep>/pdf/seemyBill.js
$(window).load(function() {
var centertd = $("#center").height();
var docheight = $(document).height();
var lineheight = $(".line").height();
var current = centertd + lineheight;
var remain= 2200 - current;
var lineDiv = remain / 4;
$(".line").css("padding-top", lineDiv);
$(".line").css("padding-bottom", lineDiv);
});
<file_sep>/setEvent.js
function setEvent() {
var event = $('#event').attr('value');
var date = $('#datepicker').attr('value');
var data ="event="+event+"&date="+date;
$.ajax({
url:"customer.php",
data:data,
success:function(result){
$('.done').html(result);
},
});
}
function getEvent(index) {
$("#eventbl").hide();
var eventId = index;
var data ="eventId="+eventId;
$.ajax({
url:"customer.php",
data:data,
success:function(result) {
$("#titsm").html(result);
},
});
}<file_sep>/getContents1.php
<?php
include('database_connection.php');
session_start();
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w
3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<head>
<html xmlns="http://www.w3.org/1999/xhtml">
<title>Members Area</title>
<META http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<META http-equiv="Content-language" content="us-en" />
<title></title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
<script src="http://thebestbangforyourbuck.tk/gist/jquery/lib/jquery.js"></script>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.9.2/themes/base/jquery-ui.css" />
<script src="http://code.jquery.com/jquery-1.8.3.js"></script>
<script src="http://code.jquery.com/ui/1.9.2/jquery-ui.js"></script>
<script src="cust.js"></script>
<script src="submitForm.js"></script>
<script src="selectProduct.js"></script>
<script src="selectPro.js"></script>
<script src="add.js"></script>
<script src="enterItem.js"></script>
<script src="Addd.js"></script>
<script src="drag.js"></script>
<script src="iSubmitForm.js"></script>
<script src="sendComment.js"></script>
<script src="allReady1.js"></script>
<script src="upInv.js"></script>
<script src="upCust.js"></script>
<script src="slideForm.js"></script>
<script src="cSetting.js"></script>
<script src="deleteFrom.js"></script>
<script src="settingAnimate.js"></script>
<script src="saveMe.js"></script>
<script src="subGroup.js"></script>
<script src="searchMe.js"></script>
<script src="sItem.js"></script>
<script src="addjForm.js"></script>
<script src="autoCom.js"></script>
<script src="jobSelect.js"></script>
<script src="showMyJob.js"></script>
<script src="JizzEm.js"></script>
<script src="emailInv.js"></script>
<meta content="text/css">
<link rel="stylesheet" type="text/ css" href="Cust.css"></link>
<STYLE type="text/css" MEDIA="screen, projection">
<!--
@import url(Cust.css);
-->
</STYLE>
<script>
function hParts(index) {
$(".hpartslist"+index).slideToggle("slow");
}
</script>
<? if(isset($_GET['id'])) {
$tom = "SELECT * FROM `members` WHERE `id` = '".$_GET['id']."'";
$delo = mysqli_query($dbc, $tom);
if(!$delo) die(mysqli_error($dbc));
$fart = mysqli_fetch_array($delo);
}
?>
</head>
<body>
<div id="slide"></div>
<div id="slides"></div>
<table id="center" align="center">
<div id="EmailI" onclick="emailMe(); return false;">Email</div>
<div id="emailinv"></div>
<div id="invoiceN">Invoice #:<br/><?echo($_GET['invvid']);?></div><br/>
<tr valign="top">
<td id="centertd">
<div id="info">
<table id="invoice" align="left">
<tr valign="top">
<td>
<?php if(!$fart['img'] == '0'){ echo '<img class="img" src="img/'.$fart['img'].'" height="200" width="250"/>';}?>
</td>
</tr>
</table><br/>
<table align="right" id="contact">
<tr valign="top">
<td id="con" class="colorr">
<span class="bname"><?echo($fart['Bname']);?></span><br/>
<span class="con">Phone:</span> <?echo($fart['phone']);?><br/>
<span class="con">Fax:</span> <?echo($fart['fax']);?><br/>
<span class="con">Address:</span> <?echo($fart['addr']);?><br/>
</td>
</tr>
</table><br/>
<table align="center" id="custable" class="colorr">
<tr valign="top">
<td id="icusttd" class="colorr">
<?
$get = "SELECT `cust` FROM `invoices` WHERE `invid` = '".$_GET['invvid']."' AND `midd` = '".$_GET['id']."'";
$cget = mysqli_query($dbc, $get);
$gett = mysqli_fetch_object($cget);
echo($gett->cust);
?>
</td></tr>
</table><br/>
<div class="linee"><?echo($fart['slogan']);?></div>
<div class="line">
<div id="sel1" value="sel1" class="zzselect" onClick="selectProduct(1); return false;">Select Item</div><div id="enter1" class="zzenter" onClick="inputFeild(1); return false;" value="sel1">Enter An Item</div>
<?
$get = "SELECT * FROM `invoices` WHERE `invid`='".$_GET['invvid']."' AND `midd` = '".$_GET['id']."' ";
$p ="SELECT * FROM `dataa` WHERE `invid`='".$_GET['invvid']."' AND `midd` = '".$_GET['id']."'";
$poop = mysqli_query($dbc, $get);
$ppoop = mysqli_query($dbc, $p);
while($vv = mysqli_fetch_array($ppoop)) {
$get = "SELECT * FROM `invoices` WHERE `invid`='".$_GET['invvid']."' AND `midd` = '".$_GET['id']."' ";
$p ="SELECT * FROM `dataa` WHERE `invid`='".$_GET['invvid']."' AND `midd` = '".$_GET['id']."' ";
$poop = mysqli_query($dbc, $get);
$ppoop = mysqli_query($dbc, $p);
while($vv = mysqli_fetch_array($ppoop)) {
for($i=1; $i<=12; $i++) {
echo '<div id="prohidden'.$i.'" class="sel1">'.$vv['data'.$i.''].'</div>';
echo '<input type="hidden" name="invid" id="invid1" value="'.$_GET['invvid'].'" />';
echo '<input type="hidden" name="pro'.$i.'" id="pro'.$i.'" value="'.$i.'"/>';
}
}
}
?>
</div>
<div id="div1"></div>
<button id="sub-button" class="button" name="sub-button" value="<?echo($_GET['id']);?>" onClick="Add(); return false;">Total</button><br/><br/><div id="total">
</div>
<div id="notes">
<input type="button" name="txt-button" id="txt-button" class="button" onClick="txt(); return false;" value="Okay" /></span>
<span class="special">Special Notes:<br/>
<? $ff = "SELECT * FROM `invoices` WHERE `midd` = '".$_GET['id']."' AND `invid` = '".$_GET['invvid']."' ";
$fag = mysqli_query($dbc, $ff);
if(!$fag) {
die(mysqli_error($dbc));
}
$tits = mysqli_fetch_array($fag);
if($tits['special'] =='') {
?>
<div id="asnotes">
<textarea cols="90" rows="6" WRAP="VIRTUAL" class="button" id="snotes">
</textarea>
</div>
<?
}
else {
echo ''.$tits['special'].'';
}
?>
</div>
<table align="left">
<tr valign="top">
<td ><label id="disc">Disclaimer:</label><br/>
<? $go = "SELECT * FROM `members` WHERE `id`='".$_GET['id']."' ";
$get = mysqli_query($dbc, $go);
while($res = mysqli_fetch_array($get)) {
echo '<div id="ddisc" class="colorr">'.$res['disclaimer'].'</div><br/>';
}
?>
</td>
</tr>
</table>
<table style="float:left;">
<tr valing="top"><td><input type="button" name="ready-button" id="ready" onClick="allReady(); return false;" class="button" value="Print"/></td>
<td><input type="button" id="saveit" onClick="saveIt(); return false;" value="Save me!" class="button"/></td><br/><br/>
<td><div id="sign"><span style="color:red;">Customer Signiture[ X ]</span>____________________________________</div></td></tr>
</table>
<?php
$date = new DateTime('');
$date->add(new DateInterval('P0Y0M3DT0H0M0S'));
$date1 = $date->format('M-d-y') ."\n";
?>
<input type="hidden" id="dateinv" value="<?echo($date1);?>"/>
<input type="hidden" id="sid" value="<?echo($fart['id']);?>"/>
<input type="hidden" value="<?echo($_GET['invvid']);?>" id="saveinv" />
</div>
</td>
</tr>
</table>
</body>
</html>
<file_sep>/aboutUs.php
<?php
if(isset($_GET['1'])) {
?>
<div class="aboutHead">Store Customer Information:
</div>
<p class="about">
<ul class="aboutUl"><span class="system">Our system allows you to:</span><br/><br/>
<li>Store each one of your customers information online.</li>
<li>All of your customer data will be saved online for you to view anywhere.</li>
<li>Keep track of who still owes you money and who is paid in full.</li>
</ul>
</p>
<?
}
if(isset($_GET['2'])) {
?>
<div class="aboutHead">Store / Save Invoices
</div>
<p class="about">
<ul class="aboutUl"><span class="system">Our system allows you to:</span><br/><br/>
<li>Store / Save each and every invoice you create.</li>
<li>Edit any invoice you've created anywhere and anytime.</li>
<li>See who still owes you and who is paid in full.</li>
<li>Print / duplicate invoices with the click of a button.</li>
<li>Find previous invoices for warranty work.</li>
</ul>
</p>
<?
}
if(isset($_GET['3'])) {
?>
<div class="aboutHead">Send invoices via E-mail
</div>
<p class="about">
<ul class="aboutUl"><span class="system">Our system allows you to:</span><br/><br/>
<li>Directly E-mail your invoices with the click of a button.</li>
<li>The customer can print or view their invoice online.</li>
<li>A PDF version of your invoice will also be attatched to the E-mail.
</ul>
</p>
<?
}
if(isset($_GET['4'])) {
?>
<div class="aboutHead">Inventory Management
</div>
<p class="about">
<ul class="aboutUl"><span class="system">Our system allows you to:</span><br/><br/>
<li>Save all of your inventory online.</li>
<li>Download or print your parts list.</li>
<li>Find your parts / products fast and easy.</li>
<li>Organize your parts / products into groups.</li>
<li>Find which parts / products are selling best.</li>
</ul>
</p>
<?
}
if(isset($_GET['5'])) {
?>
<div class="aboutHead">Profit Calculator
</div>
<p class="about">
<ul class="aboutUl"><span class="system">Our system allows you to:</span><br/><br/>
<li>Find Profits made on each invoice</li>
<li>Tax amount / totals.</li>
<li>Parts amount / totals.</li>
<li>Labor amount / totals.</li>
<li>Each months profits.</li>
</ul>
</p>
<?
}
if(isset($_GET['6'])) {
?>
<div class="aboutHead">Compare Vendor Prices
</div>
<p class="about">
<ul class="aboutUl"><span class="system">Our system allows you to:</span><br/><br/>
<li>Compare prices on parts / products you get from your vendors.</li>
<li>Automatically identify the same parts boughten from different vendors.</li>
<li>Automatically calculate who offers that part/ product the cheapest.</li>
</ul>
</p>
<?
}
if(isset($_GET['7'])) {
?>
<div class="aboutHead">Add Jobs
</div>
<p class="about">
<ul class="aboutUl"><span class="system">Our system allows you to:</span><br/><br/>
<li>Create a "Job" for faster invoicing and organization.</li>
<li>Add up to ten Parts and ten labor items for each job.</li>
</ul>
</p>
<?
}
if(isset($_GET['8'])) {
?>
<div class="aboutHead">Easy Online Management
</div>
<p class="about">
<ul class="aboutUl"><span class="system">Key Features:</span><br/><br/>
<li>Invoice-Masters Stores / Saves all your data online.</li>
<li>Edit, create, and manage your business from anywhere that has Internet.</li>
<li>Easily print / E-mail / or save your invoices for later.</li>
</ul>
</p>
<?
}
if(isset($_GET['9'])) {
?>
<div class="aboutHead">Reminders / Events
</div>
<p class="about">
<ul class="aboutUl"><span class="system">Key Features:</span><br/><br/>
<li>Set reminders.</li>
<li>Organize your plans for tomorrow or next week.</li>
<li>Create events to be done on a certain date.</li>
</ul>
</p>
<?
}
if(isset($_GET['10'])) {
?>
<div class="aboutHead">Fast and Easy Invoicing
</div>
<p class="about">
<ul class="aboutUl"><span class="system">Key Features:</span><br/><br/>
<li>Once a customer has been stored in the database, the next time you are typing an invoice for them, our auto-complete function will save you a lot of time!</li>
<li>Your parts will be organized for fast access.</li>
<li>Easily Print / E-mail each invoice. </li>
<li>Our program is easy to use!</li>
</ul>
</p>
<?
}
if(isset($_GET['11'])) {
?>
<div class="aboutHead">100% Free To Use
</div>
<p class="about">
<ul class="aboutUl"><span class="system">Key Features:</span><br/><br/>
<li>Our program is 100% free to use.</li>
<li>If you don't like the invoice template our program comes with, You may pay us to build you a custom invoice.</li>
<li>If you know html, create your own invoice and upload it for you to use!</li>
</ul>
</p>
<?
}
?>
<file_sep>/logout.php
<?php
session_destroy();
header("location:http://invoice-masters.com");
?>
<file_sep>/pass.php
<html>
<body>
I Forgot My Password:
<form action="<?$PHP_SELF?>" method="POST">
<label class="loginlbl">Username</label><br/>
<input type="text" name="name"/><br/>
<label class="loginlbl">E-mail</label><br/>
<input type="text" name="email"/><br/>
<input type="submit" value="submit" name="submit"/>
</form>
<?
if(isset($_POST['submit'])) {
include('database_connection.php');
$usr = mysql_real_escape_string($_POST['name']);
$email = mysql_real_escape_string($_POST['email']);
if($usr == '') {
die('Username Required');
}
else
if($email =='') {
die("E-mail Required");
}
else {
$go = "SELECT `pass` FROM `members` WHERE `email`='$email' AND `usr`='$usr'";
$send = mysqli_query($dbc, $go);
$car = mysqli_num_rows($send);
if($car == 0) {
echo('Sorry, no record found in our database, please check your spelling or Email: <EMAIL> For more support');
}
else {
$res = mysqli_fetch_object($send);
$user_pass = $res->pass;
$subject = "Invoice-Masters invoicing registration\r\n";
$message = "You have requested to see your account information. Your account Password is :\r\n ".$user_pass."\r\n If you do not know why you recieved this E-mail, Please disregard it. ";
$header = "From: <EMAIL>\r\n";
$header .= "Reply-To: <EMAIL>\r\n";
$header .= "Return-Path: <EMAIL>\r\n";
$poop = mail($email,$subject,$message,$header);
if(!$poop) {
die(mysqli_error($dbc));
}
else {
echo 'An E-mail containing your password has been sent to: '.$email.'';
}
}
}
}
?>
<a href="index.php">Back</a><br/>
</body>
</html>
<file_sep>/Binvoice/bob.php
<?
include('database_connection.php');
session_start();
//this is for Binvoice.php file
if(isset($_GET['optionn'])) {
ob_start();
$option = $_GET['optionn'];
$cream = $_GET['cream'];
$creame = $_GET['creame'];
$quan = $_GET['quan'];
$go = "SELECT * FROM `inventory` WHERE `midd`='".$_SESSION['id']."' AND `name`= '".$option."' LIMIT 1";
$res = mysqli_query($dbc, $go);
if(!$res) {
die('failed');
}
$dec = "UPDATE `inventory` SET `amount` = `amount`-'".$quan."' WHERE `midd`='".$_SESSION['id']."' AND `name`= '".$option."'";
$deac = mysqli_query($dbc, $dec);
if(!$deac) {
die(mysqli_error($dbc));
}
else {
echo '<table id="protable" align="center">';
while($get = mysqli_fetch_array($res)) {
$quan = $_GET['quan'];
$i= $_GET['num'] + 1;
$b = $_GET['num'];
$price = $get['price'];
$pricel = $get['lprice'];
$whole = $get['yprice'];
$name = $get['name'];
$tell = $get['desc'];
if($quan >= 1) {
$whole = $whole * $quan;
$price = $price * $quan;
$pricel = $pricel * $quan;
$price = number_format($price, 2);
$pricel = number_format($pricel, 2);
$whole = number_format($whole, 2);
}
echo '<tr valign="top">';
echo '<td><span class="item">Quantity:</span><br/><input type="text" class="bob" id="itemd">'.$quan.'</span></td>';
echo '<td><span class="item">Part#:</span><br/><span class="itemn" id="itemn">'.$name.'</span></td>';
echo '<td><span class="item">Description:</span><br/><span class="itemn" id="itemn">'.$tell.'</span></td>';
echo '<td><span class="itemp">Parts:</span><br/>$<input type="text" class="bob" id="itemm" value="'.$price.'" size="5"/>';
echo '<br/><span class="itemp">Labor:</span><br/>$<input type="text" class="bobl" id="itemm" value="'.$pricel.'" size="6"/>';
echo '<input type="hidden" value="'.$whole.'" id="whole'.$i.'" class="whole" />';
echo '<div id="sel'.$i.'" value="sel'.$i.'" class="zzselect" onClick="selectProduct('.$i.'); return false;">Select Item</div>';
echo '<div id="enter'.$i.'" class="zzenter" onClick="inputFeild('.$i.'); return false;" value="sel'.$i.'">Enter An Item</div>';
echo '<div class="late"></div>';
echo '<input type="hidden" name="invid" id="invid'.$i.'" value="'.$get['yprice'].'" />';
//inserts into database//
$currr =''.ob_get_contents().'';
$get = "SELECT * FROM `dataa` WHERE `invid` ='".$creame."' AND `midd` ='".$_SESSION['id']."' ";
$cget = mysqli_query($dbc, $get);
if(!$cget) {
die(mysqli_error($dbc));
}
$none = mysqli_num_rows($cget);
if($none == 0) {
$ii ="INSERT INTO `dataa` (`invid`, `midd`, `data$b`) VALUES ('".$creame."', '".$_SESSION['id']."', '".$currr."')";
$io = mysqli_query($dbc, $ii);
if(!$io) {
die(mysqli_error($dbc));
}
}
if($none > 0) {
$hh ="UPDATE `dataa` SET `data$b` = '".$currr."' WHERE `invid` = '".$creame."' AND `midd` = '".$_SESSION['id']."'";
$hj = mysqli_query($dbc, $hh);
if(!$hh) {
die(mysqli_error($dbc));
}
}
ob_end_flush();
}
}
}
//end Binvoe file
if(isset($_GET['jobop'])) {
ob_start();
$option = $_GET['jobop'];
$cream = $_GET['cream'];
$creame = $_GET['creame'];
$quan = $_GET['quan'];
$i= $_GET['num'] + 1;
$b = $_GET['num'];
$go = "SELECT * FROM `jobs` WHERE `midd`='".$_SESSION['id']."' AND `Jname`= '".$option."' ";
$res = mysqli_query($dbc, $go);
if(!$res) {
die(mysqli_error($dbc));
}
while($get = mysqli_fetch_array($res)) {
$price = $get['Jtotal'];
$pricel = $get['Jlabortot'];
$whole = $get['jprofite'];
echo '<div id="items"><span class="itemn">Job:</span><span class="itemm"> '.$get['Jname'].'</span><br/><span class="itemd">Description:</span>';
echo '<span class="itemm"> '.$get['Jdesc'].'</span></div>';
if($quan >= 1) {
$whole = $whole * $quan;
$price = $price * $quan;
$pricel = $pricel * $quan;
$price = number_format($price, 2);
$pricel = number_format($pricel, 2);
$whole = number_format($whole, 2);
}
echo '<span class="itemp">Quantity:</span><span type="text" class="bob" >'.$quan.'</span><br/>';
echo '<div class="CLOSE" onClick="hParts('.$b.'); return false;">[ X ]</div><div class="hpartslist'.$b.'">';
for($k=1; $k<10; $k++) {
if($get['jparts'.$k.''] != '') {
echo '<div class="bjob"><span class="itemj">Part:</span>'.$get['jparts'.$k.''].'<span class="itemjob">Price:$<input type="text" id="itemm" value="'.$get['Jpart'.$k.''].'" size="6"/></span></div>';
}
}
for($k=1; $k<5; $k++) {
if($get['Jlabor'.$k.''] != '') {
echo '<div class="bjob"><span class="itemj">Labor:</span>'.$get['Jlabor'.$k.''].'<span class="itemjob">Price:$<input type="text" id="itemm" value="'.$get['jjlabor'.$k.''].'" size="6"/></span></div>';
}
}
echo '</div>';
echo '<span class="itemp">Total Parts:</span>$<input type="text" class="bob" id="itemm" value="'.$price.'" size="5"/>';
echo '<br/><span class="itemp">Total Labor:</span>$<input type="text" class="bobl" id="itemm" value="'.$pricel.'" size="6"/>';
echo '<input type="hidden" value="'.$whole.'" id="whole'.$i.'" class="whole" />';
echo '<div id="sel'.$i.'" value="sel'.$i.'" class="zzselect" onClick="selectProduct('.$i.'); return false;">Select Item</div>';
echo '<div id="enter'.$i.'" class="zzenter" onClick="inputFeild('.$i.'); return false;" value="sel'.$i.'">Enter An Item</div>';
echo '<div class="late"></div>';
echo '<input type="hidden" name="invid" id="invid'.$i.'" value="'.$whole.'" />';
}
//inserts into database//
$currr =''.ob_get_contents().'';
$get = "SELECT * FROM `dataa` WHERE `invid` ='".$creame."' AND `midd` ='".$_SESSION['id']."' ";
$cget = mysqli_query($dbc, $get);
if(!$cget) {
die(mysqli_error($dbc));
}
$none = mysqli_num_rows($cget);
if($none == 0) {
$ii ="INSERT INTO `dataa` (`invid`, `midd`, `data$b`) VALUES ('".$creame."', '".$_SESSION['id']."', '".$currr."')";
$io = mysqli_query($dbc, $ii);
if(!$io) {
die(mysqli_error($dbc));
}
}
if($none != 0) {
$hh ="UPDATE `dataa` SET `data$b` = '".$currr."' WHERE `invid` = '".$creame."' AND `midd` = '".$_SESSION['id']."'";
$hj = mysqli_query($dbc, $hh);
if(!$hh) {
die(mysqli_error($dbc));
}
}
ob_end_flush();
}
//end
if(isset($_GET['comments'])) {
ob_start();
$cream = $_GET['creams'];
$creame = $_GET['creames'];
$b = $_GET['nums'] - 1;
$comment = $_GET['comments'];
if($comment != '') {
echo '<span class="coms">Comments: </span><span class="comtxt">'.$_GET['comments'].'</span>';
$currr =''.ob_get_contents().'';
$get = "SELECT * FROM `datacom` WHERE `invid` ='".$creame."' AND `midd` ='".$_SESSION['id']."' ";
$cget = mysqli_query($dbc, $get);
if(!$cget) {
die(mysqli_error($dbc));
}
$none = mysqli_num_rows($cget);
if($none == 0) {
$ii ="INSERT INTO `datacom` (`invid`, `midd`, `data$b`) VALUES ('".$creame."', '".$_SESSION['id']."', '".$currr."')";
$io = mysqli_query($dbc, $ii);
if(!$io) {
die(mysqli_error($dbc));
}
}
}
if($none != 0) {
$hh ="UPDATE `datacom` SET `data$b` = '".$currr."' WHERE `invid` = '".$creame."' AND `midd` = '".$_SESSION['id']."'";
$hj = mysqli_query($dbc, $hh);
if(!$hh) {
die(mysqli_error($dbc));
}
}
ob_end_flush();
}
if(isset($_GET['txt'])) {
if(!$_GET['txt'] == '') {
$creame = $_GET['creames'];
ob_start();
echo '<div id="aasnotes"><div id="comtxt">'.$_GET['txt'].'</div></div>';
$currr =''.ob_get_contents().'';
$ii ="UPDATE `invoices` SET `special` = '".mysql_real_escape_string($currr)."' WHERE (`invid` = '".$creame."' AND `midd` = '".$_SESSION['id']."')";
$io = mysqli_query($dbc, $ii);
if(!$io) {
die(mysqli_error($dbc));
}
}
ob_end_flush();
}
?><file_sep>/11.php
<?
include('wkk.php');
$url ='http://invoicerfree.tk';
$blah = shell_exec("wkhtmltoimage-amd64 http://invoicerfree.tk /opt/lampp/htdocs/invoice/tmp/shiffft.pdf");
if(!$blah)die();
$str = file_get_contents("/opt/lampp/htdocs/invoice/tmp/shiffft.pdf");
header('Content-Type: application/pdf');
header('Content-Length: '.strlen($str));
header('Content-Disposition: inline; filename="pdf.pdf"');
header('Cache-Control: private, max-age=0, must-revalidate');
header('Pragma: public');
ini_set('zlib.output_compression','0');
die($str);
?><file_sep>/query.php
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w
3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<head>
<html xmlns="http://www.w3.org/1999/xhtml">
<title>Members Area</title>
<META http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<META http-equiv="Content-language" content="us-en" />
</head>
<body>
<?
include('database_connection.php');
session_start();
if(isset($_GET['name'])) {
$name = $_GET['name'];
if($name == '') {
$name ='none';
}
$lastname = $_GET['lastname'];
if($lastname == '') {
$lastname ='none';
}
$phone = $_GET['phone'];
if($phone == '') {
$phone ='none';
}
$wphone = $_GET['wphone'];
if($wphone == '') {
$wphone='none';
}
$mid = $_GET['mid'];
$addr = $_GET['addr'];
if($addr == '') {
$addr ='none';
}
$email = $_GET['email'];
if($email == '') {
$email ='none';
}
$date = new DateTime('');
$date->add(new DateInterval('P0Y0M3DT0H0M0S'));
$date1 = $date->format('Y-m-d H:i:s') ."\n";
$insert = "INSERT INTO `customers`(`name`, `lastname`, `phone`, `wphone`, `mid`, `date`, `addr`, `email`)
VALUES ( '".$name."', '".$lastname."', '".$phone."', '".$wphone."', '".$mid."', '".$date1."', '".$addr."', '".$email."')";
$go = mysqli_query($dbc, $insert);
if(!$go) {
die ('Query Failed');
}
else {
echo ' Sucess!';
}
}
// add inventory///////////////
if(isset($_GET['namee'])) {
$namee = $_GET['namee'];
if($namee == '') {
$namee ='none';
}
$altname = $_GET['altname'];
if($altname == '') {
$altname ='none';
}
$amount= $_GET['amount'];
if($amount == '') {
$amount ='none';
}
$price= $_GET['price'];
if($price == '') {
$price ='none';
}
$desc= $_GET['desc'];
if($desc == '') {
$desc ='none';
}
$group= $_GET['group'];
if($group == '') {
$group ='none';
}
$labor = $_GET['labor'];
if($labor == '') {
$labor ='0';
}
$yprice = $_GET['yprice'];
if($yprice == '') {
$yprice = 'none';
}
$ven = $_GET['vendor'];
if($ven == '') {
$ven = 'none';
}
$midd= $_GET['midd'];
$insert = "INSERT INTO `inventory`(`name`, `altname`, `amount`, `price`, `desc`, `group`, `midd`, `lprice`, `yprice`, `vendor`)
VALUES ('".$namee."', '".addcslashes($altname, "\x00\n\r\'\#\x1a\x3c\x3c\x3e\x25")."', '".$amount."', '".$price."', '".$desc."', '".$group."', '".$midd."', '".$labor."', '".$yprice."', '".$ven."')";
$go = mysqli_query($dbc, $insert);
if(!$go) {
die(mysqli_error($dbc));
}
else {
echo ' Success! You may edit your inventory by clicking the inventory link to the left.';
}
}
if(isset($_GET['iname'])) {
ob_start();
$name = $_GET['iname'];
if($name == '') {
$name ='none';
}
$lastname = $_GET['ilastname'];
if($lastname == '') {
$lastname ='none';
}
$phone = $_GET['iphone'];
if($phone == '') {
$phone ='none';
}
$wphone = $_GET['iwphone'];
if($wphone == '') {
$wphone='none';
}
$mid = $_GET['imid'];
$addr = $_GET['iaddr'];
if($addr == '') {
$addr ='none';
}
$email = $_GET['iemail'];
if($email == '') {
$email ='none';
}
$invid = $_GET['index'];
$date1 = date('M-d-y');
echo '<div class="callwtf">';
echo '<span class="call">Name:</span><span class="dcall">'.$name.'</span><br/>';
if($lastname != 'none') {
echo '<span class="call">Last Name:</span><span class="dcall">'.$lastname.'</span><br/>';
}
if($phone != 'none') {
echo '<span class="call">Phone:</span><span class="dcall">'.$phone.'</span><br/>';
}
if($wphone != 'none') {
echo '<span class="call">Work-Phone:</span><span class="dcall">'.$wphone.'</span><br/>';
}
if($addr != 'none') {
echo '<span class="call">Address:</span><span class="dcall">'.$addr.'</span><br/>';
}
if($email != 'none') {
echo '<span class="call">E-mail:</span><span class="dcall">'.$email.'</span><br/>';
}
echo '<span class="call">Invoice #:</span><span class="dcall">'.$invid.'</span><br/>';
echo '<span class="call">Date:</span><span class="dcall">'.$date1.'</span><br/>';
echo '<input type="hidden" name="invid" id="invidd" value="'.$invid.'" />';
echo '<span class="editcall" onclick="editCall(); return false;">edit</span></div>';
$get = "SELECT `cust` FROM `invoices` WHERE `invid` ='".$invid."' AND `midd` = '".$_SESSION['id']."' ";
$cget = mysqli_query($dbc, $get);
if(!$cget) {
die(mysqli_error($dbc));
}
$data = ob_get_contents();
$check = mysqli_num_rows($cget);
while($gett = mysqli_fetch_object($cget)) {
$add = "UPDATE `invoices` SET `cust`= '".$data."', `date`='$date1' WHERE `invid` = '".$invid."' AND `midd` = '".$_SESSION['id']."' ";
$adds = mysqli_query($dbc, $add);
if(!$adds) {
echo ' Failed ';
}
}
$fagstick = "SELECT * FROM `customers` WHERE `invoice` = '$invid' AND `mid` = '".$_SESSION['id']."'";
$yeah = mysqli_query($dbc, $fagstick);
if(!$yeah) die(mysqli_error($dbc));
$goog = mysqli_fetch_array($yeah);
if($invid == $goog['invoice']) {
$talk ="UPDATE `customers` SET `name` = '$name', lastname = '$lastname', phone = '$phone', wphone = '$wphone', mid = '$mid', date = '$date1', addr = '$addr', email = '$email', invoice = '$invid' WHERE invoice = '$invid'";
$done = mysqli_query($dbc, $talk);
if(!$done) die(mysqli_error($dbc));
}
else if($invid != $goog['invoice']) {
$insert = "INSERT INTO `customers`(`name`, `lastname`, `phone`, `wphone`, `mid`, `date`, `addr`, `email`, `invoice`)
VALUES ( '".$name."', '".$lastname."', '".$phone."', '".$wphone."', '".$mid."', '".$date1."', '".$addr."', '".$email."', '".$invid."')";
$go = mysqli_query($dbc, $insert);
if(!$go) {
die(mysqli_query($dbc));
}
}
ob_end_flush();
}
if(isset($_GET['jj'])) {
$D ="DELETE FROM `jobs` WHERE `midd` = '".$_SESSION['id']."' AND `job num` = '".$_GET['jj']."'";
$hh = mysqli_query($dbc, $D);
if(!$hh) die(mysqli_error($dbc));
if($hh) {
echo 'Deleted';
}
}
//JOb add
if(isset($_GET['Jparts1'])) {
for($ii=1; $ii<11; $ii++) {
$Jquan[$ii] = mysql_real_escape_string($_GET['Jquan'.$ii.'']);
}
////////////////////////////////////////
for($i=1; $i<11; $i++) {
$Ptotal[$i] = mysql_real_escape_string($_GET['Jparts'.$i.'']);
if(isset($_GET['Jquan'.$i.''])) {
$Ptotal[$i] = $Ptotal[$i] * $_GET['Jquan'.$i.''];
}
}
$dim = array_sum($Ptotal);
////////////////////////////////////
/////////////////////////////////////
for($f=1; $f<6; $f++) {
$Ltotal[$f] = mysql_real_escape_string($_GET['Jlabor'.$f.'']);
}
$dogs = array_sum($Ltotal);
//////////////////////////////////////
////////////////////////////////////
$whole = $_GET['Jwhole'];
$Jp = $_SESSION['tax'] / 100;
$jj = number_format($Jp, 2);
$Jpp = $jj * $dim;
$tax = number_format($Jpp, 2); //Taxes
$Gtot = $dogs + $dim + $tax;
echo($Gtot);
//////////////////////////////////////
$Gtotal = number_format($Gtot, 2); // Grand total
//////////////////////////////////////
$joe = $dim + $dogs;
$Pro = $joe - $whole;
$profit = number_format($Pro, 2);//Profit made
/////////////////////////////////////////
/////////////////////////////////////////
$turd = $_GET['index'];
if(isset($_GET['jobnum'])) {
$turd = $_GET['jobnum'];
}
$Jl = number_format($dogs, 2);// total of labor
$cock = number_format($dim, 2);
$gaky = "SELECT * FROM `jobs` WHERE `midd` = '".$_SESSION['id']."' AND `job num` = '".$turd."'";
$hkh = mysqli_query($dbc, $gaky);
if(!$hkh) {
die(mysqli_error($dbc));
}
$how = mysqli_num_rows($hkh);
if($how == 1) {
$titsk = "UPDATE `jobs` SET `Jwhole`='$whole', `midd`='".$_SESSION['id']."', `Jtotal`='$Gtotal', `Jtax`='$tax', `Jpartstot`='$cock', `Jlabortot`='$Jl', `Jprofite`='$profit' WHERE( `midd`='".$_SESSION['id']."' AND `job num`='".$turd."')";
$gobk = mysqli_query($dbc, $titsk);
if(!$gobk) {
die(mysqli_error($dbc));
}
else {
echo '<div style="border:1px solid red; padding:5px 5px 5px 5px;">';
echo '$<input type="text" id="Jparts" name="Jparts" value="'.$cock.'" size="6"/>Total Parts<br/>';
echo '$<input type="text" id="Jlabor" name="Jlabor" value="'.$Jl.'" size="6"/ />Total Labor: <br/>';
echo '$<input type="text" id="Jtotal" name="Jtotal" value="'.$Gtotal.'" size="6"/ />Total: <br/>';
echo '$<input type="text" id="Jprofit" name="Jprofit" value="'.$profit.'" size="6"/ />Profits: <br/>';
echo '$<input type="text" id="Jtax" name="Jtax" value="'.$tax.'" size="6"/ />Tax: <br/>';
echo '<input type="hidden" value="'.$turd.'" class="jobnum"/>';
echo '</div>';
}
}
if($how == 0) {
$gay = "SELECT * FROM `jobs` WHERE `midd` = '".$_SESSION['id']."' ORDER BY `job num` DESC LIMIT 1";
$hh = mysqli_query($dbc, $gay);
if(!$hh) {
die(mysqli_error($dbc));
}
$ho = mysqli_fetch_array($hh);
$jobnum = $ho['job num'] + 1;
echo '<div style="border:1px solid black;">';
echo '$<input type="text" id="Jparts" name="Jparts" value="'.$cock.'" size="6"/>Total Parts<br/>';
echo '$<input type="text" id="Jlabor" name="Jlabor" value="'.$Jl.'" size="6"/ />Total Labor: <br/>';
echo '$<input type="text" id="Jtotal" name="Jtotal" value="'.$Gtotal.'" size="6"/ />Total: <br/>';
echo '$<input type="text" id="Jprofit" name="Jprofit" value="'.$profit.'" size="6"/ />Profits: <br/>';
echo '$<input type="text" id="Jtax" name="Jtax" value="'.$tax.'" size="6"/ />Tax: <br/>';
echo '</div>';
$tits = "INSERT INTO `jobs` (`midd`, `job num`, `Jtotal`, `Jtax`, `Jpartstot`, `Jlabortot`, `Jprofite`) VALUES ('".$_SESSION['id']."', '$jobnum', '$Gtotal', '$tax', '$cock', '$Jl', '$profit')";
$gob = mysqli_query($dbc, $tits);
if(!$gob) {
die(mysqli_error($dbc));
}
else {
$gay ="SELECT * FROM `jobs` WHERE `midd` = '".$_SESSION['id']."' ORDER BY `job num` DESC LIMIT 1";
$fu = mysqli_query($dbc, $gay);
if(!$fu) die(mysqli_error($dbc));
$fuck = mysqli_fetch_array($fu);
echo 'Success! Now submit the form!';
echo '<input type="hidden" value="'.$fuck['job num'].'" class="jobnum"/>';
}
}
}
//end
//sInventory from Searchme.js
if(isset($_GET['sdata'])) {
$sdata = $_GET['sdata'];
$id = $_SESSION['id'];
$find = "SELECT * FROM inventory WHERE name LIKE '%".($sdata)."%' AND `midd`= '$id' OR `altname` LIKE '%".($sdata)."%' AND `midd`= '$id' OR `desc` LIKE '%".($sdata)."%' AND `midd`= '$id'";
$got = mysqli_query($dbc, $find);
if(!$got) die(mysqli_error($dbc));
$num = mysqli_num_rows($got);
if($num == 0) {
echo '<div style="color:blue; font-size:17px;">Sorry, No search results found for '.$sdata.'</div>';
}
else {
echo '<div id="sresult" style="color:red; font-size:17px;">Search result for '.$sdata.'</div>';
while($cust = mysqli_fetch_array($got)) {
echo '<table class="inventable" align="center">';
echo '<div id="ppp"></div>';
echo '<tr valign="top">';
echo '<td><span class="names" id=hippie">Name:<br/></span><input type="text" id="tname'.$cust['id'].'" onClick="showMe('.$cust['id'].'); return false;" value="'.$cust['name'].'" class="blend" size="9"/></td><td><span class="names">Part Number:<br/></span><input type="text" onClick="showMe('.$cust['id'].'); return false;" id="taname'.$cust['id'].'" value="'.$cust['altname'].'" class="blend" size="12" /></td>';
echo '<td><span class="names">Quantity:<br/></span><input type="text" onClick="showMe('.$cust['id'].'); return false;" id="tamount'.$cust['id'].'" value="'.$cust['amount'].'" class="blend" size="9"/></td>';
echo '<td><span class="names">Retail:<br/></span>$<input onClick="showMe('.$cust['id'].'); return false;" type="text" id="tprice'.$cust['id'].'" value="'.$cust['price'].'" class="blend" size="6"/></td>';
echo '<td><span class="names">Wholesale:<br/></span>$<input onClick="showMe('.$cust['id'].'); return false;" type="text" id="typrice'.$cust['id'].'" value="'.$cust['yprice'].'" class="blend" size="6"/></td>';
echo '<td><span class="names">Vendor:<br/></span><input onClick="showMe('.$cust['id'].'); return false;" type="text" id="tvendor'.$cust['id'].'" value="'.$cust['vendor'].'" class="blend" size="8"/></td>';
echo '<td><span class="names">Group:<br/></span><input type="text" id="tgroup'.$cust['id'].'" onClick="showMe('.$cust['id'].'); return false;" value="'.$cust['group'].'" class="blend" size="9" /></td>';
echo '<td><span class="names">Description:<br/></span><input type="text" onClick="showMe('.$cust['id'].'); return false;" id="tdesc'.$cust['id'].'" value="'.$cust['desc'].'" class="blend" size="10" /></td>';
echo '<td><a href="#" class="hidebutton" name="upCust" id="upinv'.$cust['id'].'" onclick="upInv('.$cust['id'].'); return false;">Update</a><br/>';
echo '<a href="#" class="hidebutton" name="delete" id="delete'.$cust['id'].'" onclick="deleteMe('.$cust['id'].'); return false;">Delete</a></td>';
echo '</tr></table>';
}
}
echo '</div>';
}
//end
if(isset($_GET['com'])) { //script in upCust.js
$comment = mysql_real_escape_string($_GET['com']);
$get ="SELECT `comments` FROM `invoices` WHERE `midd` = '".$_SESSION['id']."' AND `invid`='".$_GET['invid']."'";
$got = mysqli_query($dbc, $get);
if(!$got) die(mysqli_error($dbc));
$row = mysqli_num_rows($got);
$yes = mysqli_fetch_object($got);
$tard = "UPDATE invoices SET comments = '$comment' WHERE(midd='".$_SESSION['id']."' AND invid = '".$_GET['invid']."')";
$ff = mysqli_query($dbc, $tard);
if(!$ff) die(mysqli_error($dbc));
if($ff) {
echo '<span style="color:red;">Added!</span>';
}
}
//submitForm.js function for showing more customer information under envoices callback
if(isset($_GET['invoice'])) {
$index = $_GET['invoice'];
$get ="SELECT `cust` FROM `invoices` WHERE `invid`='$index' AND `midd` ='".$_SESSION['id']."'";
$got = mysqli_query($dbc, $get);
if(!$got) { die(mysqli_error($dbc)); }
else {
$res = mysqli_fetch_object($got);
echo($res->cust);
}
}
//end
//for members .php if they want to click the dates
if(isset($_GET['date'])) {
$change = str_replace('-', '/', $_GET['date']);
$two1 = strtotime($change);
$get = "SELECT * FROM events WHERE `midd` = '".$_SESSION['id']."' AND date='$two1'";
$got = mysqli_query($dbc, $get); $num = mysqli_num_rows($got); if($num <= 0) die('No events or reminders for this date.');
$kk ="SELECT * FROM `invoices` WHERE `midd`='".$_SESSION['id']."' ORDER BY `date` ASC ";
$got = mysqli_query($dbc, $get);
$ff = mysqli_query($dbc, $kk);
while($rees = mysqli_fetch_array($got)) {
$gdate = date('m-d-Y', $rees['date']);
echo '<div class="heventdate">'.$gdate.'<br/>';
echo '<span class="hevents">'.$rees['event'].'</span></div>';
}
}
//end
//update inventory from dashboard -- upQuan.js
if(isset($_GET['id'])) {
$get = "SELECT * FROM `inventory` WHERE `id`='".$_GET['id']."' AND `midd`='".$_SESSION['id']."'";
$got = mysqli_query($dbc, $get); if(!$got) die(mysqli_error($dbc));
echo '<div id="showIt">';
echo '<div id="upItem">Update Item:</div><a href="#" id="closeItems" onclick="closeItem(); return false;" title="close">Close</a>';
while($cust = mysqli_fetch_array($got)) {
echo '<div class="ainventable">';
echo '<table class="inventable" align="center">';
echo '<div id="ppp"></div>';
echo '<tr valign="top">';
echo '<td><span class="names" id=hippie">Name:<br/></span><input type="text" id="tname'.$cust['id'].'" onClick="showMe('.$cust['id'].'); return false;" value="'.$cust['name'].'" class="blend" size="9"/></td><td><span class="names">Part Number:<br/></span><input type="text" onClick="showMe('.$cust['id'].'); return false;" id="taname'.$cust['id'].'" value="'.$cust['altname'].'" class="blend" size="12" /></td>';
echo '<td><span class="names">Quantity:<br/></span><input type="text" onClick="showMe('.$cust['id'].'); return false;" id="tamount'.$cust['id'].'" value="'.$cust['amount'].'" class="blend" size="9"/></td>';
echo '<td><span class="names">Retail:<br/></span>$<input onClick="showMe('.$cust['id'].'); return false;" type="text" id="tprice'.$cust['id'].'" value="'.$cust['price'].'" class="blend" size="6"/></td>';
echo '<td><span class="names">Wholesale:<br/></span>$<input onClick="showMe('.$cust['id'].'); return false;" type="text" id="typrice'.$cust['id'].'" value="'.$cust['yprice'].'" class="blend" size="6"/></td>';
echo '<td><span class="names">Vendor:<br/></span><input onClick="showMe('.$cust['id'].'); return false;" type="text" id="tvendor'.$cust['id'].'" value="'.$cust['vendor'].'" class="blend" size="8"/></td>';
echo '<td><span class="names">Group:<br/></span><input type="text" id="tgroup'.$cust['id'].'" onClick="showMe('.$cust['id'].'); return false;" value="'.$cust['group'].'" class="blend" size="9" /></td>';
echo '<td><span class="names">Description:<br/></span><input type="text" onClick="showMe('.$cust['id'].'); return false;" id="tdesc'.$cust['id'].'" value="'.$cust['desc'].'" class="blend" size="10" /></td>';
echo '<td><a href="#" class="hidebutton" name="upCust" id="upinv'.$cust['id'].'" onclick="upInv('.$cust['id'].'); return false;">Update</a><br/>';
echo '<a href="#" class="hidebutton" name="delete" id="delete'.$cust['id'].'" onclick="deleteMe('.$cust['id'].'); return false;">Delete</a></td>';
echo '</tr></table>';
echo '</div>';
}
echo '</div>';
}
//end
//remove item from invoice
if(isset($_GET['remove'])) {
$b = $_GET['remove'] - 1;
$c = $_GET['invidn'] + 1;
$rem ="UPDATE `dataa` SET `data$b`='' WHERE `midd`='".$_SESSION['id']."' AND `invid`='$c'";
$remo = mysqli_query($dbc, $rem); if(!$remo) {
die(mysqli_error($dbc));
}
else echo($b);
}
?>
</body>
</html><file_sep>/database_connection.php
<?php
/*Define constant to connect to database */
DEFINE('DATABASE_USER', 'root');
DEFINE('DATABASE_PASSWORD', '<PASSWORD>');
DEFINE('DATABASE_HOST', 'localhost');
DEFINE('DATABASE_NAME', 'invoice');
/*Default time zone ,to be able to send mail */
date_default_timezone_set('MST');
//This is the address that will appear coming from ( Sender )
define('EMAIL', '<<EMAIL>>');
/*Define the root url where the script will be found such as http://website.com or http://website.com/Folder/ */
DEFINE('WEBSITE_URL', 'http://invoice-masters.com/activate.php');
// Make the connection:
$dbc = @mysqli_connect(DATABASE_HOST, DATABASE_USER, DATABASE_PASSWORD,
DATABASE_NAME);
if (!$dbc) {
trigger_error('Could not connect to MySQL: ' . mysqli_connect_error());
}
?>
<file_sep>/sendComment.js
function sendComment(index) {
var comments = document.getElementById('comment'+index).value;
var nums = document.getElementById('pro'+index).value;
var creams = document.getElementById('invid'+index).value;
var creames = document.getElementById('invidd').value;
var comString = "?comments="+comments+"&nums="+nums+"&creams="+creams+"&creames="+creames;
http.open("GET", "bob.php" +
comString, true);
http.onreadystatechange = Dohttp;
http.myCustomValue = index;
http.send(null);
}
function txt() {
var creames = document.getElementById('invidd').value;
var txt = document.getElementById("snotes").value;
var txtString = "?txt="+txt+"&creames="+creames;
http.open("GET", "bob.php" +
txtString, true);
http.onreadystatechange = Dohttpp;
http.send(null);
}
function Dohttpp() {
if (http.readyState == 4) {
replyt = http.responseText; // These following lines get the response and update the page
document.getElementById('asnotes').innerHTML = replyt;
}
}
function Dohttp(index) {
if (http.readyState == 4) {
reply = http.responseText; // These following lines get the response and update the page
var index = http.myCustomValue;
document.getElementById('comments'+index).innerHTML = reply;
}
}
function getXHTTP() {
var xhttp;
try { // The following "try" blocks get the XMLHTTP object for various browsers…
xhttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
xhttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e2) {
// This block handles Mozilla/Firefox browsers...
try {
xhttp = new XMLHttpRequest();
} catch (e3) {
xhttp = false;
}
}
}
return xhttp; // Return the XMLHTTP object
}
var http = getXHTTP(); // This executes when the page first loads.
<file_sep>/misc.js
//FOR show vendors
function showVen(index) {
$("#vvid"+index).slideToggle("slow");
}
//end
<file_sep>/sItem.js
function sItem(index, inde) {
var quan = window.prompt("Quantity");
if(quan) {
$(".sel").hide();
var optionnB = document.getElementById('soption'+inde).value;
var num = document.getElementById('proo'+index).value;
var cream = document.getElementById('invid'+index).value;
var creame = document.getElementById('invidd').value;
var qqqueryString = "?optionnB="+optionnB+"&num="+num+"&quan="+quan+"&cream="+cream+"&creame="+creame;
http.open("GET", "bob.php" +
qqqueryString, true);
http.onreadystatechange = gggetHttpRes;
http.myCustomValue = index;
http.send(null);
}
}
function sItems(index, inde) {
var quan = window.prompt("Quantity");
if(quan) {
$(".sel").hide();
var jobop = document.getElementById('soption'+inde).value;
var num = document.getElementById('proo'+index).value;
var cream = document.getElementById('invid'+index).value;
var creame = document.getElementById('invidd').value;
var qqquerryString = "?jobop="+jobop+"&num="+num+"&quan="+quan+"&cream="+cream+"&creame="+creame;
http.open("GET", "bob.php" +
qqquerryString, true);
http.onreadystatechange = gggetHttpRes;
http.myCustomValue = index;
http.send(null);
}
}
function gggetHttpRes(index) {
if (http.readyState == 4) {
rress = http.responseText; // These following lines get the response and update the page
var index = http.myCustomValue;
document.getElementById('prohidden'+index).innerHTML = rress;
}
}
function getXHTTP() {
var xhttp;
try { // The following "try" blocks get the XMLHTTP object for various browsers…
xhttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
xhttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e2) {
// This block handles Mozilla/Firefox browsers...
try {
xhttp = new XMLHttpRequest();
} catch (e3) {
xhttp = false;
}
}
}
return xhttp; // Return the XMLHTTP object
}
var http = getXHTTP(); // This executes when the page first loads.
<file_sep>/index.php
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<meta http-equiv="Content-language" content="us-en" />
<meta name="keywords" content="Free Invoices, customer management, business management, small business, invoicing, Free invoicing Software, Automotive software, parts software, inventory managment, customer managment, Free"/>
<meta name="description" content="Free online Invoicing, customer management, inventory management, and business management. " />
<script src="http://thebestbangforyourbuck.tk/gist/jquery/lib/jquery.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
<link rel="stylesheet" type="text/ css" href="indexcss.css"/>
<script src="index.js"></script>
<STYLE type="text/css" MEDIA="screen, projection">
<!--
@import url(indexcss.css);
-->
</STYLE>
</head>
<body>
<table align="center" id="tTable">
<tr valign="top">
<td class="tTd">
<h1> Welcome to Invoice-Masters</h1>
<img src="img/chart.png" alt="Profit chart" title="Profit chart"/></img>
<img src="img/chart1.png" alt="Invoice-masters pie chart" title="invoice-masters pie chart"/></img>
<div id="acslide">
<a href="#" id="login" class="cslide" title="Login to Invoice-Masters.com">Login</a>
<a href="#" class="ccslide" id="cAslide" title="Register at Invoice-masters.com">Register</a>
</div>
</td>
<span class="success"></span>
<td id="less">
<?
if(isset($_POST['submit'])) {
include('database_connection.php');
session_start();
$usr = $_POST['usr'];
if($usr == '') {
die( 'All feilds must be filled in');
}
else {
$pass = $_POST['pass'];
if($pass == '') {
die('All feild must be filled in');
}
}
$go = "SELECT * FROM `members` WHERE `usr` = '".mysql_real_escape_string($usr)."' AND `pass` = '".mysql_real_escape_string($pass)."'";
$goo = mysqli_query($dbc, $go);
if (@mysqli_num_rows($goo) == 1) //if Query is successfull
{ // A match was made.
$_SESSION = mysqli_fetch_array($goo, MYSQLI_ASSOC);//Assign the result of this query to SESSION Global Variable
header("location:members.php");
}
else {
echo('Username or Password Incorrect');
}
}
?>
<div class="nav">Login:</div><br/><form action="index.php" method="POST" id="form">
<label class="loginlbl">Username:</label>
<input type="text" name="usr" id="usr"/><br/><br/>
<label class="loginlbll">Password:</label>
<input type="password" id="pass" name="pass"/><br/>
<input type="submit" name="submit" id="submit" value="login"/><br/>
<a class="sa" href="pass.php">Forgot Your Password?</a>
</form>
</td>
</tr>
</table>
<table id="center" align="center">
<tr valign="top">
<td id="listtd">
<h3> What We Have To Offer:</h3>
<ul id="list">
<li onclick="aboutUs(1); return false;">Store Customer Information</li>
<li onclick="aboutUs(2); return false;">Store Invoices</li>
<li onclick="aboutUs(3); return false;">Send Invoices Via E-mail</li>
<li onclick="aboutUs(4); return false;" >Inventory Managment</li>
<li onclick="aboutUs(5); return false;">Profit Calculator</li>
<li onclick="aboutUs(6); return false;">Compare Vendor Prices</li>
<li onclick="aboutUs(7); return false;">Add Jobs</li>
<li onclick="aboutUs(8); return false;">Easy Online Managment</li>
<li onclick="aboutUs(9); return false;">Reminders / Events</li>
<li onclick="aboutUs(10); return false;">Fast and Easy Invoicing</li>
<li onclick="aboutUs(11); return false;">It's free!</li>
</ul>
</td>
<td id="centertd">
<h2>Get Started Invoicing For Free!</h2>
<div id="img"><img src="img/invoice.jpg" height="150px;" width="200px;" alt="Free online invoicing"/></div>
<p class="about">
Whether you own a automotive repair business
or trailer dealership / parts dealership, our program will work great for you! Invoice-Masters is a completely free - to - use online invoicing program. Allowing you to
Manage your business from anywhere you would like to. Start managing your inventory and creating invoices in less than 3 minutes with our user friendly website.
Managing your business has never been this easy! Send invoices via E-mail and in a PDF format directly to your customers. See how much money your making each month and
which products are selling the best. Sign up today! Its 100% free to use. Want a 100% custom invoice? Email us at <EMAIL> to get your custom invoice created.
</p>
</td>
</tr>
</table>
</body>
</html><file_sep>/bob.php
<?
include('database_connection.php');
session_start();
//this is for the invoices.php file//
if(isset($_GET['optionn'])) {
ob_start();
$option = $_GET['optionn'];
$cream = $_GET['cream'];
$creame = $_GET['creame'];
$quan = $_GET['quan'];
$go = "SELECT * FROM `inventory` WHERE `midd`='".$_SESSION['id']."' AND `name`= '".$option."' LIMIT 1";
$res = mysqli_query($dbc, $go);
if(!$res) {
die('failed');
}
$dec = "UPDATE `inventory` SET `amount` = `amount`-'".$quan."' WHERE `midd`='".$_SESSION['id']."' AND `name`= '".$option."'";
$deac = mysqli_query($dbc, $dec);
if(!$deac) {
die(mysqli_error($dbc));
}
else {
while($get = mysqli_fetch_array($res)) {
$quan = $_GET['quan'];
$i= $_GET['num'] + 1;
$b = $_GET['num'];
$price = $get['price'];
$pricel = $get['lprice'];
$whole = $get['yprice'];
echo '<div id="items"><span class="itemn">Product:</span><span class="itemm"> '.$get['name'].'</span><br/><span class="itemd">Description:</span>';
echo '<span class="itemm"> '.$get['desc'].'</span></div>';
if($quan >= 1) {
$whole = $whole * $quan;
$price = $price * $quan;
$pricel = $pricel * $quan;
$price = number_format($price, 2);
$pricel = number_format($pricel, 2);
$whole = number_format($whole, 2);
}
echo '<span class="itemp">Quantity:</span><span type="text" class="bob" id="itemn">'.$quan.'</span><br/>';
echo '<span class="itemp">Parts:</span>$<input type="text" class="bob" id="itemn" value="'.$price.'" size="5"/>';
echo '<br/><span class="itemp">Labor:</span>$<input type="text" class="bobl" id="itemm" value="'.$pricel.'" size="6"/>';
echo '<input type="hidden" value="'.$whole.'" id="whole'.$i.'" class="whole" />';
echo '<div id="sel'.$i.'" value="sel'.$i.'" class="zzselect" onClick="selectProduct('.$i.'); return false;">Select Item</div>';
echo '<div id="enter'.$i.'" class="zzenter" onClick="inputFeild('.$i.'); return false;" value="sel'.$i.'">Enter An Item</div>';
echo '<div class="late"></div>';
echo '<input type="hidden" name="invid" id="invid'.$i.'" value="'.$get['yprice'].'" />';
//inserts into database//
$currr =''.ob_get_contents().'';
$get = "SELECT * FROM `dataa` WHERE `invid` ='".$creame."' AND `midd` ='".$_SESSION['id']."' ";
$cget = mysqli_query($dbc, $get);
if(!$cget) {
die(mysqli_error($dbc));
}
$none = mysqli_num_rows($cget);
if($none == 0) {
$ii ="INSERT INTO `dataa` (`invid`, `midd`, `data$b`) VALUES ('".$creame."', '".$_SESSION['id']."', '".$currr."')";
$io = mysqli_query($dbc, $ii);
if(!$io) {
die(mysqli_error($dbc));
}
}
if($none > 0) {
$hh ="UPDATE `dataa` SET `data$b` = '".$currr."' WHERE `invid` = '".$creame."' AND `midd` = '".$_SESSION['id']."'";
$hj = mysqli_query($dbc, $hh);
if(!$hh) {
die(mysqli_error($dbc));
}
}
ob_end_flush();
}
}
}
//end
//end invoices.php file
//this is for Binvoice.php file
if(isset($_GET['optionnB'])) {
ob_start();
$option = $_GET['optionnB'];
$cream = $_GET['cream'];
$creame = $_GET['creame'];
$quan = $_GET['quan'];
$go = "SELECT * FROM `inventory` WHERE `midd`='".$_SESSION['id']."' AND `name`= '".$option."' LIMIT 1";
$res = mysqli_query($dbc, $go);
if(!$res) {
die('failed');
}
$dec = "UPDATE `inventory` SET `amount` = `amount`-'".$quan."' WHERE `midd`='".$_SESSION['id']."' AND `name`= '".$option."'";
$deac = mysqli_query($dbc, $dec);
if(!$deac) {
die(mysqli_error($dbc));
}
else {
$v= $_GET['num'] + 1;
echo '<table class="protable" id="protable'.$v.'" align="center">';
while($get = mysqli_fetch_array($res)) {
$quan = $_GET['quan'];
$i= $_GET['num'] + 1;
$b = $_GET['num'];
$price = $get['price'];
$pricel = $get['lprice'];
if($price =='none') {
$price ='0.00';
}
if($pricel =='none') {
$pricel ='0.00';
}
$whole = $get['yprice'];
$name = $get['name'];
$tell = $get['desc'];
$priceH = $get['lprice'];
echo '<tr valign="top"><a href="#" class="keep" id="keep'.$v.'" onclick="removeItem('.$v.'); return false;">[ remove ]</a>';
echo '<td class="itemP"><span class="itemn">Quantity:</span><br/><span class="">'.$quan.'</span></td>';
echo '<td class="itemN"><span class="itemn">Part#:</span><br/><span class="itemp">'.$name.'</span></td>';
echo '<td class="itemD"><span class="itemn">Description:</span><br/><span class="itemp">'.$tell.'</span></td>';
if($quan > 1) {
if($priceH == 0) {
$tprice = $price + $pricel;
$sprice = number_format($tprice, 2);
$whole = $whole * $quan;
$price = $price * $quan;
$pricel = $pricel * $quan;
$whole = number_format($whole, 2);
$zprice = $price + $pricel;
$zzprice = number_format($price, 2);
$priceG = $get['price'];
echo '<td class="itemG"><span class="itemn">Price:</span><br/>$<input type="text" class="bobu" size="4" value="'.$priceG.'"></td>';
echo '<td class="itemF"><span class="itemn">Total:</span><br/>$<input type="text" class="bob" value="'.$zzprice.'" size="4"/></td>';
}
else {
$tprice = $price + $pricel;
$sprice = number_format($tprice, 2);
$whole = $whole * $quan;
$price = $price * $quan;
$pricel = $pricel * $quan;
$whole = number_format($whole, 2);
$zprice = number_format($price, 2);
$zzprice = number_format($pricel, 2);
$priceG = $get['price'];
echo '<td class="itemG"><span class="itemn">Labor:</span><br/>$<input type="text" class="bobl" size="4" value="'.$zzprice.'"></td>';
echo '<td class="itemF"><span class="itemn">Parts:</span><br/>$<input type="text" class="bob" value="'.$zprice.'" size="4"/></td>';
}
}
else {
if($priceH == 0) {
$sprice = number_format($price, 2);
echo '<td class="itemG"></td>';
echo '<td class="itemF"><span class="itemn">Total:</span><br/>$<input type="text" class="bob" value="'.$sprice.'" size="4"/></td>';
}
else {
$tprice = number_format($pricel, 2);
$sprice = number_format($price, 2);
echo '<td class="itemG"><span class="itemn">Labor:</span><br/>$<input type="text" class="bobl" size="4" value="'.$tprice.'"></td>';
echo '<td class="itemF"><span class="itemn">Parts:</span><br/>$<input type="text" class="bob" value="'.$sprice.'" size="4"/></td>';
}
}
echo '<input type="hidden" value="'.$whole.'" id="whole'.$i.'" class="whole"/>';
echo '</tr></table>';
echo '<div id="sel'.$i.'" value="sel'.$i.'" class="zzselect" onClick="selectProduct('.$i.'); return false;">Select Item</div>';
echo '<div id="enter'.$i.'" class="zzenter" onClick="inputFeild('.$i.'); return false;" value="sel'.$i.'">Enter An Item</div>';
echo '<div class="late"></div>';
echo '<input type="hidden" name="invid" id="invid'.$i.'" value="'.$get['yprice'].'" />';
echo '<input type="hidden" name="invoice" id="invidn'.$v.'" value="'.$creame.'" />';
//inserts into database//
$currr =''.ob_get_contents().'';
$get = "SELECT * FROM `dataa` WHERE `invid` ='".$creame."' AND `midd` ='".$_SESSION['id']."' ";
$cget = mysqli_query($dbc, $get);
if(!$cget) {
die(mysqli_error($dbc));
}
$none = mysqli_num_rows($cget);
if($none == 0) {
$ii ="INSERT INTO `dataa` (`invid`, `midd`, `data$b`) VALUES ('".$creame."', '".$_SESSION['id']."', '".$currr."')";
$io = mysqli_query($dbc, $ii);
if(!$io) {
die(mysqli_error($dbc));
}
}
if($none > 0) {
$hh ="UPDATE `dataa` SET `data$b` = '".$currr."' WHERE `invid` = '".$creame."' AND `midd` = '".$_SESSION['id']."'";
$hj = mysqli_query($dbc, $hh);
if(!$hh) {
die(mysqli_error($dbc));
}
}
}
ob_end_flush();
}
}
//end Binvoe file
if(isset($_GET['jobop'])) {
ob_start();
$option = $_GET['jobop'];
$cream = $_GET['cream'];
$creame = $_GET['creame'];
$quan = $_GET['quan'];
$i= $_GET['num'] + 1;
$b = $_GET['num'];
$go = "SELECT * FROM `jobs` WHERE `midd`='".$_SESSION['id']."' AND `job num`= '".$option."' ";
$res = mysqli_query($dbc, $go);
if(!$res) {
die(mysqli_error($dbc));
}
echo '<table class="protable" align="center">';
while($get = mysqli_fetch_array($res)) {
$price = $get['Jpartstot'];
$whole = $get['jprofite'];
$pricel = $get['Jlabortot'];
if($quan >= 1) {
$whole = $whole * $quan;
$price = $price * $quan;
$pricel = $pricel * $quan;
$price = number_format($price, 2);
$pricel = number_format($pricel, 2);
$whole = number_format($whole, 2);
}
$uno = $get['Jpartstot'] + $get['Jlabortot'];
$uuno = number_format($uno, 2);
$one = $price + $pricel;
$two = number_format($one, 2);
echo '<tr valign="top"><td class="itemP"><span class="itemn">Quantity:</span><br/><span type="text" class="bob" >'.$quan.'</span></td>';
echo '<td class="itemN"><span class="itemn">Job:</span><br/><span class="itemp"> '.$get['Jname'].'</span></td>';
echo '<td class="itemD"><span class="itemn">Description:</span><br/><span class="itemp"> '.$get['Jdesc'].'</span></td>';
echo '<td class="itemGG"><span class="itemn">Price:</span><br/>$<input type="text" class="bobu" value="'.$uuno.'" size="4"/></td>';
echo '<td class="itemF"><span class="itemn">Total:</span><br/>$<input type="text" class="bobu" value="'.$two.'" size="4"/></td></tr>';
echo '<div class="clozze" id="clozze'.$b.'" onClick="sParts('.$b.'); return false;">[ X ]</div>';
for($k=1; $k<11; $k++) {
if($get['jparts'.$k.''] != '' AND $get['Jpart'.$k.''] != '') {
$Jquan = $get['Jquan'.$k.''];
if($quan > 1) {
if($Jquan > 1) {
$Jquan = $Jquan * $quan;
}
if($Jquan <= 1) {
$Jquan = $quan;
}
}
echo '<tr valign="top" class="hPP'.$b.'"><td class="itemP"><span class="itemn">Quantity:</span><br/><span type="text" class="bob" >'.$Jquan.'</span></td>';
echo '<td class="itemN"><span class="itemn">Part#:</span><br/><span class="itemp"> '.$get['Jpart'.$k.''].'</span></td>';
echo '<td class="itemD"><span class="itemn"></span><br/><span class="itemp"></span></td>';
if($Jquan > 1) {
$iprice = $get['jparts'.$k.''] * $Jquan;
$pricee = number_format($iprice, 2);
echo '<td class="itemG"><span class="itemn"></span><br/>$<input type="text" class="bobu" value="'.$get['jparts'.$k.''].'" size="4"/></td>';
echo '<td class="itemF"><span class="itemn"></span><br/>$<input type="text" class="bob" value="'.$pricee.'" size="4"/></td></tr>';
}
else {
$pricee = $get['jparts'.$k.''];
echo '<td class="itemG"><input type="text" class="bobu" size="4"/></td>';
echo '<td class="itemF"><span class="itemn"></span><br/>$<input type="text" class="bob" value="'.$pricee.'" size="4"/></td></tr>';
}
}
}
for($k=1; $k<6; $k++) {
if($get['Jlabor'.$k.''] !='' AND $get['jjlabor'.$k.''] !='') {
$ipricel = $get['jjlabor'.$k.''] * $quan;
$pricell = number_format($ipricel, 2);
echo '<tr valign="top" class="hPP'.$b.'"><td class="itemP"><span class="itemn">Quantity:</span><br/><span type="text" class="bobl" >'.$quan.'</span></td>';
echo '<td class="itemN"><span class="itemn">Labor:</span><br/><span class="itemp"> '.$get['Jlabor'.$k.''].'</span></td>';
echo '<td class="itemD"><span class="itemn"></span><br/><span class="itemm"></span></td>';
if($quan > 1) {
echo '<td class="itemG"><span class="itemn"></span><br/>$<input type="text" class="bobu" value="'.$get['jjlabor'.$k.''].'" size="4"/></td>';
echo '<td class="itemF"><span class="itemn"></span><br/>$<input type="text" class="bobl" value="'.$pricell.'" size="4"/></td></tr>';
}
else {
echo '<td class="itemG"><input type="text" class="bobu" size="4"/></td>';
echo '<td class="itemF"><span class="itemn"></span><br/>$<input type="text" class="bobl" value="'.$pricell.'" size="4"/></td></tr>';
}
}
}
echo '</span>';
echo '</table>';
echo '<input type="hidden" value="'.$whole.'" id="whole'.$i.'" class="whole" />';
echo '<div id="sel'.$i.'" value="sel'.$i.'" class="zzselect" onClick="selectProduct('.$i.'); return false;">Select Item</div>';
echo '<div id="enter'.$i.'" class="zzenter" onClick="inputFeild('.$i.'); return false;" value="sel'.$i.'">Enter An Item</div>';
echo '<div class="late"></div>';
echo '<input type="hidden" name="invid" id="invid'.$i.'" value="'.$whole.'" />';
}
//inserts into database//
$currr =''.ob_get_contents().'';
$get = "SELECT * FROM `dataa` WHERE `invid` ='".$creame."' AND `midd` ='".$_SESSION['id']."' ";
$cget = mysqli_query($dbc, $get);
if(!$cget) {
die(mysqli_error($dbc));
}
$none = mysqli_num_rows($cget);
if($none == 0) {
$ii ="INSERT INTO `dataa` (`invid`, `midd`, `data$b`) VALUES ('".$creame."', '".$_SESSION['id']."', '".$currr."')";
$io = mysqli_query($dbc, $ii);
if(!$io) {
die(mysqli_error($dbc));
}
}
if($none != 0) {
$hh ="UPDATE `dataa` SET `data$b` = '".$currr."' WHERE `invid` = '".$creame."' AND `midd` = '".$_SESSION['id']."'";
$hj = mysqli_query($dbc, $hh);
if(!$hh) {
die(mysqli_error($dbc));
}
}
ob_end_flush();
}
//end
if(isset($_GET['comments'])) {
ob_start();
$cream = $_GET['creams'];
$creame = $_GET['creames'];
$b = $_GET['nums'] - 1;
$comment = $_GET['comments'];
if($comment != '') {
echo '<span class="coms">Comments: </span><span class="comtxt">'.$_GET['comments'].'</span>';
$currr =''.ob_get_contents().'';
$get = "SELECT * FROM `datacom` WHERE `invid` ='".$creame."' AND `midd` ='".$_SESSION['id']."' ";
$cget = mysqli_query($dbc, $get);
if(!$cget) {
die(mysqli_error($dbc));
}
$none = mysqli_num_rows($cget);
if($none == 0) {
$ii ="INSERT INTO `datacom` (`invid`, `midd`, `data$b`) VALUES ('".$creame."', '".$_SESSION['id']."', '".$currr."')";
$io = mysqli_query($dbc, $ii);
if(!$io) {
die(mysqli_error($dbc));
}
}
}
if($none != 0) {
$hh ="UPDATE `datacom` SET `data$b` = '".$currr."' WHERE `invid` = '".$creame."' AND `midd` = '".$_SESSION['id']."'";
$hj = mysqli_query($dbc, $hh);
if(!$hh) {
die(mysqli_error($dbc));
}
}
ob_end_flush();
}
if(isset($_GET['txt'])) {
if(!$_GET['txt'] == '') {
$creame = $_GET['creames'];
ob_start();
echo '<div id="aasnotes"><div id="comtxt">'.$_GET['txt'].'</div></div>';
$currr =''.ob_get_contents().'';
$ii ="UPDATE `invoices` SET `special` = '".mysql_real_escape_string($currr)."' WHERE (`invid` = '".$creame."' AND `midd` = '".$_SESSION['id']."')";
$io = mysqli_query($dbc, $ii);
if(!$io) {
die(mysqli_error($dbc));
}
}
ob_end_flush();
}
?><file_sep>/cust.js
function enterCust(index) {
$("#centertd").slideUp("slow")
.slideDown("slow")
.css("width", "auto");
$("#center").css("box-shadow", "none");
var idd = document.getElementById('li'+index).value;
if(idd == 1) {
$("#info").css("width", "auto")
.css("height", "auto");
$("#EmailI").show();
$("#leftul").hide();
$("#show").show();
$("#show").click(function() {
var save = confirm("Do you want to save this invoice?");
if(save == false) {
var cancle = document.getElementById('saveinv').value;
$("#leftul").show();
$("#show").hide();
var queryString = "?cancle="+cancle;
http.open("GET", "delete.php" +
queryString, true);
http.onreadystatechange = getHttpRes;
http.send(null);
}
else {
$("#leftul").show();
$("#show").hide();
}
return false;
});
$("#info").css("background", "white");
$("#centertd").css("background", "white");
var idd = document.getElementById('li'+index).value;
var queryString = "?idd="+idd;
http.open("GET", "Binvoice.php" +
queryString, true);
http.onreadystatechange = getHttpRes;
http.send(null);
state = false;
}
if(idd == 2) {
$("#left").animate({display:"block", opacity:"1.0"}, 900);
$("#info").css("width", "900")
.css("height", "auto");
var id = document.getElementById('li'+index).value;
var queryString = "?id="+id;
http.open("GET", "customer.php" +
queryString, true);
http.onreadystatechange = getHttpRes;
http.send(null);
}
if(idd == 3) {
$("#info").css("width", "1000")
.css("height", "auto");
var iddd = document.getElementById('li'+index).value;
var queryString = "?iddd="+iddd;
http.open("GET", "customer.php" +
queryString, true);
http.onreadystatechange = getHttpRes;
http.send(null);
}
if(idd == 4) {
$("#info").css("width", "auto")
.css("height", "auto");
var idddd = document.getElementById('li'+index).value;
var queryString = "?idddd="+idddd;
http.open("GET", "customer.php" +
queryString, true);
http.onreadystatechange = getHttpRes;
http.send(null);
}
if(idd == 5) {
$("#info").css("width", "auto")
.css("height", "auto");
var inv = document.getElementById('li'+index).value;
var queryString = "inv="+inv;
$.ajax({
url:"customer.php",
data:queryString,
success:function(result) {
$("#info").html(result);
$(".callback").css("height", "130")
.css("width", "250");
$(".call").css("font-size", "14px");
$(".dcall").css("font-size", "12px");
},
});
}
if(idd == 6) {
$("#info").css("width", "auto")
.css("height", "auto");
var profits = document.getElementById('li'+index).value;
var queryString = "?profits="+profits;
http.open("GET", "customer.php" +
queryString, true);
http.onreadystatechange = getHttpRes;
http.send(null);
}
if(idd == 7) {
$("#info").css("width", "1175")
.css("height", "auto");
var vendors = document.getElementById('li'+index).value;
var queryString = "?vendors="+vendors;
http.open("GET", "customer.php" +
queryString, true);
http.onreadystatechange = getHttpRes;
http.send(null);
}
if(idd == 8) {
$("#info").css("width", "auto")
.css("height", "auto");
$("#left").animate({display:"block", opacity:"1.0"}, 900);
$("#centertd").css("background", "#d8d8d8");
$("#info").css("background", "#d8d8d8");
$("#info").css("width", "1000");
var events = document.getElementById('li'+index).value;
var queryString = "?events="+events;
http.open("GET", "customer.php" +
queryString, true);
http.onreadystatechange = getHttpRes;
http.send(null);
}
if(idd == 9) {
$("#info").css("width", "1000")
.css("height", "auto");
var vendors = document.getElementById('li'+index).value;
var queryString = "?vendors="+vendors;
http.open("GET", "home.php" +
queryString, true);
http.onreadystatechange = getHttpRes;
http.send(null);
}
}
function getHttpRes() {
if (http.readyState == 4) {
res = http.responseText; // These following lines get the response and update the page
document.getElementById('info').innerHTML = res;
}
}
function getXHTTP() {
var xhttp;
try { // The following "try" blocks get the XMLHTTP object for various browsers…
xhttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
xhttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e2) {
// This block handles Mozilla/Firefox browsers...
try {
xhttp = new XMLHttpRequest();
} catch (e3) {
xhttp = false;
}
}
}
return xhttp; // Return the XMLHTTP object
}
var http = getXHTTP(); // This executes when the page first loads.
<file_sep>/settings.php
<?php
session_start();
if(!isset($_SESSION['usr'])){
header("location:http://invoiceit.tk");
}
if(isset($_GET['company'])) {
include('database_connection.php');
$com = mysql_real_escape_string($_GET['company']);
$tax = mysql_real_escape_string($_GET['ctax']);
$phone = mysql_real_escape_string($_GET['cphone']);
$fax = mysql_real_escape_string($_GET['cfax']);
$addr = mysql_real_escape_string($_GET['caddr']);
$disc = mysql_real_escape_string($_GET['discs']);
$slogan = mysql_real_escape_string($_GET['slogan']);
$id = mysql_real_escape_string($_SESSION['id']);
$go = "UPDATE `members` SET `Bname`='$com', `tax`='$tax', `phone`='$phone', `fax`='$fax', `addr`='$addr', `slogan`='$slogan', `disclaimer`='$disc' WHERE `id`='$id' ";
$goo = mysqli_query($dbc, $go);
if(!$goo) {
die(mysqli_error($dbc));
}
else {
echo ' Thanks your information has been Updated, You will need to log out and log back in for these to tak effect.<br/> After that your invoice templete will now show the changes!';
}
}
?>
<? function jobForm() {
?>
<p class="ll" style="color:red; text-align:center;"><span style="font-size:18px; font-weight:bold; color:blue;">To add a job;</span><br/> Fill out the form bellow, When you are done: use the <span style="color:blue; text-transform:italic; text-decoration:italic;">Total Button</span>
to add up the total of the job and save your prices. Make sure you enter in a whole-sale price first so you will know how much money you will be making off the job. Don't click Add Job untill you have clicked Total.</p>
<table align="left" id="Jobtable" style="padding-top:10px;">
<tr valign="top">
<td id="Jmain" style="float:left">
<form id="Jform" action="jobPhp.php" method="get">
<div id="formright" style="float:right;">
<label class="lblss">Job Name:</label><br/>
<input type="text" id="Jname" name="Jname" /><br/>
<label class="lblss">Job Group:</label><br/>
<input type="text" id="Jgroup" name="Jgroup"><br/>
<label class="lblss">Job description:</label><br/>
<input type="text" id="Jdesc" name="Jdesc"/><br/>
<label class="lblss">Job Wholesale:</label><br/>
$<input type="text" id="Jwhole" size="7" name="Jwhole"/><br/>
<label type="text" class="lblss">Tax:</label><br/>
<?echo($_SESSION['tax']);?>%<br/>
</td>
<td id="par">
<div id="formright" style="float:right;">
<?
for($i=1; $i<11; $i++) {
echo '<label class="lbls">Quantity - Price - Part#'.$i.':</label><br/>';
echo '<input type="text" id="Jquan'.$i.'" name="Jquan'.$i.'" size="1">';
echo '$<input type="text" id="jparts'.$i.'" name="jparts'.$i.'" size="5">';
echo ' - <input type="text" id="Jparts'.$i.'" name="Jparts'.$i.'"/><br/>';
}
?>
</td>
<td style="float:right; padding-bottom:210px;" id="lab">
<?
for($k=1; $k<6; $k++) {
echo '<label class="lbls">Price - Labor #'.$k.':</label><br/>';
echo '$<input type="text" id="jlabor'.$k.'" name="jlabor'.$k.'" size="5">';
echo ' - <input type="text" id="Jlabor'.$k.'" name="Jlabor'.$k.'"/><br/>';
}
?>
<br/>
<div id="Jstotal"></div>
<input type="submit" id="Jsend" value="Add Job" name="submit"/>
</form>
</div>
<input type="submit" id="Jadd" value="Total" onClick="addjForm(); return false"/><br/><br/>
</tr>
</td>
</table>
<?
}
?><file_sep>/addjForm.js
function addDelete(index) {
var jj = document.getElementById('MIDD').value;
http.myCustomValue = index;
var qqueeryString = "?jj="+jj+"&index="+index;
http.open("GET", "query.php" +
qqueeryString, true);
http.onreadystatechange = qgeetHttpRes;
http.send(null);
}
function addjForm(index) {
if (index) {
var Jparts1 = document.getElementById('jparts1'+index).value;
var Jparts2 = document.getElementById('jparts2'+index).value;
var Jparts3 = document.getElementById('jparts3'+index).value;
var Jparts4 = document.getElementById('jparts4'+index).value;
var Jparts5 = document.getElementById('jparts5'+index).value;
var Jparts6 = document.getElementById('jparts6'+index).value;
var Jparts7 = document.getElementById('jparts7'+index).value;
var Jparts8 = document.getElementById('jparts8'+index).value;
var Jparts9 = document.getElementById('jparts9'+index).value;
var Jparts10 = document.getElementById('jparts10'+index).value;
var Jlabor1 = document.getElementById('jlabor1'+index).value;
var Jlabor2 = document.getElementById('jlabor2'+index).value;
var Jlabor3 = document.getElementById('jlabor3'+index).value;
var Jlabor4 = document.getElementById('jlabor4'+index).value;
var Jlabor5 = document.getElementById('jlabor5'+index).value;
var Jquan1 = document.getElementById('Jquan1'+index).value;
var Jquan2 = document.getElementById('Jquan2'+index).value;
var Jquan3 = document.getElementById('Jquan3'+index).value;
var Jquan4 = document.getElementById('Jquan4'+index).value;
var Jquan5 = document.getElementById('Jquan5'+index).value;
var Jquan6 = document.getElementById('Jquan6'+index).value;
var Jquan7 = document.getElementById('Jquan7'+index).value;
var Jquan8 = document.getElementById('Jquan8'+index).value;
var Jquan9 = document.getElementById('Jquan9'+index).value;
var Jquan10 = document.getElementById('Jquan10'+index).value;
var Jwhole = document.getElementById('Jwhole'+index).value;
http.myCustomValue = index;
var qqueeryString = "?Jparts1="+Jparts1+"&Jparts2="+Jparts2+"&Jparts2="+Jparts2+"&Jparts3="+Jparts3+"&Jparts4="+Jparts4+"&Jparts5="+Jparts5+"&Jparts6="+Jparts6+"&Jparts7="+Jparts7+"&Jparts8="+Jparts8+"&Jparts9="+Jparts9+"&Jparts10="+Jparts10+"&Jlabor1="+Jlabor1+"&Jlabor2="+Jlabor2+"&Jlabor3="+Jlabor3+"&Jlabor4="+Jlabor4+"&Jlabor5="+Jlabor5+"&Jwhole="+Jwhole+"&index="+index+"&Jquan1="+Jquan1+"&Jquan2="+Jquan2+"&Jquan3="+Jquan3+"&Jquan4="+Jquan4+"&Jquan5="+Jquan5+"&Jquan6="+Jquan6+"&Jquan7="+Jquan7+"&Jquan8="+Jquan8+"&Jquan9="+Jquan9+"&Jquan10="+Jquan10;
http.open("GET", "query.php" +
qqueeryString, true);
http.onreadystatechange = qgeetHttpRes;
http.send(null);
}
else {
var jobnum = $(".jobnum").attr('value');
var Jparts1 = document.getElementById('jparts1').value;
var Jparts2 = document.getElementById('jparts2').value;
var Jparts3 = document.getElementById('jparts3').value;
var Jparts4 = document.getElementById('jparts4').value;
var Jparts5 = document.getElementById('jparts5').value;
var Jparts6 = document.getElementById('jparts6').value;
var Jparts7 = document.getElementById('jparts7').value;
var Jparts8 = document.getElementById('jparts8').value;
var Jparts9 = document.getElementById('jparts9').value;
var Jparts10 = document.getElementById('jparts10').value;
var Jquan1 = document.getElementById('Jquan1').value;
var Jquan2= document.getElementById('Jquan2').value;
var Jquan3 = document.getElementById('Jquan3').value;
var Jquan4 = document.getElementById('Jquan4').value;
var Jquan5 = document.getElementById('Jquan5').value;
var Jquan6 = document.getElementById('Jquan6').value;
var Jquan7 = document.getElementById('Jquan7').value;
var Jquan8 = document.getElementById('Jquan8').value;
var Jquan9 = document.getElementById('Jquan9').value;
var Jquan10 = document.getElementById('Jquan10').value;
var Jlabor1 = document.getElementById('jlabor1').value;
var Jlabor2 = document.getElementById('jlabor2').value;
var Jlabor3 = document.getElementById('jlabor3').value;
var Jlabor4 = document.getElementById('jlabor4').value;
var Jlabor5 = document.getElementById('jlabor5').value;
var Jwhole = document.getElementById('Jwhole').value;
var qqueeryString = "?Jparts1="+Jparts1+"&jobnum="+jobnum+"&Jparts2="+Jparts2+"&Jparts2="+Jparts2+"&Jparts3="+Jparts3+"&Jparts4="+Jparts4+"&Jparts5="+Jparts5+"&Jparts6="+Jparts6+"&Jparts7="+Jparts7+"&Jparts8="+Jparts8+"&Jparts9="+Jparts9+"&Jparts10="+Jparts10+"&Jlabor1="+Jlabor1+"&Jlabor2="+Jlabor2+"&Jlabor3="+Jlabor3+"&Jlabor4="+Jlabor4+"&Jlabor5="+Jlabor5+"&Jwhole="+Jwhole+"&index="+index+"&Jquan1="+Jquan1+"&Jquan2="+Jquan2+"&Jquan3="+Jquan3+"&Jquan4="+Jquan4+"&Jquan5="+Jquan5+"&Jquan6="+Jquan6+"&Jquan7="+Jquan7+"&Jquan8="+Jquan8+"&Jquan9="+Jquan9+"&Jquan10="+Jquan10;
http.open("GET", "query.php" +
qqueeryString, true);
http.onreadystatechange = qgeetHttpRes;
http.send(null);
}
}
function qgeetHttpRes() {
if (http.readyState == 4) {
qrees = http.responseText; // These following lines get the response and update the page
var index = http.myCustomValue;
if(index){
document.getElementById('Jstotals').innerHTML = qrees;
}
else {
document.getElementById('Jstotal').innerHTML = qrees;
}
}
}
function getXHTTP() {
var xhttp;
try { // The following "try" blocks get the XMLHTTP object for various browsers…
xhttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
xhttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e2) {
// This block handles Mozilla/Firefox browsers...
try {
xhttp = new XMLHttpRequest();
} catch (e3) {
xhttp = false;
}
}
}
return xhttp; // Return the XMLHTTP object
}
var http = getXHTTP(); // This executes when the page first loads.
<file_sep>/Binvoice/Binvoice.php
<head>
<meta content="text/css">
<link rel="stylesheet" type="text/ css" href="main.css"></link>
<STYLE type="text/css" MEDIA="screen, projection">
<!--
@import url(main.css);
-->
</STYLE>
</head>
<?php
//creat new invoice number
session_start();
if(isset($_GET['idd'])) {
include('database_connection.php');
$got = "SELECT * FROM `invoices` WHERE `midd` ='".$_SESSION['id']."' ORDER BY `invid` DESC LIMIT 1 ";
$gp = mysqli_query($dbc, $got);
$hd = mysqli_fetch_array($gp);
$row = mysqli_num_rows($gp);
if($row == 0) {
$poke = "INSERT INTO `invoices` (`invid`, `midd`) VALUES ('1', '".$_SESSION['id']."')";
$mon = mysqli_query($dbc, $poke);
$cream = '1';
}
if($row > 0) {
$goty = "SELECT * FROM `invoices` WHERE `midd` ='".$_SESSION['id']."' ORDER BY `invid` DESC LIMIT 1 ";
$hh = mysqli_query($dbc, $goty);
$jy = mysqli_fetch_array($hh);
$cream = $jy['invid'] + 1;
$pokey = "INSERT INTO `invoices` (`invid`, `midd`) VALUES ('".$cream."', '".$_SESSION['id']."')";
$cocka = mysqli_query($dbc, $pokey);
if(!$cocka){
die(mysqli_error($dbc));
}
}
?>
<div id="EmailI" onclick="emailMe(); return false;">Email</div>
<div id="emailinv"></div>
<div id="invoiceN">Invoice #:<br/><?echo($cream);?></div><br/>
<table id="invoice" align="left">
<tr valign="top">
<td>
<?php if(!$_SESSION['img'] == '0'){ echo '<img class="img" src="img/'.$_SESSION['img'].'" height="200" width="250"/>';}?>
</td>
</tr>
</table><br/>
<table align="right" id="contact">
<tr valign="top">
<td id="con" class="colorr">
<span class="bname"><?echo($_SESSION['Bname']);?></span><br/>
<span class="con">Phone:</span> <?echo($_SESSION['phone']);?><br/>
<span class="con">Fax:</span> <?echo($_SESSION['fax']);?><br/>
<span class="con">Address:</span> <?echo($_SESSION['addr']);?><br/>
</td>
</tr>
</table><br/>
<table align="center" id="custable" class="colorr">
<tr valign="top">
<td id="icusttd" class="colorr">
<form action="" method="GET" id="custform">
<input type="text" name="iname" id="iname" onClick="runTime(); return false;"/>
<label class="lbl">Customer Name:</label><br/>
<span id="getauto">
<input type="text" name="ilast name" id="ilastname"/>
<label class="lbl">Last Name:</label><br/>
<input type="text" name="iphone" id="iphone"/>
<label class="lbl">Phone:</label><br/>
<input type="text" name="iwphone" id="iwphone"/>
<label class="lbl">Work Phone:</label><br/>
<input type="text" name="iaddr" id="iaddr"/>
<label class="lbl">Address</label><br/>
<input type="text" name="iemail" id="iemail"/>
<label class="lbl">E-mail</label><br/>
</span>
<input type="hidden" name="imid" id="imid" value="<? echo($_SESSION['id']);?>"/>
<input type="hidden" name="invidd" id="invidd" value="<?echo($cream);?>" />
<input type="hidden" name="idate" id="idate" value=""/>
<input type="submit" name="submit" id="icust-submit" onclick="iSubmitForm(); return false;" value="submit"/>
</form>
</td>
</tr>
</table><br/>
<div class="linee"><?echo($_SESSION['slogan']);?>
</div>
<div class="line">
<table id="zztable" align="center" class="colorr">
<div id="sel1" value="sel1" class="zzselect" onClick="selectProduct(1); return false;">Select Item
</div>
<div id="enter1" class="zzenter" onClick="inputFeild(1); return false;" value="sel1">Enter An Item
</div>
<div id="prohidden1" class="sel1">
</div>
<input type="hidden" name="pro1" id="pro1" value="1"/>
<input type="hidden" name="invid" id="invid1" value="<?echo($cream);?>" />
<input type="hidden" name="pro2" id="pro2" value="2"/>
<div id="prohidden2" class="sel1" >
</div>
<input type="hidden" name="pro3" id="pro3" value="3"/>
<div id="prohidden3" class="sel1" >
</div>
<input type="hidden" name="pro4" id="pro4" value="4"/>
<div id="prohidden4" class="sel1" ></div>
<input type="hidden" name="pro5" id="pro5" value="5"/>
<div id="prohidden5" class="sel1" ></div>
<input type="hidden" name="pro6" id="pro6" value="6"/>
<div id="prohidden6" class="sel1" ></div>
<input type="hidden" name="pro7" id="pro7" value="7"/>
<div id="prohidden7" class="sel1" ></div>
<input type="hidden" name="pro8" id="pro8" value="8"/>
<div id="prohidden8" class="sel1" ></div>
<input type="hidden" name="pro9" id="pro9" value="9"/>
<div id="prohidden9" class="sel1" ></div>
<input type="hidden" name="pro10" id="pro10" value="10"/>
<div id="prohidden10" class="sel1" ></div>
<input type="hidden" name="pro11" id="pro11" value="11"/>
<div id="prohidden11" class="sel1" ></div>
</table>
</div>
<div id="div1">
</div>
<button id="sub-button" class="button" name="sub-button" value="<?echo($_SESSION['id']);?>" onClick="Add(); return false;">Total
</button><br/><br/>
<div id="total">
</div>
<div id="notes">
<input type="button" name="txt-button" id="txt-button" class="button" onClick="txt(); return false;" value="Okay" />
<span class="special">Special Notes:<br/>
<div id="asnotes">
<textarea cols="90" rows="6" WRAP="VIRTUAL" class="button" id="snotes">
</textarea>
</div>
<table align="left">
<tr valign="top">
<td >
<label id="disc">Disclaimer:
</label><br/>
<? $go = "SELECT * FROM `members` WHERE `id`='".$_SESSION['id']."' ";
$get = mysqli_query($dbc, $go);
while($res = mysqli_fetch_array($get)) {
echo '<div id="ddisc" class="colorr">'.$res['disclaimer'].'</div><br/>';
}
?>
</td>
</tr>
</table>
<table align="left">
<tr valing="top">
<td>
<input type="button" name="ready-button" id="ready" onClick="allReady(); return false;" class="button" value="Print"/>
</td>
<td>
<input type="button" id="saveit" onClick="saveIt(); return false;" value="Save Me" class="button"/>
</td>
<td>
<div id="sign">
<span style="color:red;">Customer Signiture[ X ]
</span>____________________________________
</div>
<div id="talk">http://InvoicerFree.tk</div>
</td>
</tr>
</table>
<?php
$date = new DateTime('');
$date->add(new DateInterval('P0Y0M3DT0H0M0S'));
$date1 = $date->format('M-d-y') ."\n";
?>
<input type="hidden" value="<?echo($cream);?>" id="saveinv" />
<input type="hidden" id="dateinv" value="<?echo($date1);?>"/>
<input type="hidden" id="sid" value="<?echo($_SESSION['id']);?>"/>
</body>
</html>
<?php
}
?>
<file_sep>/img/poop_files/upCust.js
function showMee(index) {
$("#upCust"+index).show();
$("#Cdelete"+index).show();
}
function upCust(index) {
var tnaame = document.getElementById('tnaame'+index).value;
var tlast = document.getElementById('tlast'+index).value;
var tphone = document.getElementById('tphone'+index).value;
var twphone = document.getElementById('twphone'+index).value;
var taddr = document.getElementById('taddr'+index).value;
var tdate = document.getElementById('tdate'+index).value;
var temail = document.getElementById('temail'+index).value;
var rsquerrySstring = "?tnaame="+tnaame+"&tlast="+tlast+"&tphone="+tphone+"&twphone="+twphone+"&taddr="+taddr+"&tdate="+tdate+"&index="+index+"&temail="+temail;
http.open("GET", "customer.php" +
rsquerrySstring, true);
http.onreadystatechange = rsrgetHttpResss;
http.myCustomValue = index;
http.send(null);
$("#upCust"+index).hide();
}
function CdeleteMe(index) {
var sure = confirm("The invoice belonging to this customer will also be deleted.\r\n Are you sure you want to deleted this customer and invoice?");
if(sure == true) {
var Ftnaame = document.getElementById('tnaame'+index).value;
var tlast = document.getElementById('tlast'+index).value;
var tphone = document.getElementById('tphone'+index).value;
var twphone = document.getElementById('twphone'+index).value;
var taddr = document.getElementById('taddr'+index).value;
var tdate = document.getElementById('tdate'+index).value;
var temail = document.getElementById('temail'+index).value;
var Cinv = document.getElementById('Cinv'+index).value;
var rsquerrySstring = "?Ftnaame="+Ftnaame+"&tlast="+tlast+"&tphone="+tphone+"&twphone="+twphone+"&taddr="+taddr+"&tdate="+tdate+"&index="+index+"&temail="+temail+"&Cinv="+Cinv;
http.open("GET", "customer.php" +
rsquerrySstring, true);
http.onreadystatechange = rsrgetHttpResss;
http.myCustomValue = index;
http.send(null);
$("#upCust"+index).hide();
}
}
function rsrgetHttpResss() {
if (http.readyState == 4) {
rreesss = http.responseText; // These following lines get the response and update the page
var index = http.myCustomValue;
document.getElementById('names'+index).innerHTML = rreesss;
}
}
function getXHTTP() {
var xhttp;
try { // The following "try" blocks get the XMLHTTP object for various browsers…
xhttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
xhttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e2) {
// This block handles Mozilla/Firefox browsers...
try {
xhttp = new XMLHttpRequest();
} catch (e3) {
xhttp = false;
}
}
}
return xhttp; // Return the XMLHTTP object
}
var http = getXHTTP(); // This executes when the page first loads.
<file_sep>/gg.php
<?php
include('database_connection.php');
session_start();
if(isset($_GET['name'])) {
$gg = "SELECT * FROM `customers` WHERE `name` = '".$_GET['name']."' AND `mid` = '".$_SESSION['id']."' LIMIT 1";
$jk = mysqli_query($dbc, $gg);
if(!$jk) {
die(mysqli_error($dbc));
}
$KK = mysqli_num_rows($jk);
if($KK == 0) {
?>
<input type="text" name="ilast name" id="ilastname" value="Last Name"/><br/>
<input type="text" name="iphone" id="iphone" value="Phone Number"/><br/>
<input type="text" name="iwphone" id="iwphone" value="Work-Phone"/><br/>
<input type="text" name="iaddr" id="iaddr" value="Address"/><br/>
<input type="text" name="iemail" id="iemail" value="E-Mail Address"/><br/>
<?
}
else {
while($JK = mysqli_fetch_array($jk)) {
echo ' <input type="text" name="ilast name" id="ilastname" value="'.$JK['lastname'].'"/><br/>';
echo ' <input type="text" name="iphone" id="iphone" value="'.$JK['phone'].'"/><br/>';
echo ' <input type="text" name="iwphone" id="iwphone" value="'.$JK['wphone'].'"/><br/>';
echo ' <input type="text" name="iaddr" id="iaddr" value="'.$JK['addr'].'"/><br/>';
echo ' <input type="text" name="iemail" id="iemail" value="'.$JK['email'].'"/><br/>';
}
}
}
?>
<file_sep>/img/members.php_files/allReady1.js
function allReady() {
$(".edit").remove();
$(".button").remove();
$(".zzenter").remove();
$(".zzselect").remove();
$("#left").hide()
.css("z-index", "-1");
$("#center").animate({left: "+150"}, "slow");
$("#header").hide();
$("h1").hide();
}
function removeHead() {
$("#header").remove();
$("#h3").remove();
}
function savePage() {
var prompt = alert("To save your file: Click and hold ctrl S. Keep all of your files in one area so you can acces them!");
}
<file_sep>/img.php
<?
include('database_connection.php');
ob_start();
session_start();
define ("MAX_SIZE","800");
//This function reads the extension of the file. It is used to determine if the
// file is an image by checking the extension.
function getExtension($str) {
$i = strrpos($str,".");
if (!$i) { return ""; }
$l = strlen($str) - $i;
$ext = substr($str,$i+1,$l);
return $ext;
}
//This variable is used as a flag. The value is initialized with 0 (meaning no
// error found)
//and it will be changed to 1 if an errro occures.
//If the error occures the file will not be uploaded.
$errors=0;
$image=$_FILES['image']['name'];
//if it is not empty
if ($image)
{
//get the original name of the file from the clients machine
$filename = stripslashes($_FILES['image']['name']);
//get the extension of the file in a lower case format
$extension = getExtension($filename);
$extension = strtolower($extension);
//if it is not a known extension, we will suppose it is an error and
// will not upload the file,
//otherwise we will do more tests
if (($extension != "jpg") && ($extension != "jpeg") && ($extension !=
"png") && ($extension != "gif"))
{
//print error message
echo '<h1>Unknown extension!</h1>';
$errors=1;
}
else
{
//get the size of the image in bytes
//$_FILES['image']['tmp_name'] is the temporary filename of the file
//in which the uploaded file was stored on the server
$size=filesize($_FILES['image']['tmp_name']);
//compare the size with the maxim size we defined and print error if bigger
if ($size > MAX_SIZE*800)
{
if($extension == "jpg")
{
$poop = $_FILES['image']['tmp_name'] ;
$src = imagecreatefromJPEG($poop);
}
if($extension == "jpeg")
{
$poop = $_FILES['image']['tmp_name'] ;
$src = imagecreatefromJPEG($poop);
}
if($extension == "png") {
$poop = $_FILES['image']['tmp_name'] ;
$src = imagecreatefrompng($poop);
}
if($extension == "gif") {
$poop = $_FILES['image']['tmp_name'] ;
$src = imagecreatefromgif($poop);
}
// Capture the original size of the uploaded image
list($width,$height)=getimagesize($poop);
// For our purposes, I have resized the image to be
// 600 pixels wide, and maintain the original aspect
// ratio. This prevents the image from being "stretched"
// or "squashed". If you prefer some max width other than
// 600, simply change the $newwidth variable
$newwidth=600;
$newheight=($height/$width)*600;
$tmp=imagecreatetruecolor($newwidth,$newheight);
// this line actually does the image resizing, copying from the original
// image into the $tmp image
$ooo = imagecopyresampled($tmp,$src,0,0,0,0,$newwidth,$newheight,$width,$height);
if(!$ooo){ die(mysql_error()); }
$image_name= '4x4fail-'.time().'.'.$extension;
$newname="img/".$image_name;
$copied = copy($_FILES['image']['tmp_name'], $newname);
if (!$copied)
{
die('<h1>Copy unsuccessfull! Image too large!</h1>');
}
imagejpeg($tmp,$newname,100);
imagedestroy($src);
imagedestroy($tmp); // NOTE: PHP will clean up the temp file it created when the request
// has completed.
}
else {
//we will give an unique name, for example the time in unix time format
$image_name= 'inv-'.time().'.'.$extension;
//the new name will be containing the full path where will be stored (images
//folder)
$newname="img/".$image_name;
//we verify if the image has been uploaded, and print error instead
$copied = copy($_FILES['image']['tmp_name'], $newname);
if (!$copied)
{
die('<h1>Copy unsuccessfull! '.$newimage.' Image to large </h1>');
$errors=1;
}}}}
//If no errors registred, print the success message
if(isset($_POST['Submit']) && !$errors)
{
//copy the video and insert into database
// end
echo '<img src="img/'.$image_name.' "> <br />';
echo 'Thanks! Your image has been uploaded! ';
$ho = "UPDATE `members` SET `img` ='".$image_name."' WHERE `id` = '".$_SESSION['id']."'";
$hoo = mysqli_query($dbc, $ho);
if($hoo) {
echo '<a href="http://invoicerFree.tk/logout.php">back</a>';
}
else {
die(mysqli_error($dbc));
}
}
?>
<file_sep>/img/poop_files/selectPro.js
function selectPro(index) {
var quan = window.prompt("Quantity");
$(".sel").hide();
var optionn = document.getElementById('selectinv').value;
var num = document.getElementById('gopro'+index).value;
var cream = document.getElementById('invid'+index).value;
var qqueryString = "?optionn="+optionn+"&num="+num+"&quan="+quan+"&cream="+cream;
http.open("GET", "bob.php" +
qqueryString, true);
http.onreadystatechange = ggetHttpRes;
http.myCustomValue = index;
http.send(null);
}
function ggetHttpRes(index) {
if (http.readyState == 4) {
rres = http.responseText; // These following lines get the response and update the page
var index = http.myCustomValue;
document.getElementById('prohidden'+index).innerHTML = rres;
}
}
function getXHTTP() {
var xhttp;
try { // The following "try" blocks get the XMLHTTP object for various browsers…
xhttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
xhttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e2) {
// This block handles Mozilla/Firefox browsers...
try {
xhttp = new XMLHttpRequest();
} catch (e3) {
xhttp = false;
}
}
}
return xhttp; // Return the XMLHTTP object
}
var http = getXHTTP(); // This executes when the page first loads.
<file_sep>/deleteFrom.js
function newItem(index) {
var del = document.getElementById('del'+index).value;
var id = document.getElementById('session'+index).value;
var sqsuerryString = "?del="+del+"&id="+id;
http.open("GET", "delete.php" +
sqsuerryString, true);
http.onreadystatechange = srsgetHttpRess;
http.myCustomValue = index;
http.send(null);
}
function srsgetHttpRess() {
if (http.readyState == 4) {
resess = http.responseText; // These following lines get the response and update the page
var index = http.myCustomValue;
document.getElementById('prohidden'+index).innerHTML = resss;
}
}
function getXHTTP() {
var xhttp;
try { // The following "try" blocks get the XMLHTTP object for various browsers…
xhttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
xhttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e2) {
// This block handles Mozilla/Firefox browsers...
try {
xhttp = new XMLHttpRequest();
} catch (e3) {
xhttp = false;
}
}
}
return xhttp; // Return the XMLHTTP object
}
var http = getXHTTP(); // This executes when the page first loads.
| 24d51209881c0524f89fee2990fea00e31e51dc9 | [
"JavaScript",
"HTML",
"PHP"
] | 55 | JavaScript | csechols38/invoice-masters | 68f51bba5477898949f4fc899670e8ae0bfcfb5e | 5907f39a52ec7ed145f110e47194544004f5b1b4 |
refs/heads/master | <file_sep>class ApiController < ApplicationController
def show
barbecue = Barbecue.find_by(id: params[:id])
title = barbecue.title
date = barbecue.date
venue = barbecue.venue
all_together = { :title => title, :date => date, :venue => venue}
render json: all_together
end
def join
barbecue = Barbecue.find_by(id: params[:id])
unless barbecue || current_user
render json: {error: "this is not working" },status: 404
end
barbecue.users.push(current_user)
render json: barbecue, status: 202
end
end
| 21a409480ccc96003a4336f4edc2ba19d411ef11 | [
"Ruby"
] | 1 | Ruby | john-fitz/bbq | 259efdff4f7b49d0c038bb20a27265695bb50eed | cc1f39ed0b73048734e215280e2cbb53d35daf1f |
refs/heads/master | <file_sep>import subprocess
import webbrowser
webbrowser.open("/home/catchthemall/textfile.txt")
subprocess.Popen(["python", '/home/catchthemall/question.py'])
<file_sep>FROM ubuntu:latest
# update and install tools
RUN apt update && apt -y upgrade \
&& apt-get install -y python python-pip \
--no-install-recommends \
&& rm -rf /var/lib/apt/lists/*
# create directory
RUN mkdir -p /home/hackerlevel
COPY . /home/hackerlevel
EXPOSE 11111
RUN useradd -s /bin/bash ctfuser
USER ctfuser
CMD "python" "/home/hackerlevel/flag_question.py" && "python" "/home/hackerlevel/server.py"
<file_sep>import os
flagfile = open("/home/messy-aes/flag.txt", "r")
ctf_flag = flagfile.readline().strip()
print "\nWe were playing around with AES encryption and lost our flag in http://localhost:63000/textfiles/given.txt \n"
print "This is all we know: e220eb994c8fc16388dbd60a969d4953f042fc0bce25dbef573cf522636a1ba3fafa1a7c21ff824a5824c5dc4a376e75 \n"
print "Hint: Block."
while True:
user_flag = raw_input("\nThe flag looks like FLAG{...} \nInsert here: ")
if ctf_flag in user_flag:
print "Correct!! \n"
break;
else:
print "Nope. Try again \n"
<file_sep>import os
#flagfile= open('/home/hackerlevel/flag.txt', 'r')
#ctf_flag = flagfile.readline()
print("hint: A true hacker uses pwn too\n")
print( "hello world\n")
#"""while True:
# user_flag = raw_input("\nThe flag looks like FLAG{...} \nInsert here:")
# if ctf_flag in user_flag:
# print "Correct!! \n"
# break;
# else:
# print "Nope. Try again \n" ""
<file_sep>FROM ubuntu:latest
RUN apt update && apt -y upgrade \
&& apt-get install -y python python-pip \
--no-install-recommends \
&& rm -rf /var/lib/apt/lists/*
RUN mkdir /home/witcher
COPY . /home/witcher
RUN useradd -s /bin/bash ctfuser
USER ctfuser
CMD "python" /home/witcher/question.py
<file_sep>import os
flagfile = open('/home/php/flag.txt','r')
ctf_flag = flagfile.readline().strip()
print "Go here: http://localhost:10800"
print "Hint: Make the buffers flow."
while True:
user_flag = raw_input("\nThe flag looks like FLAG{...} \nInsert here:")
if ctf_flag in user_flag:
print "Correct!! \n"
break;
else:
print "Nope. Try again \n"
<file_sep>#!/usr/bin/python
# -*- coding: utf-8 -*-
import random
import sys
flagfile= open('/home/hackerlevel/flag.txt', 'r')
ctf_flag = flagfile.readline()
#print("\nhint: A true hacker uses pwn too\n")
#print("The flag looks like FLAG{...} \n")
total=0
for i in range(0,10000):
x = random.randrange(0,1000)
y = str(x).encode('base64')
y = y[:-1]
y+='=='
print str(y)
sys.stdout.flush()
ans = raw_input()
if str(ans) == str(x):
total+=1
if total == 10000:
print "You are a true hacker, you hacker level is over 9k. Here is your prize.\n"
sys.stdout.flush()
print ctf_flag
sys.stdout.flush()
else:
print "Nope"
sys.stdout.flush()
<file_sep>service nginx start
sudo -u ctfuser python /home/droid/question.py
<file_sep>service nginx start
service php7.0-fpm start
#sudo -u ctfuser php /home/php/datai/index.php
sudo -u ctfuser python /home/php/question.py
<file_sep>How to build:
$docker build -t <user_name>/witches .
how to run:
$docker run -it --rm <user_name>/witches
<file_sep>How to build:
$docker build -t <user_name>/hiddenfile .
How to run:
$docker run -it --rm -p 50000:50000 <user_name>/hiddenfile
<file_sep>How to build:
$docker build -t <user_name>/easy-rsa .
How to run:
$docker run -it --rm -p 55000:55000 <user_name>/easy-rsa
<file_sep>FROM ubuntu:16.04
ARG DEBIAN_FRONTEND=noninteractive
# UPDATE AND INSTALL TOOLS
RUN apt-get update && apt-get install -y --no-install-recommends \
python python-pip sudo php7.0-fpm php7.0-mysql \
nginx software-properties-common \
--no-install-recommends \
&& add-apt-repository 'deb http://archive.ubuntu.com/ubuntu trusty universe' \
&& apt-get update && apt-get install -y mysql-server-5.6 \
--no-install-recommends \
&& rm -rf /var/lib/apt/lists/*
RUN mkdir -p /home/sqli /srv/http
COPY . /home/sqli
#REMOVE DEFAULT CONFIGURATION
RUN rm -rf /etc/nginx/sites-enabled /etc/nginx/sites-available \
/etc/nginx/modules-available \
/etc/nginx/nginx.conf \
/etc/mysql/debian.cnf
RUN mkdir /etc/nginx/sites-available \
/etc/nginx/sites-enabled \
/srv/http/site3 \
&& chmod 755 /etc/nginx/sites-available /etc/nginx/sites-enabled \
&& groupadd site3 \
&& useradd -g site3 site3
ADD data /srv/http/site3/data
COPY nginx.conf /etc/nginx
COPY my.cnf /etc/mysql/my.cnf
COPY debian.cnf /etc/mysql/debian.cnf
#PHP CONFIGURATION
RUN rm -f /etc/php/7.0/fpm/pool.d/www.conf \
/etc/php/7.0/fpm/php.ini
COPY site3.conf /etc/php/7.0/fpm/pool.d
COPY php.ini /etc/php/7.0/fpm
COPY 10-opcache.ini /etc/php/7.0/fpm/conf.d
#SITE3 CONFIGURATION
COPY site3 /etc/nginx/sites-available
RUN chown -R nobody:site3 /etc/nginx/sites-available/site3 \
&& ln -s /etc/nginx/sites-available/site3 /etc/nginx/sites-enabled/site3 \
&& chown -R nobody:site3 /etc/nginx/sites-enabled/site3 \
&& chmod 711 /srv/http \
&& chown -R nobody:site3 /srv/http/site3 \
&& chown root:root /etc/mysql/debian.cnf \
&& chmod 400 /etc/mysql/debian.cnf \
&& chmod 011 /srv/http/site3 /srv/http/site3/* \
&& chmod 044 /srv/http/site3/data/*
EXPOSE 10811
RUN useradd -s /bin/bash ctfuser
CMD "/bin/bash" "/home/sqli/start.sh"
<file_sep>service nginx start
service php7.0-fpm start
service mysql start
mysql -u root -e 'source /home/sqli/mysql-alldbs.sql'
mysql -u root -e 'flush privileges'
#sudo -u ctfuser php /home/php/datai/index.php
sudo -u ctfuser python /home/sqli/question.py
<file_sep># base image
FROM ubuntu:latest
# update and install tools
RUN apt update && apt -y upgrade \
&& apt-get install -y python python-pip \
--no-install-recommends \
&& rm -rf /var/lib/apt/lists/*
# create directory
RUN mkdir -p /home/stolen-pw
COPY . /home/stolen-pw
# expose port used
EXPOSE 20202
RUN useradd -s /bin/bash ctfuser
USER ctfuser
CMD python "/home/stolen-pw/question.py" && python "/home/stolen-pw/server.py"
<file_sep>sudo -u ctfuser python /home/ssb/question.py
/usr/sbin/nginx
sudo -u ctfuser python /home/ssb/server.py
<file_sep>How to build:
$docker build -t <user_name>/race .
How to run:
$docker run -it --rm -p 19999:19999 <user_name>/race
<file_sep>import os
flagfile = open("/home/stolen-pw/flag.txt", "r")
ctf_flag = flagfile.readline().strip()
print "\nCan you crack a password for me, if I can log on I will give you the flag. Connect here: nc 127.0.0.1 20202\n"
print "Hint: Luckily these 5 MaD people weren't salty. \n"
print ("\nThe flag looks like FLAG{...} \n")
<file_sep>import os
flagfile = open("/home/hiddenfile/flag.txt", "r")
ctf_flag = flagfile.readline().strip()
print "\nSometimes a file is used to hide other files. Go to http://localhost:50000/Spurs.jpg and seeif there is anything in this image?\n"
print "Hint: Try comparing it to the original\n"
while True:
user_flag = raw_input("\nThe flag looks like FLAG{...} \nInsert here: ")
if ctf_flag in user_flag:
print "Correct!! \n"
break;
else:
print "Nope. Try again \n"
<file_sep># base image
FROM ubuntu:latest
# update and install tools
RUN apt update && apt -y upgrade \
&& apt-get install -y nginx \
python python-pip \
sudo \
--no-install-recommends \
&& rm -rf /var/lib/apt/lists/*
# create directory
RUN mkdir -p /home/easy-rsa
COPY . /home/easy-rsa
# remove default configurations from nginx
RUN rm -rf /etc/nginx/sites-enabled \
/etc/nginx/sites-available \
/etc/nginx/modules-available
# copy my cofiguration to nginx
COPY nginx.conf /etc/nginx/nginx.conf
COPY data /etc/nginx/data
# expose port used
EXPOSE 55000
RUN useradd -s /bin/bash ctfuser
CMD "/bin/bash" "/home/easy-rsa/start.sh"
<file_sep>How to build:
$docker build -t <user_name>/escape .
How to run:
$docker run -it --rm -p 17777:17777 <user_name>/escape
<file_sep>import os
flagfile = open('/home/ssb/flag.txt','r')
ctfflag = flagfile.readlines()
print "Open a terminal and nc 127.0.0.1 13131. Can you find our flag? \nDowloading this file might help http://localhost:64000/executables/smb\n"
print "Hint: Make the buffers flow."
#while True:
# user_flag = raw_input("\nThe flag looks like FLAG{...} \nInsert here:")
# if ctf_flag in user_flag:
# print "Correct!! \n"
# break;
#else:
# print "Nope. Try again \n"
<file_sep>import os
flagfile = open("/home/droid/flag.txt", "r")
ctf_flag = flagfile.readline().strip()
print "\nCan you find the flag in this file: http://localhost:60000/ReverseMe.apk ?"
print "You might need this tool: http://localhost:60000/tools.zip \n"
print "Hint: Tools are helpful. \n"
while True:
user_flag = raw_input("\nThe flag looks like FLAG{...} \nInsert here: ")
if ctf_flag in user_flag:
print "Correct!! \n"
break;
else:
print "Nope. Try again \n"
<file_sep>print ("\nRace me at: nc 127.0.0.1 19999\n")
print ("Hint: Pwn tools must be used to win this race.\n")
print("The flag looks like FLAG{.....}")
<file_sep># base image
FROM ubuntu:latest
# update and install tools
RUN apt update && apt -y upgrade \
&& apt-get install -y python python-pip \
--no-install-recommends \
&& rm -rf /var/lib/apt/lists/*
# create directory
RUN mkdir -p /home/escape
COPY . /home/escape
COPY flag.txt /
# expose port used
EXPOSE 17777
RUN useradd -s /bin/bash ctfuser
USER ctfuser
CMD python "/home/escape/question.py" && python "/home/escape/server.py"
<file_sep>service nginx start
sudo -u ctfuser python /home/easy-rsa/question.py
<file_sep>import os
flagfile = open("/home/easy-rsa/flag.txt", "r")
ctf_flag = flagfile.readline().strip()
print "\nWe encrypted the flag with rsa. Can you crack it? The file is in http://localhost:55000/easy-rsa.tar.gz \n"
print "Hint: Short public key. \n"
while True:
user_flag = raw_input("\nThe flag looks like FLAG{...} \nInsert here: ")
if ctf_flag in user_flag:
print "Correct!! \n"
break;
else:
print "Nope. Try again \n"
<file_sep>import os
ctf_flag = "FLAG{THIS_IS_AN_EASY_CODING_PROBLEM}"
print "\nGO TO http://localhost:65000/textfiles/catchthemall.txt \n"
print "Can you find the flag in the textfile?"
print "Hint: That is a lot of text, maybe a script would help."
while True:
user_flag = raw_input("\nThe flag looks like FLAG{...} \nInsert here:")
if ctf_flag in user_flag:
print "Correct!! \n"
break;
else:
print "Nope. Try again \n"
<file_sep>FROM yukoff/alpine-32bit
# update and install tools #--arch x86
RUN apk update && apk add --no-cache --upgrade nginx \
python2 \
openrc \
libc6-compat \
sudo \
bash \
&& rm -rf /var/lib/cache/apk/*
# create directory
RUN mkdir -p /home/ssb \
/run/nignx
COPY . /home/ssb
COPY flag.txt /
RUN rm -rf /etc/nginx/sites-enabled \
/etc/nginx/sites-available \
/etc/nginx/modules-available \
&& chmod 777 /home/ssb/overflow
COPY nginx.conf /etc/nginx/nginx.conf
COPY data /etc/nginx/data
EXPOSE 13131
EXPOSE 64000
RUN addgroup -S ctfgroup && adduser -S ctfuser -G ctfgroup
CMD "/bin/bash" "/home/ssb/start.sh"
<file_sep>How to build:
$docker build -t <user_name>/ssb
How to run:
$docker run -it --rm -p 10800:10800 <user_name>/php
<file_sep>import os
flagfile = open("/home/caesar/flag.txt", "r")
ctf_flag = flagfile.readline().strip()
print "\nCan you find the flag in http://localhost:45000/file.enc "
print "Hint: There are two ingredients in this salad.\n"
while True:
user_flag = raw_input("\nThe flag looks like FLAG{...} \nInsert here: ")
if ctf_flag in user_flag:
print "Correct!! \n"
break;
else:
print "Nope. Try again \n"
<file_sep># CTF problem setup
Step 1) Copy files in local directory
$git clone https://github.com/saa114/CTF.git
Step 2) Make an account in docker
https://www.docker.com/
Step 3) Go to local directory where the github files are.
$docker login
#Then type user name and password
Step 4) Build docker container
$docker build -t <docker_username>/<name_your_container> .
Example: docker build -t saa114/race .
NOTE: Do not forget the dot(.) at the end
Step 4) Run docker application
#To run application in interactive mode
$docker run -it --rm -p 4000:19999 saa114/race
Note: The port on the left can be random
Note: The port on the right must match the port
in the server and Dockerfile.
#To run application constantly on port.
$docker run --rm -p 4000:19999 saa114/race
Step 5) To connect to the server
$curl localhost:4000
Step 6) To kill a process running constantly on port
#First get container ID.
$docker ps
#Then kill the Process.
$docker kill <container_id>
Step 7) To push your container to docker hub
$docker push saa114/race
<file_sep># Get latest ubuntu image
FROM ubuntu:latest
# Get python configurations
RUN apt update && apt -y upgrade \
python python-pip \
--no-install-recommends \
&& rm -rf /var/lib/apt/lists/*
# Create a directory in docker container
RUN mkdir -p /home/race
# Copy continents from current local directory to docker directory
COPY . /home/race
#Open port in docker(must be same port in server)
EXPOSE 19999
#Adds user with non-root permission
RUN useradd -s /bin/bash ctfuser
#Allows user to execute cmd
USER ctfuser
# Execute Program(s)
CMD "python" /home/race/question.py && "python" /home/race/server.py
<file_sep>How to build:
$docker build -t <user_name>/messy-aes
How to run:
$docker run -it --rm -p 63000:63000 saa114/messy-aes
<file_sep>service nginx start
sudo -u ctfuser python /home/caesar/question.py
<file_sep>import os
flagfile = open("/home/escape/flag.txt", "r")
ctf_flag = flagfile.readline().strip()
print "\nCan you break out of jail? nc 127.0.0.1 17777"
print "Hint: You might get out early, based on your evaluation. \n"
print ("\nThe flag looks like FLAG{...} \n")
<file_sep>How to build:
$docker build -t <user_name>/stolen-pw .
How to run:
$docker run -it --rm -p 20202:20202 <user_name>/stolen-pw
<file_sep>import os
flagfile = open('/home/sqli/flag.txt','r')
ctf_flag = flagfile.readline().strip()
print "\nCan you log into the system? http://127.0.0.1:10811/ \n"
print "Hint: There is a databse storing login information, maybe it can be injected.\n "
while True:
user_flag = raw_input("\nThe flag looks like FLAG{...} \nInsert here:")
if ctf_flag in user_flag:
print "Correct!! \n"
break;
else:
print "Nope. Try again \n"
<file_sep>service nginx start
sudo -u ctfuser python /home/hiddenfile/question.py
<file_sep>import os
ctf_flag = "FLAG{3nCod1nG_4nD_d3c0D1nG}"
final_flag = ''
print "Can you turn this string into a flag? 464c41477b336e436f64316e475f346e445f6433633044316e477d. "
user_flag = raw_input("The flag looks like this FLAG{...}. \n")
for i in user_flag:
if i != ' ':
final_flag += i
if final_flag == ctf_flag:
print "Correct!"
else:
print "Try again"
<file_sep>import SocketServer, subprocess
HOST = '0.0.0.0'
PORT = 4000
class handler(SocketServer.BaseRequestHandler):
def handle(self):
filename = open("/home/catchthemall/textfile.txt", "rb")
text = filename.read()
filename.close()
self.request.send(text)
subprocess.Popen(["python", "/home/catchthemall/handler.py"])
if __name__ == "__main__":
server = SocketServer.TCPServer((HOST,PORT), handler)
server.allow_reuse_address = True
server.serve_forever()
<file_sep>How to build:
$docker build -t <user_name>/sqli .
How to run:
$docker run -it --rm -p 10811:10811 <user_name>/sqli
<file_sep>
How to build:
$docker build -t <user_name>/hackerlevel .
How to run:
$docker run -it --rm -p 11111:11111 <user_name>/hackerlevel
<file_sep>How to build:
$docker build -t <user_name>/droid
How to run:
$docker run -it --rm -p 60000:60000 <user_name>/droid
<file_sep>service nginx start
sudo -u ctfuser python /home/catchthemall/question.py
<file_sep>service nginx start
sudo -u ctfuser python /home/messy-aes/question.py
<file_sep>How to build:
$docker build -t <user_name>/catchthemall .
How to run:
$docker run -it --rm -p 65000:65000 <user_name>/catchthemall
<file_sep>How to build:
$docker build -t <user_name>/caesar .
How to run:
$docker run -it --rm -p 45000:45000 <user_name>/caeser
<file_sep>FROM ubuntu:16.04
#Makes tools avoid asking questions when downloading.
ARG DEBIAN_FRONTEND=noninteractive
# update and install tools
RUN apt-get update && apt-get install -y \
python python-pip sudo php7.0-fpm php7.0-mysql \
nginx software-properties-common \
--no-install-recommends \
&& rm -rf /var/lib/apt/lists/*
#Create a directory
RUN mkdir -p /home/php \
/srv/http \
/srv/http/site1
COPY . /home/php
#Change Nginx Configurations
RUN rm -rf /etc/nginx/sites-enabled \
/etc/nginx/sites-available \
/etc/nginx/modules-available \
/etc/php/7.0/fpm/pool.d/www.conf \
/etc/php/7.0/fpm/php.ini
ADD data /srv/http/site1/data
COPY nginx.conf /etc/nginx
#Create a new user and group
RUN groupadd site1 \
&& useradd -g site1 site1 \
&& useradd -s /bin/bash ctfuser
#PHP CONFIGURATION
COPY site1.conf /etc/php/7.0/fpm/pool.d
COPY php.ini /etc/php/7.0/fpm
COPY 10-opcache.ini /etc/php/7.0/fpm/conf.d
#Expose port
EXPOSE 10800
CMD "/bin/bash" "/home/php/start.sh"
<file_sep>How to build:
$docker build -t <user_name>/ssb .
How to run:
$docker run -it --rm -p 13131:13131 -p 64000:64000 <user_name>/ssb
| a59a9a6b2c5923c025ac9281efc2aa676212971d | [
"Markdown",
"Python",
"Dockerfile",
"Shell"
] | 50 | Python | saa114/CTF | 948308f4498087c84187f138df3ab75ca87fbb90 | 40272e60a191744735a0eff04850204d6f90b54c |
refs/heads/master | <file_sep>#!/bin/bash
. $TEAM_LIB/serf-event.lib
require serf
require etcd
serf_event_is query etcd-token && serf_get etcd-token
serf_event_is user etcd-token && serf_set etcd-token
serf_event_is member-join && etcd_cluster-resize
serf_event_is member-leave && etcd_cluster-resize
serf_event_is member-fail && etcd_cluster-resize
serf_event_is member-join && etcd_master-election
serf_event_is member-leave && etcd_master-election
serf_event_is member-fail && etcd_master-election
serf_event_is query etcd-member-election && etcd_stand-for-member-election
serf_event_is query etcd-master-election && etcd_stand-for-master-election
serf_event_is user etcd-elect-master && etcd_become-master<file_sep>#!/bin/bash
MODULE=path
. $TEAM_LIB/dependency.lib
require $MODULE
_${MODULE}_test 2>/dev/null
arg=$1
shift
${MODULE}_$arg $*<file_sep>#!/bin/bash
. $TEAM_LIB/serf-event.lib
require serf
serf_event_is member-join && serf_event serf-check
serf_event_is member-update && serf_event serf-check
serf_event_is member-leave && serf_event serf-check
serf_event_is user serf-check && serf_check
serf_event_is query elected-master && serf_get elected-master
serf_event_is user elected-master && serf_set elected-master<file_sep>#!/bin/bash
. $TEAM_LIB/serf-event.lib
require serf
serf_event_is query swarm-token && serf_get swarm-token
serf_event_is user swarm-token && serf_set swarm-token<file_sep>#!/bin/bash
. $TEAM_LIB/serf-event.lib
require serf
require zookeeper
serf_event_is query zookeeper-ip && zookeeper_local-ip
serf_event_is user zookeeper-ip && serf_set zookeeper-ip
<file_sep>#!/bin/bash
. $TEAM_LIB/dependency.lib
require rancher
arg=$1
shift
case "$arg" in
ranch)
echo $(ranch)
;;
set)
case "$1" in
ranch)
set_ranch $2
;;
esac
;;
esac
<file_sep>#!/bin/bash
. $TEAM_LIB/serf-event.lib
require serf
require etcd
require flanneld
require docker
require ssh
require zookeeper
require bee
require swarm
require interlock
require registry
require dokku
require router
serf_event_is user serf-update && etcd_install
serf_event_is user etcd-update && flanneld_install
serf_event_is user flanneld-update && zookeeper_install
serf_event_is user flanneld-update && ssh_start
serf_event_is user flanneld-update && bee_install
serf_event_is user bee-update && swarm_install
serf_event_is user swarm-update && interlock_install
serf_event_is user interlock-update && registry_install
serf_event_is user registry-update && dokku_install
serf_event_is user dokku-update && router_start dokku<file_sep>#!/bin/bash
MODULE=debug
. $TEAM_LIB/dependency.lib
require debug
arg=$1
shift
${MODULE}_ $arg $*
<file_sep>#!/bin/sh
. $TEAM_LIB/dependency.lib
require team
for module in journald ssh docker serf bee swarm flanneld etcd interlock registry zookeeper dokku router; do
echo -n "Shutdown $module ... "
$TEAM $module clean 2>/dev/null && echo "ok" || echo "failed"
done<file_sep>#!/bin/bash
. $TEAM_LIB/dependency.lib
require team
require serf-event
require log
[[ -z "$SERF_EVENT" ]] && exit 0
[[ "$SERF_EVENT" = "user" ]] && PAYLOAD=$(cat)
_log debug "Handling $SERF_EVENT evt: $SERF_USER_EVENT, qry: $SERF_QUERY_NAME, pyl: $PAYLOAD"
serf_event_handlers | while read handler; do
echo $PAYLOAD | /bin/bash -i $handler $* 2>/dev/null
done
exit 0<file_sep>#!/bin/bash
MODULE=docker
. $TEAM_LIB/dependency.lib
require $MODULE
arg=$1
shift
${MODULE}_$arg $*<file_sep>#!/bin/bash
PROJECT_REPO=https://github.com/steigr/team
make_prefix() { mkdir "$(dirname $1)" 2>/dev/null; echo "$1"; }
prefix() { make_prefix "${PREFIX:-/opt/lib/team}"; }
has_git() { test -d $(prefix)/.git; }
can_update() { touch $(prefix)/.git 2>/dev/null; }
git_update() { can_update && (cd $(prefix); git reset -q --hard; git pull -q origin master); }
git_clone() { (git clone -q "$PROJECT_REPO" $(prefix) ); }
team_script() { echo "$(prefix)/bin/team"; }
abs_called() { test "x$(called)" = "x$(team_script)"; }
module() { echo "$(team_script)-${1:-serf-event}"; }
has_module() { test -x "$1"; }
team_lib() { echo "$(prefix)/lib"; }
called() { echo "${BASH_SOURCE[0]%*.orig}"; }
is_linked() { test -L $(called); }
has_git || git_clone
if abs_called; then
cmd=$(module $*)
shift
has_module $cmd || exit 1
PREFIX=$(prefix) TEAM_LIB=$(team_lib) $cmd $*
else
is_linked || ( mv $(called) $(called).orig; ln -s $(team_script) $(called); )
git_update
$(team_script) $*
fi
exit $?<file_sep>#!/bin/bash
MODULE=boot
. $TEAM_LIB/dependency.lib
require $MODULE
_boot journald install
_boot jq install
_boot ssh update
_boot ssh stop
_boot docker update
_boot serf install
<file_sep>#!/bin/bash
. $TEAM_LIB/serf-event.lib
require serf
require router
serf_event_is user start-router && router_start $(cat)<file_sep>#!/bin/bash
MODULE=coreos
. $TEAM_LIB/dependency.lib
require $MODULE
_${MODULE}_test 2>/dev/null
arg=$1
shift
${MODULE}_$arg $*
<file_sep>#!/bin/bash
. $TEAM_LIB/serf-event.lib
require serf
require registry
serf_event_is query registry-ip && serf_get registry-ip
serf_event_is user registry-ip && serf_set registry-ip<file_sep>#!/bin/bash
. $TEAM_LIB/serf-event.lib
require serf
require dokku
serf_event_is query dokku-ip && dokku_local-ip
| 9df3c74ceac0eade9eceb2fa68b6ecd0fe063607 | [
"Shell"
] | 17 | Shell | steigr/team | 472529f893c35d1196469b1704071dcc7ea469c4 | e55d831fd4e2d4f014949f8e60c38710a1303367 |
refs/heads/master | <file_sep>package main
import (
"log"
"fmt"
"github.com/streadway/amqp"
"encoding/json"
"strings"
"io"
"time"
)
func main() {
conn, ch := setupQueue()
defer conn.Close()
defer ch.Close()
consume(ch)
}
type Message struct {
MessageId, FilePath string
}
func getMessageParts(message string) (Message) {
dec := json.NewDecoder(strings.NewReader(message))
var m Message
for {
if err := dec.Decode(&m); err == io.EOF {
break
} else if err != nil {
log.Fatal(err)
}
}
return m
}
func randomlyProcess(ch *amqp.Channel, message Message) {
var messageToPublish string
for i := 0; i < 4; i++ {
progressPart := i + 1
progress := 100 * (float64(progressPart) / 4)
messageToPublish = fmt.Sprintf(
`{"MessageId": "%s", "FilePath": "%s", "Progress": "%d%%"}`,
message.FilePath,
message.MessageId,
int(progress),
)
time.Sleep(3 * time.Second)
publish(ch, messageToPublish)
}
}
func consume(ch *amqp.Channel) {
msgs, err := ch.Consume(
"ProcessQueue", // queue
"", // consumer
true, // auto-ack
false, // exclusive
false, // no-local
false, // no-wait
nil, // args
)
failOnError(err, "Failed to register a consumer")
forever := make(chan bool)
go func() {
for d := range msgs {
msgRaw := string(d.Body)
message := getMessageParts(msgRaw)
log.Printf("Consumed [x] %s", msgRaw)
randomlyProcess(ch, message)
}
}()
log.Printf(" [*] Waiting for new process messages. To exit press CTRL+C")
<-forever
}
func publish(ch *amqp.Channel, message string) {
err := ch.Publish(
"StatusExchange", // exchange
"", // routing key
false, // mandatory
false, // immediate
amqp.Publishing{
ContentType: "text/plain",
Body: []byte(message),
})
failOnError(err, "Failed to publish a message")
log.Printf("Processed and published [x] %s", message)
}
func setupQueue() (*amqp.Connection, *amqp.Channel) {
conn, err := amqp.Dial("amqp://kyto:area126@localhost:5673/")
failOnError(err, "Failed to connect to RabbitMQ")
ch, err := conn.Channel()
failOnError(err, "Failed to open a channel")
err = ch.ExchangeDeclare(
"StatusExchange", // name
"direct", // type
true, // durable
false, // auto-deleted
false, // internal
false, // no-wait
nil, // arguments
)
failOnError(err, "Failed to declare an exchange")
err = ch.ExchangeDeclare(
"ProcessExchange", // name
"direct", // type
true, // durable
false, // auto-deleted
false, // internal
false, // no-wait
nil, // arguments
)
failOnError(err, "Failed to declare an exchange")
statusQueue, err := ch.QueueDeclare(
"StatusQueue", // name
true, // durable
false, // delete when usused
false, // exclusive
false, // no-wait
nil, // arguments
)
failOnError(err, "Failed to declare a queue")
processQueue, err := ch.QueueDeclare(
"ProcessQueue", // name
true, // durable
false, // delete when usused
false, // exclusive
false, // no-wait
nil, // arguments
)
failOnError(err, "Failed to declare a queue")
err = ch.QueueBind(
statusQueue.Name, // queue name
"", // routing key
"StatusExchange", // exchange
false,
nil)
failOnError(err, "Failed to bind a queue")
err = ch.QueueBind(
processQueue.Name, // queue name
"", // routing key
"ProcessExchange", // exchange
false,
nil)
failOnError(err, "Failed to bind a queue")
return conn, ch
}
func failOnError(err error, msg string) {
if err != nil {
log.Fatalf("%s: %s", msg, err)
panic(fmt.Sprintf("%s: %s", msg, err))
}
}
| 34c1200bb7abde0b4d4d97a5770195cfb6d0f95a | [
"Go"
] | 1 | Go | breathbath/micro_consumer | 68e190097bbcdaf8fdb90f3716ea218bbdda23b0 | e9cc51d88edaf8ec6e6bef41c8eae741470d2f34 |
refs/heads/master | <file_sep>class GetCodeReviews
include SuckerPunch::Job
def perform(response_url:)
formatted_code_reviews = GithubInfo.client.code_reviews.map do |code_review|
format_code_review(code_review)
end
uri = URI.parse(response_url)
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true
request = Net::HTTP::Post.new(
uri.request_uri,
'Content-Type' => 'application/json'
)
request.body = {
response_type: 'in_channel',
text: 'Pull requests open for review',
attachments: formatted_code_reviews
}.to_json
response = http.request(request)
end
private
def format_code_review(code_review)
{
fallback: code_review[:html_url],
title: "<#{code_review[:html_url]}|#{code_review[:title]}>",
author_name: code_review[:user][:login],
author_link: code_review[:user][:html_url],
author_icon: code_review[:user][:avatar_url],
callback_id: code_review[:html_url],
actions: [
{
name: "reviewing",
text: "I'm reviewing!",
type: "button",
value: "reviewing"
}
]
}
end
end
<file_sep>Rails.application.routes.draw do
# For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
post 'code_reviews', to: 'code_reviews#index'
post 'code_reviews/actions', to: 'code_reviews#actions'
end
<file_sep>require 'github_api'
class GithubInfo
def self.client
@client ||=
new(
user: ENV['GITHUB_USER'],
password: <PASSWORD>'],
api_url: ENV['GITHUB_API_URL'],
organization: ENV['GITHUB_ORG']
)
end
def initialize(user:, password:, api_url:, organization:)
Github.configure do |c|
c.basic_auth = "#{user}:#{password}"
c.endpoint = api_url
c.org = organization
end
@organization = organization
@github = Github.new
end
def prs_by_repo
@prs_by_repo =
repo_names.map do |repo_name|
repo_pulls = @github.pulls.list(user: @organization, repo: repo_name)
prs =
repo_pulls.map do |rp|
{ user: rp.dig(:assignee, :login), title: rp.dig(:title) }
end
{ repo: repo_name, prs: prs } unless prs.empty?
end.compact
end
def code_reviews
@code_reviews ||=
@github.issues.list(labels: 'Status: Needs Review', filter: 'all')
.map { |pull_request| pull_request.slice(:html_url, :title, :user) }
end
def repos
@repos = @github.repos.list
end
def repo_names
repos.map { |r| r['name'] }
end
end
<file_sep>class CodeReviewsController < ActionController::Base
def index
validate_slack_token(params['token'])
GetCodeReviews.perform_async(response_url: params[:response_url])
render(
json: { response_type: 'ephemeral', text: 'Getting code reviews...' },
status: 200
)
end
def actions
payload = JSON.parse(params['payload'])
validate_slack_token(payload['token'])
original_message = payload['original_message']
user = payload['user']['name']
original_message['attachments'] =
original_message['attachments'].map do |attachment|
if attachment['callback_id'] == payload['callback_id'] &&
!(attachment['text'] && attachment['text'].include?(user))
attachment['text'] = "#{attachment['text']}#{user} "
end
attachment
end
render(json: original_message.to_json, status: 200)
end
private
def validate_slack_token(token)
invalid_slack_token! unless token == ENV['SLACK_TOKEN']
end
def invalid_slack_token!
render(
json: {
response_type: 'ephemeral',
text: 'The Slack token sent to the server is invalid'
}
)
end
end
| 7453556b8ff85b2a92f042e8632c824372833e08 | [
"Ruby"
] | 4 | Ruby | Rsullivan00/code-reviews | 873e839a1e4e239501426334e874b52fb8125852 | 36af2581efc69d37c9a348ec3c565720e8544a6f |
refs/heads/master | <repo_name>SumitPandey11/funwithquizzes<file_sep>/src/QuizRunner.java
import java.util.Scanner;
public class QuizRunner {
public static void main(String [] args){
int grade = 0;
Scanner input = new Scanner(System.in);
MultipleChoice multipleChoice = new MultipleChoice();
multipleChoice.addQuestions("Question Question Question ");
multipleChoice.addAnswer("Answer one", false);
multipleChoice.addAnswer("Answer two", true);
multipleChoice.addAnswer("Answer three", false);
multipleChoice.displayQuestion();
multipleChoice.displayAnswer();
System.out.println("Enter Correct Answer ");
String userAnswer = input.nextLine();
if(multipleChoice.isCorrectAnswer(userAnswer)){
grade += 1;
}
System.out.println("You Answer is : " + multipleChoice.isCorrectAnswer(userAnswer));
System.out.println("You grade is : " + grade);
Checkbox checkbox = new Checkbox();
checkbox.addQuestions("Check box Question ");
checkbox.addAnswer("CBA1",false);
checkbox.addAnswer("CBA2",true);
checkbox.addAnswer("CBA3",false);
checkbox.addAnswer("CBA4",true);
checkbox.displayQuestion();
checkbox.displayAnswer();
}
}
| 00714fa0f191e24ab7abb2262c810963919b6e89 | [
"Java"
] | 1 | Java | SumitPandey11/funwithquizzes | 9968c462ab5d496f8cd18100f83a86810a5bca96 | 0a75730aaad3f008035d16adef9f427bbc720799 |
refs/heads/master | <repo_name>KyLeoHC/node-nestjs-frontend<file_sep>/src/project/disk/views/login/index.ts
import {
Vue,
Component
} from 'vue-property-decorator';
import {
setToken
} from '@/common/auth';
import {
postRegisterData,
postLoginData
} from '../../services/login';
@Component
export default class Login extends Vue {
public isLoginMode = true;
public username = 'James';
public password = '<PASSWORD>';
public confirmPwd = '<PASSWORD>';
public login(): void {
postLoginData({
username: this.username,
password: <PASSWORD>
}).then((token): void => {
setToken(token);
this.$router.push({
name: 'home'
});
});
}
public register(): void {
if (this.confirmPwd !== this.password) {
this.$toast.fail('error password');
return;
}
postRegisterData({
username: this.username,
password: <PASSWORD>
}).then((): void => {
this.$toast.success('register account successfully');
this.isLoginMode = true;
});
}
};
<file_sep>/src/project/disk/router/index.ts
import Vue from 'vue';
import VueRouter from 'vue-router';
import { publicPath } from '@/common/env';
Vue.use(VueRouter);
const project = 'disk';
/* eslint @typescript-eslint/explicit-function-return-type: 0 */
export default new VueRouter({
mode: 'history',
base: `${publicPath}${project}`,
routes: [
{
name: 'login',
path: '/login',
component: () => import(/* webpackChunkName: "disk/list" */ '../views/login/index.vue')
},
{
name: 'home',
path: '/home',
component: () => import(/* webpackChunkName: "disk/home" */ '../views/home/index.vue')
}
]
});
<file_sep>/src/common/auth.ts
import {
storage
} from '@/utils';
const KEY = 'token';
const webStorage = storage.local;
let currentToken = webStorage.get<string>(KEY) || '';
export function setToken(token = ''): void {
currentToken = token;
webStorage.set(KEY, currentToken);
}
export function getToken(): string {
return currentToken;
}
export function clearToken(): void {
currentToken = '';
webStorage.remove(KEY);
}
<file_sep>/src/project/disk/services/file.ts
import SparkMD5 from 'spark-md5';
import { timeout } from '@/utils';
import http from '@/common/http';
import {
baseUrl
} from '@/common/env';
import {
GET_USER_FILES_API,
CREATE_FILE_API,
UPLOAD_FILE_API,
MERGE_FILE_API,
DOWNLOAD_FILE_API,
DELETE_FILE_API
} from '@/common/api';
interface UploadOption {
size?: number;
onInit?: (progress: number) => void;
onProgress?: (loaded: number, total: number) => void;
}
const defaultUploadOption: Required<UploadOption> = {
size: 2 * 1024 * 1024,
onInit: (progress: number): void => {
console.log(progress);
},
onProgress: (loaded: number, total: number): void => {
console.log(loaded, total);
}
};
/**
* create file
* @param params
*/
export const preCreateFile = async (
params: {
filename: string;
hash: string;
segmentCount: number;
}
): Promise<string> => {
const response = await http.post<string>(CREATE_FILE_API, params);
return response.data || '';
};
/**
* upload file
* @param params
*/
export const uploadFile = async (
params: {
id: string;
hash: string;
index: number;
file: Blob;
}
): Promise<void> => {
const formData = new FormData();
formData.append('id', params.id);
formData.append('hash', params.hash);
formData.append('index', params.index + '');
formData.append('file', params.file, 'file');
await http.post<void>(UPLOAD_FILE_API, formData, {
headers: {
'Content-Type': 'multipart/form-data;charset=UTF-8'
}
});
};
/**
* merge file
* @param params
*/
export const mergeFile = async (
params: {
id: string;
}
): Promise<void> => {
await http.put<void>(MERGE_FILE_API, params);
};
/**
* upload entry
* @param files
*/
export const upload = (
files: FileList,
option?: UploadOption
): Promise<void> => {
return new Promise((resolve, reject): void => {
option = option || defaultUploadOption;
const sizeLimit: number = option.size ?? defaultUploadOption.size;
const onInit = option.onInit || defaultUploadOption.onInit;
const onProgress = option.onProgress || defaultUploadOption.onProgress;
const file = files[0];
const totalSize = file.size;
const filename = file.name;
const fileReader = new FileReader();
fileReader.onload = async (event): Promise<void> => {
if (!event.target || !event.target.result) {
reject(new Error('Can not read file data!'));
return;
}
const fileData = event.target.result as ArrayBuffer;
if (totalSize < sizeLimit) {
// Don't need to slice file
const spark = new SparkMD5.ArrayBuffer();
spark.append(fileData);
const hash = spark.end();
onInit(1);
const fileId = await preCreateFile({
filename,
hash,
segmentCount: 0
});
if (fileId) {
await uploadFile({
id: fileId,
hash,
index: -1,
file: new Blob([fileData])
});
}
} else {
// We need to slice file into smaller one
const fileSpark = new SparkMD5.ArrayBuffer();
const segments: {
size: number;
hash: string;
buffer: ArrayBuffer;
}[] = [];
const segmentCount = Math.ceil(totalSize / sizeLimit);
for (let i = 0; i < segmentCount; i++) {
const start = i * sizeLimit;
const end = Math.min(totalSize, start + sizeLimit);
const segmentBuffer = fileData.slice(start, end);
const segmentSpark = new SparkMD5.ArrayBuffer();
segmentSpark.append(segmentBuffer);
segments.push({
size: end - start,
hash: segmentSpark.end(),
buffer: segmentBuffer
});
fileSpark.append(segmentBuffer);
onInit(parseInt((i + 1) / segmentCount * 100 + ''));
await timeout(0);
}
// create file
const fileId = await preCreateFile({
filename,
segmentCount,
hash: fileSpark.end()
});
if (fileId) {
// upload segment data
let loaded = 0;
for (let i = 0; i < segmentCount; i++) {
const segment = segments[i];
await uploadFile({
id: fileId,
index: i,
hash: segment.hash,
file: new Blob([segment.buffer])
});
loaded += segment.size;
onProgress(loaded, totalSize);
}
// merge file
await mergeFile({ id: fileId });
}
}
resolve();
};
fileReader.onerror = (error): void => {
reject(error);
};
fileReader.readAsArrayBuffer(file);
});
};
export interface UserFileData {
usedSpace: number;
count: number;
files: {
id: string;
size: number;
filename: string;
createTime: number;
}[];
}
export async function getUserFiles(): Promise<UserFileData> {
const response = await http.get<UserFileData>(GET_USER_FILES_API);
if (!response.data) {
throw new Error('miss user file data');
}
return response.data;
}
/**
* delete file
* @param params
*/
export const deleteFile = async (
params: {
id: string;
}
): Promise<void> => {
await http.delete<void>(`${DELETE_FILE_API}/${params.id}`);
};
/**
* download file
* @param params
*/
export const downloadFile = async (
params: {
id: string;
}
): Promise<void> => {
window.open(`${baseUrl}${DOWNLOAD_FILE_API}/${params.id}`);
};
<file_sep>/README.md
# node-nestjs-frontend
Frontend for [node-nestjs](https://github.com/KyLeoHC/node-nestjs).
## feature
* [X] [vue 2.x](https://github.com/vuejs/vue)
* [X] [spark-md5](https://github.com/satazor/js-spark-md5) for the md5 computation of file
* [X] Support big file slice and upload
## Getting started
### Installation
Install dependencies
```bash
$ npm ci
```
or
```bash
$ npm install
```
## Run
```bash
$ npm run dev
```
## License
[MIT License](https://github.com/KyLeoHC/node-nestjs-frontend/blob/master/LICENSE)
<file_sep>/src/common/api.ts
/**
* api list
*/
export const LOGIN_API = '/auth/login';
export const REGISTER_ACCOUNT_API = '/user/register';
export const GET_USER_PROFILE_API = '/user/profile';
export const GET_USER_FILES_API = '/file/list';
export const CREATE_FILE_API = '/file/create';
export const UPLOAD_FILE_API = '/file/upload';
export const MERGE_FILE_API = '/file/merge';
export const DOWNLOAD_FILE_API = 'download';
export const DELETE_FILE_API = '/file/delete';
<file_sep>/src/common/http.ts
/* eslint @typescript-eslint/no-explicit-any: 0 */
import axios, {
AxiosInstance,
AxiosRequestConfig,
Canceler
} from 'axios';
import router from '@/project/disk/router';
import { Toast } from 'vant';
import {
getToken,
clearToken
} from '@/common/auth';
import {
baseUrl
} from './env';
export enum ServerResponseCode {
SUCCESS = '200',
UNAUTHORIZED = '401'
}
const isCancel = axios.isCancel;
const CancelToken = axios.CancelToken;
const axiosConfig: AxiosRequestConfig = {
baseURL: baseUrl,
timeout: 10000,
withCredentials: true
};
const axiosInstance = axios.create(axiosConfig);
axios.defaults.headers.post['Content-Type'] = 'application/json';
axiosInstance.interceptors.request.use(function (config): AxiosRequestConfig {
const token = getToken();
if (token) {
config.headers.common.Authorization = `Bearer ${token}`;
}
return config;
}, function (error): Promise<any> {
return Promise.reject(error);
});
axiosInstance.interceptors.response.use(function (response): any {
let message = '';
const data = response.data || { code: '' };
if (data.code === ServerResponseCode.SUCCESS) {
return data;
} else if (data.code === ServerResponseCode.UNAUTHORIZED) {
router.push({ name: 'login' });
message = 'invalid login';
clearToken();
} else {
message = data.message || 'unknown error';
}
Toast.clear();
return new Promise((resolve, reject): void => {
Toast.fail({
message,
onClose(): void {
reject(data);
}
});
});
}, function (error): Promise<any> {
const webErrorResponse = {
isWebError: true,
msg: ''
};
if (isCancel(error)) {
console.log('Request canceled:', error);
} else if (/timeout\sof[\w\s]+exceeded/.test(error.toString())) {
webErrorResponse.msg = 'request timeout!';
} else if (/(Request failed)|(Network Error)/.test(error.toString())) {
webErrorResponse.msg = 'network error!';
}
if (webErrorResponse.msg) {
Toast.clear();
Toast.fail(webErrorResponse.msg);
}
return Promise.reject(webErrorResponse.msg ? webErrorResponse : error);
});
/**
* basic data structure of server response
*/
export interface ServerResponse<T = any> {
code: string;
message?: string;
data?: T;
}
class Http {
private _axiosInstance: AxiosInstance;
private _cancelerMap: Map<string, Canceler> = new Map<string, Canceler>();
public constructor(axiosInstance: AxiosInstance) {
this._axiosInstance = axiosInstance;
}
/**
* check and cancel the same request
* @param url
* @param config
* @private
*/
private _processCancelTokenConfig(url: string, config: AxiosRequestConfig = {}): AxiosRequestConfig {
const cancelerMap = this._cancelerMap;
const canceler = cancelerMap.get(url);
if (canceler) {
cancelerMap.delete(url);
canceler('cancel previous request');
}
if (!config.cancelToken) {
config.cancelToken = new CancelToken(function (canceler): void {
cancelerMap.set(url, canceler);
});
}
return config;
}
/**
* check if the request is sending
* @param url
*/
public checkRequestSending(url = ''): boolean {
return this._cancelerMap.has(url);
}
/**
* wrap the 'get' method of axios
* @param url
* @param config
*/
public get<T>(url: string, config?: AxiosRequestConfig): Promise<ServerResponse<T>> {
config = this._processCancelTokenConfig(url, config);
return new Promise((resolve, reject): void => {
this._axiosInstance.get<ServerResponse<T>, ServerResponse<T>>(url, config)
.then((response): void => {
this._cancelerMap.delete(url);
resolve(response);
})
.catch((error): void => {
if (!isCancel(error)) {
this._cancelerMap.delete(url);
reject(error);
}
});
});
}
/**
* wrap the 'post' method of axios
* @param url
* @param data
* @param config
*/
public post<T>(url: string, data?: any, config?: AxiosRequestConfig): Promise<ServerResponse<T>> {
config = this._processCancelTokenConfig(url, config);
return new Promise((resolve, reject): void => {
this._axiosInstance.post<ServerResponse<T>, ServerResponse<T>>(url, data, config)
.then((response): void => {
this._cancelerMap.delete(url);
resolve(response);
})
.catch((error): void => {
if (!isCancel(error)) {
this._cancelerMap.delete(url);
reject(error);
}
});
});
}
/**
* wrap the 'put' method of axios
* @param url
* @param data
* @param config
*/
public put<T>(url: string, data?: any, config?: AxiosRequestConfig): Promise<ServerResponse<T>> {
config = this._processCancelTokenConfig(url, config);
return new Promise((resolve, reject): void => {
this._axiosInstance.put<ServerResponse<T>, ServerResponse<T>>(url, data, config)
.then((response): void => {
this._cancelerMap.delete(url);
resolve(response);
})
.catch((error): void => {
if (!isCancel(error)) {
this._cancelerMap.delete(url);
reject(error);
}
});
});
}
/**
* wrap the 'delete' method of axios
* @param url
* @param config
*/
public delete<T>(url: string, config?: AxiosRequestConfig): Promise<ServerResponse<T>> {
config = this._processCancelTokenConfig(url, config);
return new Promise((resolve, reject): void => {
this._axiosInstance.delete<ServerResponse<T>, ServerResponse<T>>(url, config)
.then((response): void => {
this._cancelerMap.delete(url);
resolve(response);
})
.catch((error): void => {
if (!isCancel(error)) {
this._cancelerMap.delete(url);
reject(error);
}
});
});
}
}
const http = new Http(axiosInstance);
export {
isCancel
};
export default http;
<file_sep>/src/project/disk/views/home/index.ts
import {
Vue,
Component
} from 'vue-property-decorator';
import {
dateFormat
} from '@/utils';
import {
UserProfile,
getUserProfileData
} from '../../services/home';
import {
upload,
getUserFiles,
deleteFile,
downloadFile
} from '../../services/file';
interface HTMLInputEvent extends Event {
target: HTMLInputElement & EventTarget;
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
type PromiseType<T extends Promise<any>> = T extends Promise<infer P> ? P : never;
@Component({
filters: {
dateFormat
}
})
export default class Home extends Vue {
public isShowUserPopup = false;
public user: UserProfile | null = null;
public userFileData: PromiseType<ReturnType<typeof getUserFiles>> | null = null;
public async mounted(): Promise<void> {
const toastLoading = this.$toast.loading();
this.user = await getUserProfileData();
await this.loadUserFiles();
toastLoading.close();
}
public async loadUserFiles(): Promise<void> {
this.userFileData = await getUserFiles();
}
public async uploadFile(event: HTMLInputEvent): Promise<void> {
const target = event.target;
if (target && target.files && target.files.length) {
const toastLoading = this.$toast.loading();
await upload(target.files, {
onInit: (progress): void => {
toastLoading.message = `初始化${progress}%`;
},
onProgress: (loaded, total): void => {
toastLoading.message = `上传中${parseInt((loaded / total * 100).toFixed(2))}%`;
}
});
toastLoading.clear();
this.$toast.success('upload file successfully!');
this.loadUserFiles();
}
}
public fileSizeFormat(size: number): string {
const kilobyte = 1024;
const megabyte = kilobyte * 1024;
const gigabyte = megabyte * 1024;
let num = 0;
let unit = '';
if (size < kilobyte) {
num = size;
unit = 'B';
} else if (size < megabyte) {
num = parseFloat((size / kilobyte).toFixed(2));
unit = 'KB';
} else if (size < gigabyte) {
num = parseFloat((size / megabyte).toFixed(2));
unit = 'MB';
} else {
num = parseFloat((size / gigabyte).toFixed(2));
unit = 'G';
}
return `${num}${unit}`;
}
public async deleteFile(id: string): Promise<void> {
await this.$dialog.confirm({
title: 'Alert',
message: 'Are you sure to delete this file?'
});
const toastLoading = this.$toast.loading();
await deleteFile({ id });
await this.loadUserFiles();
toastLoading.close();
}
public download(id: string): void {
downloadFile({ id });
}
};
<file_sep>/src/project/disk/services/login.ts
import http from '@/common/http';
import {
LOGIN_API,
REGISTER_ACCOUNT_API
} from '@/common/api';
/**
* register a account
* @param params
*/
const postRegisterData = (
params: {
username: string;
password: string;
}
): Promise<void> => {
return new Promise<void>((resolve, reject): void => {
http.post<void>(REGISTER_ACCOUNT_API, params)
.then((): void => {
resolve();
})
.catch((response): void => {
reject(response);
});
});
};
/**
* login
* @param params
*/
const postLoginData = (
params: {
username: string;
password: string;
}
): Promise<string> => {
return new Promise<string>((resolve, reject): void => {
http.post<string>(LOGIN_API, params)
.then((response): void => {
resolve(response.data || '');
})
.catch((response): void => {
reject(response);
});
});
};
export {
postRegisterData,
postLoginData
};
<file_sep>/src/project/disk/services/home.ts
import http from '@/common/http';
import {
GET_USER_PROFILE_API
} from '@/common/api';
export interface UserProfile {
id: string;
username: string;
}
/**
* get user profile data
* @param params
*/
const getUserProfileData = (): Promise<UserProfile> => {
return new Promise<UserProfile>((resolve, reject): void => {
http.get<UserProfile>(GET_USER_PROFILE_API)
.then((response): void => {
resolve(response.data);
})
.catch((response): void => {
reject(response);
});
});
};
export {
getUserProfileData
};
<file_sep>/src/project/disk/index.ts
/* eslint no-unused-vars: 0 */
import Vue, { VNode } from 'vue';
import {
loadCSSByArray
} from '@/utils';
import polyfill from '@/common/polyfill';
import router from './router';
import App from './app.vue';
import {
Field,
Button,
NavBar,
PullRefresh,
CellGroup,
Toast,
Icon,
Popup,
Dialog,
Locale
} from 'vant';
// eslint-disable-next-line @typescript-eslint/ban-ts-ignore
// @ts-ignore
import enUS from 'vant/lib/locale/lang/en-US';
polyfill();
Locale.use('en-US', enUS);
Toast.setDefaultOptions('loading', {
forbidClick: true,
duration: 0
});
Vue.use(Field)
.use(Button)
.use(NavBar)
.use(CellGroup)
.use(PullRefresh)
.use(Toast)
.use(Icon)
.use(Popup)
.use(Dialog);
loadCSSByArray([
'//at.alicdn.com/t/font_1007376_mqnhabrqmch.css',
...(window.__cssList || [])
]).finally((): void => {
new Vue({
router,
render: (h): VNode => h(App)
}).$mount('#app');
});
<file_sep>/src/utils/timeout.ts
/**
* wrap `setTimeout` function with Promise
* @param delay
*/
export function timeout(delay: number): Promise<void> {
return new Promise((resolve): void => {
setTimeout(function () {
resolve();
}, delay);
});
}
| c44d3e68aff27f28e046fe2ab3296db4db684bfe | [
"Markdown",
"TypeScript"
] | 12 | TypeScript | KyLeoHC/node-nestjs-frontend | 4f97e0eee3b2fc4c3d51fdf51dee84eaec03a685 | 871c0d0dd7580a4c059b5de3dc0475a5eaf4b0fb |
refs/heads/master | <repo_name>tidatida/Threaded-Client-Server-Application<file_sep>/server/threadedcstserver.h
#ifndef THREADEDCSTSERVER_H
#define THREADEDCSTSERVER_H
#include <QTcpServer>
class ThreadedCSTServer : public QTcpServer
{
Q_OBJECT
public:
ThreadedCSTServer(QObject *parent = 0);
private:
void incomingConnection(int socketId);
};
#endif // THREADEDCSTSERVER_H
<file_sep>/client/ui_tcst.h
/********************************************************************************
** Form generated from reading UI file 'tcst.ui'
**
** Created: Thu Dec 9 19:14:36 2010
** by: Qt User Interface Compiler version 4.7.0
**
** WARNING! All changes made in this file will be lost when recompiling UI file!
********************************************************************************/
#ifndef UI_TCST_H
#define UI_TCST_H
#include <QtCore/QVariant>
#include <QtGui/QAction>
#include <QtGui/QApplication>
#include <QtGui/QButtonGroup>
#include <QtGui/QComboBox>
#include <QtGui/QDialog>
#include <QtGui/QGridLayout>
#include <QtGui/QHBoxLayout>
#include <QtGui/QHeaderView>
#include <QtGui/QLabel>
#include <QtGui/QLineEdit>
#include <QtGui/QListWidget>
#include <QtGui/QPushButton>
#include <QtGui/QSpacerItem>
#include <QtGui/QVBoxLayout>
#include <QtGui/QWidget>
QT_BEGIN_NAMESPACE
class Ui_TCSTClass
{
public:
QWidget *widget;
QGridLayout *gridLayout;
QVBoxLayout *verticalLayout;
QLabel *userLabel;
QLineEdit *userLineEdit;
QLabel *passLabel;
QLineEdit *passLineEdit;
QLabel *statusLabel;
QComboBox *comboBox;
QHBoxLayout *horizontalLayout;
QSpacerItem *horizontalSpacer;
QPushButton *registerButton;
QPushButton *loginButton;
QPushButton *cancelButton;
QPushButton *button1;
QPushButton *button2;
QListWidget *resultList;
QSpacerItem *horizontalSpacer_2;
void setupUi(QDialog *TCSTClass)
{
if (TCSTClass->objectName().isEmpty())
TCSTClass->setObjectName(QString::fromUtf8("TCSTClass"));
TCSTClass->resize(400, 300);
widget = new QWidget(TCSTClass);
widget->setObjectName(QString::fromUtf8("widget"));
widget->setGeometry(QRect(30, 80, 331, 151));
gridLayout = new QGridLayout(widget);
gridLayout->setSpacing(6);
gridLayout->setContentsMargins(11, 11, 11, 11);
gridLayout->setObjectName(QString::fromUtf8("gridLayout"));
gridLayout->setContentsMargins(0, 0, 0, 0);
verticalLayout = new QVBoxLayout();
verticalLayout->setSpacing(6);
verticalLayout->setObjectName(QString::fromUtf8("verticalLayout"));
userLabel = new QLabel(widget);
userLabel->setObjectName(QString::fromUtf8("userLabel"));
verticalLayout->addWidget(userLabel);
userLineEdit = new QLineEdit(widget);
userLineEdit->setObjectName(QString::fromUtf8("userLineEdit"));
verticalLayout->addWidget(userLineEdit);
passLabel = new QLabel(widget);
passLabel->setObjectName(QString::fromUtf8("passLabel"));
verticalLayout->addWidget(passLabel);
passLineEdit = new QLineEdit(widget);
passLineEdit->setObjectName(QString::fromUtf8("passLineEdit"));
verticalLayout->addWidget(passLineEdit);
gridLayout->addLayout(verticalLayout, 0, 0, 1, 1);
horizontalLayout = new QHBoxLayout();
horizontalLayout->setSpacing(6);
horizontalLayout->setObjectName(QString::fromUtf8("horizontalLayout"));
horizontalSpacer = new QSpacerItem(40, 20, QSizePolicy::Expanding, QSizePolicy::Minimum);
horizontalLayout->addItem(horizontalSpacer);
registerButton = new QPushButton(widget);
registerButton->setObjectName(QString::fromUtf8("registerButton"));
horizontalLayout->addWidget(registerButton);
loginButton = new QPushButton(widget);
loginButton->setObjectName(QString::fromUtf8("loginButton"));
horizontalLayout->addWidget(loginButton);
cancelButton = new QPushButton(widget);
cancelButton->setObjectName(QString::fromUtf8("cancelButton"));
horizontalLayout->addWidget(cancelButton);
horizontalSpacer_2 = new QSpacerItem(40, 20, QSizePolicy::Expanding, QSizePolicy::Minimum);
horizontalLayout->addItem(horizontalSpacer_2);
gridLayout->addLayout(horizontalLayout, 1, 0, 1, 1);
retranslateUi(TCSTClass);
QMetaObject::connectSlotsByName(TCSTClass);
} // setupUi
void retranslateUi(QDialog *TCSTClass)
{
TCSTClass->setWindowTitle(QApplication::translate("TCSTClass", "TCST", 0, QApplication::UnicodeUTF8));
userLabel->setText(QApplication::translate("TCSTClass", "Username:", 0, QApplication::UnicodeUTF8));
passLabel->setText(QApplication::translate("TCSTClass", "Password:", 0, QApplication::UnicodeUTF8));
registerButton->setText(QApplication::translate("TCSTClass", "Register", 0, QApplication::UnicodeUTF8));
loginButton->setText(QApplication::translate("TCSTClass", "Login", 0, QApplication::UnicodeUTF8));
cancelButton->setText(QApplication::translate("TCSTClass", "Cancel", 0, QApplication::UnicodeUTF8));
} // retranslateUi
};
namespace Ui {
class TCSTClass: public Ui_TCSTClass {};
} // namespace Ui
QT_END_NAMESPACE
#endif // UI_TCST_H
<file_sep>/server/clientsocket.h
/*
* clientsocket.h
*
* Created on: Dec 5, 2010
* Author: Yogi
*/
#ifndef CLIENTSOCKET_H_
#define CLIENTSOCKET_H_
#include <QTcpSocket>
class ClientSocket : public QTcpSocket
{
Q_OBJECT
public:
ClientSocket(QObject *parent = 0);
private slots:
void readClient();
private:
void generateReply(const QString &name, const QString &pass);
void registerClient(const QString &name, const QString &pass);
void readFile(QString &file);
void loadLoginFile();
void saveUserPass();
void searchForFile(QString &text);
quint16 nextBlockSize;
qint64 cposition;
QMap<QString, QString> loginInfo;
QList<QString> fileList;
};
#endif /* CLIENTSOCKET_H_ */
<file_sep>/client/debug/moc_tcst.cpp
/****************************************************************************
** Meta object code from reading C++ file 'tcst.h'
**
** Created: Thu Dec 9 19:18:44 2010
** by: The Qt Meta Object Compiler version 62 (Qt 4.7.0)
**
** WARNING! All changes made in this file will be lost!
*****************************************************************************/
#include "../tcst.h"
#if !defined(Q_MOC_OUTPUT_REVISION)
#error "The header file 'tcst.h' doesn't include <QObject>."
#elif Q_MOC_OUTPUT_REVISION != 62
#error "This file was generated using the moc from 4.7.0. It"
#error "cannot be used with the include files from this version of Qt."
#error "(The moc has changed too much.)"
#endif
QT_BEGIN_MOC_NAMESPACE
static const uint qt_meta_data_TCST[] = {
// content:
5, // revision
0, // classname
0, 0, // classinfo
16, 14, // methods
0, 0, // properties
0, 0, // enums/sets
0, 0, // constructors
0, // flags
0, // signalCount
// slots: signature, parameters, type, tag, flags
6, 5, 5, 5, 0x08,
23, 5, 5, 5, 0x08,
47, 5, 5, 5, 0x08,
67, 5, 5, 5, 0x08,
83, 5, 5, 5, 0x08,
101, 5, 5, 5, 0x08,
115, 5, 5, 5, 0x08,
126, 5, 5, 5, 0x08,
141, 5, 5, 5, 0x08,
167, 155, 5, 5, 0x08,
210, 5, 5, 5, 0x08,
237, 5, 5, 5, 0x08,
253, 5, 5, 5, 0x08,
266, 5, 5, 5, 0x08,
287, 5, 5, 5, 0x08,
301, 5, 5, 5, 0x08,
0 // eod
};
static const char qt_meta_stringdata_TCST[] = {
"TCST\0\0button1Clicked()\0registerButtonClicked()\0"
"browseForLocation()\0browseForFile()\0"
"connectToServer()\0sendRequest()\0"
"sendFile()\0updateLabels()\0confirmFile()\0"
"socketError\0displayError(QAbstractSocket::SocketError)\0"
"connectionClosedByServer()\0sessionOpened()\0"
"reloadMenu()\0registerWithServer()\0"
"printStatus()\0reconnect()\0"
};
const QMetaObject TCST::staticMetaObject = {
{ &QDialog::staticMetaObject, qt_meta_stringdata_TCST,
qt_meta_data_TCST, 0 }
};
#ifdef Q_NO_DATA_RELOCATION
const QMetaObject &TCST::getStaticMetaObject() { return staticMetaObject; }
#endif //Q_NO_DATA_RELOCATION
const QMetaObject *TCST::metaObject() const
{
return QObject::d_ptr->metaObject ? QObject::d_ptr->metaObject : &staticMetaObject;
}
void *TCST::qt_metacast(const char *_clname)
{
if (!_clname) return 0;
if (!strcmp(_clname, qt_meta_stringdata_TCST))
return static_cast<void*>(const_cast< TCST*>(this));
return QDialog::qt_metacast(_clname);
}
int TCST::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
_id = QDialog::qt_metacall(_c, _id, _a);
if (_id < 0)
return _id;
if (_c == QMetaObject::InvokeMetaMethod) {
switch (_id) {
case 0: button1Clicked(); break;
case 1: registerButtonClicked(); break;
case 2: browseForLocation(); break;
case 3: browseForFile(); break;
case 4: connectToServer(); break;
case 5: sendRequest(); break;
case 6: sendFile(); break;
case 7: updateLabels(); break;
case 8: confirmFile(); break;
case 9: displayError((*reinterpret_cast< QAbstractSocket::SocketError(*)>(_a[1]))); break;
case 10: connectionClosedByServer(); break;
case 11: sessionOpened(); break;
case 12: reloadMenu(); break;
case 13: registerWithServer(); break;
case 14: printStatus(); break;
case 15: reconnect(); break;
default: ;
}
_id -= 16;
}
return _id;
}
QT_END_MOC_NAMESPACE
<file_sep>/server/clientsocket.cpp
/*
* clientsocket.cpp
*
* Created on: Dec 5, 2010
* Author: Yogi
*/
#include <QTcpSocket>
#include <QFile>
#include "clientsocket.h"
ClientSocket::ClientSocket(QObject *parent)
: QTcpSocket(parent)
{
connect(this, SIGNAL(readyRead()), this, SLOT(readClient()));
connect(this, SIGNAL(disconnected()), this, SLOT(deleteLater()));
nextBlockSize = 0;
loadLoginFile();
}
void ClientSocket::readClient(){
QDataStream in(this);
in.setVersion(QDataStream::Qt_4_1);
if(nextBlockSize == 0){
if(bytesAvailable() < sizeof(quint16)){
return;
}
in >> nextBlockSize;
}
if(bytesAvailable() < nextBlockSize){
return;
}
quint8 requestType;
QString user;
QString pass;
QString f;
QString search;
in >> requestType;
if(requestType == 'L'){
in >> user >> pass;
//printf("the user name is: %s\n", qPrintable(user));
//printf("the password is: %s\n", qPrintable(pass));
generateReply(user, pass);
//QDataStream out(this);
//out << quint16(0xFFFF);
this->disconnectFromHost();
}else if(requestType == 'R'){
in >> user >> pass;
//printf("the user name is: %s\n", qPrintable(user));
//printf("the password is: %s\n", qPrintable(pass));
registerClient(user, pass);
//QDataStream out(this);
//out << quint16(0xFFFF);
this->disconnectFromHost();
}
else if(requestType == 'F'){
//printf("Trying to read in QByteArray from client.\n");
in >> f;
readFile(f);
//QDataStream out(this);
//out << quint16(0xFFFF);
this->disconnectFromHost();
}else if(requestType == 'S'){
printf("Got your search request\n");
in >> search;
searchForFile(search);
}
//close();
}
void ClientSocket::loadLoginFile(){
QFile file("userpass.dat");
file.open(QIODevice::ReadOnly);
QDataStream in(&file);
in.setVersion(QDataStream::Qt_4_1);
in >> loginInfo;
}
void ClientSocket::saveUserPass(){
QFile file("userpass.dat");
file.open(QIODevice::WriteOnly);
QDataStream out(&file);
out.setVersion(QDataStream::Qt_4_1);
out << loginInfo;
}
void ClientSocket::generateReply(const QString &user, const QString &pass){
//printf("in the generateReply method\n");
//printf("the user name is: %s\n", qPrintable(user));
//printf("the password is: %s\n", qPrintable(pass));
QByteArray block;
QDataStream out(&block, QIODevice::WriteOnly);
out.setVersion(QDataStream::Qt_4_1);
QString logged;
if(loginInfo.contains(user)){
if(loginInfo.value(user).compare(pass) == 0){
logged = "You have logged in to the server";
out << quint16(0) << logged;
}
else{
logged = "Your username and password were not correct.\n Please try again or Register.";
out << quint16(0) << logged;
}
}
else{
logged = "Your username and password were not correct.\n Please try again or Register.";
out << quint16(0) << logged;
}
out << quint16(0) << logged;
//printf("sent the logged message to the data stream\n");
//printf("the message is: %s\n", qPrintable(logged));
out.device()->seek(0);
out << quint16(block.size() - sizeof(quint16));
write(block);
nextBlockSize = 0;
}
void ClientSocket::registerClient(const QString &name, const QString &pass){
loginInfo.insertMulti(name, pass);
saveUserPass();
QByteArray block;
QDataStream out(&block, QIODevice::WriteOnly);
out.setVersion(QDataStream::Qt_4_1);
QString logged = "You have registered with the server.";
out << quint16(0) << logged;
//printf("sent the logged message to the data stream\n");
//printf("the message is: %s\n", qPrintable(logged));
out.device()->seek(0);
out << quint16(block.size() - sizeof(quint16));
write(block);
nextBlockSize = 0;
}
void ClientSocket::readFile(QString &file){
//printf("In readFile.\n");
QString f = file;
//printf("File: %s\n", qPrintable(f));
QFile writefile("savesFiles.txt");
writefile.open(QIODevice::WriteOnly | QIODevice::Append);
// if(writefile.exists()){
// printf("this file exists\n");
// if(!writefile.openMode() == 0x0000){
// printf("The file is open");
// }
// }
cposition = writefile.pos();
QTextStream writeOut(&writefile);
writeOut.device()->seek(cposition);
writeOut << f << endl;
cposition = writefile.pos();
QByteArray block;
QDataStream out(&block, QIODevice::WriteOnly);
out.setVersion(QDataStream::Qt_4_1);
QString logged = "We received your file.";
out << quint16(0) << logged;
//printf("sent the logged message to the data stream\n");
//printf("the message is: %s\n", qPrintable(logged));
out.device()->seek(0);
out << quint16(block.size() - sizeof(quint16));
write(block);
}
void ClientSocket::searchForFile(QString &text){
//printf("Searching for file: %s\n", qPrintable(text));
QFile file("savesFiles.txt");
file.open(QIODevice::ReadOnly);
QTextStream readIn(&file);
while(!readIn.atEnd()){
QString line = readIn.readLine();
if(line.contains(text, Qt::CaseInsensitive)){
printf("Next line: %s\n", qPrintable(line));
fileList.append(line);
}
}
QByteArray block;
QDataStream out(&block, QIODevice::WriteOnly);
out.setVersion(QDataStream::Qt_4_1);
QString logged = "Results coming";
out << quint16(0) << logged << fileList;
//printf("sent the logged message to the data stream\n");
//printf("the message is: %s\n", qPrintable(logged));
out.device()->seek(0);
out << quint16(block.size() - sizeof(quint16));
write(block);
}
<file_sep>/client/registerdialog.cpp
#include <QtNetwork>
#include <QMessageBox>
#include "registerdialog.h"
RegisterDialog::RegisterDialog(QWidget *parent)
: QDialog(parent)
{
ui.setupUi(this);
connect(ui.okButton, SIGNAL(clicked()), this, SLOT(accept()));
connect(ui.cancelButton, SIGNAL(clicked()), this, SLOT(close()));
//connect(&tcpSocket, SIGNAL(connected()), this, SLOT(sendRequest()));
//connect(&tcpSocket, SIGNAL(disconnected()), this, SLOT(connectionClosedByServer()));
//connect(&tcpSocket, SIGNAL(readyRead()), this, SLOT(updateLabels()));
//connect(&tcpSocket, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(error()));
QList<QHostAddress> ipAddressList = QNetworkInterface::allAddresses();
for(int i = 0; i < ipAddressList.size(); ++i){
if(ipAddressList.at(i) != QHostAddress::LocalHost && ipAddressList.at(i).toIPv4Address()){
ipAddress = ipAddressList.at(i).toString();
break;
}
}
if(ipAddress.isEmpty()){
ipAddress = QHostAddress(QHostAddress::LocalHost).toString();
}
//ui.cancelButton->setEnabled(false);
ui.statusLabel->setText("When you are done typing in a username and password,\n click ok then click register again to register with the server.");
}
void RegisterDialog::connectToServer(){
tcpSocket.connectToHost(ipAddress, 34);
//ui.label->setText("Connecting to server...");
printf("Connecting to server...\n");
nextBlockSize = 0;
}
void RegisterDialog::sendRequest(){
QByteArray block;
QDataStream out(&block, QIODevice::WriteOnly);
out.setVersion(QDataStream::Qt_4_1);
out << quint16(0) << quint8('R') << ui.nameEdit->text() << ui.passEdit->text();
out.device()->seek(0);
out << quint16(block.size() - sizeof(quint16));
tcpSocket.write(block);
//ui.label->setText(tr("Sending request..."));
printf("Sending Request...\n");
}
void RegisterDialog::updateLabels(){
QDataStream in(&tcpSocket);
in.setVersion(QDataStream::Qt_4_1);
forever{
if(nextBlockSize == 0){
if(tcpSocket.bytesAvailable() < sizeof(quint16)){
break;
}
in >> nextBlockSize;
}
if(nextBlockSize == 0xFFFF){
closeConnection();
//ui.label->setText(tr("Finished reading from server"));
break;
}
if(tcpSocket.bytesAvailable() < nextBlockSize){
break;
}
QString status;
in >> status;
printf("The status from the server is: %s\n", qPrintable(status));
ui.statusLabel->setText(status);
nextBlockSize = 0;
//ui.cancelButton->setEnabled(true);
}
}
void RegisterDialog::displayError(QAbstractSocket::SocketError socketError){
switch (socketError) {
case QAbstractSocket::RemoteHostClosedError:
break;
case QAbstractSocket::HostNotFoundError:
QMessageBox::information(this, tr("Client"),
tr("The host was not found. Please check the "
"host name and port settings."));
break;
case QAbstractSocket::ConnectionRefusedError:
QMessageBox::information(this, tr("Client"),
tr("The connection was refused by the peer. "
"Make sure the fortune server is running, "
"and check that the host name and port "
"settings are correct."));
break;
default:
QMessageBox::information(this, tr("Client"),
tr("The following error occurred: %1.")
.arg(tcpSocket.errorString()));
}
}
void RegisterDialog::closeConnection(){
tcpSocket.close();
}
void RegisterDialog::connectionClosedByServer(){
if(nextBlockSize != 0xFFFF){
ui.statusLabel->setText("Error: Connection closed by server");
//printf("Error: Connection closed by server...\n");
closeConnection();
}
}
<file_sep>/client/client.h
#ifndef CLIENT_H
#define CLIENT_H
#include <QDialog>
#include <QTcpSocket>
#include <QNetworkSession>
#include <QtGui/QLabel>
#include <QtGui/QLineEdit>
#include <QtGui/QGridLayout>
#include <QtGui/QListWidget>
#include <QtGui/QPushButton>
#include <QtGui/QComboBox>
#include <QtGui/QDialogButtonBox>
class Client : public QDialog
{
Q_OBJECT
public:
Client(QWidget *parent = 0);
private slots:
void requestNewConnection();
void registerWithServer();
void browseForFile();
void connectionClosedByServer();
void displayError(QAbstractSocket::SocketError socketError);
void sessionOpened();
void sendLoginInfo();
void sendRegistration();
void sendSearchInfo();
void updateLabels();
void reloadMenu();
void printStatus();
void createMoveLayout();
void createLocateLayout();
void sendFile();
private:
void createMenuLayout();
void closeConnection();
void addItems();
QLabel *userLabel;
QLabel *passLabel;
QLineEdit *userLineEdit;
QLineEdit *passLineEdit;
QLabel *statusLabel;
QPushButton *loginButton;
QPushButton *cancelButton;
QPushButton *registerButton;
QPushButton *moveButton;
QPushButton *locateButton;
QPushButton *menuButton;
QPushButton *moveFilesButton;
QPushButton *browseButton;
QPushButton *searchButton;
QPushButton *openButton;
QListWidget *resultList;
QComboBox *comboBox;
QDialogButtonBox *buttonBox;
QGridLayout *mainLayout;
QTcpSocket *tcpSocket;
QString ipAddress;
quint16 blockSize;
QNetworkSession *networkSession;
QString cLayout;
QString message;
QList<QString> fileList;
};
#endif // CLIENT_H
<file_sep>/server/debug/qrc_server.cpp
/****************************************************************************
** Resource object code
**
** Created: Fri Dec 10 18:07:04 2010
** by: The Resource Compiler for Qt version 4.7.0
**
** WARNING! All changes made in this file will be lost!
*****************************************************************************/
#include <QtCore/qglobal.h>
static const unsigned char qt_resource_data[] = {
// C:/Users/Yogi/Documents/6210 Advanced Operating Systems/Special Project/ThreadedCSTServer/userpass.dat
0x0,0x0,0x0,0x1a,
0x0,
0x0,0x0,0x1,0x0,0x0,0x0,0x6,0x0,0x79,0x0,0x61,0x0,0x6b,0x0,0x0,0x0,
0x8,0x0,0x74,0x0,0x69,0x0,0x6d,0x0,0x65,
// C:/Users/Yogi/Documents/6210 Advanced Operating Systems/Special Project/ThreadedCSTServer/savesFiles.txt
0x0,0x0,0x0,0x11,
0x63,
0x6f,0x6d,0x62,0x6f,0x2e,0x63,0xa,0x74,0x65,0x73,0x74,0x2e,0x74,0x78,0x74,0xa,
};
static const unsigned char qt_resource_name[] = {
// userpass.dat
0x0,0xc,
0x7,0x39,0xd8,0x44,
0x0,0x75,
0x0,0x73,0x0,0x65,0x0,0x72,0x0,0x70,0x0,0x61,0x0,0x73,0x0,0x73,0x0,0x2e,0x0,0x64,0x0,0x61,0x0,0x74,
// savesFiles.txt
0x0,0xe,
0x3,0x5e,0xbc,0x14,
0x0,0x73,
0x0,0x61,0x0,0x76,0x0,0x65,0x0,0x73,0x0,0x46,0x0,0x69,0x0,0x6c,0x0,0x65,0x0,0x73,0x0,0x2e,0x0,0x74,0x0,0x78,0x0,0x74,
};
static const unsigned char qt_resource_struct[] = {
// :
0x0,0x0,0x0,0x0,0x0,0x2,0x0,0x0,0x0,0x2,0x0,0x0,0x0,0x1,
// :/savesFiles.txt
0x0,0x0,0x0,0x1e,0x0,0x0,0x0,0x0,0x0,0x1,0x0,0x0,0x0,0x1e,
// :/userpass.dat
0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x1,0x0,0x0,0x0,0x0,
};
QT_BEGIN_NAMESPACE
extern Q_CORE_EXPORT bool qRegisterResourceData
(int, const unsigned char *, const unsigned char *, const unsigned char *);
extern Q_CORE_EXPORT bool qUnregisterResourceData
(int, const unsigned char *, const unsigned char *, const unsigned char *);
QT_END_NAMESPACE
int QT_MANGLE_NAMESPACE(qInitResources_server)()
{
QT_PREPEND_NAMESPACE(qRegisterResourceData)
(0x01, qt_resource_struct, qt_resource_name, qt_resource_data);
return 1;
}
Q_CONSTRUCTOR_FUNCTION(QT_MANGLE_NAMESPACE(qInitResources_server))
int QT_MANGLE_NAMESPACE(qCleanupResources_server)()
{
QT_PREPEND_NAMESPACE(qUnregisterResourceData)
(0x01, qt_resource_struct, qt_resource_name, qt_resource_data);
return 1;
}
Q_DESTRUCTOR_FUNCTION(QT_MANGLE_NAMESPACE(qCleanupResources_server))
<file_sep>/client/registerdialog.h
#ifndef REGISTERDIALOG_H
#define REGISTERDIALOG_H
#include <QtGui/QDialog>
#include <QTcpSocket>
#include "ui_registerdialog.h"
class RegisterDialog : public QDialog
{
Q_OBJECT
public: QString name(){
return ui.nameEdit->text();
}
public: QString pass(){
return ui.passEdit->text();
}
public:
RegisterDialog(QWidget *parent = 0);
private slots:
void connectToServer();
void sendRequest();
void updateLabels();
void displayError(QAbstractSocket::SocketError socketError);
void connectionClosedByServer();
private:
Ui::RegisterDialogClass ui;
void closeConnection();
QTcpSocket tcpSocket;
quint16 nextBlockSize;
QString ipAddress;
};
#endif // REGISTERDIALOG_H
<file_sep>/client/client.cpp
#include <QFile>
#include <QFileInfo>
#include <QFileDialog>
#include <QMessageBox>
#include <QtNetwork>
#include "client.h"
#include "registerdialog.h"
Client::Client(QWidget *parent)
: QDialog(parent), networkSession(0)
{
// find out which IP to connect to
QList<QHostAddress> ipAddressesList = QNetworkInterface::allAddresses();
// use the first non-localhost IPv4 address
for (int i = 0; i < ipAddressesList.size(); ++i) {
if (ipAddressesList.at(i) != QHostAddress::LocalHost &&
ipAddressesList.at(i).toIPv4Address()) {
ipAddress = ipAddressesList.at(i).toString();
break;
}
}
// if we did not find one, use IPv4 localhost
if (ipAddress.isEmpty())
ipAddress = QHostAddress(QHostAddress::LocalHost).toString();
userLabel = new QLabel("Username: ");
passLabel = new QLabel("Password: ");
statusLabel = new QLabel();
userLineEdit = new QLineEdit();
passLineEdit = new QLineEdit();
passLineEdit->setEchoMode(QLineEdit::Password);
registerButton = new QPushButton("Register");
loginButton = new QPushButton("Login");
cancelButton = new QPushButton("Cancel");
buttonBox = new QDialogButtonBox();
buttonBox->addButton(registerButton, QDialogButtonBox::ActionRole);
buttonBox->addButton(loginButton, QDialogButtonBox::ActionRole);
buttonBox->addButton(cancelButton, QDialogButtonBox::RejectRole);
mainLayout = new QGridLayout;
mainLayout->addWidget(userLabel, 0, 0, 1, 2);
mainLayout->addWidget(userLineEdit, 1, 0, 1, 5);
mainLayout->addWidget(passLabel, 2, 0, 1, 2);
mainLayout->addWidget(passLineEdit, 3, 0, 1, 5);
mainLayout->addWidget(statusLabel, 4, 0, 3, 4);
mainLayout->addWidget(buttonBox, 7, 1, 1, 2);
setLayout(mainLayout);
tcpSocket = new QTcpSocket(this);
connect(registerButton, SIGNAL(clicked()), this, SLOT(registerWithServer()));
connect(cancelButton, SIGNAL(clicked()), this, SLOT(close()));
connect(loginButton, SIGNAL(clicked()), this, SLOT(requestNewConnection()));
connect(tcpSocket, SIGNAL(connected()), this, SLOT(sendLoginInfo()));
connect(tcpSocket, SIGNAL(readyRead()), this, SLOT(updateLabels()));
//connect(tcpSocket, SIGNAL(disconnected()), this, SLOT(connectionClosedByServer()));
QNetworkConfigurationManager manager;
if (manager.capabilities() & QNetworkConfigurationManager::NetworkSessionRequired) {
// Get saved network configuration
QSettings settings(QSettings::UserScope, QLatin1String("Trolltech"));
settings.beginGroup(QLatin1String("QtNetwork"));
const QString id = settings.value(QLatin1String("DefaultNetworkConfiguration")).toString();
settings.endGroup();
// If the saved network configuration is not currently discovered use the system default
QNetworkConfiguration config = manager.configurationFromIdentifier(id);
if ((config.state() & QNetworkConfiguration::Discovered) !=
QNetworkConfiguration::Discovered) {
config = manager.defaultConfiguration();
}
networkSession = new QNetworkSession(config, this);
connect(networkSession, SIGNAL(opened()), this, SLOT(sessionOpened()));
statusLabel->setText(tr("Opening network session."));
networkSession->open();
}
}
void Client::connectionClosedByServer(){
statusLabel->setText("Error: Connection closed by server");
}
void Client::requestNewConnection(){
blockSize = 0;
tcpSocket->abort();
if((cLayout.compare("Move") == 0 && !userLineEdit->text().isEmpty())
|| (cLayout.compare("Locate") == 0 && !userLineEdit->text().isEmpty())){
tcpSocket->connectToHost(ipAddress, 49209);
}
else if(!(userLineEdit->text().isEmpty()) && !(passLineEdit->text().isEmpty())){
tcpSocket->connectToHost(ipAddress, 49209);
}else if(!cLayout.compare("Move") == 0 && !cLayout.compare("Locate") == 0){
statusLabel->setText("Please enter a username and a password");
}
}
void Client::registerWithServer(){
RegisterDialog rd(this);
if(rd.exec()){
QString name = rd.name();
QString pass = rd.pass();
userLineEdit->setText(name);
passLineEdit->setText(pass);
disconnect(tcpSocket, SIGNAL(connected()), this, SLOT(sendLoginInfo()));
requestNewConnection();
connect(tcpSocket, SIGNAL(connected()), this, SLOT(sendRegistration()));
}
}
void Client::sendRegistration(){
QByteArray block;
QDataStream out(&block, QIODevice::WriteOnly);
out.setVersion(QDataStream::Qt_4_1);
out << quint16(0) << quint8('R') << userLineEdit->text() << passLineEdit->text();
out.device()->seek(0);
out << quint16(block.size() - sizeof(quint16));
tcpSocket->write(block);
//ui.label->setText(tr("Sending request..."));
//printf("In sendRegistration. Sending Request...\n");
}
void Client::sendLoginInfo(){
QByteArray block;
QDataStream out(&block, QIODevice::WriteOnly);
out.setVersion(QDataStream::Qt_4_1);
out << quint16(0) << quint8('L') << userLineEdit->text() << passLineEdit->text();
out.device()->seek(0);
out << quint16(block.size() - sizeof(quint16));
tcpSocket->write(block);
//ui.label->setText(tr("Sending request..."));
//printf("Sending Request...\n");
}
void Client::sendFile(){
QByteArray block;
//QFile *file = new QFile(userLineEdit->text());
//file->open(QIODevice::ReadOnly);
QDataStream out(&block, QIODevice::WriteOnly);
out.setVersion(QDataStream::Qt_4_1);
QString file = userLineEdit->text();
if(!userLineEdit->text().isEmpty()){
//printf("File from edit: %s\n", qPrintable(file));
out << quint16(0) << quint8('F') << userLineEdit->text();
out.device()->seek(0);
out << quint16(block.size() - sizeof(quint16));
tcpSocket->write(block);
}else{
statusLabel->setText("Please choose a file to move to the server");
}
//ui.label->setText(tr("Sending request..."));
//printf("Sending Request...\n");
}
void Client::sendSearchInfo(){
QByteArray block;
QDataStream out(&block, QIODevice::WriteOnly);
out.setVersion(QDataStream::Qt_4_1);
//if(!userLineEdit->text().isEmpty()){
out << quint16(0) << quint8('S') << userLineEdit->text();
out.device()->seek(0);
out << quint16(block.size() - sizeof(quint16));
tcpSocket->write(block);
//}else{
// statusLabel->setText("Please enter a file to search for");
//}
//ui.label->setText(tr("Sending request..."));
//printf("Sending Request...\n");
}
void Client::updateLabels(){
QDataStream in(tcpSocket);
in.setVersion(QDataStream::Qt_4_0);
if (blockSize == 0) {
if (tcpSocket->bytesAvailable() < (int)sizeof(quint16))
return;
in >> blockSize;
}
if (tcpSocket->bytesAvailable() < blockSize)
return;
QString status;
in >> status;
message = status;
//statusLabel->setText(status);
//printf("Status: %s\n", qPrintable(status));
if(status.compare("You have logged in to the server") == 0){
createMenuLayout();
}else if(status.compare("We received your file.") == 0){
//printf("got it");
statusLabel->setText(status);
}else if(status.compare("You have registered with the server.") == 0){
createMenuLayout();
}else if(status.compare("Results coming") == 0){
in >> fileList;
if(fileList.isEmpty()){
//printf("The file list is empty");
statusLabel->setText("No files were found");
}
for(int i = 0; i < fileList.size(); ++i){
new QListWidgetItem(fileList.at(i), resultList);
}
}else{
statusLabel->setText(status);
}
}
void Client::browseForFile(){
QString file = QFileDialog::getOpenFileName(this,
tr("Find Files"));
QFileInfo f(file);
file = f.fileName();
if (!file.isEmpty()) {
userLineEdit->setText(file);
}
}
void Client::sessionOpened(){
// Save the used configuration
QNetworkConfiguration config = networkSession->configuration();
QString id;
if (config.type() == QNetworkConfiguration::UserChoice)
id = networkSession->sessionProperty(QLatin1String("UserChoiceConfiguration")).toString();
else
id = config.identifier();
QSettings settings(QSettings::UserScope, QLatin1String("Trolltech"));
settings.beginGroup(QLatin1String("QtNetwork"));
settings.setValue(QLatin1String("DefaultNetworkConfiguration"), id);
settings.endGroup();
statusLabel->setText(tr("This examples requires that you run the "
"Fortune Server example as well."));
}
void Client::displayError(QAbstractSocket::SocketError socketError){
switch (socketError) {
case QAbstractSocket::RemoteHostClosedError:
break;
case QAbstractSocket::HostNotFoundError:
QMessageBox::information(this, tr("Client"),
tr("The host was not found. Please check the "
"host name and port settings."));
break;
case QAbstractSocket::ConnectionRefusedError:
QMessageBox::information(this, tr("Client"),
tr("The connection was refused by the peer. "
"Make sure the fortune server is running, "
"and check that the host name and port "
"settings are correct."));
break;
default:
QMessageBox::information(this, tr("Client"),
tr("The following error occurred: %1.")
.arg(tcpSocket->errorString()));
}
}
void Client::reloadMenu(){
if(cLayout.compare("Move") == 0){
delete userLabel;
delete userLineEdit;
delete statusLabel;
delete browseButton;
delete menuButton;
delete moveFilesButton;
delete cancelButton;
delete buttonBox;
statusLabel = new QLabel();
userLabel = new QLabel("Move Files");
passLabel = new QLabel("Locate Files");
moveButton = new QPushButton("Move");
locateButton = new QPushButton("Locate");
cancelButton = new QPushButton("Cancel");
mainLayout->addWidget(statusLabel, 0, 4, 1, 1);
mainLayout->addWidget(userLabel, 1, 4, 1, 1);
mainLayout->addWidget(moveButton, 2, 4, 1, 1);
mainLayout->addWidget(passLabel, 3, 4, 1, 1);
mainLayout->addWidget(locateButton, 4, 4, 1, 1);
mainLayout->addWidget(cancelButton, 5, 4, 1, 1);
setLayout(mainLayout);
connect(cancelButton, SIGNAL(clicked()), this, SLOT(close()));
connect(moveButton, SIGNAL(clicked()), this, SLOT(createMoveLayout()));
connect(locateButton, SIGNAL(clicked()), this, SLOT(createLocateLayout()));
}
else if (cLayout.compare("Locate") == 0){
delete userLineEdit;
delete searchButton;
delete userLabel;
delete resultList;
delete statusLabel;
delete menuButton;
delete openButton;
delete cancelButton;
delete buttonBox;
statusLabel = new QLabel();
userLabel = new QLabel("Move Files");
passLabel = new QLabel("Locate Files");
moveButton = new QPushButton("Move");
locateButton = new QPushButton("Locate");
cancelButton = new QPushButton("Cancel");
mainLayout->addWidget(statusLabel, 0, 4, 1, 1);
mainLayout->addWidget(userLabel, 1, 4, 1, 1);
mainLayout->addWidget(moveButton, 2, 4, 1, 1);
mainLayout->addWidget(passLabel, 3, 4, 1, 1);
mainLayout->addWidget(locateButton, 4, 4, 1, 1);
mainLayout->addWidget(cancelButton, 5, 4, 1, 1);
setLayout(mainLayout);
connect(cancelButton, SIGNAL(clicked()), this, SLOT(close()));
connect(moveButton, SIGNAL(clicked()), this, SLOT(createMoveLayout()));
connect(locateButton, SIGNAL(clicked()), this, SLOT(createLocateLayout()));
}
}
void Client::printStatus(){
printf("You are connected again\n");
//statusLabel->setText("You are connected");
}
void Client::createMenuLayout(){
delete userLabel;
delete userLineEdit;
delete passLabel;
delete passLineEdit;
delete statusLabel;
delete registerButton;
delete loginButton;
delete cancelButton;
delete buttonBox;
statusLabel = new QLabel(message);
userLabel = new QLabel("Move Files");
passLabel = new QLabel("Locate Files");
moveButton = new QPushButton("Move");
locateButton = new QPushButton("Locate");
cancelButton = new QPushButton("Cancel");
mainLayout->addWidget(statusLabel, 0, 4, 1, 1);
mainLayout->addWidget(userLabel, 1, 4, 1, 1);
mainLayout->addWidget(moveButton, 2, 4, 1, 1);
mainLayout->addWidget(passLabel, 3, 4, 1, 1);
mainLayout->addWidget(locateButton, 4, 4, 1, 1);
mainLayout->addWidget(cancelButton, 5, 4, 1, 1);
setLayout(mainLayout);
connect(cancelButton, SIGNAL(clicked()), this, SLOT(close()));
connect(moveButton, SIGNAL(clicked()), this, SLOT(createMoveLayout()));
connect(locateButton, SIGNAL(clicked()), this, SLOT(createLocateLayout()));
}
void Client::createMoveLayout(){
delete statusLabel;
delete userLabel;
delete moveButton;
delete passLabel;
delete locateButton;
delete cancelButton;
disconnect(tcpSocket, SIGNAL(connected()), this, SLOT(sendLoginInfo()));
if(cLayout.compare("Locate") == 0){
disconnect(tcpSocket, SIGNAL(connected()), this, SLOT(sendSearchInfo()));
}
userLabel = new QLabel("File to move:");
userLineEdit = new QLineEdit();
browseButton = new QPushButton("Browse");
statusLabel = new QLabel();
menuButton = new QPushButton("Menu");
moveFilesButton = new QPushButton("Move Files");
cancelButton = new QPushButton("Cancel");
buttonBox = new QDialogButtonBox;
buttonBox->addButton(menuButton, QDialogButtonBox::ActionRole);
buttonBox->addButton(moveFilesButton, QDialogButtonBox::ActionRole);
buttonBox->addButton(cancelButton, QDialogButtonBox::RejectRole);
mainLayout->addWidget(userLabel, 0, 0, 1, 1);
mainLayout->addWidget(userLineEdit, 1, 0, 1, 4);
mainLayout->addWidget(browseButton, 1, 4, 1, 1);
mainLayout->addWidget(statusLabel, 2, 1, 1, 4);
mainLayout->addWidget(buttonBox, 3, 1, 1, 3);
setLayout(mainLayout);
connect(cancelButton, SIGNAL(clicked()), this, SLOT(close()));
connect(moveFilesButton, SIGNAL(clicked()), this, SLOT(requestNewConnection()));
connect(menuButton, SIGNAL(clicked()), this, SLOT(reloadMenu()));
connect(browseButton, SIGNAL(clicked()), this, SLOT(browseForFile()));
connect(tcpSocket, SIGNAL(connected()), this, SLOT(sendFile()));
cLayout = "Move";
}
void Client::createLocateLayout(){
delete statusLabel;
delete userLabel;
delete moveButton;
delete passLabel;
delete locateButton;
delete cancelButton;
disconnect(tcpSocket, SIGNAL(connected()), this, SLOT(sendLoginInfo()));
if(cLayout.compare("Move") == 0){
disconnect(tcpSocket, SIGNAL(connected()), this, SLOT(sendFile()));
}
userLineEdit = new QLineEdit();
searchButton = new QPushButton("Search");
userLabel = new QLabel("Results");
resultList = new QListWidget();
statusLabel = new QLabel();
menuButton = new QPushButton("Menu");
openButton = new QPushButton("Open");
cancelButton = new QPushButton("Cancel");
buttonBox = new QDialogButtonBox;
buttonBox->addButton(menuButton, QDialogButtonBox::ActionRole);
buttonBox->addButton(openButton, QDialogButtonBox::ActionRole);
buttonBox->addButton(cancelButton, QDialogButtonBox::RejectRole);
mainLayout->addWidget(userLineEdit, 0, 0, 1, 3);
mainLayout->addWidget(searchButton, 0, 3, 1, 1);
mainLayout->addWidget(userLabel, 1, 0, 1, 1);
mainLayout->addWidget(resultList, 2, 0, 3, 3);
mainLayout->addWidget(statusLabel, 5, 1, 1, 3);
mainLayout->addWidget(buttonBox, 6, 1, 1, 3);
setLayout(mainLayout);
connect(searchButton, SIGNAL(clicked()), this, SLOT(requestNewConnection()));
connect(cancelButton, SIGNAL(clicked()), this, SLOT(close()));
connect(menuButton, SIGNAL(clicked()), this, SLOT(reloadMenu()));
connect(tcpSocket, SIGNAL(connected()), this, SLOT(sendSearchInfo()));
cLayout = "Locate";
}
<file_sep>/client/ui_registerdialog.h
/********************************************************************************
** Form generated from reading UI file 'registerdialog.ui'
**
** Created: Thu Dec 9 22:13:11 2010
** by: Qt User Interface Compiler version 4.7.0
**
** WARNING! All changes made in this file will be lost when recompiling UI file!
********************************************************************************/
#ifndef UI_REGISTERDIALOG_H
#define UI_REGISTERDIALOG_H
#include <QtCore/QVariant>
#include <QtGui/QAction>
#include <QtGui/QApplication>
#include <QtGui/QButtonGroup>
#include <QtGui/QDialog>
#include <QtGui/QHeaderView>
#include <QtGui/QLabel>
#include <QtGui/QLineEdit>
#include <QtGui/QPushButton>
QT_BEGIN_NAMESPACE
class Ui_RegisterDialogClass
{
public:
QPushButton *okButton;
QPushButton *cancelButton;
QLabel *nameLabel;
QLabel *passLabel;
QLineEdit *nameEdit;
QLineEdit *passEdit;
QLabel *statusLabel;
void setupUi(QDialog *RegisterDialogClass)
{
if (RegisterDialogClass->objectName().isEmpty())
RegisterDialogClass->setObjectName(QString::fromUtf8("RegisterDialogClass"));
RegisterDialogClass->resize(341, 206);
okButton = new QPushButton(RegisterDialogClass);
okButton->setObjectName(QString::fromUtf8("registerButton"));
okButton->setGeometry(QRect(120, 170, 75, 23));
cancelButton = new QPushButton(RegisterDialogClass);
cancelButton->setObjectName(QString::fromUtf8("cancelButton"));
cancelButton->setGeometry(QRect(210, 170, 75, 23));
nameLabel = new QLabel(RegisterDialogClass);
nameLabel->setObjectName(QString::fromUtf8("nameLabel"));
nameLabel->setGeometry(QRect(50, 10, 81, 16));
passLabel = new QLabel(RegisterDialogClass);
passLabel->setObjectName(QString::fromUtf8("passLabel"));
passLabel->setGeometry(QRect(50, 60, 81, 16));
nameEdit = new QLineEdit(RegisterDialogClass);
nameEdit->setObjectName(QString::fromUtf8("nameEdit"));
nameEdit->setGeometry(QRect(50, 30, 231, 20));
passEdit = new QLineEdit(RegisterDialogClass);
passEdit->setObjectName(QString::fromUtf8("passEdit"));
passEdit->setGeometry(QRect(50, 80, 231, 20));
statusLabel = new QLabel(RegisterDialogClass);
statusLabel->setObjectName(QString::fromUtf8("statusLabel"));
statusLabel->setGeometry(QRect(30, 110, 281, 41));
retranslateUi(RegisterDialogClass);
QMetaObject::connectSlotsByName(RegisterDialogClass);
} // setupUi
void retranslateUi(QDialog *RegisterDialogClass)
{
RegisterDialogClass->setWindowTitle(QApplication::translate("RegisterDialogClass", "Register", 0, QApplication::UnicodeUTF8));
okButton->setText(QApplication::translate("RegisterDialogClass", "Register", 0, QApplication::UnicodeUTF8));
cancelButton->setText(QApplication::translate("RegisterDialogClass", "Cancel", 0, QApplication::UnicodeUTF8));
nameLabel->setText(QApplication::translate("RegisterDialogClass", "New Username:", 0, QApplication::UnicodeUTF8));
passLabel->setText(QApplication::translate("RegisterDialogClass", "New Password:", 0, QApplication::UnicodeUTF8));
statusLabel->setText(QString());
} // retranslateUi
};
namespace Ui {
class RegisterDialogClass: public Ui_RegisterDialogClass {};
} // namespace Ui
QT_END_NAMESPACE
#endif // UI_REGISTERDIALOG_H
<file_sep>/server/serverthread.cpp
/*
* serverthread.cpp
*
* Created on: Dec 5, 2010
* Author: Yogi
*/
#include "serverthread.h"
#include "clientsocket.h"
ServerThread::ServerThread(QObject *parent, int socketDescriptor)
: QThread(parent), socketDescriptor(socketDescriptor)
{
}
void ServerThread::run(){
ClientSocket *socket = new ClientSocket(this);
socket->setSocketDescriptor(socketDescriptor);
this->exec();
this->exit(0);
}
<file_sep>/server/serverthread.h
/*
* serverthread.h
*
* Created on: Dec 5, 2010
* Author: Yogi
*/
#ifndef SERVERTHREAD_H_
#define SERVERTHREAD_H_
#include <QThread>
class ServerThread : public QThread{
Q_OBJECT
public:
ServerThread(QObject *parent, int socketDescriptor);
void run();
private:
int socketDescriptor;
};
#endif /* SERVERTHREAD_H_ */
<file_sep>/server/main.cpp
#include "threadedcstserver.h"
#include <QtGui>
#include <QApplication>
#include <QtNetwork>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
ThreadedCSTServer w;
if(!w.listen(QHostAddress::Any, 49209)){
printf("Failed to bind to port");
return 1;
}
QPushButton quitButton(QObject::tr("Quit"));
quitButton.setWindowTitle(QObject::tr("TServer"));
QObject::connect(&quitButton, SIGNAL(clicked()), &a, SLOT(quit()));
quitButton.show();
return a.exec();
}
<file_sep>/server/threadedcstserver.cpp
#include "threadedcstserver.h"
#include "clientsocket.h"
#include "serverthread.h"
ThreadedCSTServer::ThreadedCSTServer(QObject *parent)
: QTcpServer(parent)
{
}
void ThreadedCSTServer::incomingConnection(int socketId){
//ClientSocket *socket = new ClientSocket(this);
//socket->setSocketDescriptor(socketId);
ServerThread *thread = new ServerThread(this, socketId);
connect(thread, SIGNAL(finished()), thread, SLOT(deleteLater()));
thread->start();
}
| 22597c5c10f1988b089daab011ba33e231fc7bd2 | [
"C++"
] | 15 | C++ | tidatida/Threaded-Client-Server-Application | 6614dfd92ddfcc29cc021933b684c604f6486eac | 7721cd823d3d452e9e66fb904aed7af2403ec42d |
refs/heads/main | <repo_name>oguzturkaslan/mindBehindCase<file_sep>/src/test/java/com/mindBehindCase/mindBehindCase/business/concretes/APIManagerTest.java
package com.mindBehindCase.mindBehindCase.business.concretes;
import com.mindBehindCase.mindBehindCase.core.utilities.results.Result;
import com.mindBehindCase.mindBehindCase.core.utilities.results.SuccessResult;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
/**
*
* @author oguz_
*/
public class APIManagerTest {
@Test
public void testGetComments() {
System.out.println("getComments");
APIManager instance = new APIManager();
Result expResult = new SuccessResult(true);
Result result = instance.getComments();
assertEquals(expResult, result);
fail("The test case is a prototype.");
}
/**
* Test of requestHTTP method, of class APIManager.
*/
@Test
public void testRequestHTTP() {
System.out.println("requestHTTP");
APIManager instance = new APIManager();
Result expResult = null;
Result result = instance.requestHTTP();
assertEquals(expResult, result);
fail("The test case is a prototype.");
}
}
<file_sep>/src/main/java/com/mindBehindCase/mindBehindCase/core/utilities/results/Result.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.mindBehindCase.mindBehindCase.core.utilities.results;
/**
*
* @author oguz.turkaslan
*/
public class Result<T> {
private T data;
private boolean success;
private int errorCode;
private String message;
public Result(boolean success, int errorCode, String message) {
this.success = success;
this.errorCode = errorCode;
this.message = message;
}
public Result(boolean success) {
this.success = success;
}
public Result(T data, int errorCode, String message) {
this.data = data;
this.errorCode = errorCode;
this.message = message;
}
public Result() {
}
public boolean isSuccess() {
return success;
}
public void setSuccess(boolean success) {
this.success = success;
}
public int getErrorCode() {
return errorCode;
}
public void setErrorCode(int errorCode) {
this.errorCode = errorCode;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public T getData() {
return data;
}
public void setData(T data) {
this.data = data;
}
}
<file_sep>/src/main/java/com/mindBehindCase/mindBehindCase/business/concretes/CommentsManager.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.mindBehindCase.mindBehindCase.business.concretes;
import com.mindBehindCase.mindBehindCase.business.abstracts.APIService;
import com.mindBehindCase.mindBehindCase.business.abstracts.CommentsService;
import com.mindBehindCase.mindBehindCase.core.utilities.results.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
/**
*
* @author oguz.turkaslan
*/
@Service
public class CommentsManager implements CommentsService {
private APIService apiService;
@Autowired
public CommentsManager(APIService apiService) {
this.apiService = apiService;
}
@Override
public Result getComments() {
return (Result) apiService.getComments();
}
}
<file_sep>/src/main/java/com/mindBehindCase/mindBehindCase/core/utilities/results/SuccessResult.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.mindBehindCase.mindBehindCase.core.utilities.results;
/**
*
* @author oguz.turkaslan
*/
public class SuccessResult extends Result {
public SuccessResult(boolean success) {
super(success, 200, "Yorumlar Listelenip output.txt Dosyasına yazıldı.");
}
}
<file_sep>/src/main/java/com/mindBehindCase/mindBehindCase/model/Comments.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.mindBehindCase.mindBehindCase.model;
import lombok.Data;
/**
*
* @author oguz.turkaslan
*/
@Data
public class Comments {
private int id;
private String body;
private int postId;
}
<file_sep>/src/main/java/com/mindBehindCase/mindBehindCase/business/concretes/APIManager.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.mindBehindCase.mindBehindCase.business.concretes;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.mindBehindCase.mindBehindCase.business.abstracts.APIService;
import com.mindBehindCase.mindBehindCase.core.utilities.results.ErrorResult;
import com.mindBehindCase.mindBehindCase.core.utilities.results.Result;
import com.mindBehindCase.mindBehindCase.core.utilities.results.SuccessResult;
import com.mindBehindCase.mindBehindCase.model.Comments;
import java.io.BufferedReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.springframework.stereotype.Service;
/**
*
* @author oguz.turkaslan
*/
@Service
public class APIManager implements APIService {
@Override
public Result getComments() {
List<Comments> commentsList = new ArrayList<>();
Gson gson = new Gson();
Result requestAPI = requestHTTP();
if (requestAPI.getData().equals("error")) {
return new ErrorResult(false, requestAPI.getErrorCode(), requestAPI.getMessage());
} else if (requestAPI.getErrorCode() > HttpURLConnection.HTTP_OK) {
return new ErrorResult(false, requestAPI.getErrorCode(), requestAPI.getMessage());
} else {
String commentsJson = (String) requestAPI.getData();
commentsList = gson.fromJson(commentsJson, new TypeToken<List<Comments>>() {
}.getType());
FileWriter writer;
try {
writer = new FileWriter("output.txt");
for (Comments comment : commentsList) {
writer.write(comment.getId() + ":" + comment.getBody() + ", ");
}
writer.close();
} catch (IOException ex) {
Logger.getLogger(APIManager.class.getName()).log(Level.SEVERE, null, ex);
}
return new SuccessResult(true);
}
}
public Result requestHTTP() {
URL url;
HttpURLConnection con = null;
StringBuilder sb = null;
InputStream is;
BufferedReader br;
Result result = null;
try {
url = new URL("https://my-json-server.typicode.com/typicode/demo/comments");
con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("GET");
con.setDoOutput(true);
sb = new StringBuilder();
String line;
if (con.getResponseCode() < HttpURLConnection.HTTP_BAD_REQUEST) {
is = con.getInputStream();
br = new BufferedReader(new InputStreamReader(is));
while ((line = br.readLine()) != null) {
sb.append(line);
}
result = new Result(sb.toString(), con.getResponseCode(), con.getResponseMessage());
br.close();
} else {
is = con.getErrorStream();
br = new BufferedReader(new InputStreamReader(is));
sb.append("{")
.append("\"errorCode\"" + ":")
.append(con.getResponseCode())
.append(",")
.append("\"message\"" + ":")
.append("\"" + con.getResponseMessage() + "\"")
.append("}");
result = new Result(sb.toString(), con.getResponseCode(), con.getResponseMessage());
}
} catch (IOException ex) {
result = new Result("error", 0, "Connection Error");
Logger.getLogger(APIManager.class.getName()).log(Level.SEVERE, null, ex);
}
return result;
}
}
| 3f34984988ab57fe30bcde8a0c204dcf7fb1d705 | [
"Java"
] | 6 | Java | oguzturkaslan/mindBehindCase | ffd1504f1406d4e13bb63f5c4fd733a25544555e | 85cac307a1c8900c88d4bd2ab210453caa79db39 |
refs/heads/master | <repo_name>kobayosi/AudioMiscTest<file_sep>/WinWaveOutTest.c
#include "stdafx.h"
#include <stdio.h>
#include <windows.h>
#include <mmsystem.h>
#include <stdlib.h>
#include <memory.h>
#include <math.h>
static HWAVEOUT hWaveOut;
static const WORD Channels = 2;
static const DWORD SamplePerSec = 44100;
static const WORD BitsPerSample= 16;
UINT32 openWaveDevice(UINT id)
{
MMRESULT result;
const WORD wftx_nChannels = Channels;
const DWORD wftx_nSamplesPerSec = SamplePerSec;
const WORD wftx_wBitsPerSample = BitsPerSample;
WORD wffx_nBlockAlign = wftx_nChannels * wftx_wBitsPerSample / 8;
WORD wftx_nAvgBytesPerSec= wftx_nSamplesPerSec * wffx_nBlockAlign;
const WORD wftx_cbSize = 0;
WAVEFORMATEX wftx/*={
.wFormatTag = WAVE_FORMAT_PCM,
.nChannels = wftx_nChannels,
.nSamplesPerSec = wftx_nSamplesPerSec,
.nAvgBytesPerSec= wftx_nAvgBytesPerSec ,
.nBlockAlign = wffx_nBlockAlign;
.wBitsPerSample =wftx_wBitsPerSample;
.cbSize = wftx_cbSize;
}*/;
wftx.wFormatTag = WAVE_FORMAT_PCM;
wftx.nChannels = wftx_nChannels;
wftx.nSamplesPerSec = wftx_nSamplesPerSec;
wftx.nAvgBytesPerSec= wftx_nAvgBytesPerSec;
wftx.nBlockAlign = wffx_nBlockAlign;
wftx.wBitsPerSample =wftx_wBitsPerSample;
wftx.cbSize = wftx_cbSize;
//waveOutOpen(&hWaveOut,id,&wftx,NULL,NULL,CALLBACK_NULL);
if(MMSYSERR_NOERROR != (result = waveOutOpen(&hWaveOut,id,&wftx,NULL,NULL,CALLBACK_NULL)))
{
printf_s("OpenFailed! ErrorCode:%x",result);
return 1;
}
return -1;
}
static UINT16 *pWave = NULL;
static UINT waveBufferLength = 0;
static UINT waveLengthSecond = 5;
static void generateWave(UINT index)
{
UINT i;
UINT buffersize;
pWave = malloc((sizeof(UINT16) * (buffersize = Channels * SamplePerSec * waveLengthSecond)));
waveBufferLength = Channels * SamplePerSec * waveLengthSecond;
/* if(index == 0) */
{
for(i = 0 ; i < buffersize/2 ; i++)
{
*(pWave + i*2 ) = sin((double)i * 2000/ 44100) * 0x7FFF;
*(pWave + i*2 + 1) = rand();
}
}
}
static void disposeWave(void)
{
if(pWave)
free(pWave);
pWave = NULL;
waveBufferLength = 0;
}
void playWaveSingleTime()
{
WAVEHDR whdr;
MMRESULT result;
whdr.lpData = pWave;
whdr.dwBufferLength = waveBufferLength;
whdr.dwFlags = WHDR_BEGINLOOP | WHDR_ENDLOOP;
whdr.dwLoops=1;
result = waveOutPrepareHeader(hWaveOut,&whdr,sizeof(WAVEHDR));
if(MMSYSERR_NOERROR !=result)
{
printf_s("Error:waveOutPrepareHeader! ErrorCode:%x",result);
goto freeandend;
}
result = waveOutWrite(hWaveOut,&whdr,sizeof(WAVEHDR));
if(MMSYSERR_NOERROR !=result)
{
printf_s("Error:waveOutWrite! ErrorCode:%x",result);
goto freeandend;
}
Sleep(waveLengthSecond*500);
freeandend:
result = waveOutReset(hWaveOut);
if(MMSYSERR_NOERROR !=result)
{
printf_s("Error:waveOutReset! ErrorCode:%x",result);
}
result = waveOutUnprepareHeader(hWaveOut,&whdr,sizeof(WAVEHDR));
if(MMSYSERR_NOERROR !=result)
{
printf_s("Error:waveOutUnprepareHeader! ErrorCode:%x",result);
}
free(pWave);
pWave = NULL;
}
void closeWaveDevice()
{
waveOutReset(hWaveOut);
waveOutClose(hWaveOut);
}
void showWaveDeviceCaps()
{
UINT numDevs;
int i;
WAVEOUTCAPS cap;
numDevs = waveOutGetNumDevs();
printf_s("NumDevs:%d\n",numDevs);
for(i=0 ; i < numDevs ; i++)
{
waveOutGetDevCaps(i,&cap,sizeof(cap));
printf_s("id:%d,Mid:%d,wPid:%d,DriverVersion:%x,ProductName:%s,Formats:%x,Channels:%d,dwSupport:%x\n"
,i
,cap.wMid,cap.wPid
,cap.vDriverVersion
,cap.szPname
,cap.dwFormats
,cap.wChannels
,cap.dwSupport);
}
}
void main()
{
showWaveDeviceCaps();
generateWave(0);
openWaveDevice(0);
playWaveSingleTime();
disposeWave();
closeWaveDevice();
return;
}<file_sep>/WinWaveOutTest2.c
#include "stdafx.h"
#include <stdio.h>
#include <windows.h>
#include <mmsystem.h>
#include <stdlib.h>
#include <memory.h>
#include <math.h>
static HWAVEOUT hWaveOut;
static const WORD Channels = 2;
static const DWORD SamplePerSec = 44100;
static const WORD BitsPerSample= 16;
static int playCount = 5;
static int waveSel = 1;
static WAVEHDR whdr,whdr2;
enum {
WAVE_IDLE,
WAVE_PLAYING
} wavePlayStatus = WAVE_IDLE;
static VOID CALLBACK waveCallbackProc(HWAVEOUT hwo,
UINT uMsg, DWORD dwInstance, DWORD dwParam1, DWORD dwParam2)
{
switch(uMsg)
{
case MM_WOM_OPEN:
wavePlayStatus = WAVE_PLAYING;
break;
case MM_WOM_DONE:
if(playCount > 0)
{
if(waveSel == 1)
{
waveSel = 0;
waveOutWrite(hWaveOut,&whdr,sizeof(WAVEHDR));
}
else
{
waveSel = 1;
waveOutWrite(hWaveOut,&whdr2,sizeof(WAVEHDR));
}
playCount--;
}
else
{
wavePlayStatus = WAVE_IDLE;
}
break;
default:
break;
}
return 0; //DefWindowProc(hwnd, uMsg, wParam, lParam);
}
UINT32 openWaveDevice(UINT id)
{
MMRESULT result;
const WORD wftx_nChannels = Channels;
const DWORD wftx_nSamplesPerSec = SamplePerSec;
const WORD wftx_wBitsPerSample = BitsPerSample;
WORD wffx_nBlockAlign = wftx_nChannels * wftx_wBitsPerSample / 8;
WORD wftx_nAvgBytesPerSec= wftx_nSamplesPerSec * wffx_nBlockAlign;
const WORD wftx_cbSize = 0;
WAVEFORMATEX wftx/*={
.wFormatTag = WAVE_FORMAT_PCM,
.nChannels = wftx_nChannels,
.nSamplesPerSec = wftx_nSamplesPerSec,
.nAvgBytesPerSec= wftx_nAvgBytesPerSec ,
.nBlockAlign = wffx_nBlockAlign;
.wBitsPerSample =wftx_wBitsPerSample;
.cbSize = wftx_cbSize;
}*/;
wftx.wFormatTag = WAVE_FORMAT_PCM;
wftx.nChannels = wftx_nChannels;
wftx.nSamplesPerSec = wftx_nSamplesPerSec;
wftx.nAvgBytesPerSec= wftx_nAvgBytesPerSec;
wftx.nBlockAlign = wffx_nBlockAlign;
wftx.wBitsPerSample =wftx_wBitsPerSample;
wftx.cbSize = wftx_cbSize;
//waveOutOpen(&hWaveOut,id,&wftx,NULL,NULL,CALLBACK_NULL);
if(MMSYSERR_NOERROR != (result = waveOutOpen(&hWaveOut,id,&wftx,(DWORD)waveCallbackProc/*NULL*/,NULL,CALLBACK_FUNCTION)))
{
printf_s("OpenFailed! ErrorCode:%x",result);
return 1;
}
return -1;
}
static UINT16 *pWave = NULL;
static UINT waveBufferLength = 0;
static UINT waveLengthSecond = 1;
static void generateWave(UINT index)
{
UINT i;
UINT buffersize;
pWave = malloc((sizeof(UINT16) * (buffersize = Channels * SamplePerSec * waveLengthSecond)));
waveBufferLength = Channels * SamplePerSec * waveLengthSecond;
/* if(index == 0) */
{
for(i = 0 ; i < buffersize/2 ; i++)
{
*(pWave + i*2 ) = sin((double)i * 2000/ 44100) * 0x7FFF;
*(pWave + i*2 + 1) = rand();
}
}
}
static UINT16 *pWave2 = NULL;
static UINT waveBufferLength2 = 0;
static UINT waveLengthSecond2 = 1;
static void generate2ndWave(UINT index)
{
UINT i;
UINT buffersize;
pWave2 = malloc((sizeof(UINT16) * (buffersize = Channels * SamplePerSec * waveLengthSecond)));
waveBufferLength2 = Channels * SamplePerSec * waveLengthSecond2;
/* if(index == 0) */
{
for(i = 0 ; i < buffersize/2 ; i++)
{
*(pWave2 + i*2 ) = rand();
*(pWave2 + i*2 + 1 ) = sin((double)i * 1000/ 44100) * 0x7FFF;
}
}
}
static void disposeWave(void)
{
waveOutUnprepareHeader(hWaveOut,&whdr,sizeof(WAVEHDR));
if(pWave)
free(pWave);
pWave = NULL;
waveBufferLength = 0;
}
static void dispose2ndWave(void)
{
waveOutUnprepareHeader(hWaveOut,&whdr2,sizeof(WAVEHDR));
if(pWave2)
free(pWave2);
pWave2 = NULL;
waveBufferLength2 = 0;
}
void playWaveSingleTime()
{
MMRESULT result;
whdr.lpData = pWave;
whdr.dwBufferLength = waveBufferLength;
whdr.dwFlags = WHDR_BEGINLOOP | WHDR_ENDLOOP;
whdr.dwLoops=1;
result = waveOutPrepareHeader(hWaveOut,&whdr,sizeof(WAVEHDR));
if(MMSYSERR_NOERROR !=result)
{
printf_s("Error:waveOutPrepareHeader! ErrorCode:%x",result);
//goto freeandend;
}
whdr2.lpData = pWave2;
whdr2.dwBufferLength = waveBufferLength2;
whdr2.dwFlags = WHDR_BEGINLOOP | WHDR_ENDLOOP;
whdr2.dwLoops=1;
result = waveOutPrepareHeader(hWaveOut,&whdr2,sizeof(WAVEHDR));
if(MMSYSERR_NOERROR !=result)
{
printf_s("Error:waveOutPrepareHeader! ErrorCode:%x",result);
//goto freeandend;
}
result = waveOutWrite(hWaveOut,&whdr,sizeof(WAVEHDR));
if(MMSYSERR_NOERROR !=result)
{
printf_s("Error:waveOutWrite! ErrorCode:%x",result);
//goto freeandend;
}
result = waveOutWrite(hWaveOut,&whdr2,sizeof(WAVEHDR));
if(MMSYSERR_NOERROR !=result)
{
printf_s("Error:waveOutWrite! ErrorCode:%x",result);
//goto freeandend;
}
//Sleep(waveLengthSecond*1000);
#if 0
freeandend:
result = waveOutReset(hWaveOut);
if(MMSYSERR_NOERROR !=result)
{
printf_s("Error:waveOutReset! ErrorCode:%x",result);
}
result = waveOutUnprepareHeader(hWaveOut,&whdr,sizeof(WAVEHDR));
if(MMSYSERR_NOERROR !=result)
{
printf_s("Error:waveOutUnprepareHeader! ErrorCode:%x",result);
}
free(pWave);
pWave = NULL;
#endif /* 0 */
}
void closeWaveDevice()
{
//waveOutReset(hWaveOut);
waveOutClose(hWaveOut);
}
void showWaveDeviceCaps()
{
UINT numDevs;
int i;
WAVEOUTCAPS cap;
numDevs = waveOutGetNumDevs();
printf_s("NumDevs:%d\n",numDevs);
for(i=0 ; i < numDevs ; i++)
{
waveOutGetDevCaps(i,&cap,sizeof(cap));
printf_s("id:%d,Mid:%d,wPid:%d,DriverVersion:%x,ProductName:%s,Formats:%x,Channels:%d,dwSupport:%x\n"
,i
,cap.wMid,cap.wPid
,cap.vDriverVersion
,cap.szPname
,cap.dwFormats
,cap.wChannels
,cap.dwSupport);
}
}
void waitForWaveOutCompletion()
{
while(wavePlayStatus == WAVE_PLAYING)
Sleep(100);
}
void main()
{
showWaveDeviceCaps();
generateWave(0);
generate2ndWave(0);
openWaveDevice(0);
playWaveSingleTime();
Sleep(500);
waitForWaveOutCompletion();
closeWaveDevice();
disposeWave();
dispose2ndWave();
return;
} | 89afc7d1961c9219ce46baef454dc61660944994 | [
"C"
] | 2 | C | kobayosi/AudioMiscTest | 131c30bfb2628704a32e89afdc7463f6d2931307 | ea21074140b0ea4f076050a499690f0c060a57c4 |
refs/heads/master | <repo_name>GuyHadas/BillboardTopTen<file_sep>/frontend/components/title.jsx
import React from 'react';
import ReactDOM from 'react-dom';
class Title extends React.Component{
constructor(props){
super(props);
this.state = {
genres: {
hot100: 'Hot 100',
alternative: 'Alternative',
hiphop: 'Hip Hop',
country: 'Country',
rap: 'Rap',
electric: 'Electric'
}
};
this.formatGenre = this.formatGenre.bind(this);
}
trimArtist(artist) {
return artist.indexOf('Featuring') === -1 ? artist : artist.substring(0, artist.indexOf(' Featuring'));
}
formatGenre(genre) {
return this.state.genres[genre];
}
render() {
let sound = this.props.isSoundOn ? <i className="fa fa-volume-up"/> : <i className="fa fa-volume-off"/>;
return (
<div id='titleBox'>
<div id="navLogo">
<img id="billboard-logo" src="billboard-logo.png" width='100'/>
<span id="genre-title">{this.formatGenre(this.props.genre)}</span>
</div>
<div id='navHeader'>
<span id='titleArtist'>{this.trimArtist(this.props.artist)}</span>
<span>was #1 on</span>
<span id='titleDate'>{this.props.date}</span>
</div>
<div onClick={this.props.toggleSound}
className='toggle-sound'>
{sound}
</div>
</div>
);
}
}
export default Title;
<file_sep>/frontend/components/genre.jsx
import React from 'react';
import ReactDOM from 'react-dom';
class Genres extends React.Component{
constructor(props){
super(props);
}
render() {
let genreList;
if (this.props.isLoadingGenres) {
genreList = <img id='loader' src='loader.gif'/>;
} else {
genreList = [
<div className='genre' id='hot100Genre' onClick={() => this.props.playGenre('hot100')}></div>,
<div className='genre' id='alternativeGenre' onClick={() => this.props.playGenre('alternative')}></div>,
<div className='genre' id='hiphopGenre' onClick={() => this.props.playGenre('hiphop')}></div>,
<div className='genre' id='countryGenre' onClick={() => this.props.playGenre('country')}></div>,
<div className='genre' id='rapGenre' onClick={() => this.props.playGenre('rap')}></div>,
<div className='genre' id='electricGenre' onClick={() => this.props.playGenre('electric')}></div>
];
}
return (
<div id='genres'>
{genreList}
</div>
);
}
}
export default Genres;
<file_sep>/frontend/components/graph.jsx
import React from 'react';
import ReactDOM from 'react-dom';
import _ from 'lodash';
import Track from './track.jsx';
class Graph extends React.Component{
constructor(props){
super(props);
}
render() {
const stagingAreaRank = 11;
const currentTracks = _.map(this.props.chart, 'title'); // title must act as primary key
const nextChartTracks = _.map(this.props.nextChart, 'title'); // title must act as primary key
const trackComponents = _.map(this.props.chart, track => {
let nextTrackRank = nextChartTracks.indexOf(track.title) + 1; // index 0 should be rank 1, etc...
if (nextTrackRank === 0) {
nextTrackRank = stagingAreaRank; // if track is not in next week's charts, animate to bottom of list
}
let albumImage = this.props.albumImages[`${track.artist}/${track.title}`];
albumImage = albumImage ? albumImage : 'http://24.media.tumblr.com/tumblr_m3j315A5l31r6luwpo1_500.png';
return <Track key={track.title} track={track} nextTrackRank={nextTrackRank} albumImage={albumImage} getColorForTitle={this.props.getColorForTitle}/>;
});
let tracksOnDeck = _.filter(this.props.nextChart, trackOnDeck => {
return !(_.includes(currentTracks, trackOnDeck.title));
});
const trackOnDeckComponents = tracksOnDeck.map(trackOnDeck => {
// renders the track to the staging area at the bottom of the list
const dummyTrack = {
title: trackOnDeck.title,
rank: stagingAreaRank
};
let albumImage = this.props.albumImages[`${trackOnDeck.artist}/${trackOnDeck.title}`];
albumImage = albumImage ? albumImage : 'http://24.media.tumblr.com/tumblr_m3j315A5l31r6luwpo1_500.png';
return <Track key={trackOnDeck.title} track={dummyTrack} nextTrackRank={trackOnDeck.rank} albumImage={albumImage} getColorForTitle={this.props.getColorForTitle}/>;
});
return (
<div id='graph'>
<ul id='trackList'>
{trackComponents}
{trackOnDeckComponents}
</ul>
<div id='stagingArea'/>
</div>
);
}
}
export default Graph;
<file_sep>/public/billboard-script.py
import billboard
from time import sleep
f = open('hot100.txt', 'w')
i = 0
chart = billboard.ChartData('hot-100')
while chart.previousDate:
print chart.date
if len(chart) < 10:
chart = billboard.ChartData('hot-100', chart.previousDate)
f.write("*****")
f.write("\n")
f.write(chart.date)
f.write("\n")
for x in range(0, 10):
f.write(str(chart[x].title))
f.write("\n")
f.write(str(chart[x].artist))
f.write("\n")
f.write(str(chart[x].weeks))
f.write("\n")
f.write(str(chart[x].rank))
f.write("\n")
f.write(str(chart[x].spotifyID))
f.write("\n")
f.write(str(chart[x].spotifyLink))
f.write("\n")
chart = billboard.ChartData('hot-100', chart.previousDate)
f.write("\n")
sleep(2)
i += 1
f.close()
<file_sep>/db/seeds.rb
# cities = City.create([{ name: 'Chicago' }, { name: 'Copenhagen' }])
# Mayor.create(name: 'Emanuel', city: cities.first)
require 'grooveshark'
client = Grooveshark::Client.new
# songs = client.search_songs('Nirvana')
#
# songs.each do |s|
# s.id # Song ID
# s.name # Song name
# s.artist # Song artist name
# s.album # Song album name
# s.duration # Song duration in seconds (not always present, 0 by default)
# end
<file_sep>/frontend/components/datePicker.jsx
import React from 'react';
import ReactDOM from 'react-dom';
import _ from 'lodash';
import moment from 'moment';
import Decade from './decade.jsx';
class DatePicker extends React.Component{
constructor(props){
super(props);
this.getDecades = this.getDecades.bind(this);
this.showYears = this.showYears.bind(this);
this.state = {
decades: this.getDecades(),
decade: null,
tab: null
};
}
getDecades() {
let firstYear = Object.keys(this.props.charts)[Object.keys(this.props.charts).length - 1].slice(0, 4);
let lastYear = Object.keys(this.props.charts)[0].slice(0, 4);
let years = _.range(Number(firstYear), Number(lastYear) + 1);
let decades = {};
_.each(years, year => {
let decade = year.toString().slice(0, 3) + "0's";
if (!decades[decade]) {
decades[decade] = [year];
} else {
decades[decade].push(year);
}
});
return decades;
}
showYears(decade) {
this.setState({ decade: decade });
}
render() {
let decadeComponents = _.map(_.keys(this.state.decades).sort(), decade => {
return <Decade currentDate={this.props.currentDate} key={decade} decade={decade} years={this.state.decades[decade]} dates={_.keys(this.props.charts)} setChartDate={this.props.setChartDate}/>;
});
return (
<div id='datePicker'>
{decadeComponents}
</div>
);
}
}
export default DatePicker;
<file_sep>/Readme.md
# BillboardTopTen
[BillboardTopTen][heroku] is a web application that allows music enthusiasts to explore Billboard's top ten charts throughout history. Inspired by [Billboard charts][Billboard], BillboardTopTen is built using Ruby on Rails on the backend, React.JS on the Front-end, and a PostgreSQL database.

[heroku]: https://billboardtopten.herokuapp.com/
[Billboard]: http://www.billboard.com/charts
## BillboardTopTen Features
* Dynamic visualization of Billboard's top ten charts for every week
* Week's top song playing while charts are displayed
* Smooth music fade in fade out transitions between different charts
* Date Picker for user exploration of top ten charts through history
* Genre Picker for user exploration of different music genres
* Album Images associated with each artist on the chart
## BillboardTopTen Walk-through
### BillboardTopTen Web Scraping and Search APIs
BillboardTopTen depends on web scraping HTML form [Billboard charts][Billboard] to retrieve all of the charts. A Python script using [billboard.py][billboardpy] API for accessing music charts was written to scrape ten songs for each chart. Each song in a chart contained the following fields: title, artist, weeks, rank, spotifyId, and spotifyLink.
[billboardpy]: https://github.com/guoguo12/billboard-charts
#### Sample Web Scraping Script Snippet
```python
import billboard
from time import sleep
f = open('edm.txt', 'w')
i = 0
chart = billboard.ChartData('dance-electronic-songs')
while chart.previousDate:
print chart.date
if len(chart) < 10:
chart = billboard.ChartData('dance-electronic-songs', chart.previousDate)
f.write("*****")
f.write("\n")
f.write(chart.date)
f.write("\n")
for x in range(0, 10):
f.write(str(chart[x].title))
f.write("\n")
f.write(str(chart[x].artist))
f.write("\n")
...
```
Similarly, scraping is done to retrieve track samples from iTunes, and album images for the top songs in each week.
#### Sample iTunes Search API Script Snippet
```ruby
def get_itunes_track(query)
res = HTTP.get("https://itunes.apple.com/search?term=#{query}&country=us&limit=1&media=music")
if res.code == 200
JSON.parse(res)
else
p "GOT 403"
return {"resultCount" => 0}
end
end
def build_query(chart, spotify_id)
begin
track = JSON.parse(HTTP.get("https://api.spotify.com/v1/tracks/#{spotify_id}").to_s)
title = track['name'].gsub(/[^0-9a-zA-Z ]/, "").split(" ").join("+")
artist = track['artists'][0]['name'].gsub(/[^0-9a-zA-Z ]/, "").split(" ").join("+");
rescue
title = chart[0]['title'].gsub(/[^0-9a-zA-Z ]/, "").split(' ').join('+')
artist = chart[0]['artist'].gsub(/[^0-9a-zA-Z ]/, "").split(' ').join('+')
ensure
return [title, artist].join("+");
end
end
trackMeta = {}
charts = JSON.parse(File.read("public/charts/electric/billboard-data.json"))
charts.each do |date, chart|
sleep 2
p date
top_song = chart[0]
query = build_query(chart, top_song['spotify_id'])
response = get_itunes_track(query)
i = 1
until response["resultCount"] != 0 || i == 10
query = build_query(chart, chart[i])
response = get_itunes_track(query)
i += 1
end
if (response["resultCount"] > 0)
itunes_track = response["results"][0]
unless trackMeta[itunes_track['trackId']]
trackMeta[date] = { 'previewUrl' => itunes_track['previewUrl'], 'albumImg' => itunes_track['artworkUrl100'] }
end
end
end
File.write("public/charts/electric/previewUrls.json", JSON.generate(trackMeta))
```
### Data Visualization and Graphing
BillboardTopTen takes advantage of React.JS rapid render library for smooth visualization of Billboard's charts. There are two separate React components in charge of data visualization for BillboardTopTen: Charts component and Graph component.
The first component is the charts component. This component displays a track's progression over time by drawing out distinct lines following a tracks ranking. Using a set velocity, the lines are animated across the screen.
<!--  -->
#### Sample Charts Code Snippet
```javascript
class Chart extends React.Component{
constructor(props){
super(props);
this.state = {
offset: 0
};
}
componentDidMount() {
// This is called 150 times throughout a chart interval
// Line must move 175 pixels every chart interval
const VELOCITY = (175 / 75);
this.offsetInterval = setInterval(() => {
this.setState({ offset: this.state.offset + VELOCITY });
}, 40);
}
...
getLinesForSection(sectionNum, startingChart, endingChart) {
const STAGING_AREA_RANK = 11;
const startingTracks = _.map(startingChart, 'title');
const endingTracks = _.map(endingChart, 'title');
const tracksOnDeck = _.filter(endingChart, trackOnDeck => {
return !(_.includes(startingTracks, trackOnDeck.title));
});
let lines = _.map(startingChart, track => {
let nextTrackRank = endingTracks.indexOf(track.title) + 1; // index 0 should be rank 1, etc...
if (nextTrackRank === 0) {
nextTrackRank = STAGING_AREA_RANK; // if track is not in next week's charts, animate to bottom of list
}
return <Line
offset={this.state.offset}
color={this.props.getColorForTitle(track.title)}
key={`${track.title}sec${sectionNum}rank${track.rank}`}
weekPosition={sectionNum}
y1={this.getPositionForRank(track.rank)}
y2={this.getPositionForRank(nextTrackRank)}/>;
});
const tracksOnDeckLines = tracksOnDeck.map(trackOnDeck => {
return <Line
offset={this.state.offset}
color={this.props.getColorForTitle(trackOnDeck.title)}
key={`${trackOnDeck.title}sec${sectionNum}rank${trackOnDeck.rank}`}
weekPosition={sectionNum}
y1={this.getPositionForRank(STAGING_AREA_RANK)}
y2={this.getPositionForRank(trackOnDeck.rank)}/>;
});
return lines.concat(tracksOnDeckLines);
}
render() {
const sectionZero = this.getLinesForSection(0, this.props.chart, this.props.nextChart);
const sectionOne = this.getLinesForSection(1, this.props.prevChart, this.props.chart);
const sectionTwo = this.getLinesForSection(2, this.props.twoWeeksBackChart, this.props.prevChart);
const sectionThree = this.getLinesForSection(3, this.props.threeWeeksBackChart, this.props.twoWeeksBackChart);
const sectionFour = this.getLinesForSection(4, this.props.fourWeeksBackChart, this.props.threeWeeksBackChart);
return (
<div id="chart-wrap-wrapper">
<div id="chart-wrap">
<ul id="chart-y-axis">
<li>1 —</li>
<li>2 —</li>
<li>3 —</li>
<li>4 —</li>
<li>5 —</li>
<li>6 —</li>
<li>7 —</li>
<li>8 —</li>
<li>9 —</li>
<li>10 —</li>
</ul>
<svg width={700} height={579} style={{ borderBottom: '1px solid white', backgroundColor: 'transparent' }}>
{sectionZero}
{sectionOne}
{sectionTwo}
{sectionThree}
{sectionFour}
</svg>
</div>
<svg width={700} height={50} style={{ backgroundColor: 'rgb(0, 0, 0)', color: 'white', marginLeft: 'auto' }}>
<GraphDate offset={this.state.offset} weekPosition={-1} date={this.props.nextChartDate}/>
<GraphDate offset={this.state.offset} weekPosition={0} date={this.props.currentDate}/>
<GraphDate offset={this.state.offset} weekPosition={1} date={this.props.prevChartDate}/>
<GraphDate offset={this.state.offset} weekPosition={2} date={this.props.twoWeeksBackChartDate}/>
<GraphDate offset={this.state.offset} weekPosition={3} date={this.props.threeWeeksBackChartDate}/>
<GraphDate offset={this.state.offset} weekPosition={4} date={this.props.fourWeeksBackChartDate}/>
</svg>
</div>
);
}
}
```
The second component is the graph component. this component is in charge of rendering ten album images and track names according to their ranking for a given week. Updates in state coupled with CSS transitions will change positions of tracks.
<!--  -->
#### Sample Graph Code Snippet
```javascript
class Graph extends React.Component{
constructor(props){
super(props);
}
render() {
const stagingAreaRank = 11;
const currentTracks = _.map(this.props.chart, 'title'); // title must act as primary key
const nextChartTracks = _.map(this.props.nextChart, 'title'); // title must act as primary key
const trackComponents = _.map(this.props.chart, track => {
let nextTrackRank = nextChartTracks.indexOf(track.title) + 1; // index 0 should be rank 1, etc...
if (nextTrackRank === 0) {
nextTrackRank = stagingAreaRank; // if track is not in next week's charts, animate to bottom of list
}
let albumImage = this.props.albumImages[`${track.artist}/${track.title}`];
albumImage = albumImage ? albumImage : 'http://24.media.tumblr.com/tumblr_m3j315A5l31r6luwpo1_500.png';
return <Track key={track.title} track={track} nextTrackRank={nextTrackRank} albumImage={albumImage} getColorForTitle={this.props.getColorForTitle}/>;
});
let tracksOnDeck = _.filter(this.props.nextChart, trackOnDeck => {
return !(_.includes(currentTracks, trackOnDeck.title));
});
const trackOnDeckComponents = tracksOnDeck.map(trackOnDeck => {
// renders the track to the staging area at the bottom of the list
const dummyTrack = {
title: trackOnDeck.title,
rank: stagingAreaRank
};
let albumImage = this.props.albumImages[`${trackOnDeck.artist}/${trackOnDeck.title}`];
albumImage = albumImage ? albumImage : 'http://24.media.tumblr.com/tumblr_m3j315A5l31r6luwpo1_500.png';
return <Track key={trackOnDeck.title} track={dummyTrack} nextTrackRank={trackOnDeck.rank} albumImage={albumImage} getColorForTitle={this.props.getColorForTitle}/>;
});
return (
<div id='graph'>
<ul id='trackList'>
{trackComponents}
{trackOnDeckComponents}
</ul>
<div id='stagingArea'/>
</div>
);
}
}
```
### Music
BillboardTopTen plays music synchronously with it's visuals. For every week, BillboardTopTen will play the number one ranked track in the background. Through the used of React Sound library, sound component's containing track URL's will play music.
BillboardTopTen makes use of React's rapid state handling to control which component is playing music and at what volume. BillboardTopTen is able to seamless fade in fade out track samples.
#### Sample Music Snippet
```javascript
fadeInFadeOut() {
if (this.isNextSongDifferent()) {
if (this.fadeOutOneFadeInTwoInterval) clearInterval(this.fadeOutOneFadeInTwoInterval);
if (this.fadeOutTwoFadeInOneInterval) clearInterval(this.fadeOutTwoFadeInOneInterval);
if (this.activeSoundComponent === 'one') {
this.fadeOutOneFadeInTwoInterval = setInterval(() => {
this.setState({
volOne: this.state.volOne - 1.5,
volTwo: this.state.volTwo + 1.5
});
}, (1000 / 30));
} else {
this.fadeOutTwoFadeInOneInterval = setInterval(() => {
this.setState({
volOne: this.state.volOne + 1.5,
volTwo: this.state.volTwo - 1.5
});
}, (1000 / 30));
}
}
}
...
componentDidUpdate() {
if ((this.isNextSongDifferent() && !this.areBothPlaying()) && this.state.isSoundOn) {
this.fadeInFadeOut();
let trackURLSoundComponentOne = this.activeSoundComponent === 'one' ? this.state.currentTrackURL : this.state.nextTrackURL;
let trackURLSoundComponentTwo = this.activeSoundComponent === 'one' ? this.state.nextTrackURL : this.state.currentTrackURL;
this.setState({
trackURLSoundComponentOne: trackURLSoundComponentOne,
trackURLSoundComponentTwo: trackURLSoundComponentTwo,
soundComponentOneStatus: Sound.status.PLAYING,
soundComponentTwoStatus: Sound.status.PLAYING
});
}
}
...
```
### Date and Genre Picker
A feature of BillboardTopTen that can keep users engaged for extended periods of time is the ability to explore different music genres and dates for Billboard's charts.
#### Date Picker Code Snippet
```javascript
...
setChartDate(date) {
const trackMetaData = this.state.trackMetaData[this.state.genre];
const charts = this.state.charts[this.state.genre];
this.i = Object.keys(charts).indexOf(date);
if (this.nextDateInterval) clearInterval(this.nextDateInterval);
if (this.fadeOutOneFadeInTwoInterval) clearInterval(this.fadeOutOneFadeInTwoInterval);
if (this.fadeOutTwoFadeInOneInterval) clearInterval(this.fadeOutTwoFadeInOneInterval);
if ( this.i === Object.keys(charts).length - 1) { // Last song was chosen
this.i -= 3;
}
if (this.state.isSoundOn) {
this.setState({
soundComponentOneStatus: this.activeSoundComponent === 'one' ? Sound.status.STOPPED : Sound.status.PLAYING,
soundComponentTwoStatus: this.activeSoundComponent === 'one' ? Sound.status.PLAYING : Sound.status.STOPPED
});
}
let volOne = this.activeSoundComponent === 'one' ? 0 : 100;
let volTwo = this.activeSoundComponent === 'one' ? 100 : 0;
let trackURLSoundComponentOne = this.activeSoundComponent === 'one' ? trackMetaData[this.getDate(charts, this.i + 1)]['previewUrl'] :
trackMetaData[this.getDate(charts, this.i)]['previewUrl'];
let trackURLSoundComponentTwo = this.activeSoundComponent === 'one' ? trackMetaData[this.getDate(charts, this.i)]['previewUrl'] :
trackMetaData[this.getDate(charts, this.i + 1)]['previewUrl'];
this.activeSoundComponent = this.activeSoundComponent === 'one' ? 'two' : 'one';
this.setState({
fourWeeksBackChartDate: this.getDate(charts, this.i - 4),
threeWeeksBackChartDate: this.getDate(charts, this.i - 3),
twoWeeksBackChartDate: this.getDate(charts, this.i - 2),
lastChartDate: this.getDate(charts, this.i - 1),
currentDate: this.getDate(charts, this.i),
nextChartDate: this.getDate(charts, this.i + 1),
currentTrackURL: trackMetaData[this.getDate(charts, this.i)]['previewUrl'],
nextTrackURL: trackMetaData[this.getDate(charts, this.i + 1)]['previewUrl'],
trackURLSoundComponentOne: trackURLSoundComponentOne,
trackURLSoundComponentTwo: trackURLSoundComponentTwo,
volOne: volOne,
volTwo: volTwo
});
this.i += 1;
this.createInterval();
}
...
```
<file_sep>/frontend/components/introModal.jsx
import React from 'react';
import ReactDOM from 'react-dom';
import Modal from 'react-modal';
class IntroModal extends React.Component{
constructor(props){
super(props);
this.style = {
overlay : {
position: 'fixed',
display: 'flex',
justifyContent: 'center',
alignItems: 'center',
top: 0,
left: 0,
right: 0,
bottom: 0,
backgroundColor: 'rgba(0, 0, 0, 0.2)',
backgroundImage: 'url("BackgroundModal.png")',
backgroundSize: 'cover'
},
content : {
top: 0,
left: 0,
right: 0,
bottom: 0,
position: 'relative',
display: 'flex',
flexDirection: 'column',
justifyContent: 'center',
alignItems: 'center',
width: 600,
height: 400,
border: '1px solid white',
backgroundImage: 'url("AlbumCovers.png")',
backgroundSize: 'cover',
background: 'black',
overflow: 'auto',
borderRadius: '25px',
outline: 'none',
padding: 'none',
boxShadow: '2px 2px 2px 1px rgba(0, 0, 0, 0.2)'
}
};
}
componentWillMount() {
Modal.setAppElement('body');
}
render() {
let playButton = this.props.isLoading ? <img id='loader' src='loader.gif'/> :
<img id='modalPlayButton' src="Triangle.png" onClick={this.props.onRequestClose}/>;
return (
<Modal
isOpen={this.props.isModalOpen}
style={this.style}
contentLabel='modal'>
<div id='modalDescription'>
A visualization of how
<img src='billboard-logo.png' width='100'/>
top 10 music has changed over time
</div>
{playButton}
<img id='modalHeadphonesImg' src="Headphones.png"/>
<span id='modalFooter'>Headphones Suggested</span>
</Modal>
);
}
}
export default IntroModal;
<file_sep>/frontend/components/year.jsx
import React from 'react';
import ReactDOM from 'react-dom';
import _ from 'lodash';
class Year extends React.Component{
constructor(props){
super(props);
this.playFromYear = this.playFromYear.bind(this);
}
playFromYear() {
if (!this.props.isCurrentYear) {
this.props.setChartDate(this.props.yearDates[this.props.yearDates.length - 1]); // play from last song in year
}
this.props.showMonths(this.props.year);
}
render() {
let hvrPulse = this.props.isCurrentYear ? 'hvr-pulse' : '';
return (
<div className={`${hvrPulse} decadeYear`} onClick={this.playFromYear}>
{this.props.year}
</div>
);
}
}
export default Year;
<file_sep>/frontend/components/chart.jsx
import React from 'react';
import ReactDOM from 'react-dom';
import _ from 'lodash';
import Line from './line.jsx';
import GraphDate from './graphDate.jsx';
class Chart extends React.Component{
constructor(props){
super(props);
this.state = {
offset: 0
};
}
componentDidMount() {
// This is called 150 times throughout a chart interval
// Line must move 175 pixels every chart interval
const VELOCITY = (175 / 75);
this.offsetInterval = setInterval(() => {
this.setState({ offset: this.state.offset + VELOCITY });
}, 40);
}
componentWillReceiveProps(nextProps) {
if (nextProps.chart !== this.props.chart) {
this.setState({ offset: 0 });
}
}
componentWillUnmount() {
clearInterval(this.offsetInterval);
}
getPositionForRank(rank) {
return rank * 55;
}
getLinesForSection(sectionNum, startingChart, endingChart) {
const STAGING_AREA_RANK = 11;
const startingTracks = _.map(startingChart, 'title');
const endingTracks = _.map(endingChart, 'title');
const tracksOnDeck = _.filter(endingChart, trackOnDeck => {
return !(_.includes(startingTracks, trackOnDeck.title));
});
let lines = _.map(startingChart, track => {
let nextTrackRank = endingTracks.indexOf(track.title) + 1; // index 0 should be rank 1, etc...
if (nextTrackRank === 0) {
nextTrackRank = STAGING_AREA_RANK; // if track is not in next week's charts, animate to bottom of list
}
return <Line
offset={this.state.offset}
color={this.props.getColorForTitle(track.title)}
key={`${track.title}sec${sectionNum}rank${track.rank}`}
weekPosition={sectionNum}
y1={this.getPositionForRank(track.rank)}
y2={this.getPositionForRank(nextTrackRank)}/>;
});
const tracksOnDeckLines = tracksOnDeck.map(trackOnDeck => {
return <Line
offset={this.state.offset}
color={this.props.getColorForTitle(trackOnDeck.title)}
key={`${trackOnDeck.title}sec${sectionNum}rank${trackOnDeck.rank}`}
weekPosition={sectionNum}
y1={this.getPositionForRank(STAGING_AREA_RANK)}
y2={this.getPositionForRank(trackOnDeck.rank)}/>;
});
return lines.concat(tracksOnDeckLines);
}
render() {
const sectionZero = this.getLinesForSection(0, this.props.chart, this.props.nextChart);
const sectionOne = this.getLinesForSection(1, this.props.prevChart, this.props.chart);
const sectionTwo = this.getLinesForSection(2, this.props.twoWeeksBackChart, this.props.prevChart);
const sectionThree = this.getLinesForSection(3, this.props.threeWeeksBackChart, this.props.twoWeeksBackChart);
const sectionFour = this.getLinesForSection(4, this.props.fourWeeksBackChart, this.props.threeWeeksBackChart);
return (
<div id="chart-wrap-wrapper">
<div id="chart-wrap">
<ul id="chart-y-axis">
<li>1 —</li>
<li>2 —</li>
<li>3 —</li>
<li>4 —</li>
<li>5 —</li>
<li>6 —</li>
<li>7 —</li>
<li>8 —</li>
<li>9 —</li>
<li>10 —</li>
</ul>
<svg width={700} height={579} style={{ borderBottom: '1px solid white', backgroundColor: 'transparent' }}>
{sectionZero}
{sectionOne}
{sectionTwo}
{sectionThree}
{sectionFour}
</svg>
</div>
<svg width={700} height={50} style={{ backgroundColor: 'rgb(0, 0, 0)', color: 'white', marginLeft: 'auto' }}>
<GraphDate offset={this.state.offset} weekPosition={-1} date={this.props.nextChartDate}/>
<GraphDate offset={this.state.offset} weekPosition={0} date={this.props.currentDate}/>
<GraphDate offset={this.state.offset} weekPosition={1} date={this.props.prevChartDate}/>
<GraphDate offset={this.state.offset} weekPosition={2} date={this.props.twoWeeksBackChartDate}/>
<GraphDate offset={this.state.offset} weekPosition={3} date={this.props.threeWeeksBackChartDate}/>
<GraphDate offset={this.state.offset} weekPosition={4} date={this.props.fourWeeksBackChartDate}/>
</svg>
</div>
);
}
}
export default Chart;
<file_sep>/frontend/components/month.jsx
import React from 'react';
import ReactDOM from 'react-dom';
import _ from 'lodash';
import moment from 'moment';
class Month extends React.Component{
constructor(props){
super(props);
this.playFromMonth = this.playFromMonth.bind(this);
this.getMonthDates = this.getMonthDates.bind(this);
}
getMonthDates() {
// formats as YYYY-MM to find dates that belong to this month in this year
let yearMonthDate = `${this.props.year}-${moment().month(this.props.month).format('MM')}`;
return _.filter(this.props.dates, date => {
return date.slice(0, 7) === yearMonthDate;
}).reverse();
}
playFromMonth() {
let monthDates = this.getMonthDates();
this.props.setChartDate(monthDates[monthDates.length - 1]); // play from last song in month
}
render() {
let hvrPulse = this.props.isCurrentMonth ? 'hvr-pulse' : '';
return (
<div className={`${hvrPulse} month`} onClick={this.playFromMonth}>
{this.props.month}
</div>
);
}
}
export default Month;
<file_sep>/frontend/billboard.jsx
import React from "react";
import ReactDOM from "react-dom";
import { Link, IndexRoute, Route, Router, hashHistory } from 'react-router';
import Home from "./components/home";
class Billboard extends React.Component {
render() {
return (
<div>
{this.props.children}
</div>
);
}
}
const routes = (
<Route path="/" component={Billboard}>
<IndexRoute component={Home} />
</Route>
);
document.addEventListener("DOMContentLoaded", function(){
ReactDOM.render(
<Router history={hashHistory}>
{routes}
</Router>, document.getElementById('root'));
});
<file_sep>/frontend/components/home.jsx
import React from 'react';
import ReactDOM from 'react-dom';
import { hashHistory } from 'react-router';
import moment from 'moment';
import StringHash from 'string-hash';
import Promise from 'bluebird';
import _ from 'lodash';
import Graph from './graph.jsx';
import Title from './title.jsx';
import Sound from 'react-sound';
import Chart from './chart.jsx';
import Tabs from './tabs.jsx';
import IntroModal from './introModal.jsx';
class Home extends React.Component {
constructor(props) {
super(props);
this.state = {
albumImages: {},
charts: {},
trackMetaData: {},
lastChartDate: null,
twoWeeksBackChartDate: null,
threeWeeksBackChartDate: null,
fourWeeksBackChartDate: null,
currentDate: null,
nextChartDate: null,
currentTrackURL: null, //current track playing
nextTrackURL: null, //next track to be cached
trackURLSoundComponentOne: null, //track url set on Sound component one
trackURLSoundComponentTwo: null, //track url set on Sound component two
soundComponentOneStatus: Sound.status.PLAYING,
soundComponentTwoStatus: Sound.status.STOPPED,
volOne: 100,
volTwo: 0,
isSoundOn: true,
genre: 'hot100',
isModalOpen: true,
isLoading: true,
isLoadingGenres: true
};
this.incrementCharts = this.incrementCharts.bind(this);
this.getDate = this.getDate.bind(this);
this.formatDate = this.formatDate.bind(this);
this.setChartDate = this.setChartDate.bind(this);
this.createInterval = this.createInterval.bind(this);
this.toggleSound = this.toggleSound.bind(this);
this.handleSongFinishedPlayingOne = this.handleSongFinishedPlayingOne.bind(this);
this.handleSongFinishedPlayingTwo = this.handleSongFinishedPlayingTwo.bind(this);
this.isNextSongDifferent = this.isNextSongDifferent.bind(this);
this.areBothPlaying = this.areBothPlaying.bind(this);
this.incrementSameTrack = this.incrementSameTrack.bind(this);
this.incrementDifferentTrack = this.incrementDifferentTrack.bind(this);
this.fadeInFadeOut = this.fadeInFadeOut.bind(this);
this.stopInterval = this.stopInterval.bind(this);
this.startCharts = this.startCharts.bind(this);
this.playGenre = this.playGenre.bind(this);
this.closeModal = this.closeModal.bind(this);
this.loadCharts = this.loadCharts.bind(this);
}
componentDidMount() {
this.loadCharts();
}
loadCharts() {
this.loadChart('hot100')
.then(() => {
return Promise.all([
this.loadChart('rap'),
this.loadChart('alternative'),
this.loadChart('country'),
this.loadChart('electric'),
this.loadChart('hiphop')
])
.then(() => {
return this.setState({ isLoadingGenres: false });
});
});
}
loadChart(genre) {
let charts, albumImages;
return $.get(`charts/${genre}/charts.json`)
.then(_charts => {
charts = _charts;
return $.get(`charts/${genre}/images.json`);
})
.then(_albumImages => {
albumImages = _albumImages;
return $.get(`charts/${genre}/previewUrls.json`);
})
.then(trackMetaData => {
let newGenreChart = {};
newGenreChart[genre] = charts;
let newCharts = _.extend({}, this.state.charts, newGenreChart);
let newGenreTrackMetaData = {};
newGenreTrackMetaData[genre] = trackMetaData;
let newTrackMetaData = _.extend({}, this.state.trackMetaData, newGenreTrackMetaData);
let newGenreAlbumImages = {};
newGenreAlbumImages[genre] = albumImages;
let newAlbumImages = _.extend({}, this.state.albumImages, newGenreAlbumImages);
this.setState({
trackMetaData: newTrackMetaData,
albumImages: newAlbumImages,
charts: newCharts
});
if (genre === 'hot100') {
this.setState({ isLoading: false });
}
});
}
startCharts(genre) {
this.i = 0;
const charts = this.state.charts[genre];
const trackMetaData = this.state.trackMetaData[genre];
this.setState({
fourWeeksBackChartDate: this.getDate(charts, this.i - 4),
threeWeeksBackChartDate: this.getDate(charts, this.i - 3),
twoWeeksBackChartDate: this.getDate(charts, this.i - 2),
lastChartDate: this.getDate(charts, this.i - 1),
currentDate: this.getDate(charts, this.i),
nextChartDate: this.getDate(charts, this.i + 1),
currentTrackURL: trackMetaData[this.getDate(charts, this.i)]['previewUrl'],
nextTrackURL: trackMetaData[this.getDate(charts, this.i + 1)]['previewUrl']
});
if (trackMetaData[this.getDate(charts, 0)]['previewUrl'] !== trackMetaData[this.getDate(charts, 1)]['previewUrl']) {
this.incrementDifferentTrack(genre);
} else {
this.incrementSameTrack(genre);
}
this.incrementCharts();
}
incrementCharts() {
this.i = 1;
this.createInterval();
}
incrementDifferentTrack(genre) {
const currentGenre = genre ? genre : this.state.genre;
const trackMetaData = this.state.trackMetaData[currentGenre];
const charts = this.state.charts[currentGenre];
let volOne = this.activeSoundComponent === 'one' ? 0 : 100;
let volTwo = this.activeSoundComponent === 'one' ? 100 : 0;
let soundComponentOneStatus;
let soundComponentTwoStatus;
if(this.state.isSoundOn){
soundComponentOneStatus = this.activeSoundComponent === 'one' ? Sound.status.STOPPED : Sound.status.PLAYING;
soundComponentTwoStatus = this.activeSoundComponent === 'one' ? Sound.status.PLAYING : Sound.status.STOPPED;
} else {
soundComponentOneStatus = this.activeSoundComponent === 'one' ? Sound.status.STOPPED : this.state.soundComponentOneStatus;
soundComponentTwoStatus = this.activeSoundComponent === 'one' ? this.state.soundComponentTwoStatus : Sound.status.STOPPED;
}
let trackURLSoundComponentOne = this.activeSoundComponent === 'one' ? trackMetaData[this.getDate(charts, this.i + 1)]['previewUrl'] :
trackMetaData[this.getDate(charts, this.i)]['previewUrl'];
let trackURLSoundComponentTwo = this.activeSoundComponent === 'one' ? trackMetaData[this.getDate(charts, this.i)]['previewUrl'] :
trackMetaData[this.getDate(charts, this.i + 1)]['previewUrl'];
this.activeSoundComponent = this.activeSoundComponent === 'one' ? 'two' : 'one';
this.setState({
fourWeeksBackChartDate: this.getDate(charts, this.i - 4),
threeWeeksBackChartDate: this.getDate(charts, this.i - 3),
twoWeeksBackChartDate: this.getDate(charts, this.i - 2),
lastChartDate: this.getDate(charts, this.i - 1),
currentDate: this.getDate(charts, this.i),
nextChartDate: this.getDate(charts, this.i + 1),
currentTrackURL: trackMetaData[this.getDate(charts, this.i)]['previewUrl'],
nextTrackURL: trackMetaData[this.getDate(charts, this.i + 1)]['previewUrl'],
trackURLSoundComponentOne: trackURLSoundComponentOne,
trackURLSoundComponentTwo: trackURLSoundComponentTwo,
soundComponentOneStatus: soundComponentOneStatus,
soundComponentTwoStatus: soundComponentTwoStatus,
volOne: volOne,
volTwo: volTwo
});
}
incrementSameTrack(genre) {
const currentGenre = genre ? genre : this.state.genre;
const trackMetaData = this.state.trackMetaData[currentGenre];
const charts = this.state.charts[currentGenre];
let volOne = this.activeSoundComponent === 'one' ? 100 : 0;
let volTwo = this.activeSoundComponent === 'one' ? 0 : 100;
let trackURLSoundComponentOne = this.activeSoundComponent === 'one' ? trackMetaData[this.getDate(charts, this.i)]['previewUrl'] :
trackMetaData[this.getDate(charts, this.i + 1)]['previewUrl'];
let trackURLSoundComponentTwo = this.activeSoundComponent === 'one' ? trackMetaData[this.getDate(charts, this.i + 1)]['previewUrl'] :
trackMetaData[this.getDate(charts, this.i)]['previewUrl'];
this.setState({
fourWeeksBackChartDate: this.getDate(charts, this.i - 4),
threeWeeksBackChartDate: this.getDate(charts, this.i - 3),
twoWeeksBackChartDate: this.getDate(charts, this.i - 2),
lastChartDate: this.getDate(charts, this.i - 1),
currentDate: this.getDate(charts, this.i),
nextChartDate: this.getDate(charts, this.i + 1),
currentTrackURL: trackMetaData[this.getDate(charts, this.i)]['previewUrl'],
nextTrackURL: trackMetaData[this.getDate(charts, this.i + 1)]['previewUrl'],
trackURLSoundComponentOne: trackURLSoundComponentOne,
trackURLSoundComponentTwo: trackURLSoundComponentTwo,
volOne: volOne,
volTwo: volTwo
});
}
createInterval() {
if (this.nextDateInterval) {
clearInterval(this.nextDateInterval);
}
this.nextDateInterval = setInterval(() => {
clearInterval(this.fadeOutOneFadeInTwoInterval);
clearInterval(this.fadeOutTwoFadeInOneInterval);
if (this.isNextSongDifferent()) {
this.incrementDifferentTrack();
} else {
this.incrementSameTrack();
}
this.i += 1;
if ( this.i >= Object.keys(this.state.charts[this.state.genre]).length - 2) { // Stop incrementing on second to last date
this.i = 0;
}
}, 3000);
}
setChartDate(date) {
const trackMetaData = this.state.trackMetaData[this.state.genre];
const charts = this.state.charts[this.state.genre];
this.i = Object.keys(charts).indexOf(date);
if (this.nextDateInterval) clearInterval(this.nextDateInterval);
if (this.fadeOutOneFadeInTwoInterval) clearInterval(this.fadeOutOneFadeInTwoInterval);
if (this.fadeOutTwoFadeInOneInterval) clearInterval(this.fadeOutTwoFadeInOneInterval);
if ( this.i === Object.keys(charts).length - 1) { // Last song was chosen
this.i -= 3;
}
if (this.state.isSoundOn) {
this.setState({
soundComponentOneStatus: this.activeSoundComponent === 'one' ? Sound.status.STOPPED : Sound.status.PLAYING,
soundComponentTwoStatus: this.activeSoundComponent === 'one' ? Sound.status.PLAYING : Sound.status.STOPPED
});
}
let volOne = this.activeSoundComponent === 'one' ? 0 : 100;
let volTwo = this.activeSoundComponent === 'one' ? 100 : 0;
let trackURLSoundComponentOne = this.activeSoundComponent === 'one' ? trackMetaData[this.getDate(charts, this.i + 1)]['previewUrl'] :
trackMetaData[this.getDate(charts, this.i)]['previewUrl'];
let trackURLSoundComponentTwo = this.activeSoundComponent === 'one' ? trackMetaData[this.getDate(charts, this.i)]['previewUrl'] :
trackMetaData[this.getDate(charts, this.i + 1)]['previewUrl'];
this.activeSoundComponent = this.activeSoundComponent === 'one' ? 'two' : 'one';
this.setState({
fourWeeksBackChartDate: this.getDate(charts, this.i - 4),
threeWeeksBackChartDate: this.getDate(charts, this.i - 3),
twoWeeksBackChartDate: this.getDate(charts, this.i - 2),
lastChartDate: this.getDate(charts, this.i - 1),
currentDate: this.getDate(charts, this.i),
nextChartDate: this.getDate(charts, this.i + 1),
currentTrackURL: trackMetaData[this.getDate(charts, this.i)]['previewUrl'],
nextTrackURL: trackMetaData[this.getDate(charts, this.i + 1)]['previewUrl'],
trackURLSoundComponentOne: trackURLSoundComponentOne,
trackURLSoundComponentTwo: trackURLSoundComponentTwo,
volOne: volOne,
volTwo: volTwo
});
this.i += 1;
this.createInterval();
}
getDate(charts, index) {
return Object.keys(charts)[index];
}
formatDate(date) {
return moment(date).format('MMMM D, YYYY');
}
isNextSongDifferent(){
return this.state.currentTrackURL !== this.state.nextTrackURL;
}
areBothPlaying() {
return (this.state.soundComponentTwoStatus === Sound.status.PLAYING) && (this.state.soundComponentOneStatus === Sound.status.PLAYING);
}
fadeInFadeOut() {
if (this.isNextSongDifferent()) {
if (this.fadeOutOneFadeInTwoInterval) clearInterval(this.fadeOutOneFadeInTwoInterval);
if (this.fadeOutTwoFadeInOneInterval) clearInterval(this.fadeOutTwoFadeInOneInterval);
if (this.activeSoundComponent === 'one') {
this.fadeOutOneFadeInTwoInterval = setInterval(() => {
this.setState({
volOne: this.state.volOne - 1.5,
volTwo: this.state.volTwo + 1.5
});
}, (1000 / 30));
} else {
this.fadeOutTwoFadeInOneInterval = setInterval(() => {
this.setState({
volOne: this.state.volOne + 1.5,
volTwo: this.state.volTwo - 1.5
});
}, (1000 / 30));
}
}
}
componentDidUpdate() {
if ((this.isNextSongDifferent() && !this.areBothPlaying()) && this.state.isSoundOn) {
this.fadeInFadeOut();
let trackURLSoundComponentOne = this.activeSoundComponent === 'one' ? this.state.currentTrackURL : this.state.nextTrackURL;
let trackURLSoundComponentTwo = this.activeSoundComponent === 'one' ? this.state.nextTrackURL : this.state.currentTrackURL;
this.setState({
trackURLSoundComponentOne: trackURLSoundComponentOne,
trackURLSoundComponentTwo: trackURLSoundComponentTwo,
soundComponentOneStatus: Sound.status.PLAYING,
soundComponentTwoStatus: Sound.status.PLAYING
});
}
}
handleSongFinishedPlayingOne() {
this.setState({ trackURLSoundComponentOne: this.state.trackURLSoundComponentOne});
}
handleSongFinishedPlayingTwo() {
this.setState({ trackURLSoundComponentTwo: this.state.trackURLSoundComponentTwo});
}
songComponentOne(trackURLSoundComponentOne) {
if(trackURLSoundComponentOne){
return <Sound playStatus={this.state.soundComponentOneStatus}
volume={this.state.volOne}
url={this.state.trackURLSoundComponentOne}
onFinishedPlaying={this.handleSongFinishedPlayingOne}/>;
}
}
songComponentTwo(trackURLSoundComponentTwo) {
if(trackURLSoundComponentTwo){
return <Sound playStatus={this.state.soundComponentTwoStatus}
url={this.state.trackURLSoundComponentTwo}
volume={this.state.volTwo}
onFinishedPlaying={this.handleSongFinishedPlayingTwo}/>;
}
}
toggleSound() {
if (this.state.isSoundOn) {
this.setState({
soundComponentOneStatus: Sound.status.PAUSED,
soundComponentTwoStatus: Sound.status.PAUSED,
isSoundOn: false
});
} else {
if (this.activeSoundComponent === 'one') {
this.setState({
soundComponentOneStatus: Sound.status.PLAYING,
isSoundOn: true
});
} else {
this.setState({
soundComponentTwoStatus: Sound.status.PLAYING,
isSoundOn: true
});
}
}
}
getColorForTitle(trackTitle) {
let hash = StringHash(trackTitle);
let colors = [
'#FEF59E', // yellow
'#98CC9F', // lime green
'#998AC0', // dark purple
'#8AD2F4', // turquoise
'#F4B589', // red orange
'#C897C0', // light purple
'#FFB347', // orange
'#B1E2DA', // teal
'#FF6961', // red
'#779ECB', // navy blue
'#DEA5A4', // light red
'#CBFFCB', // light green
];
return colors[hash % colors.length];
}
stopInterval() {
clearInterval(this.nextDateInterval);
}
playGenre(genre) {
if (genre !== this.state.genre) {
this.setState({ genre: genre });
this.startCharts(genre);
}
}
closeModal() {
this.setState({ isModalOpen: false });
this.activeSoundComponent = 'one';
this.startCharts(this.state.genre);
}
render() {
const currentChart = this.state.charts[this.state.genre];
let graphComponent;
let audioComponent;
let datePickerComponent;
let titleBoxComponent;
let chartComponent;
let tabsComponent;
if (currentChart && this.state.currentTrackURL) {
titleBoxComponent = <Title
date={this.formatDate(this.state.currentDate)}
artist={currentChart[this.state.currentDate][0].artist}
toggleSound={this.toggleSound}
isSoundOn={this.state.isSoundOn}
genre={this.state.genre}
/>;
graphComponent = <Graph
date={this.state.currentDate}
chart={currentChart[this.state.currentDate]}
nextChart={currentChart[this.state.nextChartDate]}
albumImages={this.state.albumImages[this.state.genre]}
getColorForTitle={this.getColorForTitle}
/>;
const trackURLSoundComponentOne = this.state.trackURLSoundComponentOne;
const trackURLSoundComponentTwo = this.state.trackURLSoundComponentTwo;
audioComponent =
<div>
{this.songComponentOne(trackURLSoundComponentOne)}
{this.songComponentTwo(trackURLSoundComponentTwo)}
</div>;
tabsComponent = <Tabs
charts={currentChart}
setChartDate={this.setChartDate.bind(this)}
currentDate={this.state.currentDate}
playGenre={this.playGenre}
isLoadingGenres={this.state.isLoadingGenres}/>;
chartComponent = <Chart
chart={currentChart[this.state.currentDate]}
nextChart={currentChart[this.state.nextChartDate]}
prevChart={currentChart[this.state.lastChartDate]}
twoWeeksBackChart={currentChart[this.state.twoWeeksBackChartDate]}
threeWeeksBackChart={currentChart[this.state.threeWeeksBackChartDate]}
fourWeeksBackChart={currentChart[this.state.fourWeeksBackChartDate]}
getColorForTitle={this.getColorForTitle}
currentDate={this.state.currentDate}
nextChartDate={this.state.nextChartDate}
prevChartDate={this.state.lastChartDate}
twoWeeksBackChartDate={this.state.twoWeeksBackChartDate}
threeWeeksBackChartDate={this.state.threeWeeksBackChartDate}
fourWeeksBackChartDate={this.state.fourWeeksBackChartDate}
/>;
}
return (
<div>
{titleBoxComponent}
<IntroModal isModalOpen={this.state.isModalOpen} onRequestClose={this.closeModal} isLoading={this.state.isLoading}/>
<section id='mainContainer'>
{tabsComponent}
{chartComponent}
{graphComponent}
</section>
{audioComponent}
</div>
);
}
}
export default Home;
| e8582e1e473e759eb1dd3cb2f3db73fc7354527e | [
"JavaScript",
"Python",
"Ruby",
"Markdown"
] | 13 | JavaScript | GuyHadas/BillboardTopTen | 3b63e17e7124ef729750ff10ea81f0da62dc691c | 9c8850f779b14db5b9974a5fa5cbd23cc34200c3 |
refs/heads/master | <repo_name>hcnelson99/rl<file_sep>/src/map.h
#pragma once
#include <assert.h>
#include <vector>
#include <unordered_set>
#include "pcg_variants.h"
#include "vector.h"
#define MAP_X 235
#define MAP_Y 73
const Vector2 MAP_SIZE = {MAP_X, MAP_Y};
#define MAP_TILE_COUNT (MAP_X * MAP_Y)
const Vector2 ADJACENTS[8] = {
{1, 1},
{1, 0},
{1, -1},
{0, 1},
{0, -1},
{-1, 1},
{-1, 0},
{-1, -1},
};
const Vector2 ORTHOGONALS[4] = {
{-1, 0},
{1, 0},
{0, -1},
{0, 1},
};
enum class Tile {
Wall,
Floor,
};
inline Vector2 index_to_pos(int i) {
return {i % MAP_SIZE.x, i / MAP_SIZE.x};
}
inline int pos_to_index(const Vector2 &pos) {
return pos.y * MAP_SIZE.x + pos.x;
}
inline bool pos_in_range(const Vector2 &pos) {
return pos.y >= 0 && pos.y < MAP_SIZE.y && pos.x >= 0 && pos.x < MAP_SIZE.x;
}
inline bool index_in_range(int i) {
return i >= 0 && i < MAP_TILE_COUNT;
}
struct Map {
Tile map[MAP_TILE_COUNT];
inline Tile *at(const Vector2 &pos) {
assert(pos_in_range(pos));
return &map[pos_to_index(pos)];
}
inline const Tile *at(const Vector2 &pos) const {
assert(pos_in_range(pos));
return &map[pos_to_index(pos)];
}
inline Tile *at(int i) {
assert(index_in_range(i));
return &map[i];
}
inline const Tile *at(int i) const {
assert(index_in_range(i));
return &map[i];
}
inline bool occupied(const Vector2 &pos) const {
assert(pos_in_range(pos));
return *at(pos) == Tile::Wall;
}
int count_neighbors(const Vector2 &pos) const;
void cellular_automata_iteration();
void smooth();
void visibility(const Vector2 &player_pos, bool visible[MAP_TILE_COUNT]) const;
bool operator==(const Map &o) const;
bool operator!=(const Map &o) const;
};
void clear_visibility(bool visible[MAP_TILE_COUNT]);
std::vector<std::unordered_set<Vector2>> floodfill(const Map &map);
bool pos_in_range(const Vector2 &pos);
void empty_map(Map *map);
void filled_map(Map *map);
void bezier(Map *map);
void cave_map(Map *map);
void random_map(Map *map, pcg32_random_t *gen, unsigned int percent);
<file_sep>/src/CMakeLists.txt
add_executable(rl
main.cpp
util.cpp
map.cpp
curses_render.cpp
path_map.cpp)
find_package(Curses REQUIRED)
include_directories(${EntityX_INCLUDE_DIRS})
target_link_libraries(rl ${CURSES_LIBRARIES} entityx pcg-random)
<file_sep>/src/path_map.cpp
#include "path_map.h"
#include <string.h>
#include <assert.h>
#include <algorithm>
PathMap::PathMap() {
for (int i = 0; i < MAP_TILE_COUNT; i++) {
*at(i) = PATH_MAP_MAX;
}
}
int *PathMap::at(const Vector2 &pos) {
assert(pos_in_range(pos));
return &map[pos_to_index(pos)];
}
const int *PathMap::at(const Vector2 &pos) const {
assert(pos_in_range(pos));
return &map[pos_to_index(pos)];
}
int *PathMap::at(int i) {
assert(index_in_range(i));
return &map[i];
}
const int *PathMap::at(int i) const {
assert(index_in_range(i));
return &map[i];
}
void PathMap::set_goal(const Vector2 &pos) {
*at(pos) = 0;
}
void PathMap::set_goal(int i) {
*at(i) = 0;
}
bool PathMap::operator==(const PathMap &o) const {
for (int i = 0; i < MAP_TILE_COUNT; i++) {
if (*at(i) != *o.at(i)) {
return false;
}
}
return true;
}
bool PathMap::operator!=(const PathMap &o) const {
return !(*this == o);
}
void PathMap::smooth(const Map &map) {
PathMap old_path_map;
do {
memcpy(&old_path_map, this, sizeof(PathMap));
for (int i = 0; i < MAP_TILE_COUNT; i++) {
Vector2 pos = index_to_pos(i);
if (*map.at(pos) == Tile::Floor) {
int min = PATH_MAP_MAX;
for (const Vector2 &o : ORTHOGONALS) {
Vector2 adj = pos + o;
if (pos_in_range(adj)) {
min = std::min(*at(adj), min);
}
}
if (*at(pos) > min + 1) {
*at(pos) = min + 1;
}
}
}
} while (old_path_map != *this);
}
<file_sep>/src/map.cpp
#include <stdint.h>
#include <string.h>
#include <queue>
#include <algorithm>
#include "map.h"
#include "util.h"
#include "path_map.h"
int Map::count_neighbors(const Vector2 &pos) const {
int neighbors = 0;
for (unsigned int i = 0; i < ARRAY_LEN(ADJACENTS); i++) {
Vector2 adj = pos + ADJACENTS[i];
if (pos_in_range(adj)) {
if (occupied(adj)) {
neighbors++;
}
} else {
neighbors++;
}
}
return neighbors;
}
void Map::cellular_automata_iteration() {
Map old_map;
memcpy(&old_map, &map, sizeof(Map));
for (int x = 0; x < MAP_SIZE.x; x++) {
for (int y = 0; y < MAP_SIZE.y; y++) {
Vector2 pos = {x, y};
int threshold = old_map.occupied(pos) ? 3 : 5;
*at(pos) = old_map.count_neighbors(pos) >= threshold
? Tile::Wall
: Tile::Floor;
}
}
}
bool Map::operator==(const Map &o) const {
for (int i = 0; i < MAP_TILE_COUNT; i++) {
if (*at(i) != *o.at(i)) {
return false;
}
}
return true;
}
bool Map::operator!=(const Map &o) const {
return !(*this == o);
}
void Map::smooth() {
Map old_map;
do {
memcpy(&old_map, this, sizeof(Map));
cellular_automata_iteration();
} while (old_map != *this);
}
// p1 is upper left (inclusive), p2 is upper right (exclusive)
struct Rect {
Vector2 p1, p2;
};
void random_room(Rect *room, pcg32_random_t *gen) {
assert(room);
assert(gen);
int width = pcg32_boundedrand_r(gen, 10) + 8;
int height = pcg32_boundedrand_r(gen, 10) + 8;
room->p1.x = pcg32_boundedrand_r(gen, MAP_SIZE.x - width + 1);
room->p1.y = pcg32_boundedrand_r(gen, MAP_SIZE.y - height + 1);
room->p2.x = room->p1.x + width;
room->p2.y = room->p1.y + height;
}
bool overlaps(const Rect &r1, const Rect &r2) {
return !(r1.p2.x < r2.p1.x || r1.p2.y < r2.p1.y ||
r2.p2.x < r1.p1.x || r2.p2.y < r1.p1.y);
}
void random_map(Map *map, pcg32_random_t *gen, unsigned int percent) {
assert(map);
assert(gen);
for (int i = 0; i < MAP_TILE_COUNT; i++) {
if (pcg32_boundedrand_r(gen, 100) < percent) {
*map->at(i) = Tile::Wall;
} else {
*map->at(i) = Tile::Floor;
}
}
}
// Returns room_num since number of requested rooms may not be placed
int generate_random_rooms(Rect *rooms, int room_num, pcg32_random_t *gen) {
for (int i = 0; i < room_num; i++) {
Rect room;
bool overlap;
const int iteration_limit = 100;
int n = 0;
do {
overlap = false;
random_room(&room, gen);
Vector2 border = {5, 5};
Rect larger_room { room.p1 - border, room.p2 + border};
if (larger_room.p1.x < 0) larger_room.p1.x = 0;
if (larger_room.p1.y < 0) larger_room.p1.y = 0;
if (larger_room.p2.x > MAP_SIZE.x - 1) larger_room.p2.x = MAP_SIZE.x - 1;
if (larger_room.p2.y > MAP_SIZE.y - 1) larger_room.p2.y = MAP_SIZE.y - 1;
for (int j = 0; j < i; j++) {
if (overlaps(larger_room, rooms[j])) {
overlap = true;
}
}
n++;
} while (overlap && n < iteration_limit);
if (n == iteration_limit) {
room_num = i;
break;
} else {
rooms[i] = room;
}
}
return room_num;
}
void fill_edges(Map *map) {
// Fill edges
for (int x = 0; x < MAP_SIZE.x; x++) {
Vector2 pos1 = {x, 0};
Vector2 pos2 = {x, MAP_SIZE.y - 1};
*map->at(pos1) = Tile::Wall;
*map->at(pos2) = Tile::Wall;
}
for (int y = 0; y < MAP_SIZE.y; y++) {
Vector2 pos1 = {0, y};
Vector2 pos2 = {MAP_SIZE.x - 1, y};
*map->at(pos1) = Tile::Wall;
*map->at(pos2) = Tile::Wall;
}
}
void fill_rooms(Map *map, Rect *rooms, int room_num) {
for (int i = 0; i < room_num; i++) {
Rect room = rooms[i];
for (int x = room.p1.x; x < room.p2.x; x++) {
for (int y = room.p1.y; y < room.p2.y; y++) {
*map->at({x, y}) = Tile::Wall;
}
}
}
}
void clear_room_interiors(Map *map, Rect *rooms, int room_num) {
for (int i = 0; i < room_num; i++) {
Rect room = rooms[i];
room.p1 += Vector2 {1, 1};
room.p2 -= Vector2 {1, 1};
for (int x = room.p1.x; x < room.p2.x; x++) {
for (int y = room.p1.y; y < room.p2.y; y++) {
*map->at({x, y}) = Tile::Floor;
}
}
}
}
std::vector<std::unordered_set<Vector2>> floodfill(const Map &map) {
std::vector<std::unordered_set<Vector2>> regions;
std::unordered_set<Vector2> visited;
for (int i = 0; i < MAP_TILE_COUNT; i++) {
Vector2 pos = index_to_pos(i);
if (*map.at(i) == Tile::Floor && !contains(visited, pos)) {
std::queue<Vector2> queue;
std::unordered_set<Vector2> pocket;
queue.push(pos);
pocket.insert(pos);
do {
pos = queue.front();
queue.pop();
for (const Vector2 &o : ORTHOGONALS) {
Vector2 adj = pos + o;
if (pos_in_range(adj) && *map.at(adj) == Tile::Floor && !contains(pocket, adj)) {
queue.push(adj);
pocket.insert(adj);
}
}
} while (!queue.empty());
visited.insert(std::begin(pocket), std::end(pocket));
regions.push_back(pocket);
}
}
return regions;
}
void connect_regions(Map *map) {
std::vector<std::unordered_set<Vector2>> regions = floodfill(*map);
while (regions.size() > 1) {
int min_dist = MAP_SIZE.x + MAP_SIZE.y;
Vector2 min1, min2;
for (unsigned int i = 1; i < regions.size(); i++) {
for (Vector2 pos1 : regions[0]) {
for (Vector2 pos2 : regions[i]) {
int dist = abs(pos1.x - pos2.x) + abs(pos1.y - pos2.y);
if (dist < min_dist) {
min_dist = dist;
min1 = pos1;
min2 = pos2;
}
}
}
}
while (min1 != min2) {
if (abs(min1.x - min2.x) > abs(min1.y - min2.y)) {
min1.x += min1.x < min2.x ? 1 : -1;
} else {
min1.y += min1.y < min2.y ? 1 : -1;
}
*map->at(min1) = Tile::Floor;
}
regions = floodfill(*map);
}
}
void cave_map(Map *map) {
pcg32_random_t gen;
auto seed = gen_seed();
LOG("map gen seed: %lu", seed);
seed_pcg32(&gen, seed);
random_map(map, &gen, 40);
const int max_room_num = 20;
Rect rooms[max_room_num];
int room_num = generate_random_rooms(rooms, max_room_num, &gen);
fill_rooms(map, rooms, room_num);
map->smooth();
clear_room_interiors(map, rooms, room_num);
fill_edges(map);
connect_regions(map);
}
void empty_map(Map *map) {
for (int x = 0; x < MAP_SIZE.x; x++) {
for (int y = 0; y < MAP_SIZE.y; y++) {
*map->at({x, y}) = Tile::Floor;
}
}
}
void filled_map(Map *map) {
for (int x = 0; x < MAP_SIZE.x; x++) {
for (int y = 0; y < MAP_SIZE.y; y++) {
*map->at({x, y}) = Tile::Wall;
}
}
}
Vector2 bezier3(const Vector2 &p0, const Vector2 &p1, const Vector2 &p2, double t) {
double x = (1 - t * t) * p0.x + 2 * (1 - t) * t * p1.x + t * t * p2.x;
double y = (1 - t * t) * p0.y + 2 * (1 - t) * t * p1.y + t * t * p2.y;
return {(int) x, (int) y};
}
#define abs(x) (x > 0 ? x : -x)
Vector2 start = {2, 2};
Vector2 end = {78, 22};
Vector2 middle = {2, 22};
void bezier(Map *map) {
pcg32_random_t gen;
seed_pcg32(&gen, 0);
Vector2 p0 = start;
Vector2 p1;
for (double t = 0; t <= 1.0; t += 1. / 50) {
p1 = bezier3(start, middle, end, t);
int dx = p1.x - p0.x;
int dy = p1.y - p0.y;
int steps = std::max(abs(dx), abs(dy));
double xi = dx / (double) steps;
double yi = dy / (double) steps;
double x = p0.x;
double y = p0.y;
for (int i = 0; i < steps; i++) {
for (int i = -1; i <= 1; i++) {
for (int j = -1; j <= 1; j++) {
if (pcg32_boundedrand_r(&gen, 100) < 60) {
*map->at({(int)(x + i), (int)(y + j)}) = Tile::Floor;
}
}
}
// map.at({x, y}) = Tile::Floor;
x += xi;
y += yi;
}
p0 = p1;
}
for (int i = 0; i < 5; i++) {
map->cellular_automata_iteration();
}
}
void Map::visibility(const Vector2 &player_pos, bool visible[MAP_TILE_COUNT]) const {
for (int t = 0; t < MAP_TILE_COUNT; t++) {
Vector2 p1 = index_to_pos(t);
int dx = p1.x - player_pos.x;
int dy = p1.y - player_pos.y;
int steps = std::max(abs(dx), abs(dy));
double xi = dx / (double) steps;
double yi = dy / (double) steps;
double x = player_pos.x;
double y = player_pos.y;
for (int i = 0; i < steps; i++) {
if (*at({(int)x, (int)y}) == Tile::Wall) {
goto next_iteration;
}
x += xi;
y += yi;
}
visible[t] = true;
next_iteration: ;
}
}
<file_sep>/src/curses_render.cpp
#include <vector>
#include <unordered_map>
#include <string.h>
#include "curses_render.h"
#include "map.h"
#include "util.h"
#define BLACK COLOR_PAIR(1)
#define LIGHT_BLACK COLOR_PAIR(9)
#define RED COLOR_PAIR(2)
#define LIGHT_RED COLOR_PAIR(10)
#define GREEN COLOR_PAIR(3)
#define LIGHT_GREEN COLOR_PAIR(11)
#define YELLOW COLOR_PAIR(4)
#define LIGHT_YELLOW COLOR_PAIR(12)
#define BLUE COLOR_PAIR(5)
#define LIGHT_BLUE COLOR_PAIR(13)
#define MAGENTA COLOR_PAIR(6)
#define LIGHT_MAGENTA COLOR_PAIR(14)
#define CYAN COLOR_PAIR(7)
#define LIGHT_CYAN COLOR_PAIR(15)
#define WHITE COLOR_PAIR(8)
#define LIGHT_WHITE 16
using namespace entityx;
// TODO: Factor out camera functions (if other graphical backends are ever written)
struct Camera {
// pos is upper left corner
Vector2 pos, view_size;
void update_scroll(const Vector2 &player_pos) {
pos = player_pos - view_size / 2;
if (pos.x < 0) { pos.x = 0; }
if (pos.y < 0) { pos.y = 0; }
if (pos.x > MAP_SIZE.x - view_size.x) { pos.x = MAP_SIZE.x - view_size.x; }
if (pos.y > MAP_SIZE.y - view_size.y) { pos.y = MAP_SIZE.y - view_size.y; }
assert(pos_in_range(pos) && pos_in_range(pos + view_size - Vector2{1, 1}));
}
};
// TODO: Factor out render information (if other graphical backends are ever written)
struct RenderInfo {
char display;
int color;
};
const std::unordered_map<MobType, RenderInfo> mob_render_info = {
{MobType::Player, {'@', BLUE}},
{MobType::Enemy, {'g', RED}},
};
WINDOW* curses_init_win() {
WINDOW *win = initscr();
if (!has_colors()) {
CRITICAL("Terminal needs to support color");
return nullptr;
}
start_color();
use_default_colors();
for (int i = 0; i < 16; i++) {
init_pair(i+1, i, -1);
}
noecho();
curs_set(0);
nodelay(win, true);
keypad(win, true);
return win;
}
void curses_render(Game &game, bool player_view_history[MAP_TILE_COUNT], bool scrolling, bool render_visible) {
assert(player_view_history);
Entity player = game.get_tagged(EntityTag::Player);
Vector2 player_pos = player.component<CPos>()->pos;
Camera camera;
if (scrolling) {
camera.view_size = {80, 24};
camera.update_scroll(player_pos);
} else {
camera.view_size = MAP_SIZE;
camera.pos = {0, 0};
}
bool visible[MAP_TILE_COUNT];
memset(visible, false, MAP_TILE_COUNT);
game.map.visibility(player_pos, visible);
for (int i = 0; i < MAP_TILE_COUNT; i++) {
if (visible[i]) {
player_view_history[i] = visible[i];
}
}
erase();
for (int y = camera.pos.y; y < camera.pos.y + camera.view_size.y; y++) {
for (int x = camera.pos.x; x < camera.pos.x + camera.view_size.x; x++) {
if (render_visible) {
if (visible[pos_to_index({x, y})]) {
printw("%s", *game.map.at({x, y}) == Tile::Wall ? "#" : ".");
} else if (player_view_history[pos_to_index({x, y})]) {
attron(LIGHT_BLACK);
printw("%s", *game.map.at({x, y}) == Tile::Wall ? "#" : ".");
attroff(LIGHT_BLACK);
} else {
printw(" ");
}
} else {
printw("%s", *game.map.at({x, y}) == Tile::Wall ? "#" : " ");
}
}
printw("\n");
}
game.ecs.each<CMob, CPos>([&](const Entity e, CMob &mob, CPos &mob_pos) {
LOG("test\n");
Vector2 screen_location = mob_pos.pos;
if (scrolling) {
screen_location -= camera.pos;
}
if (screen_location.x >= 0 && screen_location.x < camera.view_size.x &&
screen_location.y >= 0 && screen_location.y < camera.view_size.y &&
(!render_visible || visible[pos_to_index(mob_pos.pos)])) {
RenderInfo render_info = mob_render_info.at(mob.type);
attron(render_info.color);
mvprintw(screen_location.y, screen_location.x, &render_info.display);
attroff(render_info.color);
}
});
refresh();
}
<file_sep>/src/util.h
#pragma once
#include <stdio.h>
#include <libgen.h>
#include <time.h>
#include <unordered_set>
#include <syscall.h>
#include <unistd.h>
#include "pcg_variants.h"
template <typename F>
struct Defer {
Defer(F f) : f(f) {}
~Defer() { f(); }
F f;
};
template <typename F>
Defer<F> make_defer(F f) {
return Defer<F>(f);
}
#define CONCAT_1(x, y) x##y
#define CONCAT(x, y) CONCAT_1(x, y)
#define defer(expr) auto CONCAT(_defer_, __COUNTER__) = make_defer([&]() {expr;})
uint64_t gen_seed();
void seed_pcg32(pcg32_random_t *rng, uint64_t seed);
#define ARRAY_LEN(x) sizeof(x)/sizeof(x[0])
template <class T>
bool contains(const std::unordered_set<T> &s, const T &e) {
return s.find(e) != s.end();
}
enum class LogLevel {
Critical = 0,
Error,
Warning,
Log,
Debug,
};
extern FILE *log_file;
extern LogLevel log_level;
void init_log(const char *);
const char *log_level_string(LogLevel log_level);
#define LOGL_HELPER(level, fmt, ...) do { \
if (level <= log_level) { \
time_t t = time(nullptr); \
char time_str[80]; \
strftime(time_str, 80, "%F %T", localtime(&t)); \
fprintf(log_file,"[%s]\t %s %s:%d " fmt "%s\n", log_level_string(level), \
time_str, basename((char*)__FILE__), __LINE__, __VA_ARGS__); \
fflush(log_file); \
} \
} while(0)
#define LOGL(...) LOGL_HELPER(__VA_ARGS__, "")
#define CRITICAL(...) LOGL(LogLevel::Critical, __VA_ARGS__)
#define ERROR(...) LOGL(LogLevel::Error, __VA_ARGS__)
#define WARNING(...) LOGL(LogLevel::Warning, __VA_ARGS__)
#define LOG(...) LOGL(LogLevel::Log, __VA_ARGS__)
#define DEBUG(...) LOGL(LogLevel::Debug, __VA_ARGS__)
<file_sep>/external/CMakeLists.txt
set(PCG_DIR pcg-c-0.94)
add_library(pcg-random
${PCG_DIR}/src/pcg-global-32.c
${PCG_DIR}/src/pcg-global-64.c
${PCG_DIR}/src/pcg-rngs-32.c
${PCG_DIR}/src/pcg-advance-8.c
${PCG_DIR}/src/pcg-advance-128.c
${PCG_DIR}/src/pcg-rngs-64.c
${PCG_DIR}/src/pcg-rngs-128.c
${PCG_DIR}/src/pcg-output-64.c
${PCG_DIR}/src/pcg-rngs-8.c
${PCG_DIR}/src/pcg-output-32.c
${PCG_DIR}/src/pcg-advance-32.c
${PCG_DIR}/src/pcg-output-128.c
${PCG_DIR}/src/pcg-advance-64.c
${PCG_DIR}/src/pcg-rngs-16.c
${PCG_DIR}/src/pcg-output-16.c
${PCG_DIR}/src/pcg-output-8.c
${PCG_DIR}/src/pcg-advance-16.c)
target_include_directories(pcg-random PUBLIC ${PCG_DIR}/include)
add_subdirectory(entityX)
<file_sep>/src/main.cpp
#include <assert.h>
#include <thread>
#include <chrono>
#include <string.h>
#include "game.h"
#include "util.h"
#include "path_map.h"
#include "curses_render.h"
using namespace entityx;
enum class MoveType {None, Wait, Step};
struct Move {
MoveType type;
union {
struct {Vector2 step;};
};
};
bool move_mob(const Map &map, Vector2 *mob_pos, const Move &move) {
assert(mob_pos);
if (move.type == MoveType::Step) {
Vector2 new_mob_pos = *mob_pos + move.step;
if (*map.at(new_mob_pos) == Tile::Floor) {
*mob_pos = new_mob_pos;
return true;
}
}
return false;
}
void enemy_gen(Game &game) {
pcg32_random_t mob_gen;
seed_pcg32(&mob_gen, gen_seed());
int floor_count = 0;
for (int i = 0; i < MAP_TILE_COUNT; i++) {
if (*game.map.at(i) == Tile::Floor) {
floor_count++;
}
}
for (int i = 0; i < 50; i++) {
CMob enemy;
enemy.type = MobType::Enemy;
Vector2 pos;
int r = pcg32_boundedrand_r(&mob_gen, floor_count);
int fi = -1;
for (int j = 0; j < MAP_TILE_COUNT; j++) {
if (*game.map.at(j) == Tile::Floor) {
fi++;
}
if (fi == r) {
assert(*game.map.at(j) == Tile::Floor);
pos = index_to_pos(j);
break;
}
}
Entity e = game.ecs.create();
e.assign<CMob>(enemy);
e.assign<CPos>(pos);
}
}
const auto goal_frame_time = std::chrono::milliseconds(16);
int main() {
init_log("rl.log");
WINDOW *win = curses_init_win();
defer(endwin());
if (!win) {
CRITICAL("Could not initialize curses window");
return 1;
}
bool scrolling = true;
bool render_visible = true;
Game game;
cave_map(&game.map);
bool player_view_history[MAP_TILE_COUNT];
memset(player_view_history, false, MAP_TILE_COUNT);
{
CMob mob_player;
Vector2 player_pos;
mob_player.type = MobType::Player;
for (int i = 0; i < MAP_TILE_COUNT; i++) {
if (*game.map.at(i) == Tile::Floor) {
player_pos = index_to_pos(i);
break;
}
}
Entity player = game.ecs.create();
game.add_tag(player, EntityTag::Player);
player.assign<CMob>(mob_player);
player.assign<CPos>(player_pos);
}
enemy_gen(game);
bool redraw = true;
while (true) {
auto start_time = std::chrono::steady_clock::now();
int c = getch();
if (c == 'q') {
break;
}
Move player_move;
player_move.type = MoveType::None;
switch (c) {
case 'r':
cave_map(&game.map);
memset(player_view_history, false, MAP_TILE_COUNT);
redraw = true;
break;
case 'w':
player_move.type = MoveType::Step;
player_move.step = Vector2{0, -1};
break;
case 'a':
player_move.type = MoveType::Step;
player_move.step = Vector2{-1, 0};
break;
case 's':
player_move.type = MoveType::Step;
player_move.step = Vector2{0, 1};
break;
case 'd':
player_move.type = MoveType::Step;
player_move.step = Vector2{1, 0};
break;
case '.':
player_move.type = MoveType::Wait;
break;
case 'v':
if (render_visible) {
render_visible = false;
} else {
render_visible = true;
}
redraw = true;
break;
case 'c':
if (scrolling) {
scrolling = false;
} else {
scrolling = true;
}
redraw = true;
break;
case ' ':
PathMap path_map;
for (int i = 0; i < MAP_TILE_COUNT; i++) {
if (!player_view_history[i]) {
path_map.set_goal(i);
}
}
path_map.smooth(game.map);
int min = PATH_MAP_MAX;
for (const Vector2 &o : ORTHOGONALS) {
Vector2 pos = game.get_tagged(EntityTag::Player).component<CPos>()->pos + o;
if (*path_map.at(pos) < min) {
player_move.type = MoveType::Step;
player_move.step = o;
min = *path_map.at(pos);
}
}
break;
}
Vector2 *player_pos = &game.get_tagged(EntityTag::Player).component<CPos>()->pos;
if (player_move.type == MoveType::Step) {
// Refactor? Should be two steps? See if valid, if so move?
bool successful_move = move_mob(game.map, player_pos, player_move);
if (successful_move) {
redraw = true;
} else {
// If move was invalid (into wall), set player_move to None so enemies do not move
player_move.type = MoveType::None;
}
}
if (player_move.type != MoveType::None) {
PathMap enemy_path_map;
enemy_path_map.set_goal(*player_pos);
enemy_path_map.smooth(game.map);
game.ecs.each<CMob, CPos>([&] (Entity e, CMob &mob, CPos &mob_pos) {
if (mob.type == MobType::Enemy) {
Move enemy_move;
enemy_move.type = MoveType::Wait;
int min = *enemy_path_map.at(mob_pos.pos);
for (const Vector2 &o : ORTHOGONALS) {
Vector2 pos = mob_pos.pos + o;
if (*enemy_path_map.at(pos) < min) {
enemy_move.type = MoveType::Step;
enemy_move.step = o;
min = *enemy_path_map.at(pos);
}
}
move_mob(game.map, &mob_pos.pos, enemy_move);
redraw = true;
}
});
}
if (redraw) {
curses_render(game, player_view_history, scrolling, render_visible);
redraw = false;
}
auto current_time = std::chrono::steady_clock::now();
auto frame_time = current_time - start_time;
auto spare_time = goal_frame_time - frame_time;
if (spare_time < std::chrono::seconds(0)) {
// WARNING("Missed frame time by %ldns", -std::chrono::duration_cast<std::chrono::nanoseconds>(spare_time).count());
} else {
std::this_thread::sleep_for(spare_time);
}
// auto end_time = std::chrono::steady_clock::now();
// LOG("framerate: %f", 1E9 / std::chrono::duration_cast<std::chrono::nanoseconds>(end_time - start_time).count());
}
return 0;
}
<file_sep>/src/curses_render.h
#pragma once
#include <ncurses.h>
#include "game.h"
WINDOW* curses_init_win();
void curses_render(Game &game, bool player_view_history[MAP_TILE_COUNT], bool scrolling, bool render_visible);
<file_sep>/src/vector.h
#pragma once
#include <cstddef>
#include <functional>
struct Vector2 {
int x, y;
inline Vector2 operator+(const Vector2 &v) const {
return {x + v.x, y + v.y};
}
inline Vector2 operator-(const Vector2 &v) const {
return {x - v.x, y - v.y};
}
inline Vector2 operator*(int r) const {
return {x * r, y * r};
}
inline Vector2 operator/(int r) const {
return {x / r, y / r};
}
inline void operator+=(const Vector2 &v) {
(*this) = (*this) + v;
}
inline void operator-=(const Vector2 &v) {
(*this) = (*this) - v;
}
inline bool operator==(const Vector2 &v) const {
return x == v.x && y == v.y;
}
inline bool operator!=(const Vector2 &v) const {
return !((*this) == v);
}
};
template <class T>
inline void hash_combine(std::size_t& seed, const T& v)
{
std::hash<T> hasher;
seed ^= hasher(v) + 0x9e3779b9 + (seed<<6) + (seed>>2);
}
namespace std {
template<>
struct hash<Vector2> {
std::size_t operator()(const Vector2 &v) const {
std::size_t hash = 0;
hash_combine(hash, v.x);
hash_combine(hash, v.y);
return hash;
}
};
}
<file_sep>/CMakeLists.txt
cmake_minimum_required(VERSION 2.8)
# This has to come before the project line
# set(CMAKE_C_COMPILER "clang")
# set(CMAKE_CXX_COMPILER "clang++")
project(rl)
# Enable asserts in release
string(REPLACE "-DNDEBUG" "" CMAKE_CXX_FLAGS_RELEASE "${CMAKE_CXX_FLAGS_RELEASE}")
string(REPLACE "-DNDEBUG" "" CMAKE_CXX_FLAGS_RELWITHDEBINFO "${CMAKE_CXX_FLAGS_RELWITHDEBINFO}")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wall -Wextra -pedantic -ggdb -std=c++11 -fno-exceptions")
# set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -fno-omit-frame-pointer -fsanitize=address -fsanitize=undefined")
# set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -fno-omit-frame-pointer -fsanitize=memory")
# set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${CMAKE_C_FLAGS}")
add_subdirectory(external EXCLUDE_FROM_ALL)
add_subdirectory(src)
<file_sep>/external/pcg-c-0.94/CMakeLists.txt
project(pcg-random)
add_library(pcg-random
src/pcg-global-32.c
src/pcg-global-64.c
src/pcg-rngs-32.c
src/pcg-advance-8.c
src/pcg-advance-128.c
src/pcg-rngs-64.c
src/pcg-rngs-128.c
src/pcg-output-64.c
src/pcg-rngs-8.c
src/pcg-output-32.c
src/pcg-advance-32.c
src/pcg-output-128.c
src/pcg-advance-64.c
src/pcg-rngs-16.c
src/pcg-output-16.c
src/pcg-output-8.c
src/pcg-advance-16.c)
target_include_directories(lib PUBLIC include)
<file_sep>/src/path_map.h
#pragma once
#include "map.h"
#define PATH_MAP_MAX 999999
struct PathMap {
int map[MAP_TILE_COUNT];
PathMap();
int *at(const Vector2 &pos);
const int *at(const Vector2 &pos) const;
int *at(int i);
const int *at(int i) const;
void set_goal(const Vector2 &pos);
void set_goal(int i);
void smooth(const Map &map);
bool operator==(const PathMap &o) const;
bool operator!=(const PathMap &o) const;
};
<file_sep>/todo.txt
* Factor out bresenham line drawing
<file_sep>/src/util.cpp
#include "util.h"
#include <stdio.h>
#include <assert.h>
void seed_pcg32(pcg32_random_t *rng, uint64_t seed) {
pcg32_srandom_r(rng, seed, 0);
}
uint64_t gen_seed() {
uint64_t seed;
int ret = syscall(SYS_getrandom, &seed, sizeof(seed), 0);
assert(ret == sizeof(seed));
return seed;
}
const char *log_level_string(LogLevel log_level) {
const char * log_level_strings[] = {
"CRIT" ,
"ERROR",
"WARN",
"LOG",
"DEBUG",
};
return log_level_strings[static_cast<int>(log_level)];
}
FILE *log_file = nullptr;
LogLevel log_level = LogLevel::Debug;
void init_log(const char *logpath) {
assert(logpath);
log_file = fopen(logpath, "a");
log_level = LogLevel::Debug;
}
<file_sep>/src/game.h
#pragma once
#include "entityx/entityx.h"
#include "util.h"
#include "map.h"
typedef uint32_t EntityID;
enum class EntityTag : int {Player};
enum class MobType {Player, Enemy};
struct CMob {
MobType type;
};
struct CPos {
CPos(Vector2 pos) : pos(pos) {}
Vector2 pos;
};
struct Game {
Game() : ecs(events) {}
std::unordered_map<EntityTag, entityx::Entity> tags;
entityx::EventManager events;
entityx::EntityManager ecs;
Map map;
void add_tag(entityx::Entity e, EntityTag tag) {
if (!tags.insert({tag, e}).second) {
assert(false);
}
}
entityx::Entity get_tagged(EntityTag tag) const {
auto lookup = tags.find(tag);
if (lookup == tags.end()) {
CRITICAL("Could not find entity with given tag");
assert(false);
}
return lookup->second;
}
};
| 83f8e3cdfe554c7ccd8fda30d4e41ae73c0d98b4 | [
"Text",
"C",
"CMake",
"C++"
] | 16 | C++ | hcnelson99/rl | 9988f2ec75a5cebde01f7e4fa401618fc0b0b50e | d05c48f778c36e4e26cd8defb4aa99b6d9963b87 |
refs/heads/main | <repo_name>chakvigs/Project-28-Test<file_sep>/sketch.js
const Engine = Matter.Engine;
const World = Matter.World;
const Bodies = Matter.Bodies;
const Body = Matter.Body;
const Constraint = Matter.Constraint;
function preload() {
boyImage = loadImage("images/boy.png");
}
function setup() {
createCanvas(800, 700);
engine = Engine.create();
world = engine.world;
//Create the Bodies Here.
treeObject = new Tree(575, 467, 200, 400);
groundObject = new Ground(400, 675, 800, 50);
stoneObject = new Stone(100, 500, 50);
mangoObject1 = new Mango(450, 400, 30, 30);
mangoObject2 = new Mango(525, 425, 30, 30);
mangoObject3 = new Mango(575, 325, 30, 30);
mangoObject4 = new Mango(625, 375, 30, 30);
mangoObject5 = new Mango(700, 400, 30, 30);
elasticObject = new Elastic(stoneObject, {x:110, y:510})
Engine.run(engine);
}
function draw() {
rectMode(CENTER);
background(0);
treeObject.display();
groundObject.display();
stoneObject.display();
mangoObject1.display();
mangoObject2.display();
mangoObject3.display();
mangoObject4.display();
mangoObject5.display();
elasticObject.display();
image(boyImage, 100, 475, 150, 250);
drawSprites();
}
function mouseDragged(){
Matter.Body.setPosition(stoneObject.body, {x: mouseX , y: mouseY});
}
function mouseReleased(){
elasticObject.fly();
} | 562ec7bc3c00fe41a5f8d19f0f453d2e92ccef44 | [
"JavaScript"
] | 1 | JavaScript | chakvigs/Project-28-Test | 713b1dbd9dc72a089c0bcac90c1cb79ef2854609 | 9ad1440fb040d466ed2486e55cae3159e8184590 |
refs/heads/master | <file_sep><?php
// Game picks a random number between 1 and 100.
$rand = mt_rand(1, 100);
// Prompt user to guess a number.
fwrite(STDOUT, "Guess a number between 1 and 100?\n");
// Get the input from the user.
$number = fgets(STDIN);
$count = 1;
// Output the user's response.
// If lower than correct response, ask user to guess higher.
while ($number != $rand) {
if ($number < $rand)
{
fwrite(STDOUT, "Guess HIGHER\n");
$number = fgets(STDIN);
}
// If lower than correct response, ask user to guess lower.
elseif ($number > $rand) {
fwrite(STDOUT, "Guess LOWER\n");
$number = fgets(STDIN);
} $count++;
}
// If correct, say, Great job!
fwrite(STDOUT, "Great job! You are awesome!!\n");
fwrite(STDOUT, "It took you $count guesses to get the correct number.\n");
exit(0);
?><file_sep><?php
function validate($num1, $num2) {
if (!is_numeric($num1) || !is_numeric($num2)) {
// echo "ERROR! Both $num1 and $num2 should be numbers." . PHP_EOL;
// var_dump($num1);
// var_dump($num2);
return FALSE;
} else {
return TRUE;
}
}
function add($num1, $num2) {
if (validate($num1, $num2)) {
return $num1 + $num2 . PHP_EOL;
}
}
function subtract($num1, $num2) {
if (validate($num1, $num2)) {
return $num1 - $num2 . PHP_EOL;
}
}
function multiply($num1, $num2) {
if (validate($num1, $num2)) {
return $num1 * $num2 . PHP_EOL;
}
}
function divide($num1, $num2) {
if (validate($num1, $num2)) {
if ($num2 !== 0) {
return $num1 / $num2 . PHP_EOL;
} else {
return FALSE;
}
}
}
function modulus($num1, $num2) {
if (validate($num1, $num2)) {
if ($num2 != 0) {
return $num1 % $num2 . PHP_EOL;
} else {
return false;
}
}
}
$num1 = 30;
$num2 = 12;
echo add($num1, $num2);
echo subtract($num1, $num2);
echo multiply($num1, $num2);
echo divide($num1, $num2);
echo modulus($num1, $num2);
<file_sep><?php
$physicists_string = '<NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>';
$physicists_array = explode(', ', $physicists_string);
echo $physicists_array;
<file_sep><?php
$a = 100;
while ($a > 1) {
$a--;
$b = $a - 1;
echo "$a bottles of beer on the wall, $a bottles of beer. Take one down, pass it around, $b bottles of beer on the wall.\n";
} echo "No more bottles of beer on the wall, no more bottles of beer. Go to the store, buy some more, 99 bottles of beer on the wall.\n";
?><file_sep><?php
$a = 1;
$c = "<PASSWORD>";
echo "\$a outside the function is: $a\n";
function add($a, $b) {
echo "\$a outside the function is: $a\n";
echo "\$c outside the function is: $a\n";
echo ($a + $b) . "\n";
}
add(10, 11);
echo "\$a outside function is : $a\n";
<file_sep><?php
// Expr1 is the initializer, Expr2 is the condition, Expr3 is the implementation.
for ($i = 1; $i <= 100; $i++) {
if ($i % 3 == 0 && $i % 5 == 0){
echo "FIZZBUZZ!\n";
}
elseif ($i % 3 == 0) {
echo "FIZZ!\n";
}
elseif ($i % 5 == 0) {
echo "BUZZ!\n";
}
else {
echo "$i\n";
}
}
echo "\n";
?>
<file_sep><?php
// TRIM EXAMPLE
function get_input($upper = FALSE)
{
if ($upper == TRUE {
return strtoupper(trim(fgets(STDIN)));
} else {
return trim(fgets(STDIN));
}
}
// function get_input($upper = FALSE)
// $input = ($trim(fgets(STDIN)));
// if ($upper) {
// return strtoupper($input);
// } else {
// return $input;
// }
}
// SUM EXAMPLE
function sum($a, $b = 0)
{
return $a + $b;
}
<file_sep><?php
for ($i = 0; $i <= 100; $i+= 2) {
echo "\$i has a value of {$i}\n";
}
// Prompt user for starting number, ending number
// Display all numbers from starting to ending using for loop
// Refactor to allow user to increment (count by 5)
// Default increment to 1 if no input
// Make sure you are only allowing users to pass in numbers
// Give an error message if both arguments are not numeric
<file_sep><?php
$student = 'ahfdflksfjaslfhaslfh';
function is_valid_name($name) {
if (strlen($name) > 1 && <= 50) {
return TRUE;
} else {
return FALSE;
}
}
var_dump(is_valid_name($student));
// Send email
// function add($num1, $num2 = 0) {
// if (is_numeric($num1) && is_numeric($num2)) {
// return $num1 + $num2 . PHP_EOL;
// } else {
// echo " ERROR! Both args should be numbers." . PHP_EOL;
// }
// echo "Done!";
// }
// $result = add(TRUE, 3);
// echo $result . PHP_EOL;
// function trim_with_new_line($item, $newline = TRUE) {
// if ($newline === TRUE) {
// echo trim($item) . PHP_EOL;
// } else {
// echo trim($item);
// }
// }
// trim_with_new_line(' Jason ');<file_sep><?php
function paramarevalid($num1, $num2) {
return (is_numeric($num1) && (is_numeric($num2));
}
// $first = 30;
// $second = 20;
// add($first, $second);
//$sum = (20 + 22) . PHP_EOL;
//$sum2 = (35 + 7) . PHP_EOL;
//echo $sum;
//echo $sum2;
<file_sep><?php
// POP & PUSH for addding to the end of the array
// POP EXAMPLE
// $array = [1,2,3,4,5];
// $popped = array_pop($array);
// var_dump($popped);
// var_dump($array);
// $popped2 = array_pop($array);
// var_dump($array);
// PUSH EXAMPLE
// $items = ['First', 'Second', 'Third'];
// array_push($items, 'Fourth', 'Fifth', 'Sixth');
// print_r($items);
// SHIFT & UNSHIFT for adding to the beginning of the array
<file_sep><?php
// Get new instance of MySQLi object
$mysqli = new mysqli('127.0.0.1', 'codeup', 'password', '<PASSWORD>');
// Retrieve a result set using SELECT
$result = $mysqli->query("SELECT * FROM national_parks");
// // Echo the number of fields
// echo "There are {$result->field_count} fields in the national_parks table." . PHP_EOL;
// // Echo the number of rows
// echo "There are {$result->num_rows} rows in the national_parks table." . PHP_EOL;
// Use print_r() to show rows using MYSQLI_ASSOC
while ($row = $result->fetch_array(MYSQLI_ASSOC)) {
echo($row['name'].PHP_EOL);
}
?><file_sep><?php
$names = ['<NAME>', '<NAME>', '<NAME>', '<NAME>', '<NAME>', '<NAME>', '<NAME>', 'Bob
$Metcalfe', '<NAME>'];
$result = array_search('<NAME>', $names);
var_dump($result);
$result = array_Search('<NAME>', $names);
var_dump($result);
<file_sep><?php
// Converts array into list n1, n2, ..., and n3
function humanized_list($string, $sort = FALSE) {
// Your solution goes here!
$array = explode(', ', $string);
sort($exploded);
$last_item = array_pop($array);
$result = implode(', ', $array) . ", and " . $last_item;
return $result;
}
// List of famous peeps
$physicists_string = '<NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>';
// Humanize that list
$famous_fake_physicists = humanized_list($physicists_string);
// Output sentence
echo $famous_fake_physicists;
// $famous_fake_physicists = implode(', and [final item])', $physicists_string);
// echo $famous_fake_physicists;
// echo "Some of the most famous fictional theoretical physicists are {$famous_fake_physicists}.";
echo "Some of the most famous fictional theoretical physicists are $famous_fake_physicists. " . PHP_EOL;
?><file_sep><?php
$things = array('Sgt. Pepper', "11", null, array(1, 2, 3), 3.14, "12 + 7", false, (string) 11);
foreach ($things as $thing) {
if (is_array($thing)) {
echo "{$thing} is a array\n";
} elseif (is_bool($thing)) {
echo "{$thing} is a bool\n";
} elseif (is_float($thing)) {
echo "{$thing} is a float\n";
} elseif (is_int($thing)) {
echo "{$thing} is an int\n";
}
}
<file_sep><?php
// Create empty array to hold list of todo items
$items = array();
// List array items formatted for CLI
// Return string of list items separated by newlines.
function list_items($list) {
$string = '';
foreach ($list as $key => $value) {
$key++;
$string .= "[{$key}] {$items} . PHP_EOL";
}
return $string;
}
// // Get STDIN, strip whitespace and newlines,
// // and convert to uppercase if $upper is true
function get_input($upper = FALSE) {
$input = (trim(fgets(STDIN)));
return $upper ? strtoupper($input) : $input;
}
// By using the array function explode() and using the newline character as a
// delimiter, we can break the contents by line into array elements.
function read_file($filename) {
$handle = fopen($filename, 'r');
$contents = fread($handle, filesize($filename));
$contents_array = explode("\n", $contents);
fclose($handle);
// Output $contents_array
return $contents_array;
}
function write_file($array) {
$handle = fopen($filename, 'w');
foreach ($array as $item) {
fwrite($handle, PHP_EOL . $item);
}
fclose($handle);
}
function yesOrNo() {
echo 'Are you sure? (Y)es or (N)o? ';
$response = get_input(TRUE);
switch ($response) {
case 'Y':
return TRUE;
break;
default:
echo 'Last action cancelled. ';
break;
}
}
// The loop!
do {
// Echo the list produced by the function
echo list_items($items) . PHP_EOL;
// Show the menu options
echo '(N)ew item, (O)pen item, (R)emove item, (S)ave, (SO)rt, or (Q)uit : ';
// Get the input from user
$input = get_input(TRUE);
switch ($input) {
case 'N':
echo 'Enter item: ';
$addTo = get_input();
echo 'Would you like to add this item to the (B)eginning or the (E)nd of the list? ';
$beg_or_end = get_input();
if ($beg_or_end == 'B') {
array_unshift($items, $addTo);
} else {
array_push($items, $addTo);
}
break;
case 'O':
echo 'Enter the filepath and name. ';
$filename = get_input();
read_file($filename);
break;
case 'R':
echo 'Enter item number to remove: ';
// Get array key
$key = get_input();
$key--;
// Remove from array
unset($items[$key]);
$items = array($items);
echo 'Would you like to remove the (F)irst item or the (L)ast item from the list? ';
if($input == 'F') {
array_shift($items, 'remove first item ');
} else {
array_pop($items, 'remove last item ');
}
break;
// When (S)ave is chosen, the user should be able to enter the path to a file
// to have it save. Use fwrite() with the mode that starts at the beginning of
// a file and removes all the file contents, or creates a new one if it does
// not exist. After save, alert the user the save was successful and redisplay
// the list and main menu.
case 'S':
echo 'Enter the filepath to save to. ';
$filename = get_input();
if(existing_file($filename)); {
echo 'This file already exists. Would you like to overwrite it? ';
$response = yesOrNo();
if($response) {
save_file($items, $filename);
} else {
save_file($items, $filename);
echo "Save was successful.";
}
break;
case 'SO':
echo 'How would you like to sort: (A)-Z, or (Z)-A? ';
$sortBy = get_input();
if ($sortBy == 'A') {
$sort($items);
} else {
rsort($items);
}
break;
}
// Exit when input is (Q)uit
} while ($input != 'Q');
// Say Goodbye!
echo "Goodbye!\n";
// Exit with 0 errors
exit(0);<file_sep><?php
$fruits = array('apple', 'banana', 'orange', 'lime');
foreach ($fruits as $fruit) {
echo ("\$fruits has an element with a value of {$fruit}\n");
}
?>
<?php
$data = array('apple', 'banana', 5, 7 * 6, 88.0);
for each ($data as $item) {
if (is_numeric($item)) {
echo "{$item} is a number\n";
} elseif (is_string($item)) {
echo "{$item} is a string\n";
} else {
echo "{$item} is not a number or string\n";
}
}
?>
<?php
for ($i = 0); $i < count($colors); I++) {
$color = $colors[$i];
echo $color . "\n";
}
}
foreach ($colors as $color) {
echo $color . "\n";
}
<?php
$instructors = array (
array('first_name' => 'Jason', 'last_name => 'Straughan'),
array('first_name' => 'Isaac', 'last_name' => 'Castillo'),
'Ben'
);
foreach ($instructors as $instructor) {
foreach ($instructor as $key => $name) {
if ($key == 'last_name') {
echo "name\n";
}
}
}<file_sep><?php
// first names
$names = ['Tina', 'Dana', 'Mike', "Amy", 'Adam'];
$compare = ['Tina', 'Dean', 'Mel', 'Amy', 'Michael'];
// Create a function that returns TRUE or FALSE if an array value is found.
function searchArrays($value, $array) {
$result = array_search($value, $array);
if ($result === FALSE) {
return FALSE;
}
return TRUE;
}
// Search for Tina and Bob in $names. Tina = yes, Bob = no!
// Create a function to compare 2 arrays that returns the number of values in common between the arrays. Use the 2 example arrays and make sure your solution uses array_search().
// Use foreach to create function.
// foreach $needles as $needles
// return
function count_matches($needles, $haystack){
$number_of_matches = 0;
}
foreach ($needles as $needle) {
result = array_search($needle, $haystack);
if(is_numeric($numeric($result)) {
$number_of_matches++;
}
}
return $number_of_matches;
$names = ['Tina', 'Dana', 'Mike', "Amy", 'Adam'];
$compare = ['Tina', 'Dean', 'Mel', 'Amy', 'Michael'];
echo count_matches($compare, $names);
<file_sep><?php
$nothing = NULL;
$something = '';
$array = array(1,2,3);
// Both NULL and " " are considered EMPTY
// array (1,2,3) is not considered EMPTY
// TEST: If var $nothing is set, display '$nothing is SET'
// function checkvalue($nothing, $something, $array) {
//echo;
// }
if (isset($nothing)) {
echo "$nothing is SET";
// TEST: If var $nothing is empty, display '$nothing is EMPTY'
elseif (empty($nothing)) {
echo "$nothing is EMPTY";
}
// TEST: If var $something is set, display '$something is SET'
if (isset($something)) {
echo "$something is SET";
}
// Serialize the array $array, and output the results
// Unserialize the array $array, and output the results
<file_sep><?php
$nothing = NULL;
$something = '';
$array = array(1,2,3);
// Both NULL and " " are considered EMPTY
// array (1,2,3) is not considered EMPTY
// Create a funciton that checks if a variable is set or empty, and display "$variable_name is SET|EMPTY"
// TEST: If var $nothing is set, display '$nothing is SET'
// function checkvalue($nothing, $something, $array) {
//echo " ";
// }
function setOrEmpty($nothing, $something) {
if (empty($var)) {
echo "$var is EMPTY";
// TEST: If var $nothing is empty, display '$nothing is EMPTY'
} else {
echo "$var is not EMPTY";
}
// TEST: If var $something is set, display '$something is SET'
if (isset($var)) {
echo "$var is SET";
} else {
echo "$var is not SET";
}
}
// call the function
setOrEmpty($nothing);
setOrEmpty($something);
// Correct: if isset && not empty,
// return __
// else
// return __
// Serialize the array $array, and output the results
// $serial = $serialize($array);
// echo "$serialize";
// Correct ^^: var_dump($serial);
// Unserialize the array $array, and output the results
// $unserial = $unserialize($serialize);
// echo "unserialized";
// Correct ^^: var_dump($unserial);
<file_sep><?php
// Exercise 1: Create a do-while loop that will count by 2's starting with 0
// and ending at 100. Follow each number with a newline.
// $a = 0;
// do {
// echo "$a\n";
// $a = $a + 2;
// } while ($a <= 100);
// Exercise 2: Alter your loop to count backwards by 5's from 100 to -10.
// $a = 100;
// do {
// echo "$a\n";
// $a = $a - 5;
// } while ($a >= -10);
// Exercise 3: Create a do-while loop that starts at 2, and returns the result
// $a * $a on each line while $a is less than 1,000,000. Output should equal:
$a = 2;
do {
echo "$a\n";
$a = $a * $a;
} while ($a < 1000000);
<file_sep><?php
$parks = [
['name' => 'Arches',
'location' => 'Utah',
'date' => '1971-11-12',
'area' => '76518.98',
'description' => 'This site features more than 2,000 natural sandstone arches, including the Delicate Arch. In a desert climate millions of years of erosion have led to these structures, and the arid ground has life-sustaining soil crust and potholes, natural water-collecting basins. Other geologic formations are stone columns, spires, fins, and towers.'],
['name' => 'Badlands',
'location' => 'South Dakota',
'date' => '1978-11-10',
'area' => '242755.94',
'description' => 'The Badlands are a collection of buttes, pinnacles, spires, and grass prairies. It has the world\'s richest fossil beds from the Oligocene epoch, and there is wildlife including bison, bighorn sheep, black-footed ferrets, and swift foxes.'],
['name' => '<NAME>',
'location' => 'California',
'date' => '1980-03-05',
'area' => '249561.00',
'description' => 'Five of the eight Channel Islands are protected, and half of the park\'s area is underwater. The islands have a unique Mediterranean ecosystem. They are home to over 2,000 species of land plants and animals, and 145 are unique to them. The islands were originally settled by the Chumash people.'],
['name' => 'Everglades',
'location' => 'Florida',
'date' => '1934-05-30',
'area' => '1508537.90',
'description' => 'The Everglades are the largest subtropical wilderness in the United States. This mangrove ecosystem and marine estuary is home to 36 protected species, including the Florida panther, American crocodile, and West Indian manatee. Some areas have been drained and developed; restoration projects aim to restore the ecology.'],
['name' => '<NAME>',
'location' => 'North Carolina, ' . ' ', ' Tennessee',
'date' => '1934-06-15',
'area' => '521,490.13',
'description' => 'The Great Smoky Mountains, part of the Appalachian Mountains, have a wide range of elevations, making them home to over 400 vertebrate species, 100 tree species, and 5000 plant species. Hiking is the park\'s main attraction, with over 800 miles (1,300 km) of trails, including 70 miles (110 km) of the Appalachian Trail. Other activities are fishing, horseback riding, and visiting some of nearly 80 historic structures.'],
['name' => '<NAME>',
'location' => 'California',
'date' => '1994-10-31',
'area' => '789745.47',
'description' => 'Covering parts of the Colorado and Mojave Deserts and the Little San Bernardino Mountains, this is the home of the Joshua tree. Across great elevation changes are sand dunes, dry lakes, rugged mountains, and granite monoliths.'],
['name' => '<NAME>',
'location' => 'Kentucky',
'date' => '1941-07-01',
'area' => '52830.19',
'description' => 'With 392 miles (631 km) of passageways mapped, Mammoth Cave is by far the world\'s longest cave system. Cave animals include eight bat species, Kentucky cave shrimp, Northern cavefish, and cave salamanders. Above ground, the park contains Green River (Kentucky), 70 miles of hiking trails, sinkholes, and springs.'],
['name' => 'Petrified Forest',
'location' => 'Arizona',
'date' => '1962-12-09',
'area' => '93532.57',
'description' => 'This portion of the Chinle Formation has a great concentration of 225-million-year-old petrified wood. The surrounding region, the Painted Desert, has eroded red-hued volcanic rock called bentonite. There are also dinosaur fossils and over 350 Native American sites.'],
['name' => '<NAME>',
'location' => 'California, ' . ' ', ' Nevada',
'date' => '1994-10-31',
'area' => '3372401.96',
'description' => 'Death Valley is the hottest, lowest, and driest place in the United States. Daytime temperatures have topped 130°F (54°C) and it is home to Badwater Basin, the lowest point in North America. There are canyons, colorful badlands, sand dunes, mountains, and over 1000 species of plants in this graben on a fault line. Further geologic points of interest are salt flats, springs, and buttes.'],
['name' => 'Yellowstone',
'location' => 'Wyoming, ' . ' ', ' Montana, ' . ' ', ' Idaho',
'date' => '1872-03-01',
'area' => '2219790.71',
'description' => 'Situated on the Yellowstone Caldera, the first national park in the world has vast geothermal areas such as hot springs and geysers, the best-known being Old Faithful and Grand Prismatic Spring. The yellow-hued Grand Canyon of the Yellowstone River has numerous waterfalls, and four mountain ranges run through the park. There are almost 60 mammal species, including the gray wolf, grizzly bear, lynx, bison, and elk.'],
];
?> | 6b45eaf31317d3b3e0c2979c4292d17f89c40e38 | [
"PHP"
] | 22 | PHP | mariom1231/codeup_exercises | 1a4b0840bd7a781eb850a2a8531c62d404b949cb | f80cf3925a17e2bd1d6b043773edfb973e9f5775 |
refs/heads/master | <repo_name>d0uph1x/nest_api<file_sep>/src/users/users.service.ts
import { Injectable } from '@nestjs/common';
import { CreateUserDto } from './dto/create-user.dto';
import { User } from './entities/user.entity';
@Injectable()
export class UsersService {
private users: any = [
{ id: 1, name: 'John' },
{ id: 2, name: 'Raymond' },
{ id: 3, name: 'Hassan' },
{ id: 4, name: 'Trackson' },
];
findAll(name?: string): User[] {
if (name) {
return this.users.filter((user) => user.name === name);
}
return this.users;
}
findById(user_id: number): User {
return this.users.find((user) => user.id === user_id);
}
// Create user
createUser = (createUserDto: CreateUserDto): User => {
const newUser = { id: Date.now(), ...createUserDto };
this.users.push(newUser);
return newUser;
};
}
| 89195d2ab216ccf0cae273a6c7e31b86dac7b2e7 | [
"TypeScript"
] | 1 | TypeScript | d0uph1x/nest_api | f70059d22bea2885c887861e5a22c270247cf851 | 79b5ce569e6bd37e1f82ea4e259e93a684072605 |
refs/heads/master | <file_sep><?php
namespace App\Models\Expenses;
use App\Models\User;
use Carbon\Carbon;
use DB;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Query\Builder;
/**
* Class Account
* @package App\Models\Expenses
* @property int user_id
* @property User user
* @property string name
* @property string type
* @property string type_name
* @property Carbon created_at
* @property Carbon updated_at
*/
class Account extends Model
{
protected $table = 'expenses_accounts';
protected $fillable = [ 'user_id', 'name', 'type' ];
protected $dates = ['created_at', 'updated_at'];
protected $appends = ['type_name'];
//
// RELATIONS
//
/**
* @return \Illuminate\Database\Eloquent\Relations\BelongsTo
*/
public function user()
{
return $this->belongsTo(User::class, 'user_id');
}
//
// Attributes
//
public function getTypeNameAttribute()
{
return AccountTypesEnum::get($this->attributes['type']);
}
//
// Scopes
//
/**
* @param Builder $query
* @return Builder $this
*/
public function scopeFilter($query)
{
return $query->select('expenses_accounts.*');
}
/**
* @param Builder $query
* @return Builder $this
*/
public function scopeGroupById($query)
{
return $query->groupBy('expenses_accounts.id');
}
/**
* @param Builder $query
* @param $user_id
* @return Builder $this
*/
public function scopeByUserId($query, $user_id)
{
return $query->where('expenses_accounts.user_id', $user_id);
}
/**
* @param Builder $query
* @return Builder $this
*/
public function scopeIncludeBalance($query)
{
return $query
->addSelect(DB::raw('sum(expenses_account_transactions.amount) as balance'))
->leftJoin('expenses_account_transactions', 'expenses_accounts.id', '=', 'expenses_account_transactions.account_id');
}
}
<file_sep><?php
namespace App\Http\Controllers\Expenses;
use App\Http\Requests\Expenses\CategoryStore;
use App\Models\Expenses\Category;
use App\Models\Expenses\TransactionTypesEnum;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
class CategoryController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
$categoryCollection = Category::byUserId($this->user->id)->orderBy('budget', 'DESC')->get();
$incomeCategoryCollection = $categoryCollection->where('type', TransactionTypesEnum::INCOME);
$expenseCategoryCollection = $categoryCollection->where('type', TransactionTypesEnum::EXPENSE);
$totalBudget = $incomeCategoryCollection->sum('budget') - $expenseCategoryCollection->sum('budget');
return view('pages.expenses.category.index', compact(
'categoryCollection',
'expenseCategoryCollection',
'incomeCategoryCollection',
'totalBudget'));
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
return view('pages.expenses.category.create');
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(CategoryStore $request)
{
$category = Category::create(['user_id' => $this->request->user()->id] + $request->all());
flash()->success("Success!", "Your new category is added.");
return redirect()->to('/expenses/category');
}
/**
* Show the form for editing the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function edit($id)
{
$category = Category::find($id);
return view('pages.expenses.category.create', compact('category'));
}
/**
* Update the specified resource in storage.
*
* @param CategoryStore|Request $request
* @param int $id
* @return \Illuminate\Http\Response
*/
public function update(CategoryStore $request, $id)
{
$category = Category::find($id);
$category->fill($request->only('name', 'budget'));
$category->save();
flash()->success("Success!", "Your category is modified.");
return redirect()->to('/expenses/category');
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroy($id)
{
$category = Category::find($id);
if($category) $category->delete();
return redirect()->back();
}
}
<file_sep><?php
use Illuminate\Foundation\Testing\WithoutMiddleware;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Illuminate\Foundation\Testing\DatabaseTransactions;
class ExpensesAccountControllerTest extends TestCase
{
/** @test */
public function it_shows_the_form_to_create_a_new_account()
{
$this->visit('expenses/account/create')->see('New Account');
}
}<file_sep><?php
namespace App\Models\Expenses;
use Carbon\Carbon;
use Illuminate\Database\Eloquent\Model;
use App\Models\User;
use Illuminate\Database\Eloquent\SoftDeletes;
/**
* Class Category
* @package App\Models\Expenses
* @property int id
* @property int user_id
* @property string type
* @property string type_name
* @property string name
* @property float budget
* @property float budget_formatted
* @property User user
* @property Carbon created_at
* @property Carbon updated_at
* @property Carbon|null deleted_at
*/
class Category extends Model
{
use SoftDeletes;
protected $table = 'expenses_categories';
protected $fillable = [ 'user_id', 'type', 'name', 'budget' ];
protected $dates = ['created_at', 'updated_at', 'deleted_at'];
protected $appends = ['type_name', 'budget_formatted'];
//
// RELATIONS
//
/**
* @return \Illuminate\Database\Eloquent\Relations\BelongsTo
*/
public function user()
{
return $this->belongsTo(User::class, 'user_id');
}
//
// ATTRIBUTES
//
public function getTypeNameAttribute()
{
return TransactionTypesEnum::get($this->attributes['type']);
}
public function getBudgetFormattedAttribute()
{
return empty($this->attributes['budget']) ? '' : '$ ' . money_format('%.2n', $this->attributes['budget']);
}
//
// SCOPES
//
public function scopeByUserId($query, $userId)
{
return $query->where('expenses_categories.user_id', $userId);
}
public function scopeByType($query, $type)
{
$func = is_array($type) ? 'whereIn' : 'where';
return $query->$func('expenses_categories.type', $type);
}
}
<file_sep><?php
Route::get('/', 'HomeController@index');
Route::get('/home', 'HomeController@index');
Route::auth();
Route::group(['middleware' => 'auth'], function(){
Route::group(['prefix' => 'expenses', 'namespace' => 'Expenses'], function(){
Route::get('/', 'HomeController@index');
Route::resource('account', 'AccountController');
Route::resource('category', 'CategoryController', [ 'except' => ['show'] ]);
Route::resource('transactions/income', 'IncomeTransactionController');
Route::resource('transactions/expense', 'ExpenseTransactionController');
});
});
<file_sep><?php
namespace App\Models\Expenses;
class TransactionTypesEnum
{
const EXPENSE = 'expense';
const INCOME = 'income';
const TRANSFER = 'transfer';
protected static $enum = [
self::EXPENSE => 'Expense',
self::INCOME => 'Income',
self::TRANSFER => 'Transfer'
];
/**
* @param string $key
* @param mixed $default
* @return mixed
*/
public static function get($key, $default = null)
{
return array_get(self::$enum, $key, $default);
}
/**
* @return array
*/
public static function getAll()
{
return self::$enum;
}
/**
* @return array
*/
public static function getKeys()
{
return array_keys(self::$enum);
}
}<file_sep><?php
namespace App\Models\Expenses;
class AccountTypesEnum
{
const CHECKINGS = 'check';
const SAVINGS = 'savings';
const CREDIT = 'credit';
const CASH = 'cash';
protected static $enum = [
self::CHECKINGS => 'Checkings',
self::SAVINGS => 'Savings',
self:: CREDIT => 'Credit',
self::CASH => 'Cash',
];
/**
* @param $key
* @param $default
* @return mixed
*/
public static function get($key, $default = null)
{
return array_get(self::$enum, $key, $default);
}
/**
* @return array
*/
public static function getAll()
{
return self::$enum;
}
/**
* @return array
*/
public static function getKeys()
{
return array_keys(self::$enum);
}
}<file_sep><?php
function flash($title = null, $message = null)
{
$flash = app(\App\Http\Flash::class);
if(func_num_args() == 0)
return $flash;
return $flash->info($title, $message);
}
function url_match($link, $url = null)
{
if(is_null($url)) $url = url()->current();
$queryStart = strpos($url, '?');
if($queryStart !== false)
$url = substr($url, 0, $queryStart);
return ends_with($url, $link);
}
function formatToMoney($value)
{
return '$ ' . money_format('%.2n', $value);
}<file_sep><?php
namespace App\Repositories\Expenses;
use App\Models\Expenses\Account;
use App\Models\User;
class AccountsRepository
{
public function getAccounts(User $user)
{
return Account::filter()
->byUserId($user->id)
->includeBalance()
->groupById()
->get();
}
/**
* @param User $user
* @param $params
* @return Account
*/
public function createAccount(User $user, $params)
{
$params['user_id'] = $user->id;
return Account::create($params);
}
public function deleteAccount(User $user, $accountId)
{
$account = Account::byUserId($user->id)->where('id', $accountId)->first();
if($account) $account->delete();
}
}<file_sep><?php
$factory->define(App\Models\User::class, function (Faker\Generator $faker) {
return [
'name' => $faker->name,
'email' => $faker->safeEmail,
'password' => <PASSWORD>('<PASSWORD>'),
'remember_token' => str_random(10),
];
});
//
// EXPENSES
//
$factory->define(App\Models\Expenses\Account::class, function (Faker\Generator $faker) {
return [
'name' => $faker->word,
'type' => $faker->randomElement(\App\Models\Expenses\AccountTypesEnum::getKeys()),
];
});
$factory->define(App\Models\Expenses\Category::class, function (Faker\Generator $faker) {
return [
'name' => $faker->word,
'type' => $faker->randomElement(\App\Models\Expenses\TransactionTypesEnum::getKeys()),
'budget' => $faker->randomFloat(),
];
});
$factory->define(App\Models\Expenses\Transaction::class, function (Faker\Generator $faker) {
return [
'description' => $faker->word,
'type' => $faker->randomElement(\App\Models\Expenses\TransactionTypesEnum::getKeys()),
'amount' => $faker->randomFloat(null, null),
'at' => $faker->dateTimeBetween('-3 months', 'now'),
];
});
<file_sep><?php
namespace App\Models\Expenses;
use App\Models\User;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\Model;
use Carbon\Carbon;
/**
* Class Transaction
* @package App\Models\Expenses
* @property int id
* @property int user_id
* @property string type
* @property string type_name
* @property int category_id
* @property string description
* @property float amount
* @property Carbon at
* @property int created_at
* @property int updated_at
*
* @property Category category
* @property User user
* @property Collection accounts
*/
class Transaction extends Model
{
protected $table = 'expenses_transactions';
protected $fillable = [
'user_id',
'type',
'category_id',
'description',
'amount',
'at'
];
protected $dates = ['at', 'created_at', 'updated_at'];
protected $appends = ['type_name', 'amount_formatted'];
/**
* @return Account|null
*/
public function getFirstAccount()
{
return (count($this->accounts) > 0) ? $this->accounts->first() : null;
}
//
// RELATIONS
//
/**
* @return \Illuminate\Database\Eloquent\Relations\BelongsTo
*/
public function category()
{
return $this->belongsTo(Category::class, 'category_id');
}
/**
* @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
*/
public function accounts()
{
return $this->belongsToMany(Account::class, 'expenses_account_transactions', 'transaction_id', 'account_id');
}
/**
* @return \Illuminate\Database\Eloquent\Relations\BelongsTo
*/
public function user()
{
return $this->belongsTo(User::class, 'user_id');
}
//
// ATTRIBUTES
//
public function getTypeNameAttribute()
{
return TransactionTypesEnum::get($this->attributes['type']);
}
public function getAmountFormattedAttribute()
{
$multiplier = 1;
if($this->type == TransactionTypesEnum::EXPENSE) $multiplier = -1;
if($this->type == TransactionTypesEnum::TRANSFER) $multiplier = 0;
$amount = array_get($this->attributes, 'amount', 0) * $multiplier;
return formatToMoney($amount);
}
//
// SCOPES
//
/**
* @param Builder $query
* @param $type
* @return Builder
*/
public function scopeByType($query, $type)
{
$where = (is_array($type)) ? 'whereIn' : 'where';
return $query->$where('expenses_transactions.type', $type);
}
/**
* @param Builder $query
* @param Carbon|null $at
* @return Builder
*/
public function scopeByMonth($query, Carbon $at = null)
{
if(empty($at)) $at = new Carbon();
$end = clone $at;
$at->startOfMonth();
$end->endOfMonth();
return $query->whereBetween('expenses_transactions.at', [$at, $end]);
}
/**
* @param Builder $query
* @return Builder
*/
public function scopeDefaultOrder($query)
{
return $query->orderBy('at', 'DESC');
}
}
<file_sep><?php
namespace App\Http\Controllers\Expenses;
use App\Http\Requests\Expenses\ExpenseTransactionStore;
use App\Models\Expenses\Account;
use App\Models\Expenses\Category;
use App\Models\Expenses\Transaction;
use App\Models\Expenses\TransactionTypesEnum;
use App\Repositories\Expenses\TransactionsRepository;
use Carbon\Carbon;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
class ExpenseTransactionController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
$at = new Carbon($this->request->get('at'));
$transactionCollection = Transaction::with('category')
->byType(TransactionTypesEnum::EXPENSE)
->byMonth($at)
->get();
return view('pages.expenses.transaction.expense.index', compact('transactionCollection', 'at'));
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
$categoryList = Category::byType(TransactionTypesEnum::EXPENSE)
->orderBy('name')
->get()
->lists('name', 'id');
$accountList = Account::orderBy('name')
->get()
->lists('name', 'id');
return view('pages.expenses.transaction.expense.create', compact('categoryList', 'accountList'));
}
/**
* Store a newly created resource in storage.
*
* @param ExpenseTransactionStore|Request $request
* @param TransactionsRepository $transactionsRepository
* @return \Illuminate\Http\Response
*/
public function store(ExpenseTransactionStore $request, TransactionsRepository $transactionsRepository)
{
$transactionsRepository->createExpense(
$this->user,
new Carbon($request->get('at')),
Category::find($request->get('category_id')),
Account::find($request->get('account_id')),
$request->get('description'),
$request->get('amount'));
return redirect()->refresh();
}
/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function show($id)
{
//
}
/**
* Show the form for editing the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function edit($id)
{
//
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param int $id
* @return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
//
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroy($id)
{
//
}
}
<file_sep><?php
namespace App\Models;
use App\Models\Expenses\Account;
use App\Models\Expenses\Category;
use App\Models\Expenses\Transaction;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Foundation\Auth\User as Authenticatable;
/**
* Class User
* @package App\Models
* @property int id
* @property string name
* @property string email
* @property string password
* @property Collection expensesAccounts
* @property Collection expensesCategories
* @property Collection expensesTransactions
*/
class User extends Authenticatable
{
protected $fillable = ['name', 'email', 'password'];
protected $hidden = ['password', 'remember_token'];
protected $dates = ['created_at', 'updated_at'];
//
// RELATIONS
//
/**
* @return \Illuminate\Database\Eloquent\Relations\HasMany
*/
public function expensesAccounts()
{
return $this->hasMany(Account::class, 'user_id');
}
/**
* @return \Illuminate\Database\Eloquent\Relations\HasMany
*/
public function expensesCategories()
{
return $this->hasMany(Category::class, 'user_id');
}
/**
* @return \Illuminate\Database\Eloquent\Relations\HasMany
*/
public function expensesTransactions()
{
return $this->hasMany(Transaction::class, 'user_id');
}
}
<file_sep><?php
namespace App\Http\Controllers\Expenses;
use App\Models\Expenses\Account;
use App\Repositories\Expenses\AccountsRepository;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
class AccountController extends Controller
{
/** @var AccountsRepository */
protected $accountsRepository;
public function __construct(Request $request, AccountsRepository $accountsRepository)
{
parent::__construct($request);
$this->accountsRepository = $accountsRepository;
}
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
$accountCollection = $this->accountsRepository->getAccounts($this->user);
return view('pages.expenses.account.index', compact('accountCollection'));
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
return view('pages.expenses.account.create');
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Requests\Expenses\CreateAccount $request)
{
$account = $this->accountsRepository->createAccount($this->user, $request->all());
flash()->success("Success!", "Your new {$account->type_name} account {$account->name} is added.");
return redirect()->to('/expenses/account/');
}
/**
* Show the form for editing the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function edit($id)
{
//
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param int $id
* @return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
//
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroy($id)
{
$this->accountsRepository->deleteAccount($this->user, $id);
return redirect()->back();
}
}
<file_sep><?php
namespace App\Http\Requests\Expenses;
use App\Http\Requests\Request;
use App\Models\Expenses\TransactionTypesEnum;
use Auth;
class ExpenseTransactionStore extends Request
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
$user = Auth::user();
$type = TransactionTypesEnum::EXPENSE;
return [
'at' => "required|date",
'category_id' => "required|exists:expenses_categories,id,user_id,{$user->id},type,{$type}",
'account_id' => "required|exists:expenses_accounts,id,user_id,{$user->id}",
'amount' => "required|numeric",
'description' => "present",
];
}
}
<file_sep><?php
namespace App\Http\Controllers\Expenses;
use App\Http\Controllers\Controller;
class HomeController extends Controller
{
public function index()
{
return view('pages.expenses.home');
}
}<file_sep><?php
namespace App\Repositories\Expenses;
use App\Models\Expenses\Account;
use App\Models\Expenses\Category;
use App\Models\Expenses\Transaction;
use App\Models\Expenses\TransactionTypesEnum;
use App\Models\User;
use Carbon\Carbon;
class TransactionsRepository
{
protected function createTransaction(User $user, Carbon $at, $type, Category $category, $description, $amount)
{
$transaction = Transaction::create([
'user_id' => $user->id,
'type' => $type,
'category_id' => $category->id,
'description' => $description,
'amount' => $amount,
'at' => $at,
]);
return $transaction;
}
public function createIncome(User $user, Carbon $at, Category $category, Account $account, $description, $amount)
{
$transaction = $this->createTransaction($user, $at, TransactionTypesEnum::INCOME, $category, $description, $amount);
$transaction->accounts()->save($account, [ 'amount' => $amount ]);
return $transaction;
}
public function createExpense(User $user, Carbon $at, Category $category, Account $account, $description, $amount)
{
$amount *= -1;
$transaction = $this->createTransaction($user, $at, TransactionTypesEnum::EXPENSE, $category, $description, $amount);
$transaction->accounts()->save($account, [ 'amount' => $amount ]);
return $transaction;
}
} | bd37bbdef7a14f20aa4916ff9c67704e28415bb0 | [
"PHP"
] | 17 | PHP | mmoreno509/guardian | bc35d9cc92e5d5597969dacd6eb0cf6b47b2fc6b | d01c807d88b2cf0e75ec0ea30c09a8a25d9626ac |
refs/heads/master | <file_sep>HR@orcl> CREATE TABLE my_employee
2 (id NUMBER(4) CONSTRAINT my_employee_id_nn NOT NULL,
3 last_name VARCHAR2(25),
4 first_name VARCHAR2(25),
5 userid VARCHAR2(8),
6 salary NUMBER(9,2));
Table created.
HR@orcl> DESCRIBE my_employee
Name Null? Type
----------------------------------------------------------------- -------- --------------------------------------------
ID NOT NULL NUMBER(4)
LAST_NAME VARCHAR2(25)
FIRST_NAME VARCHAR2(25)
USERID VARCHAR2(8)
SALARY NUMBER(9,2)
HR@orcl> INSERT INTO my_employee
2 values(1,'Patel','Ralph','rpatel',895);
1 row created.
HR@orcl> INSERT INTO my_employee (id, last_name, first_name, userid,salary)
2* VALUES (2, 'Dancs','Betty','bdancs',860)
HR@orcl> /
1 row created.
HR@orcl> select * from my_employee;
ID LAST_NAME FIRST_NAME USERID SALARY
---------- ------------------------- ------------------------- -------- ----------
1 Patel Ralph rpatel 895
2 Dancs Betty bdancs 860
HR@orcl> ed loademp.sql
HR@orcl> @loademp.sql
HR@orcl> SET ECHO OFF
Enter value for p_id: 3
Enter value for p_last_name: Biri
Enter value for p_frist_name: Ben
Enter value for p_first_name: Ben
Enter value for p_last_name: Biri
Enter value for p_salary: 1100
1 row created.
HR@orcl> @loademp.sql
HR@orcl> SET ECHO OFF
Enter value for p_id: 4
Enter value for p_last_name: Newman
Enter value for p_frist_name: Chad
Enter value for p_first_name: Chad
Enter value for p_last_name: Newman
Enter value for p_salary: 750
1 row created.
HR@orcl> select * from my_employee;
ID LAST_NAME FIRST_NAME USERID SALARY
---------- ------------------------- ------------------------- -------- ----------
1 Patel Ralph rpatel 895
2 Dancs Betty bdancs 860
3 Biri Ben bbiri 1100
4 Newman Chad cnewman 750
HR@orcl> commit;
Commit complete.
HR@orcl> update my_employee
2 set last_name = 'Drexler'
3 where id = 3;
1 row updated.
HR@orcl> update my_employee
2 set salary = 1000
3* where salary < 900
HR@orcl> /
3 rows updated.
HR@orcl> select last_name, salary from my_employee;
LAST_NAME SALARY
------------------------- ----------
Patel 1000
Dancs 1000
Drexler 1100
Newman 1000
HR@orcl> delete from my_employee
2 where last_name = 'Dancs';
1 row deleted.
HR@orcl> select * from my_employee;
ID LAST_NAME FIRST_NAME USERID SALARY
---------- ------------------------- ------------------------- -------- ----------
1 Patel Ralph rpatel 1000
3 Drexler Ben bbiri 1100
4 Newman Chad cnewman 1000
HR@orcl> commit;
Commit complete.
HR@orcl> @loademp.sql
HR@orcl> SET ECHO OFF
Enter value for p_id: 5
Enter value for p_last_name: Ropeburn
Enter value for p_frist_name: Audery
Enter value for p_first_name: Audery
Enter value for p_last_name: Ropeburn
Enter value for p_salary: 1550
1 row created.
HR@orcl> select * from my_employee;
ID LAST_NAME FIRST_NAME USERID SALARY
---------- ------------------------- ------------------------- -------- ----------
1 Patel Ralph rpatel 1000
3 Drexler Ben bbiri 1100
4 Newman Chad cnewman 1000
5 Ropeburn Audery aropebur 1550
HR@orcl> savepoint step_16;
Savepoint created.
HR@orcl> delete from my_employee;
4 rows deleted.
HR@orcl> select * from my_employee;
no rows selected
HR@orcl> rollback TO step_16;
Rollback complete.
HR@orcl> select * from my_employee;
ID LAST_NAME FIRST_NAME USERID SALARY
---------- ------------------------- ------------------------- -------- ----------
1 Patel Ralph rpatel 1000
3 Drexler Ben bbiri 1100
4 Newman Chad cnewman 1000
5 Ropeburn Audery aropebur 1550
HR@orcl> commit;
Commit complete.
HR@orcl> spool off
| 3ec4c6867efc9dee97b4f0d8ced87d256ca2661a | [
"SQL"
] | 1 | SQL | knm98989/slq3 | 1fe6b1a2429e6670022a592870a84c75d94654b4 | 6a0391971d19edf7f3c0f23124d9412301d2bf9f |
refs/heads/master | <repo_name>xiaobeiHan/vue<file_sep>/mynode/mynode.js
const express = require('express');
const app = express();
const mysql = require('mysql');
const conn = mysql.createConnection({
host: 'localhost', //数据库地址
user: 'root', //账号
password: '<PASSWORD>!', //密码
database: 'mytest', //库名
multipleStatements: true //允许执行多条语句
});
//查询出所有数据
app.get('/api/createTable', (req, res) => {
const sqlStr = 'create table my_test2 (id varchar(10));'
conn.query(sqlStr, (err, results) => {
if (err) return res.json({
err_code: 1,
message: '创建失败',
affextedRows: 0
})
res.json({
err_code: 200,
message: '创建成功'
})
})
});
app.get('/api/dropTable', (req, res) => {
const sqlStr = 'drop table my_test2;'
conn.query(sqlStr, (err, results) => {
if (err) return res.json({
err_code: 1,
message: '创建失败',
affextedRows: 0
})
res.json({
err_code: 200,
message: '创建成功'
})
})
});
app.listen(3000, () => {
console.log('正在监听端口3000,http://192.168.3.11:3000');
}) | ce3c2361237751c86310c886dd8b95cf0ff28ad0 | [
"JavaScript"
] | 1 | JavaScript | xiaobeiHan/vue | 127dfe6fabccf374491bf0e8f48c421d71ad87fc | 75957d42b6fc6e46eb01401df799dde418217bbc |
refs/heads/master | <file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Observer.Interfaces
{
interface ISubject
{
void Adicionar(IObserver observer);
void Remover(IObserver observer);
void Notificar(string mensagem);
}
}
<file_sep>using Observer.Interfaces;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Observer.Implementacao
{
class MonitorMercado : ISubject
{
List<IObserver> observadores;
string Mensagem;
string Ativo;
public MonitorMercado(string ativo)
{
Ativo = ativo;
observadores = new List<IObserver>();
}
public void Adicionar(IObserver observer)
{
observadores.Add(observer);
}
public void Notificar(string mensagem)
{
foreach (var observador in observadores)
{
observador.Update(string.Format("{0} - {1}", Ativo,mensagem));
}
}
public void Remover(IObserver observer)
{
observadores.Remove(observer);
}
}
}
<file_sep>using Observer.Implementacao;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace Observer
{
class Program
{
static void Main(string[] args)
{
int valor = 0;
Random random = new Random();
var monitor = new MonitorMercado("PETR4");
monitor.Adicionar(new MensageiroSlack());
monitor.Adicionar(new MensageiroEmail());
monitor.Adicionar(new MensageiroVoz());
Console.WriteLine("**Monitor de PETR4**");
Console.WriteLine("**UTILIZANDO NUMEROS ALEATORIOS - SE O VALOR DA AÇÃO FOR MAIOR QUE 95 O SERVIDOR CAI - **");
Console.ReadKey();
for (int i =0; i< 100; i++)
{
int valorNovo = random.Next(0, 100);
Console.WriteLine("Valor Anterior= " + valor);
Console.WriteLine("Valor Atual= " + valorNovo);
if (valorNovo >= 96)
{
monitor.Notificar("SERVIDOR CAIU !!");
break;
}
if (valorNovo > valor)
monitor.Notificar("Valorizou");
else
monitor.Notificar("Desvalorizou");
valor = valorNovo;
Console.WriteLine();
Thread.Sleep(1500);
}
Console.ReadKey();
}
}
}
<file_sep>using Observer.Interfaces;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Observer.Implementacao
{
class MensageiroVoz : IObserver
{
public void Update(string message)
{
Console.WriteLine("NOTIFICACÇÃO VOZ -- " + message);
}
}
}
| dff7861b2b7c0b64d7abd9c1a75604d2235ec09b | [
"C#"
] | 4 | C# | FelipeUsuk/Observer | 2d047919d0fa02910d09a20f07bed239c639acc8 | a023c485ff5a392a3cb403b1947b34beb67b1203 |
refs/heads/master | <file_sep>let paused=true;
let animateButton=document.querySelector('#animateButton');
let ctx=document.querySelector('canvas').getContext('2d');
let dics=[
{
x:40,
y:50,
radius:25,
velocityX:2.5,
velocityY:3.5,
color:'blue'
},
{
x:50,
y:40,
radius:25,
velocityX:2,
velocityY:-1.5,
color:'orange'
},
{
x:100,
y:100,
radius:25,
velocityX:-4.5,
velocityY:-4.5,
color:'red'
}
];
let numDics=dics.length;
function drawBackground(){
let {height,width}=ctx.canvas;
let y=height,step=12;
ctx.strokeStyle = 'lightgray';
ctx.lineWidth = 0.5;
while(y>=step*4){
ctx.beginPath();
ctx.moveTo(0,y);
ctx.lineTo(width,y);
ctx.stroke();
y-=step;
}
}
function update(){
const {width,height}=ctx.canvas;
for(let dic of dics){
const {x,y,radius,velocityX,velocityY}=dic;
if(x+velocityX+radius>width||x+velocityX-radius<0){
dic.velocityX=-velocityX;
}
if(y+velocityY+radius>height||y+velocityY-radius<0){
dic.velocityY=-velocityY;
}
dic.x=dic.velocityX+x;
dic.y=dic.velocityY+y;
}
}
function drawDics(){
for(let dic of dics){
const {x,y,radius,color}=dic;
ctx.save();
ctx.beginPath();
ctx.strokeStyle=color;
ctx.arc(x,y,radius,0,2*Math.PI,false);
ctx.stroke();
ctx.restore();
}
}
function animate(){
if(!paused){
const {width,height}=ctx.canvas;
ctx.clearRect(0,0,width,height);
drawBackground();
update();
drawDics();
requestAnimationFrame(animate);
}
}
animateButton.addEventListener('click',function(){
paused=!paused;
if(paused){
animateButton.textContent='animate';
} else {
animateButton.textContent='pause';
requestAnimationFrame(animate);
}
}) | 401c34dd4dbec8e3cda3826567e6e4ab740c2802 | [
"JavaScript"
] | 1 | JavaScript | iamzay/Exercise | c2801dac83b05e4053766cbc20502a7c78740426 | bc3e9aab7eb8dd658364e4c6ff673306fb4ec709 |
refs/heads/master | <repo_name>jrfarah/simple_text_editor<file_sep>/README.md
this is a very simple text editor framework in python. This uses Tkinter, so to use it just add a function and then add the button. This does (as of now) have some bugs.
<file_sep>/text_editor_framework_final.py
from Tkinter import *
import sys
import os
import tkMessageBox
import error_mes
import subprocess
main = Tk()
#Variables that are globally needed
file_input = "" #whats put into the text box
_FILE_= "" #File the user wants to open; readapt to be synonymous with save?
open_a_file = "" #will be the entry field for opening a file
target = ""
new_file_ = ""
new_file_name = ""
isnewfile = "no"
def get_from_text():
global file_input
try:
file_input = my_text_box.get("1.0", END)
print file_input
except:
file_input = 'UHOH'
print file_input
def save(): #This function can definitely be improved
global file_input, target, _FILE_, my_text_box, new_file_name
try:
file_input = my_text_box.get("1.0", END)
target = open(_FILE_, "r+w")
target.truncate()
target.write(file_input)
except:
file_input = my_text_box.get("1.0", END)
target = open(new_file_name, "r+w")
target.truncate()
target.write(file_input)
def exit_application():
sys.exit(0)
def menu_open_file():
global _FILE_, open_a_file, save, my_text_box
try:
open_a_file = Entry()
open_a_file.grid(row = 3, column = 0)
open_a_file.insert(0, "Path to File to Open")
#save.grid_forget()
Button(main, text = "Click to Open", command = get_file).grid(row = 4,
column = 0)
except:
error_mes.error()
def get_file():
global _FILE_, open_a_file, my_text_box
try:
_FILE_ = open_a_file.get()
target = open(_FILE_, "r+w")
opened_file = target.read()
try:
my_text_box.insert(INSERT, opened_file)
except:
error_mes.error()
except:
error_mes.error()
def new_file():
global new_file_, my_text_box
my_text_box.delete("1.0", END)
try:
new_file_ = Entry()
new_file_.grid(row = 3, column = 0)
save_button = Button(main, text = "Click to Save", command = save_new_file)
save_button.grid(row = 4, column = 0)
except:
error_mes.error()
def save_new_file():
global new_file_, new_file_name, my_text_box, target
new_file_name = new_file_.get()
target = open(new_file_name, "w")
target.write(my_text_box.get("1.0", END))
def add_date():
global my_text_box
date = subprocess.check_output('date', shell = True)
my_text_box.insert(INSERT, date)
def diary_preset():
error_mes.error()
def c_preset():
global my_text_box, target
c_preset_text = open("/home/vhx/Documents/code/python/tkinter/text_editor/c_preset.txt").read()
my_text_box.insert(INSERT, c_preset_text)
Button(main, text = "Compile", command = compile_c).grid(row = 0, column = 0)
def compile_c():
global open_a_file
os.system("cc " + open_a_file + "; ./a.out")
my_text_box = Text(main, bg = "black", fg = "white", insertbackground = "white",
tabs = ("1c"))
my_text_box.grid(row = 0, column = 0)
#The Menu
menu = Menu(main)
menu2 = Menu(main)
main.config(menu = menu)
filemenu = Menu(menu)
menu.add_cascade(label = "File", menu = filemenu)
filemenu.add_command(label = "New...", command = new_file)
filemenu.add_command(label = "Open...", command = menu_open_file)
filemenu.add_command(label = "Save", command = save)
filemenu.add_command(label = "Add Date", command = add_date)
filemenu.add_command(label = "C Preset", command = c_preset)
filemenu.add_separator()
filemenu.add_command(label = "Exit", command = exit_application)
main.mainloop() | cb77e61c975cb59a63ae8bdddd42ad8532fb4026 | [
"Markdown",
"Python"
] | 2 | Markdown | jrfarah/simple_text_editor | d8d5ea82aca1e3f911565a12fcdd157550721f29 | 82650b10d5d2bea76127d6d1bbad111311db4614 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.