file_name large_stringlengths 4 140 | prefix large_stringlengths 0 39k | suffix large_stringlengths 0 36.1k | middle large_stringlengths 0 29.4k | fim_type large_stringclasses 4
values |
|---|---|---|---|---|
did.rs | #[cfg(feature = "alloc")]
use alloc::string::String;
#[cfg(feature = "alloc")]
use alloc::string::ToString as _;
use core::cmp::Ordering;
use core::convert::TryFrom;
use core::fmt::Debug;
use core::fmt::Display;
use core::fmt::Formatter;
use core::fmt::Result as FmtResult;
use core::hash::Hash;
use core::hash::Hasher;
use core::str::FromStr;
use crate::core::Core;
use crate::error::Error;
use crate::error::Result;
#[derive(Clone, Copy)]
pub struct Inspect<'a>(&'a DID);
impl Debug for Inspect<'_> {
fn fmt(&self, f: &mut Formatter) -> FmtResult {
f.debug_struct("DID")
.field("method", &self.0.method())
.field("method_id", &self.0.method_id())
.field("path", &self.0.path())
.field("query", &self.0.query())
.field("fragment", &self.0.fragment())
.finish()
}
}
/// A Decentralized Identifier (DID).
///
/// [More Info (W3C DID Core)](https://www.w3.org/TR/did-core/)
#[derive(Clone)]
#[cfg_attr(feature = "serde", derive(Deserialize, Serialize))]
#[cfg_attr(feature = "serde", serde(into = "String", try_from = "String"))]
pub struct DID {
data: String,
core: Core,
}
impl DID {
/// The URL scheme for Decentralized Identifiers.
pub const SCHEME: &'static str = "did";
/// Parses a [`DID`] from the provided `input`.
///
/// # Errors
///
/// Returns `Err` if any DID segments are invalid.
pub fn parse(input: impl AsRef<str>) -> Result<Self> {
Ok(Self {
data: input.as_ref().to_string(),
core: Core::parse(input)?,
})
}
/// Returns a wrapped `DID` with a more detailed `Debug` implementation.
#[inline]
pub const fn inspect(&self) -> Inspect {
Inspect(self)
}
/// Returns the serialized [`DID`].
///
/// This is fast since the serialized value is stored in the [`DID`].
#[inline]
pub fn as_str(&self) -> &str {
&*self.data
}
/// Consumes the [`DID`] and returns the serialization.
#[cfg(feature = "alloc")]
#[inline]
pub fn into_string(self) -> String {
self.data
}
/// Returns the [`DID`] scheme. See [`DID::SCHEME`].
#[inline]
pub const fn scheme(&self) -> &'static str {
DID::SCHEME
}
/// Returns the [`DID`] authority.
#[inline]
pub fn authority(&self) -> &str {
self.core.authority(self.as_str())
}
/// Returns the [`DID`] method name.
#[inline]
pub fn method(&self) -> &str {
self.core.method(self.as_str())
}
/// Returns the [`DID`] method-specific ID.
#[inline]
pub fn method_id(&self) -> &str {
self.core.method_id(self.as_str())
}
/// Returns the [`DID`] path.
#[inline]
pub fn path(&self) -> &str {
self.core.path(self.as_str())
}
/// Returns the [`DID`] method query, if any.
#[inline]
pub fn query(&self) -> Option<&str> {
self.core.query(self.as_str())
}
/// Returns the [`DID`] method fragment, if any.
#[inline]
pub fn fragment(&self) -> Option<&str> {
self.core.fragment(self.as_str())
}
/// Parses the [`DID`] query and returns an iterator of (key, value) pairs.
#[inline]
pub fn query_pairs(&self) -> form_urlencoded::Parse {
self.core.query_pairs(self.as_str())
}
/// Change the method of the [`DID`].
#[inline]
pub fn set_method(&mut self, value: impl AsRef<str>) {
self.core.set_method(&mut self.data, value.as_ref());
}
/// Change the method-specific-id of the [`DID`].
#[inline]
pub fn set_method_id(&mut self, value: impl AsRef<str>) {
self.core.set_method_id(&mut self.data, value.as_ref());
}
/// Change the path of the [`DID`].
#[inline]
pub fn set_path(&mut self, value: impl AsRef<str>) {
self.core.set_path(&mut self.data, value.as_ref());
}
/// Change the query of the [`DID`].
///
/// No serialization is performed.
#[inline]
pub fn set_query(&mut self, value: Option<&str>) {
self.core.set_query(&mut self.data, value);
}
/// Change the fragment of the [`DID`].
///
/// No serialization is performed.
#[inline]
pub fn set_fragment(&mut self, value: Option<&str>) {
self.core.set_fragment(&mut self.data, value);
}
/// Creates a new [`DID`] by joining `self` with the relative DID `other`.
///
/// # Errors
///
/// Returns `Err` if any base or relative DID segments are invalid.
#[cfg(feature = "alloc")]
pub fn join(&self, other: impl AsRef<str>) -> Result<Self> {
let data: &str = other.as_ref();
let core: Core = Core::parse_relative(data)?;
resolution::transform_references(self, (data, &core))
}
}
impl Hash for DID {
fn hash<H>(&self, hasher: &mut H)
where
H: Hasher,
{
self.as_str().hash(hasher)
}
}
impl PartialEq for DID {
fn eq(&self, other: &Self) -> bool {
self.as_str() == other.as_str()
}
}
impl Eq for DID {}
impl PartialOrd for DID {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
self.as_str().partial_cmp(other.as_str())
}
}
impl Ord for DID {
fn cmp(&self, other: &Self) -> Ordering {
self.as_str().cmp(other.as_str())
}
}
impl PartialEq<str> for DID {
fn eq(&self, other: &str) -> bool {
self.as_str() == other
}
}
impl PartialEq<&'_ str> for DID {
fn eq(&self, other: &&'_ str) -> bool {
self == *other
}
}
impl Debug for DID {
fn fmt(&self, f: &mut Formatter) -> FmtResult {
f.write_fmt(format_args!("{:?}", self.as_str()))
}
}
impl Display for DID {
fn fmt(&self, f: &mut Formatter) -> FmtResult {
f.write_fmt(format_args!("{}", self.as_str()))
}
}
impl AsRef<str> for DID {
fn as_ref(&self) -> &str {
self.data.as_ref()
}
}
impl FromStr for DID {
type Err = Error;
fn from_str(string: &str) -> Result<Self, Self::Err> {
Self::parse(string)
}
}
#[cfg(feature = "alloc")]
impl TryFrom<String> for DID {
type Error = Error;
fn try_from(other: String) -> Result<Self, Self::Error> {
Self::parse(other)
}
}
#[cfg(feature = "alloc")]
impl From<DID> for String {
fn from(other: DID) -> Self {
other.into_string()
}
}
// =============================================================================
// Reference Resolution
// See RFC 3986 - https://tools.ietf.org/html/rfc3986#section-5
// =============================================================================
#[cfg(feature = "alloc")]
mod resolution {
use alloc::borrow::Cow;
use core::fmt::Display;
use core::fmt::Formatter;
use core::fmt::Result as FmtResult;
use core::str::from_utf8_unchecked;
use crate::core::Core;
use crate::did::DID;
use crate::error::Error;
use crate::error::Result;
#[derive(Debug)]
#[repr(transparent)]
pub struct Path<'a>(Cow<'a, str>);
impl<'a> Path<'a> {
pub const fn new() -> Self {
Self(Cow::Borrowed(""))
}
pub fn push(&mut self, value: impl AsRef<[u8]>) {
self
.0
.to_mut()
.push_str(unsafe { from_utf8_unchecked(value.as_ref()) });
}
pub fn pop(&mut self) {
if self.0.is_empty() {
return;
}
if let Some(index) = self.0.rfind('/') {
self.0.to_mut().replace_range(index.., "");
}
}
}
impl<'a> From<Path<'a>> for Cow<'a, str> {
fn from(other: Path<'a>) -> Self {
other.0
}
}
impl Display for Path<'_> {
fn fmt(&self, f: &mut Formatter) -> FmtResult {
Display::fmt(&self.0, f)
}
}
/// Transform References.
///
/// Transforms a DID reference into its target DID.
///
/// [More Info](https://tools.ietf.org/html/rfc3986#section-5.2.2)
#[allow(non_snake_case)]
pub fn transform_references(base: &DID, (data, core): (&str, &Core)) -> Result<DID> {
let P: &str = core.path(data);
let Q: Option<&str> = core.query(data);
let mut T: DID = base.clone();
if P.is_empty() {
T.set_path(base.path());
T.set_query(Q.or_else(|| base.query()));
} else {
if P.starts_with('/') {
T.set_path(remove_dot_segments(P));
} else {
T.set_path(remove_dot_segments(&merge_paths(base, P)?));
}
T.set_query(Q);
}
T.set_method(base.method()); // TODO: Remove? This in inherited via clone
T.set_method_id(base.method_id()); // TODO: Remove? This in inherited via clone
T.set_fragment(core.fragment(data));
Ok(T)
}
/// Merge Paths.
///
/// Merges a relative-path reference with the path of the base DID.
///
/// [More Info](https://tools.ietf.org/html/rfc3986#section-5.2.3)
pub fn merge_paths<'a>(base: &'a DID, data: &'a str) -> Result<Cow<'a, str>> {
// Ensure the base DID has an authority component.
//
// The DID authority is `<method>:<method-specific-id>` so it should always
// be present for non-relative DIDs.
if base.method().is_empty() || base.method_id().is_empty() {
return Err(Error::InvalidAuthority);
}
// 1. If the base URI has a defined authority component and an empty
// path, then return a string consisting of "/" concatenated with the
// reference's path.
if base.path().is_empty() {
return Ok(data.into());
}
// 2. Return a string consisting of the reference's path component
// appended to all but the last segment of the base URI's path (i.e.,
// excluding any characters after the right-most "/" in the base URI
// path, or excluding the entire base URI path if it does not contain
// any "/" characters).
let mut path: &str = base.path();
if let Some(index) = path.rfind('/') {
path = &path[..=index];
}
Ok([path, data].join("").into())
}
/// Remove Dot Segments.
///
/// [More Info](https://tools.ietf.org/html/rfc3986#section-5.2.4)
pub fn | (path: &str) -> Cow<str> {
fn next_segment(input: impl AsRef<[u8]>) -> Option<usize> {
match input.as_ref() {
[b'/', input @ ..] => next_segment(input).map(|index| index + 1),
input => input.iter().position(|byte| *byte == b'/'),
}
}
let mut output: Path = Path::new();
let mut input: &[u8] = path.as_bytes();
loop {
match input {
// Remove prefix ../
[b'.', b'.', b'/', ..] => {
input = &input[3..];
}
// Remove prefix ./
[b'.', b'/', ..] => {
input = &input[2..];
}
// Replace prefix /./
[b'/', b'.', b'/', ..] => {
input = &input[2..];
}
// Replace prefix /.
[b'/', b'.'] => {
input = &input[..1];
}
// Replace prefix /../
[b'/', b'.', b'.', b'/', ..] => {
input = &input[3..];
output.pop();
}
// Replace prefix /..
[b'/', b'.', b'.'] => {
input = &input[..2];
output.pop();
}
// Remove .
[b'.'] => {
input = &input[1..];
}
// Remove ..
[b'.', b'.'] => {
input = &input[2..];
}
_ => {
if let Some(index) = next_segment(input) {
output.push(&input[..index]);
input = &input[index..];
} else {
output.push(input);
break;
}
}
}
}
output.into()
}
}
| remove_dot_segments | identifier_name |
cfg_simulator.py | """
CAR CONFIG
This file is read by your car application's manage.py script to change the car
performance.
EXMAPLE
-----------
import dk
cfg = dk.load_config(config_path='~/mycar/config.py')
print(cfg.CAMERA_RESOLUTION)
"""
import os
#PATHS
CAR_PATH = PACKAGE_PATH = os.path.dirname(os.path.realpath(__file__))
DATA_PATH = os.path.join(CAR_PATH, 'data')
MODELS_PATH = os.path.join(CAR_PATH, 'models')
#VEHICLE
DRIVE_LOOP_HZ = 20 # the vehicle loop will pause if faster than this speed.
MAX_LOOPS = None # the vehicle loop can abort after this many iterations, when given a positive integer.
#CAMERA
CAMERA_TYPE = "MOCK" # (PICAM|WEBCAM|CVCAM|CSIC|V4L|D435|MOCK|IMAGE_LIST)
IMAGE_W = 160
IMAGE_H = 120
IMAGE_DEPTH = 3 # default RGB=3, make 1 for mono
CAMERA_FRAMERATE = DRIVE_LOOP_HZ
CAMERA_VFLIP = False
CAMERA_HFLIP = False
# For CSIC camera - If the camera is mounted in a rotated position, changing the below parameter will correct the output frame orientation
CSIC_CAM_GSTREAMER_FLIP_PARM = 0 # (0 => none , 4 => Flip horizontally, 6 => Flip vertically)
# For IMAGE_LIST camera
# PATH_MASK = "~/mycar/data/tub_1_20-03-12/*.jpg"
#9865, over rides only if needed, ie. TX2..
PCA9685_I2C_ADDR = 0x40 #I2C address, use i2cdetect to validate this number
PCA9685_I2C_BUSNUM = None #None will auto detect, which is fine on the pi. But other platforms should specify the bus num.
#SSD1306_128_32
USE_SSD1306_128_32 = False # Enable the SSD_1306 OLED Display
SSD1306_128_32_I2C_BUSNUM = 1 # I2C bus number
#DRIVETRAIN
#These options specify which chasis and motor setup you are using. Most are using SERVO_ESC.
#DC_STEER_THROTTLE uses HBridge pwm to control one steering dc motor, and one drive wheel motor
#DC_TWO_WHEEL uses HBridge pwm to control two drive motors, one on the left, and one on the right.
#SERVO_HBRIDGE_PWM use ServoBlaster to output pwm control from the PiZero directly to control steering, and HBridge for a drive motor.
#PIGPIO_PWM uses Raspberrys internal PWM
DRIVE_TRAIN_TYPE = "MOCK" # I2C_SERVO|DC_STEER_THROTTLE|DC_TWO_WHEEL|DC_TWO_WHEEL_L298N|SERVO_HBRIDGE_PWM|PIGPIO_PWM|MM1|MOCK
#STEERING
STEERING_CHANNEL = 1 #channel on the 9685 pwm board 0-15
STEERING_LEFT_PWM = 460 #pwm value for full left steering
STEERING_RIGHT_PWM = 290 #pwm value for full right steering
#STEERING FOR PIGPIO_PWM
STEERING_PWM_PIN = 13 #Pin numbering according to Broadcom numbers
STEERING_PWM_FREQ = 50 #Frequency for PWM
STEERING_PWM_INVERTED = False #If PWM needs to be inverted
#THROTTLE
THROTTLE_CHANNEL = 0 #channel on the 9685 pwm board 0-15
THROTTLE_FORWARD_PWM = 500 #pwm value for max forward throttle
THROTTLE_STOPPED_PWM = 370 #pwm value for no movement
THROTTLE_REVERSE_PWM = 220 #pwm value for max reverse throttle
#THROTTLE FOR PIGPIO_PWM
THROTTLE_PWM_PIN = 18 #Pin numbering according to Broadcom numbers
THROTTLE_PWM_FREQ = 50 #Frequency for PWM
THROTTLE_PWM_INVERTED = False #If PWM needs to be inverted
#DC_STEER_THROTTLE with one motor as steering, one as drive
#these GPIO pinouts are only used for the DRIVE_TRAIN_TYPE=DC_STEER_THROTTLE
HBRIDGE_PIN_LEFT = 18
HBRIDGE_PIN_RIGHT = 16
HBRIDGE_PIN_FWD = 15
HBRIDGE_PIN_BWD = 13
#DC_TWO_WHEEL - with two wheels as drive, left and right.
#these GPIO pinouts are only used for the DRIVE_TRAIN_TYPE=DC_TWO_WHEEL
HBRIDGE_PIN_LEFT_FWD = 18
HBRIDGE_PIN_LEFT_BWD = 16
HBRIDGE_PIN_RIGHT_FWD = 15
HBRIDGE_PIN_RIGHT_BWD = 13
#TRAINING
#The DEFAULT_MODEL_TYPE will choose which model will be created at training time. This chooses
#between different neural network designs. You can override this setting by passing the command
#line parameter --type to the python manage.py train and drive commands.
DEFAULT_MODEL_TYPE = 'linear' #(linear|categorical|tflite_linear|tensorrt_linear)
BATCH_SIZE = 128 #how many records to use when doing one pass of gradient decent. Use a smaller number if your gpu is running out of memory.
TRAIN_TEST_SPLIT = 0.8 #what percent of records to use for training. the remaining used for validation.
MAX_EPOCHS = 100 #how many times to visit all records of your data
SHOW_PLOT = True #would you like to see a pop up display of final loss?
VERBOSE_TRAIN = True #would you like to see a progress bar with text during training?
USE_EARLY_STOP = True #would you like to stop the training if we see it's not improving fit?
EARLY_STOP_PATIENCE = 5 #how many epochs to wait before no improvement
MIN_DELTA = .0005 #early stop will want this much loss change before calling it improved.
PRINT_MODEL_SUMMARY = True #print layers and weights to stdout
OPTIMIZER = None #adam, sgd, rmsprop, etc.. None accepts default
LEARNING_RATE = 0.001 #only used when OPTIMIZER specified
LEARNING_RATE_DECAY = 0.0 #only used when OPTIMIZER specified
SEND_BEST_MODEL_TO_PI = False #change to true to automatically send best model during training
PRUNE_CNN = False #This will remove weights from your model. The primary goal is to increase performance.
PRUNE_PERCENT_TARGET = 75 # The desired percentage of pruning.
PRUNE_PERCENT_PER_ITERATION = 20 # Percenge of pruning that is perform per iteration.
PRUNE_VAL_LOSS_DEGRADATION_LIMIT = 0.2 # The max amout of validation loss that is permitted during pruning.
PRUNE_EVAL_PERCENT_OF_DATASET = .05 # percent of dataset used to perform evaluation of model.
#Model transfer options
#When copying weights during a model transfer operation, should we freeze a certain number of layers
#to the incoming weights and not allow them to change during training?
FREEZE_LAYERS = False #default False will allow all layers to be modified by training
NUM_LAST_LAYERS_TO_TRAIN = 7 #when freezing layers, how many layers from the last should be allowed to train?
#WEB CONTROL
WEB_CONTROL_PORT = 8887 # which port to listen on when making a web controller
WEB_INIT_MODE = "user" # which control mode to start in. one of user|local_angle|local. Setting local will start in ai mode.
#JOYSTICK
USE_JOYSTICK_AS_DEFAULT = False #when starting the manage.py, when True, will not require a --js option to use the joystick
JOYSTICK_MAX_THROTTLE = 0.5 #this scalar is multiplied with the -1 to 1 throttle value to limit the maximum throttle. This can help if you drop the controller or just don't need the full speed available.
JOYSTICK_STEERING_SCALE = 1.0 #some people want a steering that is less sensitve. This scalar is multiplied with the steering -1 to 1. It can be negative to reverse dir.
AUTO_RECORD_ON_THROTTLE = True #if true, we will record whenever throttle is not zero. if false, you must manually toggle recording with some other trigger. Usually circle button on joystick.
CONTROLLER_TYPE = 'xbox' #(ps3|ps4|xbox|nimbus|wiiu|F710|rc3|MM1|custom) custom will run the my_joystick.py controller written by the `donkey createjs` command
USE_NETWORKED_JS = False #should we listen for remote joystick control over the network?
NETWORK_JS_SERVER_IP = None #when listening for network joystick control, which ip is serving this information
JOYSTICK_DEADZONE = 0.01 # when non zero, this is the smallest throttle before recording triggered.
JOYSTICK_THROTTLE_DIR = 1.0 # use -1.0 to flip forward/backward, use 1.0 to use joystick's natural forward/backward
USE_FPV = False # send camera data to FPV webserver
JOYSTICK_DEVICE_FILE = "/dev/input/js0" # this is the unix file use to access the joystick.
#For the categorical model, this limits the upper bound of the learned throttle
#it's very IMPORTANT that this value is matched from the training PC config.py and the robot.py
#and ideally wouldn't change once set.
MODEL_CATEGORICAL_MAX_THROTTLE_RANGE = 0.8
#RNN or 3D
SEQUENCE_LENGTH = 3 #some models use a number of images over time. This controls how many.
#IMU
HAVE_IMU = False #when true, this add a Mpu6050 part and records the data. Can be used with a
IMU_SENSOR = 'mpu6050' # (mpu6050|mpu9250)
IMU_DLP_CONFIG = 0 # Digital Lowpass Filter setting (0:250Hz, 1:184Hz, 2:92Hz, 3:41Hz, 4:20Hz, 5:10Hz, 6:5Hz)
#SOMBRERO
HAVE_SOMBRERO = False #set to true when using the sombrero hat from the Donkeycar store. This will enable pwm on the hat.
#ROBOHAT MM1
HAVE_ROBOHAT = False # set to true when using the Robo HAT MM1 from Robotics Masters. This will change to RC Control.
MM1_STEERING_MID = 1500 # Adjust this value if your car cannot run in a straight line
MM1_MAX_FORWARD = 2000 # Max throttle to go fowrward. The bigger the faster
MM1_STOPPED_PWM = 1500
MM1_MAX_REVERSE = 1000 # Max throttle to go reverse. The smaller the faster
MM1_SHOW_STEERING_VALUE = False
# Serial port
# -- Default Pi: '/dev/ttyS0'
# -- Jetson Nano: '/dev/ttyTHS1'
# -- Google coral: '/dev/ttymxc0'
# -- Windows: 'COM3', Arduino: '/dev/ttyACM0'
# -- MacOS/Linux:please use 'ls /dev/tty.*' to find the correct serial port for mm1
# eg.'/dev/tty.usbmodemXXXXXX' and replace the port accordingly
MM1_SERIAL_PORT = '/dev/ttyS0' # Serial Port for reading and sending MM1 data.
#RECORD OPTIONS
RECORD_DURING_AI = False #normally we do not record during ai mode. Set this to true to get image and steering records for your Ai. Be careful not to use them to train.
AUTO_CREATE_NEW_TUB = False #create a new tub (tub_YY_MM_DD) directory when recording or append records to data directory directly
#LED
HAVE_RGB_LED = False #do you have an RGB LED like https://www.amazon.com/dp/B07BNRZWNF
LED_INVERT = False #COMMON ANODE? Some RGB LED use common anode. like https://www.amazon.com/Xia-Fly-Tri-Color-Emitting-Diffused/dp/B07MYJQP8B
#LED board pin number for pwm outputs
#These are physical pinouts. See: https://www.raspberrypi-spy.co.uk/2012/06/simple-guide-to-the-rpi-gpio-header-and-pins/
LED_PIN_R = 12
LED_PIN_G = 10
LED_PIN_B = 16
#LED status color, 0-100
LED_R = 0
LED_G = 0
LED_B = 1
#LED Color for record count indicator
REC_COUNT_ALERT = 1000 #how many records before blinking alert
REC_COUNT_ALERT_CYC = 15 #how many cycles of 1/20 of a second to blink per REC_COUNT_ALERT records
REC_COUNT_ALERT_BLINK_RATE = 0.4 #how fast to blink the led in seconds on/off
#first number is record count, second tuple is color ( r, g, b) (0-100)
#when record count exceeds that number, the color will be used
RECORD_ALERT_COLOR_ARR = [ (0, (1, 1, 1)),
(3000, (5, 5, 5)),
(5000, (5, 2, 0)),
(10000, (0, 5, 0)),
(15000, (0, 5, 5)),
(20000, (0, 0, 5)), ]
#LED status color, 0-100, for model reloaded alert
MODEL_RELOADED_LED_R = 100
MODEL_RELOADED_LED_G = 0
MODEL_RELOADED_LED_B = 0
#BEHAVIORS
#When training the Behavioral Neural Network model, make a list of the behaviors,
#Set the TRAIN_BEHAVIORS = True, and use the BEHAVIOR_LED_COLORS to give each behavior a color
TRAIN_BEHAVIORS = False
BEHAVIOR_LIST = ['Left_Lane', "Right_Lane"]
BEHAVIOR_LED_COLORS =[ (0, 10, 0), (10, 0, 0) ] #RGB tuples 0-100 per chanel
#Localizer
#The localizer is a neural network that can learn to predice it's location on the track.
#This is an experimental feature that needs more developement. But it can currently be used
#to predict the segement of the course, where the course is divided into NUM_LOCATIONS segments.
TRAIN_LOCALIZER = False
NUM_LOCATIONS = 10
BUTTON_PRESS_NEW_TUB = False #when enabled, makes it easier to divide our data into one tub per track length if we make a new tub on each X button press.
#DonkeyGym
#Only on Ubuntu linux, you can use the simulator as a virtual donkey and
#issue the same python manage.py drive command as usual, but have them control a virtual car.
#This enables that, and sets the path to the simualator and the environment.
#You will want to download the simulator binary from: https://github.com/tawnkramer/donkey_gym/releases/download/v18.9/DonkeySimLinux.zip
#then extract that and modify DONKEY_SIM_PATH.
DONKEY_GYM = True
DONKEY_SIM_PATH = "path to sim" #"/home/tkramer/projects/sdsandbox/sdsim/build/DonkeySimLinux/donkey_sim.x86_64" when racing on virtual-race-league use "remote", or user "remote" when you want to start the sim manually first.
DONKEY_GYM_ENV_NAME = "donkey-generated-track-v0" # ("donkey-generated-track-v0"|"donkey-generated-roads-v0"|"donkey-warehouse-v0"|"donkey-avc-sparkfun-v0")
GYM_CONF = { "img_h" : IMAGE_H, "img_w" : IMAGE_W, "body_style" : "donkey", "body_rgb" : (128, 128, 128), "car_name" : "car", "font_size" : 100 } # body style(donkey|bare|car01) body rgb 0-255
GYM_CONF["racer_name"] = "Your Name"
GYM_CONF["country"] = "Place"
GYM_CONF["bio"] = "I race robots."
SIM_HOST = "127.0.0.1" # when racing on virtual-race-league use host "trainmydonkey.com"
SIM_ARTIFICIAL_LATENCY = 0 # this is the millisecond latency in controls. Can use useful in emulating the delay when useing a remote server. values of 100 to 400 probably reasonable.
#publish camera over network
#This is used to create a tcp service to pushlish the camera feed
PUB_CAMERA_IMAGES = False
#When racing, to give the ai a boost, configure these values.
AI_LAUNCH_DURATION = 0.0 # the ai will output throttle for this many seconds
AI_LAUNCH_THROTTLE = 0.0 # the ai will output this throttle value
AI_LAUNCH_ENABLE_BUTTON = 'R2' # this keypress will enable this boost. It must be enabled before each use to prevent accidental trigger.
AI_LAUNCH_KEEP_ENABLED = False # when False ( default) you will need to hit the AI_LAUNCH_ENABLE_BUTTON for each use. This is safest. When this True, is active on each trip into "local" ai mode.
#Scale the output of the throttle of the ai pilot for all model types.
AI_THROTTLE_MULT = 1.0 # this multiplier will scale every throttle value for all output from NN models
| PID_P = -10.0 # proportional mult for PID path follower
PID_I = 0.000 # integral mult for PID path follower
PID_D = -0.2 # differential mult for PID path follower
PID_THROTTLE = 0.2 # constant throttle value during path following
USE_CONSTANT_THROTTLE = False # whether or not to use the constant throttle or variable throttle captured during path recording
SAVE_PATH_BTN = "cross" # joystick button to save path
RESET_ORIGIN_BTN = "triangle" # joystick button to press to move car back to origin
# Intel Realsense D435 and D435i depth sensing camera
REALSENSE_D435_RGB = True # True to capture RGB image
REALSENSE_D435_DEPTH = True # True to capture depth as image array
REALSENSE_D435_IMU = False # True to capture IMU data (D435i only)
REALSENSE_D435_ID = None # serial number of camera or None if you only have one camera (it will autodetect)
# Stop Sign Detector
STOP_SIGN_DETECTOR = False
STOP_SIGN_MIN_SCORE = 0.2
STOP_SIGN_SHOW_BOUNDING_BOX = True | #Path following
PATH_FILENAME = "donkey_path.pkl" # the path will be saved to this filename
PATH_SCALE = 5.0 # the path display will be scaled by this factor in the web page
PATH_OFFSET = (0, 0) # 255, 255 is the center of the map. This offset controls where the origin is displayed.
PATH_MIN_DIST = 0.3 # after travelling this distance (m), save a path point | random_line_split |
index.js | const Long = require('long');
const csv = require('csvtojson');
const fs = require('fs');
let imgSrcPath = '/mnt/dyk/Documents/Default Documents/项目-活动-竞赛/天涯明月刀/00.各种助手/94.SFC解包重打包/PySFCExtractor/output/ImageSetsMixed/';
let imgDesPath = './img_output/';
let files = [
'FashionTable.csv', 'FashionSetTable.csv', 'EquipmentTableWaiZhuang.csv', 'AchievementRequestTable_glamour.csv', 'AchievementTable_glamour.csv', 'EquipmentTableZuoJi.csv',
];
let promises = files.map((key) => {
let data = fs.readFileSync(`./input/${key}`);
return csv({checkType: true}).fromString(data.toString().replace(/[\[\]]/g, '')); // todo ???
});
let fashionTable, setTable, itemTable, achiReqTable, achiTable;
Promise.all(promises).then(gen);
function gen(data) {
fashionTable = data[0];
setTable = | typeIcon: 'Icons/Achieve/ach_xinwang.png', // 看需求,就是花花Icon
meili: 50,
logic: 'and', // 成就条件逻辑,and或者or,全部完成还是一个就行
// 通用成就完成表
achiIdList: [24749, 24750, 24750, 24750], // 需求Id
}
};
// 遍历魅力表时,特殊的:万色、一染、丰彩染料累计、瑶光颜料累计、点染××累计
// 万色、一染。读描述的冒号前的内容,找对应套装,加到染色成就表里
// 染色魅力,todo 这里假设各个时装男女需求一样
let exampleDyeGlamour = {
23716: { // 吹雪 金
name: '一染·浮华盛锦',
originDes: '吹雪霓裳:点染·金莹',
type: '定制染色',
typeIcon: 'Icons/Achieve/ach_xinwang.png',
meili: 100, // 魅力值
logic: 'and',
// 特殊判定
setId: 328, // 用于现实
posList: [4037, 4038, 4039, 4040], // 需要达成的部位,直接遍历这个表的posList检查是否符合就行,构造时查set表拿id, todo 与achiIdList互斥
// 满足特殊属性
isSpecial: true,
base: null, // 基础染色的值,根据字符串识别 todo
advance: null,
specialType: 'gold', // 定制金染
}
};
// 染色总计魅力
let exampleDyeSumGlamour = {
23776: { // id
name: '点染·玄夜累计·8',
originDes: '累计消耗:72个点染·玄夜',
type: '累计成就',
typeIcon: 'Icons/Achieve/ach_xinwang.png',
meili: 100, // 魅力值
logic: 'none',
// 特殊判定
item: 'black', // 消耗的物品种类,手动构建,丰彩染料、瑶光、绿、蓝、红、金、黑、白
// 满足特殊属性
count: 100, // 程序里特殊逻辑处理
}
};
// 存储浏览器的数据
let storage = {
4037: { // 影头,单件id
own: true,
dyeList: [
{
isSpecial: 'false',
a: 100,
b: 100,
},
{
isSpecial: 'true',
type: 'blue'
},
]
}
};
// 每当购买、染色变化时,重新计算拥有的套装、魅力值达成(放到state里缓存吧) todo
// 按已有未有、价格排序、按分类看(直接分好)
// 小界面显示密集的已购列表(右边off on按钮)
// 小界面现实已经达成的、未达成的魅力成就
// 收藏外装、散件、特定染色、累计染色消耗
// 文件名Hash函数
function getHash(str) {
let dwHash = new Long(0x4D2960DB, 0x1712E27F, true); // 低位,高位,无符号
str = str.toUpperCase();
str = str.replace(/\//g, '\\');
for (let i = 0; i < str.length; i++) {
dwHash = dwHash.mul(67).add(str.charCodeAt(i));
}
return ('0000000000000000' + dwHash.toString(16)).slice(-16);
} | data[1];
itemTable = data[2];
achiReqTable = data[3];
achiTable = data[4];
// 新增坐骑
itemTable = itemTable.concat(data[5]);
// todo 是否可以染色
let partRes = {};
let setRes = {};
let glamourRes = {};
let dyeRes = {};
let dyesumRes = {};
// 以主表开始遍历
fashionTable.forEach(part => {
// 查item表提数据
let item = itemTable.filter(o => o.iId === part.itemId)[0];
// console.log(part.itemId, item.stItemInfo);
// 反查完成的成就小id
let achiReqList = achiReqTable.filter(o => o.fashionId === part.fashionId); // todo 有空的
// todo 保存6464小icon
let hash = getHash(`DATA\\IMAGESETS\\ICONS\\ITEMTIPSICON\\${item.szTIPS2D}.TGA`);
let fullPath = `${imgSrcPath}${hash}.tga`;
if(fs.existsSync(fullPath)) {
fs.createReadStream(fullPath).pipe(fs.createWriteStream(`${imgDesPath}${item.szTIPS2D}.tga`));
} else {
console.log('文件不存在:', item.szTIPS2D, hash);
}
partRes[part.fashionId] = {
pos: part.position, // 主表
suiyin: part.suiyin, // 主表
weight: part.weight, // 主表
itemId: part.itemId, // 主表
equipData: {
name: item.stItemInfo,
gender: (item.enumSexDemandArray + '').replace(/[\[\] ]/g, '').split('$$').map(parseFloat),
menpai: item.JobDemandArray[0], // todo UseCondition 还分门派!
// 身份、盟会职务不关键,全部显示
explain: item.szExplain,
des: item.szBackground,
icon: item.szTIPS2D, // icon是只有男的 todo 不是!男女都有!
type: item.ddCatDesc,
},
achiId: achiReqList.length === 1 ? achiReqList[0].achievementId : null, // 反查achievement request表,收集了该物品可以达成的成就小Id
};
});
// 构造套装表
setTable.forEach(set => {
// todo 保存三体型卡片
[set.iconM, set.iconF, set.iconZ, set.cardM, set.cardF, set.cardZ].forEach(filename => {
let hash = getHash(`DATA\\IMAGESETS\\ICONS\\FASHION\\${filename}.TGA`);
let fullPath = `${imgSrcPath}${hash}.tga`;
if(fs.existsSync(fullPath)) {
fs.createReadStream(fullPath).pipe(fs.createWriteStream(`${imgDesPath}${filename}.tga`));
} else {
console.log('文件不存在:', filename, hash);
}
});
// 保存数据
setRes[set.setId] = {
name: set.setName,
idList: (set.idList + '').replace(/[\[\] ]/g, '').split('$$').map(parseFloat),
origin: set.origin, // 在表最右边
originDes: set.originDes,
card: [set.cardM, set.cardF, set.cardZ],
weight: set.weight, // 排序权重,最右边
};
});
// 构造魅力值表
achiTable.forEach(achi => {
// 通用属性构建
let res = {
name: achi.name, //条件名称
originDes: achi.originDes,
type: achi.type, // 还有累计成就之类的
typeIcon: achi.typeIcon, // 看需求,就是花花Icon
meili: achi.meili,
logic: achi.logic ? 'or' : 'and', // 成就条件逻辑,and或者or,全部完成还是一个就行
};
// 特殊属性构建
if(achi.name.startsWith('万色')) {
// 普通染色魅力值
// 强行找出对应套装 todo
let setName = achi.originDes.split(':')[0];
let set = setTable.filter(o => (o.setName + '').includes(setName))[0]; // todo shuzi id
let base = parseInt(achi.originDes.match(/基础(\d*)/)[1]);
let advance;
let matchRes = achi.originDes.match(/进阶(\d*)/);
if(matchRes)
advance = matchRes[1];
else
advance = null;
res = {
...res,
// 特殊判定
setId: set.setId, // 用于显示
partList: (set.idList + '').replace(/[\[\] ]/g, '').split('$$').map(parseFloat), // 需要达成的部位,直接遍历这个表的posList检查是否符合就行,构造时查set表拿id
// 满足特殊属性
isSpecial: false,
base: base, // 基础染色的值,根据字符串识别 todo
advance: advance,
specialType: null,
};
// 保存
dyeRes[achi.achievementId] = res;
} else if(achi.name.startsWith('一染')) {
// 定制染色魅力值
// 强行找出对应套装 todo
let setName = achi.originDes.split(':')[0];
let set = setTable.filter(o => (o.setName + '').includes(setName))[0]; // todo shuzi id
let type = achi.originDes.match(/点染·(.*)/)[1];
res = {
...res,
// 特殊判定
setId: set.setId, // 用于显示
partList: (set.idList + '').replace(/[\[\] ]/g, '').split('$$').map(parseFloat), // 需要达成的部位,直接遍历这个表的posList检查是否符合就行,构造时查set表拿id
// 满足特殊属性
isSpecial: true,
base: null,
advance: null,
specialType: type,
};
// 保存
dyeRes[achi.achievementId] = res;
} else if(achi.name.startsWith('丰彩染料累计')) {
res = {
...res,
// 特殊判定
item: '丰彩', // 消耗的物品种类,手动构建,丰彩染料、瑶光、绿、蓝、红、金、黑、白的原名
// 满足特殊属性
count: achi.count, // 程序里特殊逻辑处理
};
dyesumRes[achi.achievementId] = res;
} else if(achi.name.startsWith('瑶光颜料累计')) {
res = {
...res,
// 特殊判定
item: '瑶光', // 消耗的物品种类,手动构建,丰彩染料、瑶光、绿、蓝、红、金、黑、白的原名
// 满足特殊属性
count: achi.count, // 程序里特殊逻辑处理
};
dyesumRes[achi.achievementId] = res;
} else if(achi.name.startsWith('点染')) {
let item;
if(achi.name.includes('蓝瓷')) item = '蓝瓷';
else if(achi.name.includes('竹青')) item = '蓝瓷';
else if(achi.name.includes('红烬')) item = '红烬';
else if(achi.name.includes('金莹')) item = '金莹';
else if(achi.name.includes('雪练')) item = '雪练';
else if(achi.name.includes('玄夜')) item = '玄夜';
res = {
...res,
// 特殊判定
item: item, // 消耗的物品种类,手动构建,丰彩染料、瑶光、绿、蓝、红、金、黑、白的原名
// 满足特殊属性
count: achi.count, // 程序里特殊逻辑处理
};
dyesumRes[achi.achievementId] = res;
} else {
// 普通收集类型
// 从aId1 到aId12
let idList = [];
for (let i = 1; i < 12; i++) {
if(achi['aId' + i] > 0) {
idList.push(achi['aId' + i]);
}
}
res = {
...res,
// 通用成就完成表
achiIdList: idList, // 需求Id
};
glamourRes[achi.achievementId] = res;
}
});
console.log('1');
// 写入文件
fs.writeFileSync('./output/part.json', JSON.stringify(partRes, null, 4));
fs.writeFileSync('./output/set.json', JSON.stringify(setRes, null, 4));
fs.writeFileSync('./output/common_glamour.json', JSON.stringify(glamourRes, null, 4));
fs.writeFileSync('./output/dye.json', JSON.stringify(dyeRes, null, 4));
fs.writeFileSync('./output/dye_sum.json', JSON.stringify(dyesumRes, null, 4));
}
/************************************/
/***************数据分析**************/
/************************************/
// 全部散件(Fashion主表)
let exampleParts = {
4037: { // 心王影冠Fashion id
pos: 'head', // 主表
suiyin: 0, // 主表
weight: 2227, // 主表
itemId: 6100920, // 主表
equipData: {
name: '心王·影冠',
gender: [true, true, true],
menpai: -1,
// 身份、盟会职务不关键,全部显示
explain: '使用后获得“心王·影冠”外装外形',
des: '露凝香,玉笼烟。\\n谁共我,醉明月?',
icon: 'ICON_60_equip_Head_M_M_TY_3103', // icon是只有男的
type: '外装',
},
achiId: 24749, // 反查achievement request表,收集了该物品可以达成的成就小Id
}
};
// 全部套装
let exampleSets = {
328: { // 心王影套装id
name: 'setName',
idList: [4037, 4038, 4039, 4040],
origin: 'shop', // 在表最右边
originDes: '商城购买获得',
card: ['ICON_64_equip_coat_M_M_TY_3103', 'ICON_64_equip_coat_F_F_TY_3103', 'ICON_64_equip_coat_Z_Z_TY_3103'],
weight: 309, // 排序权重,最右边
// dyeAchievements: {
//
// }, // 染色成就表
}
};
// // 染色 todo
// let exampleDye = {
//
// };
// 魅力对应
let exampleGlamour = {
24749: { // 魅力条件Id
name: '心王·影', //条件名称
originDes: '商城购买获得',
type: '外装', // 还有累计成就之类的
| identifier_body |
index.js | const Long = require('long');
const csv = require('csvtojson');
const fs = require('fs');
let imgSrcPath = '/mnt/dyk/Documents/Default Documents/项目-活动-竞赛/天涯明月刀/00.各种助手/94.SFC解包重打包/PySFCExtractor/output/ImageSetsMixed/';
let imgDesPath = './img_output/';
let files = [
'FashionTable.csv', 'FashionSetTable.csv', 'EquipmentTableWaiZhuang.csv', 'AchievementRequestTable_glamour.csv', 'AchievementTable_glamour.csv', 'EquipmentTableZuoJi.csv',
];
let promises = files.map((key) => {
let data = fs.readFileSync(`./input/${key}`);
return csv({checkType: true}).fromString(data.toString().replace(/[\[\]]/g, '')); // todo ???
});
let fashionTable, setTable, itemTable, achiReqTable, achiTable;
Promise.all(promises).then(gen);
function gen(data) {
fashionTable = data[0];
| Table = data[1];
itemTable = data[2];
achiReqTable = data[3];
achiTable = data[4];
// 新增坐骑
itemTable = itemTable.concat(data[5]);
// todo 是否可以染色
let partRes = {};
let setRes = {};
let glamourRes = {};
let dyeRes = {};
let dyesumRes = {};
// 以主表开始遍历
fashionTable.forEach(part => {
// 查item表提数据
let item = itemTable.filter(o => o.iId === part.itemId)[0];
// console.log(part.itemId, item.stItemInfo);
// 反查完成的成就小id
let achiReqList = achiReqTable.filter(o => o.fashionId === part.fashionId); // todo 有空的
// todo 保存6464小icon
let hash = getHash(`DATA\\IMAGESETS\\ICONS\\ITEMTIPSICON\\${item.szTIPS2D}.TGA`);
let fullPath = `${imgSrcPath}${hash}.tga`;
if(fs.existsSync(fullPath)) {
fs.createReadStream(fullPath).pipe(fs.createWriteStream(`${imgDesPath}${item.szTIPS2D}.tga`));
} else {
console.log('文件不存在:', item.szTIPS2D, hash);
}
partRes[part.fashionId] = {
pos: part.position, // 主表
suiyin: part.suiyin, // 主表
weight: part.weight, // 主表
itemId: part.itemId, // 主表
equipData: {
name: item.stItemInfo,
gender: (item.enumSexDemandArray + '').replace(/[\[\] ]/g, '').split('$$').map(parseFloat),
menpai: item.JobDemandArray[0], // todo UseCondition 还分门派!
// 身份、盟会职务不关键,全部显示
explain: item.szExplain,
des: item.szBackground,
icon: item.szTIPS2D, // icon是只有男的 todo 不是!男女都有!
type: item.ddCatDesc,
},
achiId: achiReqList.length === 1 ? achiReqList[0].achievementId : null, // 反查achievement request表,收集了该物品可以达成的成就小Id
};
});
// 构造套装表
setTable.forEach(set => {
// todo 保存三体型卡片
[set.iconM, set.iconF, set.iconZ, set.cardM, set.cardF, set.cardZ].forEach(filename => {
let hash = getHash(`DATA\\IMAGESETS\\ICONS\\FASHION\\${filename}.TGA`);
let fullPath = `${imgSrcPath}${hash}.tga`;
if(fs.existsSync(fullPath)) {
fs.createReadStream(fullPath).pipe(fs.createWriteStream(`${imgDesPath}${filename}.tga`));
} else {
console.log('文件不存在:', filename, hash);
}
});
// 保存数据
setRes[set.setId] = {
name: set.setName,
idList: (set.idList + '').replace(/[\[\] ]/g, '').split('$$').map(parseFloat),
origin: set.origin, // 在表最右边
originDes: set.originDes,
card: [set.cardM, set.cardF, set.cardZ],
weight: set.weight, // 排序权重,最右边
};
});
// 构造魅力值表
achiTable.forEach(achi => {
// 通用属性构建
let res = {
name: achi.name, //条件名称
originDes: achi.originDes,
type: achi.type, // 还有累计成就之类的
typeIcon: achi.typeIcon, // 看需求,就是花花Icon
meili: achi.meili,
logic: achi.logic ? 'or' : 'and', // 成就条件逻辑,and或者or,全部完成还是一个就行
};
// 特殊属性构建
if(achi.name.startsWith('万色')) {
// 普通染色魅力值
// 强行找出对应套装 todo
let setName = achi.originDes.split(':')[0];
let set = setTable.filter(o => (o.setName + '').includes(setName))[0]; // todo shuzi id
let base = parseInt(achi.originDes.match(/基础(\d*)/)[1]);
let advance;
let matchRes = achi.originDes.match(/进阶(\d*)/);
if(matchRes)
advance = matchRes[1];
else
advance = null;
res = {
...res,
// 特殊判定
setId: set.setId, // 用于显示
partList: (set.idList + '').replace(/[\[\] ]/g, '').split('$$').map(parseFloat), // 需要达成的部位,直接遍历这个表的posList检查是否符合就行,构造时查set表拿id
// 满足特殊属性
isSpecial: false,
base: base, // 基础染色的值,根据字符串识别 todo
advance: advance,
specialType: null,
};
// 保存
dyeRes[achi.achievementId] = res;
} else if(achi.name.startsWith('一染')) {
// 定制染色魅力值
// 强行找出对应套装 todo
let setName = achi.originDes.split(':')[0];
let set = setTable.filter(o => (o.setName + '').includes(setName))[0]; // todo shuzi id
let type = achi.originDes.match(/点染·(.*)/)[1];
res = {
...res,
// 特殊判定
setId: set.setId, // 用于显示
partList: (set.idList + '').replace(/[\[\] ]/g, '').split('$$').map(parseFloat), // 需要达成的部位,直接遍历这个表的posList检查是否符合就行,构造时查set表拿id
// 满足特殊属性
isSpecial: true,
base: null,
advance: null,
specialType: type,
};
// 保存
dyeRes[achi.achievementId] = res;
} else if(achi.name.startsWith('丰彩染料累计')) {
res = {
...res,
// 特殊判定
item: '丰彩', // 消耗的物品种类,手动构建,丰彩染料、瑶光、绿、蓝、红、金、黑、白的原名
// 满足特殊属性
count: achi.count, // 程序里特殊逻辑处理
};
dyesumRes[achi.achievementId] = res;
} else if(achi.name.startsWith('瑶光颜料累计')) {
res = {
...res,
// 特殊判定
item: '瑶光', // 消耗的物品种类,手动构建,丰彩染料、瑶光、绿、蓝、红、金、黑、白的原名
// 满足特殊属性
count: achi.count, // 程序里特殊逻辑处理
};
dyesumRes[achi.achievementId] = res;
} else if(achi.name.startsWith('点染')) {
let item;
if(achi.name.includes('蓝瓷')) item = '蓝瓷';
else if(achi.name.includes('竹青')) item = '蓝瓷';
else if(achi.name.includes('红烬')) item = '红烬';
else if(achi.name.includes('金莹')) item = '金莹';
else if(achi.name.includes('雪练')) item = '雪练';
else if(achi.name.includes('玄夜')) item = '玄夜';
res = {
...res,
// 特殊判定
item: item, // 消耗的物品种类,手动构建,丰彩染料、瑶光、绿、蓝、红、金、黑、白的原名
// 满足特殊属性
count: achi.count, // 程序里特殊逻辑处理
};
dyesumRes[achi.achievementId] = res;
} else {
// 普通收集类型
// 从aId1 到aId12
let idList = [];
for (let i = 1; i < 12; i++) {
if(achi['aId' + i] > 0) {
idList.push(achi['aId' + i]);
}
}
res = {
...res,
// 通用成就完成表
achiIdList: idList, // 需求Id
};
glamourRes[achi.achievementId] = res;
}
});
console.log('1');
// 写入文件
fs.writeFileSync('./output/part.json', JSON.stringify(partRes, null, 4));
fs.writeFileSync('./output/set.json', JSON.stringify(setRes, null, 4));
fs.writeFileSync('./output/common_glamour.json', JSON.stringify(glamourRes, null, 4));
fs.writeFileSync('./output/dye.json', JSON.stringify(dyeRes, null, 4));
fs.writeFileSync('./output/dye_sum.json', JSON.stringify(dyesumRes, null, 4));
}
/************************************/
/***************数据分析**************/
/************************************/
// 全部散件(Fashion主表)
let exampleParts = {
4037: { // 心王影冠Fashion id
pos: 'head', // 主表
suiyin: 0, // 主表
weight: 2227, // 主表
itemId: 6100920, // 主表
equipData: {
name: '心王·影冠',
gender: [true, true, true],
menpai: -1,
// 身份、盟会职务不关键,全部显示
explain: '使用后获得“心王·影冠”外装外形',
des: '露凝香,玉笼烟。\\n谁共我,醉明月?',
icon: 'ICON_60_equip_Head_M_M_TY_3103', // icon是只有男的
type: '外装',
},
achiId: 24749, // 反查achievement request表,收集了该物品可以达成的成就小Id
}
};
// 全部套装
let exampleSets = {
328: { // 心王影套装id
name: 'setName',
idList: [4037, 4038, 4039, 4040],
origin: 'shop', // 在表最右边
originDes: '商城购买获得',
card: ['ICON_64_equip_coat_M_M_TY_3103', 'ICON_64_equip_coat_F_F_TY_3103', 'ICON_64_equip_coat_Z_Z_TY_3103'],
weight: 309, // 排序权重,最右边
// dyeAchievements: {
//
// }, // 染色成就表
}
};
// // 染色 todo
// let exampleDye = {
//
// };
// 魅力对应
let exampleGlamour = {
24749: { // 魅力条件Id
name: '心王·影', //条件名称
originDes: '商城购买获得',
type: '外装', // 还有累计成就之类的
typeIcon: 'Icons/Achieve/ach_xinwang.png', // 看需求,就是花花Icon
meili: 50,
logic: 'and', // 成就条件逻辑,and或者or,全部完成还是一个就行
// 通用成就完成表
achiIdList: [24749, 24750, 24750, 24750], // 需求Id
}
};
// 遍历魅力表时,特殊的:万色、一染、丰彩染料累计、瑶光颜料累计、点染××累计
// 万色、一染。读描述的冒号前的内容,找对应套装,加到染色成就表里
// 染色魅力,todo 这里假设各个时装男女需求一样
let exampleDyeGlamour = {
23716: { // 吹雪 金
name: '一染·浮华盛锦',
originDes: '吹雪霓裳:点染·金莹',
type: '定制染色',
typeIcon: 'Icons/Achieve/ach_xinwang.png',
meili: 100, // 魅力值
logic: 'and',
// 特殊判定
setId: 328, // 用于现实
posList: [4037, 4038, 4039, 4040], // 需要达成的部位,直接遍历这个表的posList检查是否符合就行,构造时查set表拿id, todo 与achiIdList互斥
// 满足特殊属性
isSpecial: true,
base: null, // 基础染色的值,根据字符串识别 todo
advance: null,
specialType: 'gold', // 定制金染
}
};
// 染色总计魅力
let exampleDyeSumGlamour = {
23776: { // id
name: '点染·玄夜累计·8',
originDes: '累计消耗:72个点染·玄夜',
type: '累计成就',
typeIcon: 'Icons/Achieve/ach_xinwang.png',
meili: 100, // 魅力值
logic: 'none',
// 特殊判定
item: 'black', // 消耗的物品种类,手动构建,丰彩染料、瑶光、绿、蓝、红、金、黑、白
// 满足特殊属性
count: 100, // 程序里特殊逻辑处理
}
};
// 存储浏览器的数据
let storage = {
4037: { // 影头,单件id
own: true,
dyeList: [
{
isSpecial: 'false',
a: 100,
b: 100,
},
{
isSpecial: 'true',
type: 'blue'
},
]
}
};
// 每当购买、染色变化时,重新计算拥有的套装、魅力值达成(放到state里缓存吧) todo
// 按已有未有、价格排序、按分类看(直接分好)
// 小界面显示密集的已购列表(右边off on按钮)
// 小界面现实已经达成的、未达成的魅力成就
// 收藏外装、散件、特定染色、累计染色消耗
// 文件名Hash函数
function getHash(str) {
let dwHash = new Long(0x4D2960DB, 0x1712E27F, true); // 低位,高位,无符号
str = str.toUpperCase();
str = str.replace(/\//g, '\\');
for (let i = 0; i < str.length; i++) {
dwHash = dwHash.mul(67).add(str.charCodeAt(i));
}
return ('0000000000000000' + dwHash.toString(16)).slice(-16);
} | set | identifier_name |
index.js | const Long = require('long');
const csv = require('csvtojson');
const fs = require('fs');
let imgSrcPath = '/mnt/dyk/Documents/Default Documents/项目-活动-竞赛/天涯明月刀/00.各种助手/94.SFC解包重打包/PySFCExtractor/output/ImageSetsMixed/';
let imgDesPath = './img_output/';
let files = [
'FashionTable.csv', 'FashionSetTable.csv', 'EquipmentTableWaiZhuang.csv', 'AchievementRequestTable_glamour.csv', 'AchievementTable_glamour.csv', 'EquipmentTableZuoJi.csv',
];
let promises = files.map((key) => {
let data = fs.readFileSync(`./input/${key}`);
return csv({checkType: true}).fromString(data.toString().replace(/[\[\]]/g, '')); // todo ???
});
let fashionTable, setTable, itemTable, achiReqTable, achiTable;
Promise.all(promises).then(gen);
function gen(data) {
fashionTable = data[0];
setTable = data[1];
itemTable = data[2];
achiReqTable = data[3];
achiTable = data[4];
// 新增坐骑
itemTable = itemTable.concat(data[5]);
// todo 是否可以染色
let partRes = {};
let setRes = {};
let glamourRes = {};
let dyeRes = {};
let dyesumRes = {};
// 以主表开始遍历
fashionTable.forEach(part => {
// 查item表提数据
let item = itemTable.filter(o => o.iId === part.itemId)[0];
// console.log(part.itemId, item.stItemInfo);
// 反查完成的成就小id
let achiReqList = achiReqTable.filter(o => o.fashionId === part.fashionId); // todo 有空的
// todo 保存6464小icon
let hash = getHash(`DATA\\IMAGESETS\\ICONS\\ITEMTIPSICON\\${item.szTIPS2D}.TGA`);
let fullPath = `${imgSrcPath}${hash}.tga`;
if(fs.existsSync(fullPath)) {
fs.createReadStream(fullPath).pipe(fs.createWriteStream(`${imgDesPath}${item.szTIPS2D}.tga`));
} else {
console.log('文件不存在:', item.szTIPS2D, hash);
}
partRes[part.fashionId] = {
pos: part.position, // 主表
suiyin: part.suiyin, // 主表
weight: part.weight, // 主表
itemId: part.itemId, // 主表
equipData: {
name: item.stItemInfo,
gender: (item.enumSexDemandArray + '').replace(/[\[\] ]/g, '').split('$$').map(parseFloat),
menpai: item.JobDemandArray[0], // todo UseCondition 还分门派!
// 身份、盟会职务不关键,全部显示
explain: item.szExplain,
des: item.szBackground,
icon: item.szTIPS2D, // icon是只有男的 todo 不是!男女都有!
type: item.ddCatDesc,
},
achiId: achiReqList.length === 1 ? achiReqList[0].achievementId : null, // 反查achievement request表,收集了该物品可以达成的成就小Id
};
}); |
// 构造套装表
setTable.forEach(set => {
// todo 保存三体型卡片
[set.iconM, set.iconF, set.iconZ, set.cardM, set.cardF, set.cardZ].forEach(filename => {
let hash = getHash(`DATA\\IMAGESETS\\ICONS\\FASHION\\${filename}.TGA`);
let fullPath = `${imgSrcPath}${hash}.tga`;
if(fs.existsSync(fullPath)) {
fs.createReadStream(fullPath).pipe(fs.createWriteStream(`${imgDesPath}${filename}.tga`));
} else {
console.log('文件不存在:', filename, hash);
}
});
// 保存数据
setRes[set.setId] = {
name: set.setName,
idList: (set.idList + '').replace(/[\[\] ]/g, '').split('$$').map(parseFloat),
origin: set.origin, // 在表最右边
originDes: set.originDes,
card: [set.cardM, set.cardF, set.cardZ],
weight: set.weight, // 排序权重,最右边
};
});
// 构造魅力值表
achiTable.forEach(achi => {
// 通用属性构建
let res = {
name: achi.name, //条件名称
originDes: achi.originDes,
type: achi.type, // 还有累计成就之类的
typeIcon: achi.typeIcon, // 看需求,就是花花Icon
meili: achi.meili,
logic: achi.logic ? 'or' : 'and', // 成就条件逻辑,and或者or,全部完成还是一个就行
};
// 特殊属性构建
if(achi.name.startsWith('万色')) {
// 普通染色魅力值
// 强行找出对应套装 todo
let setName = achi.originDes.split(':')[0];
let set = setTable.filter(o => (o.setName + '').includes(setName))[0]; // todo shuzi id
let base = parseInt(achi.originDes.match(/基础(\d*)/)[1]);
let advance;
let matchRes = achi.originDes.match(/进阶(\d*)/);
if(matchRes)
advance = matchRes[1];
else
advance = null;
res = {
...res,
// 特殊判定
setId: set.setId, // 用于显示
partList: (set.idList + '').replace(/[\[\] ]/g, '').split('$$').map(parseFloat), // 需要达成的部位,直接遍历这个表的posList检查是否符合就行,构造时查set表拿id
// 满足特殊属性
isSpecial: false,
base: base, // 基础染色的值,根据字符串识别 todo
advance: advance,
specialType: null,
};
// 保存
dyeRes[achi.achievementId] = res;
} else if(achi.name.startsWith('一染')) {
// 定制染色魅力值
// 强行找出对应套装 todo
let setName = achi.originDes.split(':')[0];
let set = setTable.filter(o => (o.setName + '').includes(setName))[0]; // todo shuzi id
let type = achi.originDes.match(/点染·(.*)/)[1];
res = {
...res,
// 特殊判定
setId: set.setId, // 用于显示
partList: (set.idList + '').replace(/[\[\] ]/g, '').split('$$').map(parseFloat), // 需要达成的部位,直接遍历这个表的posList检查是否符合就行,构造时查set表拿id
// 满足特殊属性
isSpecial: true,
base: null,
advance: null,
specialType: type,
};
// 保存
dyeRes[achi.achievementId] = res;
} else if(achi.name.startsWith('丰彩染料累计')) {
res = {
...res,
// 特殊判定
item: '丰彩', // 消耗的物品种类,手动构建,丰彩染料、瑶光、绿、蓝、红、金、黑、白的原名
// 满足特殊属性
count: achi.count, // 程序里特殊逻辑处理
};
dyesumRes[achi.achievementId] = res;
} else if(achi.name.startsWith('瑶光颜料累计')) {
res = {
...res,
// 特殊判定
item: '瑶光', // 消耗的物品种类,手动构建,丰彩染料、瑶光、绿、蓝、红、金、黑、白的原名
// 满足特殊属性
count: achi.count, // 程序里特殊逻辑处理
};
dyesumRes[achi.achievementId] = res;
} else if(achi.name.startsWith('点染')) {
let item;
if(achi.name.includes('蓝瓷')) item = '蓝瓷';
else if(achi.name.includes('竹青')) item = '蓝瓷';
else if(achi.name.includes('红烬')) item = '红烬';
else if(achi.name.includes('金莹')) item = '金莹';
else if(achi.name.includes('雪练')) item = '雪练';
else if(achi.name.includes('玄夜')) item = '玄夜';
res = {
...res,
// 特殊判定
item: item, // 消耗的物品种类,手动构建,丰彩染料、瑶光、绿、蓝、红、金、黑、白的原名
// 满足特殊属性
count: achi.count, // 程序里特殊逻辑处理
};
dyesumRes[achi.achievementId] = res;
} else {
// 普通收集类型
// 从aId1 到aId12
let idList = [];
for (let i = 1; i < 12; i++) {
if(achi['aId' + i] > 0) {
idList.push(achi['aId' + i]);
}
}
res = {
...res,
// 通用成就完成表
achiIdList: idList, // 需求Id
};
glamourRes[achi.achievementId] = res;
}
});
console.log('1');
// 写入文件
fs.writeFileSync('./output/part.json', JSON.stringify(partRes, null, 4));
fs.writeFileSync('./output/set.json', JSON.stringify(setRes, null, 4));
fs.writeFileSync('./output/common_glamour.json', JSON.stringify(glamourRes, null, 4));
fs.writeFileSync('./output/dye.json', JSON.stringify(dyeRes, null, 4));
fs.writeFileSync('./output/dye_sum.json', JSON.stringify(dyesumRes, null, 4));
}
/************************************/
/***************数据分析**************/
/************************************/
// 全部散件(Fashion主表)
let exampleParts = {
4037: { // 心王影冠Fashion id
pos: 'head', // 主表
suiyin: 0, // 主表
weight: 2227, // 主表
itemId: 6100920, // 主表
equipData: {
name: '心王·影冠',
gender: [true, true, true],
menpai: -1,
// 身份、盟会职务不关键,全部显示
explain: '使用后获得“心王·影冠”外装外形',
des: '露凝香,玉笼烟。\\n谁共我,醉明月?',
icon: 'ICON_60_equip_Head_M_M_TY_3103', // icon是只有男的
type: '外装',
},
achiId: 24749, // 反查achievement request表,收集了该物品可以达成的成就小Id
}
};
// 全部套装
let exampleSets = {
328: { // 心王影套装id
name: 'setName',
idList: [4037, 4038, 4039, 4040],
origin: 'shop', // 在表最右边
originDes: '商城购买获得',
card: ['ICON_64_equip_coat_M_M_TY_3103', 'ICON_64_equip_coat_F_F_TY_3103', 'ICON_64_equip_coat_Z_Z_TY_3103'],
weight: 309, // 排序权重,最右边
// dyeAchievements: {
//
// }, // 染色成就表
}
};
// // 染色 todo
// let exampleDye = {
//
// };
// 魅力对应
let exampleGlamour = {
24749: { // 魅力条件Id
name: '心王·影', //条件名称
originDes: '商城购买获得',
type: '外装', // 还有累计成就之类的
typeIcon: 'Icons/Achieve/ach_xinwang.png', // 看需求,就是花花Icon
meili: 50,
logic: 'and', // 成就条件逻辑,and或者or,全部完成还是一个就行
// 通用成就完成表
achiIdList: [24749, 24750, 24750, 24750], // 需求Id
}
};
// 遍历魅力表时,特殊的:万色、一染、丰彩染料累计、瑶光颜料累计、点染××累计
// 万色、一染。读描述的冒号前的内容,找对应套装,加到染色成就表里
// 染色魅力,todo 这里假设各个时装男女需求一样
let exampleDyeGlamour = {
23716: { // 吹雪 金
name: '一染·浮华盛锦',
originDes: '吹雪霓裳:点染·金莹',
type: '定制染色',
typeIcon: 'Icons/Achieve/ach_xinwang.png',
meili: 100, // 魅力值
logic: 'and',
// 特殊判定
setId: 328, // 用于现实
posList: [4037, 4038, 4039, 4040], // 需要达成的部位,直接遍历这个表的posList检查是否符合就行,构造时查set表拿id, todo 与achiIdList互斥
// 满足特殊属性
isSpecial: true,
base: null, // 基础染色的值,根据字符串识别 todo
advance: null,
specialType: 'gold', // 定制金染
}
};
// 染色总计魅力
let exampleDyeSumGlamour = {
23776: { // id
name: '点染·玄夜累计·8',
originDes: '累计消耗:72个点染·玄夜',
type: '累计成就',
typeIcon: 'Icons/Achieve/ach_xinwang.png',
meili: 100, // 魅力值
logic: 'none',
// 特殊判定
item: 'black', // 消耗的物品种类,手动构建,丰彩染料、瑶光、绿、蓝、红、金、黑、白
// 满足特殊属性
count: 100, // 程序里特殊逻辑处理
}
};
// 存储浏览器的数据
let storage = {
4037: { // 影头,单件id
own: true,
dyeList: [
{
isSpecial: 'false',
a: 100,
b: 100,
},
{
isSpecial: 'true',
type: 'blue'
},
]
}
};
// 每当购买、染色变化时,重新计算拥有的套装、魅力值达成(放到state里缓存吧) todo
// 按已有未有、价格排序、按分类看(直接分好)
// 小界面显示密集的已购列表(右边off on按钮)
// 小界面现实已经达成的、未达成的魅力成就
// 收藏外装、散件、特定染色、累计染色消耗
// 文件名Hash函数
function getHash(str) {
let dwHash = new Long(0x4D2960DB, 0x1712E27F, true); // 低位,高位,无符号
str = str.toUpperCase();
str = str.replace(/\//g, '\\');
for (let i = 0; i < str.length; i++) {
dwHash = dwHash.mul(67).add(str.charCodeAt(i));
}
return ('0000000000000000' + dwHash.toString(16)).slice(-16);
} | random_line_split | |
index.js | const Long = require('long');
const csv = require('csvtojson');
const fs = require('fs');
let imgSrcPath = '/mnt/dyk/Documents/Default Documents/项目-活动-竞赛/天涯明月刀/00.各种助手/94.SFC解包重打包/PySFCExtractor/output/ImageSetsMixed/';
let imgDesPath = './img_output/';
let files = [
'FashionTable.csv', 'FashionSetTable.csv', 'EquipmentTableWaiZhuang.csv', 'AchievementRequestTable_glamour.csv', 'AchievementTable_glamour.csv', 'EquipmentTableZuoJi.csv',
];
let promises = files.map((key) => {
let data = fs.readFileSync(`./input/${key}`);
return csv({checkType: true}).fromString(data.toString().replace(/[\[\]]/g, '')); // todo ???
});
let fashionTable, setTable, itemTable, achiReqTable, achiTable;
Promise.all(promises).then(gen);
function gen(data) {
fashionTable = data[0];
setTable = data[1];
itemTable = data[2];
achiReqTable = data[3];
achiTable = data[4];
// 新增坐骑
itemTable = itemTable.concat(data[5]);
// todo 是否可以染色
let partRes = {};
let setRes = {};
let glamourRes = {};
let dyeRes = {};
let dyesumRes = {};
// 以主表开始遍历
fashionTable.forEach(part => {
// 查item表提数据
let item = itemTable.filter(o => o.iId === part.itemId)[0];
// console.log(part.itemId, item.stItemInfo);
// 反查完成的成就小id
let achiReqList = achiReqTable.filter(o => o.fashionId === part.fashionId); // todo 有空的
// todo 保存6464小icon
let hash = getHash(`DATA\\IMAGESETS\\ICONS\\ITEMTIPSICON\\${item.szTIPS2D}.TGA`);
let fullPath = `${imgSrcPath}${hash}.tga`;
if(fs.existsSync(fullPath)) {
fs.createReadStream(fullPath).pipe(fs.createWriteStream(`${imgDesPath}${item.szTIPS2D}.tga`));
} else {
console.log('文件不存在:', item.szTIPS2D, hash);
}
partRes[part.fashionId] = {
pos: part.position, // 主表
suiyin: part.suiyin, // 主表
weight: part.weight, // 主表
itemId: part.itemId, // 主表
equipData: {
name: item.stItemInfo,
gender: (item.enumSexDemandArray + '').replace(/[\[\] ]/g, '').split('$$').map(parseFloat),
menpai: item.JobDemandArray[0], // todo UseCondition 还分门派!
// 身份、盟会职务不关键,全部显示
explain: item.szExplain,
des: item.szBackground,
icon: item.szTIPS2D, // icon是只有男的 todo 不是!男女都有!
type: item.ddCatDesc,
},
achiId: achiReqList.length === 1 ? achiReqList[0].achievementId : null, // 反查achievement request表,收集了该物品可以达成的成就小Id
};
});
// 构造套装表
setTable.forEach(set => {
// todo 保存三体型卡片
[set.iconM, set.iconF, set.iconZ, set.cardM, set.cardF, set.cardZ].forEach(filename => {
let hash = getHash(`DATA\\IMAGESETS\\ICONS\\FASHION\\${filename}.TGA`);
let fullPath = `${imgSrcPath}${hash}.tga`;
if(fs.existsSync(fullPath)) {
fs.createReadStream(fullPath).pipe(fs.createWriteStream(`${imgDesPath}${filename}.tga`));
} else {
console.log('文件不存在:', filename, hash);
}
});
// 保存数据
setRes[set.setId] = {
name: set.setName,
idList: (set.idList + '').replace(/[\[\] ]/g, '').split('$$').map(parseFloat),
origin: set.origin, // 在表最右边
originDes: set.originDes,
card: [set.cardM, set.cardF, set.cardZ],
weight: set.weight, // 排序权重,最右边
};
});
// 构造魅力值表
achiTable.forEach(achi => {
// 通用属性构建
let res = {
name: achi.name, //条件名称
originDes: achi.originDes,
type: achi.type, // 还有累计成就之类的
typeIcon: achi.typeIcon, // 看需求,就是花花Icon
meili: achi.meili,
logic: achi.logic ? 'or' : 'and', // 成就条件逻辑,and或者or,全部完成还是一个就行
};
// 特殊属性构建
if(achi.name.startsWith('万色')) {
// 普通染色魅力值
// 强行找出对应套装 todo
let setName = achi.originDes.split(':')[0];
let set = setTable.filter(o => (o.setName + '').includes(setName))[0]; // todo shuzi id
let base = parseInt(achi.originDes.match(/基础(\d*)/)[1]);
let advance;
let matchRes = achi.originDes.match(/进阶(\d*)/);
if(matchRes)
advance = matchRes[1];
else
advance = null;
res = {
...res,
// 特殊判定
setId: set.setId, // 用于显示
partList: (set.idList + '').replace(/[\[\] ]/g, '').split('$$').map(parseFloat), // 需要达成的部位,直接遍历这个表的posList检查是否符合就行,构造时查set表拿id
// 满足特殊属性
isSpecial: false,
base: base, // 基础染色的值,根据字符串识别 todo
advance: advance,
specialType: null,
};
// 保存
dyeRes[achi.achievementId] = res;
} else if(achi.name.startsWith('一染')) {
// 定制染色魅力值
// 强行找出对应套装 todo
let setName = achi.originDes.split(':')[0];
let set = setTable.filter(o => (o.setName + '').includes(setName))[0]; // todo shuzi id
let type = achi.originDes.match(/点染·(.*)/)[1];
res = {
...res,
// 特殊判定
setId: set.setId, // 用于显示
partList: (set.idList + '').replace(/[\[\] ]/g, '').split('$$').map(parseFloat), // 需要达成的部位,直接遍历这个表的posList检查是否符合就行,构造时查set表拿id
// 满足特殊属性
isSpecial: true,
base: null,
advance: null,
specialType: type,
};
// 保存
dyeRes[achi.achievementId] = res;
} else if(achi.name.startsWith('丰彩染料累计')) {
res = {
...res,
// 特殊判定
item: '丰彩', // 消耗的物品种类,手动构建,丰彩染料、瑶光、绿、蓝、红、金、黑、白的原名
// 满足特殊属性
count: achi.count, // 程序里特殊逻辑处理
};
dyesumRes[achi.achievementId] = res;
} else if(achi.name.startsWith('瑶光颜料累计')) {
res = {
...res,
// 特殊判定
item: '瑶光', // 消耗的物品种类,手动构建,丰彩染料、瑶光、绿、蓝、红、金、黑、白的原名
// 满足特殊属性
count: achi.count, // 程序里特殊逻辑处理
};
dyesumRes[achi.achievementId] = res;
} else if(achi.name.startsWith('点染')) {
let item;
if(achi.name.includes('蓝瓷')) item = '蓝瓷';
else if(achi.name.includes('竹青')) item = '蓝瓷';
else if(achi.name.includes('红烬')) item = '红烬';
else if(achi.name.includes('金莹')) item = '金莹';
else if(achi.name.includes('雪练')) item = '雪练';
else if(achi.name.includes('玄夜')) item = '玄夜';
res = {
...res,
// 特殊判定
item: item, // 消耗的物品种类,手动构建,丰彩染料、瑶光、绿、蓝、红、金、黑、白的原名
// 满足特殊属性
count: achi.count, // 程序里特殊逻辑处理
};
dyesumRes[achi.achievementId] = res;
} else {
// 普通收集类型
// 从aId1 到aId12
let idList = [];
for (let i = 1; i < 12; i++) {
if(achi['aId' + i] > 0) {
idList.push(achi['aId' + i]);
}
}
res = {
...res,
// 通用成就完成表
achiIdList: idList, // 需求Id
};
glamourRes[achi.achievementId] = res;
}
});
console.log('1');
// 写入文件
fs.writeFileSync('./output/part.json', JSON.stringify(partRes, null, 4));
fs.writeFileSync('./output/set.json', JSON.stringify(setRes, null, 4));
fs.writeFileSync('./output/common_glamour.json', JSON.stringify(glamourRes, null, 4));
fs.writeFileSync('./output/dye.json', JSON.stringify(dyeRes, null, 4));
fs.writeFileSync('./output/dye_sum.json', JSON.stringify(dyesumRes, null, 4));
}
/************************************/
/***************数据分析**************/
/************************************/
// 全部散件(Fashion主表)
let exampleParts = {
4037: { // 心王影冠Fashion id
pos: 'head', // 主表
suiyin: 0, // 主表
weight: 2227, // 主表
itemId: 6100920, // 主表
equipData: {
name: '心王·影冠',
gender: [true, true, true],
| origin: 'shop', // 在表最右边
originDes: '商城购买获得',
card: ['ICON_64_equip_coat_M_M_TY_3103', 'ICON_64_equip_coat_F_F_TY_3103', 'ICON_64_equip_coat_Z_Z_TY_3103'],
weight: 309, // 排序权重,最右边
// dyeAchievements: {
//
// }, // 染色成就表
}
};
// // 染色 todo
// let exampleDye = {
//
// };
// 魅力对应
let exampleGlamour = {
24749: { // 魅力条件Id
name: '心王·影', //条件名称
originDes: '商城购买获得',
type: '外装', // 还有累计成就之类的
typeIcon: 'Icons/Achieve/ach_xinwang.png', // 看需求,就是花花Icon
meili: 50,
logic: 'and', // 成就条件逻辑,and或者or,全部完成还是一个就行
// 通用成就完成表
achiIdList: [24749, 24750, 24750, 24750], // 需求Id
}
};
// 遍历魅力表时,特殊的:万色、一染、丰彩染料累计、瑶光颜料累计、点染××累计
// 万色、一染。读描述的冒号前的内容,找对应套装,加到染色成就表里
// 染色魅力,todo 这里假设各个时装男女需求一样
let exampleDyeGlamour = {
23716: { // 吹雪 金
name: '一染·浮华盛锦',
originDes: '吹雪霓裳:点染·金莹',
type: '定制染色',
typeIcon: 'Icons/Achieve/ach_xinwang.png',
meili: 100, // 魅力值
logic: 'and',
// 特殊判定
setId: 328, // 用于现实
posList: [4037, 4038, 4039, 4040], // 需要达成的部位,直接遍历这个表的posList检查是否符合就行,构造时查set表拿id, todo 与achiIdList互斥
// 满足特殊属性
isSpecial: true,
base: null, // 基础染色的值,根据字符串识别 todo
advance: null,
specialType: 'gold', // 定制金染
}
};
// 染色总计魅力
let exampleDyeSumGlamour = {
23776: { // id
name: '点染·玄夜累计·8',
originDes: '累计消耗:72个点染·玄夜',
type: '累计成就',
typeIcon: 'Icons/Achieve/ach_xinwang.png',
meili: 100, // 魅力值
logic: 'none',
// 特殊判定
item: 'black', // 消耗的物品种类,手动构建,丰彩染料、瑶光、绿、蓝、红、金、黑、白
// 满足特殊属性
count: 100, // 程序里特殊逻辑处理
}
};
// 存储浏览器的数据
let storage = {
4037: { // 影头,单件id
own: true,
dyeList: [
{
isSpecial: 'false',
a: 100,
b: 100,
},
{
isSpecial: 'true',
type: 'blue'
},
]
}
};
// 每当购买、染色变化时,重新计算拥有的套装、魅力值达成(放到state里缓存吧) todo
// 按已有未有、价格排序、按分类看(直接分好)
// 小界面显示密集的已购列表(右边off on按钮)
// 小界面现实已经达成的、未达成的魅力成就
// 收藏外装、散件、特定染色、累计染色消耗
// 文件名Hash函数
function getHash(str) {
let dwHash = new Long(0x4D2960DB, 0x1712E27F, true); // 低位,高位,无符号
str = str.toUpperCase();
str = str.replace(/\//g, '\\');
for (let i = 0; i < str.length; i++) {
dwHash = dwHash.mul(67).add(str.charCodeAt(i));
}
return ('0000000000000000' + dwHash.toString(16)).slice(-16);
} | menpai: -1,
// 身份、盟会职务不关键,全部显示
explain: '使用后获得“心王·影冠”外装外形',
des: '露凝香,玉笼烟。\\n谁共我,醉明月?',
icon: 'ICON_60_equip_Head_M_M_TY_3103', // icon是只有男的
type: '外装',
},
achiId: 24749, // 反查achievement request表,收集了该物品可以达成的成就小Id
}
};
// 全部套装
let exampleSets = {
328: { // 心王影套装id
name: 'setName',
idList: [4037, 4038, 4039, 4040],
| conditional_block |
main.rs | use ash::extensions::{DebugReport, Surface, Swapchain};
#[cfg(all(unix, not(target_os = "android"), not(target_os = "macos")))]
use ash::extensions::{WaylandSurface, XlibSurface};
use ash::version::{DeviceV1_0, EntryV1_0, InstanceV1_0, V1_0};
use ash::vk::Image;
use ash::vk::PhysicalDevice;
use ash::vk::Semaphore;
use ash::vk::SwapchainKHR;
use ash::Entry;
use ash::{vk, vk_make_version, Device, Instance};
use std::ffi::{CStr, CString};
use std::ptr;
const WIDTH: f64 = 800.0;
const HEIGHT: f64 = 600.0;
fn main() {
let entry = create_entry();
let instance = create_instance(&entry);
let physical_device = pick_physical_device(&instance);
let props = instance.get_physical_device_properties(physical_device);
println!("GPU chosen: {:?}", &unsafe {
CStr::from_ptr(&props.device_name[0])
});
let device = create_device(&instance, &physical_device);
let queue_family_index: u32 = 0;
let present_queue = unsafe { device.get_device_queue(queue_family_index, 0) };
let mut events_loop = winit::EventsLoop::new();
let window = winit::WindowBuilder::new()
.with_title("Ash - Example")
.with_dimensions(winit::dpi::LogicalSize {
width: WIDTH,
height: HEIGHT,
})
.build(&events_loop)
.unwrap();
let (swapchain_loader, swapchain) =
unsafe { create_swapchain(&entry, &instance, &window, physical_device, &device).unwrap() };
let present_images = unsafe { get_present_images(&swapchain_loader, swapchain).unwrap() };
let present_complete_semaphore = unsafe { create_semaphore(&device).unwrap() };
let rendering_complete_semaphore = unsafe { create_semaphore(&device).unwrap() };
let mut closed = false;
while !closed {
events_loop.poll_events(|event| match event {
winit::Event::WindowEvent { event, .. } => match event {
winit::WindowEvent::CloseRequested => closed = true,
_ => {}
},
_ => {}
});
let present_index = unsafe {
swapchain_loader
.acquire_next_image_khr(
swapchain,
std::u64::MAX,
present_complete_semaphore,
vk::Fence::null(),
)
.unwrap()
};
let present_info = vk::PresentInfoKHR {
s_type: vk::StructureType::PresentInfoKhr,
p_next: ptr::null(),
wait_semaphore_count: 0,
// p_wait_semaphores: &rendering_complete_semaphore,
p_wait_semaphores: ptr::null(),
swapchain_count: 1,
p_swapchains: &swapchain,
p_image_indices: &present_index,
p_results: ptr::null_mut(),
};
unsafe {
swapchain_loader
.queue_present_khr(present_queue, &present_info)
.unwrap();
}
}
}
fn create_entry() -> Entry<V1_0> {
Entry::new().unwrap()
}
fn create_instance(entry: &Entry<V1_0>) -> Instance<V1_0> {
let app_name = CString::new("Niagara-rs").unwrap();
let raw_name = app_name.as_ptr();
let appinfo = vk::ApplicationInfo {
s_type: vk::StructureType::ApplicationInfo,
api_version: vk_make_version!(1, 0, 36),
p_application_name: raw_name,
p_engine_name: raw_name,
application_version: 0,
engine_version: 0,
p_next: ptr::null(),
};
let layer_names = [CString::new("VK_LAYER_LUNARG_standard_validation").unwrap()];
let layers_names_raw: Vec<*const i8> = layer_names
.iter()
.map(|raw_name| raw_name.as_ptr())
.collect();
let extension_names_raw = extension_names();
let create_info = vk::InstanceCreateInfo {
s_type: vk::StructureType::InstanceCreateInfo,
p_next: ptr::null(),
flags: Default::default(),
p_application_info: &appinfo,
pp_enabled_layer_names: layers_names_raw.as_ptr(),
enabled_layer_count: layers_names_raw.len() as u32,
pp_enabled_extension_names: extension_names_raw.as_ptr(),
enabled_extension_count: extension_names_raw.len() as u32,
};
unsafe {
let instance = entry
.create_instance(&create_info, None)
.expect("Instance creation error");
let debug_info = vk::DebugReportCallbackCreateInfoEXT {
s_type: vk::StructureType::DebugReportCallbackCreateInfoExt,
p_next: ptr::null(),
flags: vk::DEBUG_REPORT_ERROR_BIT_EXT
| vk::DEBUG_REPORT_WARNING_BIT_EXT
| vk::DEBUG_REPORT_PERFORMANCE_WARNING_BIT_EXT,
pfn_callback: vulkan_debug_callback,
p_user_data: ptr::null_mut(),
};
let debug_report_loader =
DebugReport::new(entry, &instance).expect("Unable to load debug report");
let _debug_call_back = debug_report_loader
.create_debug_report_callback_ext(&debug_info, None)
.unwrap();
return instance;
}
}
fn pick_physical_device(instance: &Instance<V1_0>) -> vk::PhysicalDevice {
let physical_devices = instance
.enumerate_physical_devices()
.expect("Physical device error");
if physical_devices.len() == 0 {
panic!("No GPU found!");
}
let physical_device = physical_devices
.iter()
.max_by_key(|physical_device| {
let props = instance.get_physical_device_properties(**physical_device);
match props.device_type {
vk::PhysicalDeviceType::DiscreteGpu => 2,
vk::PhysicalDeviceType::IntegratedGpu => 1,
_ => 0,
}
})
.expect("No suitable device found!");
return *physical_device;
}
#[cfg(all(unix, not(target_os = "android"), not(target_os = "macos")))]
fn extension_names() -> Vec<*const i8> {
vec![
Surface::name().as_ptr(),
XlibSurface::name().as_ptr(),
DebugReport::name().as_ptr(),
]
}
fn create_device(instance: &Instance<V1_0>, physical_device: &vk::PhysicalDevice) -> Device<V1_0> {
let queue_family_index = 0 as u32;
let priorities = [1.0];
let queue_info = vk::types::DeviceQueueCreateInfo {
s_type: vk::StructureType::DeviceQueueCreateInfo,
p_next: ptr::null(),
flags: Default::default(),
queue_family_index: queue_family_index as u32,
p_queue_priorities: priorities.as_ptr(),
queue_count: priorities.len() as u32,
};
let device_extension_names_raw = [Swapchain::name().as_ptr()];
let features = vk::PhysicalDeviceFeatures {
shader_clip_distance: 1,
..Default::default()
};
let device_create_info = vk::DeviceCreateInfo {
s_type: vk::StructureType::DeviceCreateInfo,
p_next: ptr::null(),
flags: Default::default(),
p_queue_create_infos: &queue_info,
queue_create_info_count: 1,
pp_enabled_layer_names: ptr::null(),
enabled_layer_count: 0,
pp_enabled_extension_names: device_extension_names_raw.as_ptr(),
enabled_extension_count: device_extension_names_raw.len() as u32,
p_enabled_features: &features,
};
unsafe {
let device: Device<V1_0> = instance
.create_device(*physical_device, &device_create_info, None)
.unwrap();
return device;
}
}
#[cfg(all(unix, not(target_os = "android"), not(target_os = "macos")))]
unsafe fn create_surface<E: EntryV1_0, I: InstanceV1_0>(
entry: &E,
instance: &I,
window: &winit::Window,
) -> Result<vk::SurfaceKHR, vk::Result> {
use winit::os::unix::WindowExt;
let x11_display = window.get_xlib_display().unwrap();
let x11_window = window.get_xlib_window().unwrap();
let x11_create_info = vk::XlibSurfaceCreateInfoKHR {
s_type: vk::StructureType::XlibSurfaceCreateInfoKhr,
p_next: ptr::null(),
flags: Default::default(),
window: x11_window as vk::Window,
dpy: x11_display as *mut vk::Display,
};
let xlib_surface_loader =
XlibSurface::new(entry, instance).expect("Unable to load xlib surface");
xlib_surface_loader.create_xlib_surface_khr(&x11_create_info, None)
}
unsafe fn | (
entry: &Entry<V1_0>,
instance: &Instance<V1_0>,
window: &winit::Window,
physical_device: PhysicalDevice,
device: &Device<V1_0>,
) -> Result<(Swapchain, SwapchainKHR), vk::Result> {
let surface = create_surface(entry, instance, window).unwrap();
let surface_loader =
Surface::new(entry, instance).expect("Unable to load the Surface extension");
let surface_formats = surface_loader
.get_physical_device_surface_formats_khr(physical_device, surface)
.unwrap();
let surface_format = surface_formats
.iter()
.map(|sfmt| match sfmt.format {
vk::Format::Undefined => vk::SurfaceFormatKHR {
format: vk::Format::B8g8r8Unorm,
color_space: sfmt.color_space,
},
_ => sfmt.clone(),
})
.nth(0)
.expect("Unable to find suitable surface format.");
let surface_capabilities = surface_loader
.get_physical_device_surface_capabilities_khr(physical_device, surface)
.unwrap();
let mut desired_image_count = surface_capabilities.min_image_count + 1;
if surface_capabilities.max_image_count > 0
&& desired_image_count > surface_capabilities.max_image_count
{
desired_image_count = surface_capabilities.max_image_count;
}
let surface_resolution = match surface_capabilities.current_extent.width {
std::u32::MAX => vk::Extent2D {
width: WIDTH as u32,
height: HEIGHT as u32,
},
_ => surface_capabilities.current_extent,
};
let pre_transform = if surface_capabilities
.supported_transforms
.subset(vk::SURFACE_TRANSFORM_IDENTITY_BIT_KHR)
{
vk::SURFACE_TRANSFORM_IDENTITY_BIT_KHR
} else {
surface_capabilities.current_transform
};
let present_modes = surface_loader
.get_physical_device_surface_present_modes_khr(physical_device, surface)
.unwrap();
let present_mode = present_modes
.iter()
.cloned()
.find(|&mode| mode == vk::PresentModeKHR::Mailbox)
.unwrap_or(vk::PresentModeKHR::Fifo);
let swapchain_create_info = vk::SwapchainCreateInfoKHR {
s_type: vk::StructureType::SwapchainCreateInfoKhr,
p_next: ptr::null(),
flags: Default::default(),
surface: surface,
min_image_count: desired_image_count,
image_color_space: surface_format.color_space,
image_format: surface_format.format,
image_extent: surface_resolution.clone(),
image_usage: vk::IMAGE_USAGE_COLOR_ATTACHMENT_BIT,
image_sharing_mode: vk::SharingMode::Exclusive,
pre_transform: pre_transform,
composite_alpha: vk::COMPOSITE_ALPHA_OPAQUE_BIT_KHR,
present_mode: present_mode,
clipped: 1,
old_swapchain: vk::SwapchainKHR::null(),
image_array_layers: 1,
p_queue_family_indices: ptr::null(),
queue_family_index_count: 0,
};
let swapchain_loader = Swapchain::new(instance, device).expect("Unable to load swapchain");
let swapchain = swapchain_loader
.create_swapchain_khr(&swapchain_create_info, None)
.unwrap();
Ok((swapchain_loader, swapchain))
}
unsafe fn get_present_images(
swapchain_loader: &Swapchain,
swapchain: SwapchainKHR,
) -> Result<Vec<Image>, vk::Result> {
swapchain_loader.get_swapchain_images_khr(swapchain)
}
unsafe fn create_semaphore(device: &Device<V1_0>) -> Result<Semaphore, vk::Result> {
let semaphore_create_info = vk::SemaphoreCreateInfo {
s_type: vk::StructureType::SemaphoreCreateInfo,
p_next: ptr::null(),
flags: Default::default(),
};
device.create_semaphore(&semaphore_create_info, None)
}
unsafe extern "system" fn vulkan_debug_callback(
_: vk::DebugReportFlagsEXT,
_: vk::DebugReportObjectTypeEXT,
_: vk::uint64_t,
_: vk::size_t,
_: vk::int32_t,
_: *const vk::c_char,
p_message: *const vk::c_char,
_: *mut vk::c_void,
) -> u32 {
println!("{:?}", CStr::from_ptr(p_message));
vk::VK_FALSE
}
| create_swapchain | identifier_name |
main.rs | use ash::extensions::{DebugReport, Surface, Swapchain};
#[cfg(all(unix, not(target_os = "android"), not(target_os = "macos")))]
use ash::extensions::{WaylandSurface, XlibSurface};
use ash::version::{DeviceV1_0, EntryV1_0, InstanceV1_0, V1_0};
use ash::vk::Image;
use ash::vk::PhysicalDevice;
use ash::vk::Semaphore;
use ash::vk::SwapchainKHR;
use ash::Entry;
use ash::{vk, vk_make_version, Device, Instance};
use std::ffi::{CStr, CString};
use std::ptr;
const WIDTH: f64 = 800.0;
const HEIGHT: f64 = 600.0;
fn main() {
let entry = create_entry();
let instance = create_instance(&entry);
let physical_device = pick_physical_device(&instance);
let props = instance.get_physical_device_properties(physical_device);
println!("GPU chosen: {:?}", &unsafe {
CStr::from_ptr(&props.device_name[0])
});
let device = create_device(&instance, &physical_device);
let queue_family_index: u32 = 0;
let present_queue = unsafe { device.get_device_queue(queue_family_index, 0) };
let mut events_loop = winit::EventsLoop::new();
let window = winit::WindowBuilder::new()
.with_title("Ash - Example")
.with_dimensions(winit::dpi::LogicalSize {
width: WIDTH,
height: HEIGHT,
})
.build(&events_loop)
.unwrap();
let (swapchain_loader, swapchain) =
unsafe { create_swapchain(&entry, &instance, &window, physical_device, &device).unwrap() };
let present_images = unsafe { get_present_images(&swapchain_loader, swapchain).unwrap() };
let present_complete_semaphore = unsafe { create_semaphore(&device).unwrap() };
let rendering_complete_semaphore = unsafe { create_semaphore(&device).unwrap() };
let mut closed = false;
while !closed {
events_loop.poll_events(|event| match event {
winit::Event::WindowEvent { event, .. } => match event {
winit::WindowEvent::CloseRequested => closed = true,
_ => {}
},
_ => {}
});
let present_index = unsafe {
swapchain_loader
.acquire_next_image_khr(
swapchain,
std::u64::MAX,
present_complete_semaphore,
vk::Fence::null(),
)
.unwrap()
};
let present_info = vk::PresentInfoKHR {
s_type: vk::StructureType::PresentInfoKhr,
p_next: ptr::null(),
wait_semaphore_count: 0,
// p_wait_semaphores: &rendering_complete_semaphore,
p_wait_semaphores: ptr::null(),
swapchain_count: 1,
p_swapchains: &swapchain,
p_image_indices: &present_index,
p_results: ptr::null_mut(),
};
unsafe {
swapchain_loader
.queue_present_khr(present_queue, &present_info)
.unwrap();
}
}
}
fn create_entry() -> Entry<V1_0> {
Entry::new().unwrap()
}
fn create_instance(entry: &Entry<V1_0>) -> Instance<V1_0> {
let app_name = CString::new("Niagara-rs").unwrap();
let raw_name = app_name.as_ptr();
let appinfo = vk::ApplicationInfo {
s_type: vk::StructureType::ApplicationInfo,
api_version: vk_make_version!(1, 0, 36),
p_application_name: raw_name,
p_engine_name: raw_name,
application_version: 0,
engine_version: 0,
p_next: ptr::null(),
};
let layer_names = [CString::new("VK_LAYER_LUNARG_standard_validation").unwrap()];
let layers_names_raw: Vec<*const i8> = layer_names
.iter()
.map(|raw_name| raw_name.as_ptr())
.collect();
let extension_names_raw = extension_names();
let create_info = vk::InstanceCreateInfo {
s_type: vk::StructureType::InstanceCreateInfo,
p_next: ptr::null(),
flags: Default::default(),
p_application_info: &appinfo,
pp_enabled_layer_names: layers_names_raw.as_ptr(),
enabled_layer_count: layers_names_raw.len() as u32,
pp_enabled_extension_names: extension_names_raw.as_ptr(),
enabled_extension_count: extension_names_raw.len() as u32,
};
unsafe {
let instance = entry
.create_instance(&create_info, None)
.expect("Instance creation error");
let debug_info = vk::DebugReportCallbackCreateInfoEXT {
s_type: vk::StructureType::DebugReportCallbackCreateInfoExt,
p_next: ptr::null(),
flags: vk::DEBUG_REPORT_ERROR_BIT_EXT
| vk::DEBUG_REPORT_WARNING_BIT_EXT
| vk::DEBUG_REPORT_PERFORMANCE_WARNING_BIT_EXT,
pfn_callback: vulkan_debug_callback,
p_user_data: ptr::null_mut(),
};
let debug_report_loader =
DebugReport::new(entry, &instance).expect("Unable to load debug report");
let _debug_call_back = debug_report_loader
.create_debug_report_callback_ext(&debug_info, None)
.unwrap();
return instance;
}
}
fn pick_physical_device(instance: &Instance<V1_0>) -> vk::PhysicalDevice {
let physical_devices = instance
.enumerate_physical_devices()
.expect("Physical device error");
if physical_devices.len() == 0 {
panic!("No GPU found!");
}
let physical_device = physical_devices
.iter()
.max_by_key(|physical_device| {
let props = instance.get_physical_device_properties(**physical_device);
match props.device_type {
vk::PhysicalDeviceType::DiscreteGpu => 2,
vk::PhysicalDeviceType::IntegratedGpu => 1,
_ => 0,
}
})
.expect("No suitable device found!");
return *physical_device;
}
#[cfg(all(unix, not(target_os = "android"), not(target_os = "macos")))]
fn extension_names() -> Vec<*const i8> {
vec![
Surface::name().as_ptr(),
XlibSurface::name().as_ptr(),
DebugReport::name().as_ptr(),
]
}
fn create_device(instance: &Instance<V1_0>, physical_device: &vk::PhysicalDevice) -> Device<V1_0> {
let queue_family_index = 0 as u32;
let priorities = [1.0];
let queue_info = vk::types::DeviceQueueCreateInfo {
s_type: vk::StructureType::DeviceQueueCreateInfo,
p_next: ptr::null(),
flags: Default::default(),
queue_family_index: queue_family_index as u32,
p_queue_priorities: priorities.as_ptr(),
queue_count: priorities.len() as u32,
};
let device_extension_names_raw = [Swapchain::name().as_ptr()];
let features = vk::PhysicalDeviceFeatures {
shader_clip_distance: 1,
..Default::default()
};
let device_create_info = vk::DeviceCreateInfo {
s_type: vk::StructureType::DeviceCreateInfo,
p_next: ptr::null(),
flags: Default::default(),
p_queue_create_infos: &queue_info,
queue_create_info_count: 1,
pp_enabled_layer_names: ptr::null(),
enabled_layer_count: 0,
pp_enabled_extension_names: device_extension_names_raw.as_ptr(),
enabled_extension_count: device_extension_names_raw.len() as u32,
p_enabled_features: &features,
};
unsafe {
let device: Device<V1_0> = instance
.create_device(*physical_device, &device_create_info, None)
.unwrap();
return device;
}
}
#[cfg(all(unix, not(target_os = "android"), not(target_os = "macos")))]
unsafe fn create_surface<E: EntryV1_0, I: InstanceV1_0>(
entry: &E,
instance: &I,
window: &winit::Window,
) -> Result<vk::SurfaceKHR, vk::Result> {
use winit::os::unix::WindowExt;
let x11_display = window.get_xlib_display().unwrap();
let x11_window = window.get_xlib_window().unwrap();
let x11_create_info = vk::XlibSurfaceCreateInfoKHR {
s_type: vk::StructureType::XlibSurfaceCreateInfoKhr,
p_next: ptr::null(),
flags: Default::default(),
window: x11_window as vk::Window,
dpy: x11_display as *mut vk::Display,
};
let xlib_surface_loader =
XlibSurface::new(entry, instance).expect("Unable to load xlib surface");
xlib_surface_loader.create_xlib_surface_khr(&x11_create_info, None)
}
unsafe fn create_swapchain(
entry: &Entry<V1_0>,
instance: &Instance<V1_0>,
window: &winit::Window,
physical_device: PhysicalDevice,
device: &Device<V1_0>,
) -> Result<(Swapchain, SwapchainKHR), vk::Result> {
let surface = create_surface(entry, instance, window).unwrap();
let surface_loader =
Surface::new(entry, instance).expect("Unable to load the Surface extension");
let surface_formats = surface_loader
.get_physical_device_surface_formats_khr(physical_device, surface)
.unwrap();
let surface_format = surface_formats
.iter()
.map(|sfmt| match sfmt.format {
vk::Format::Undefined => vk::SurfaceFormatKHR {
format: vk::Format::B8g8r8Unorm,
color_space: sfmt.color_space,
},
_ => sfmt.clone(),
})
.nth(0)
.expect("Unable to find suitable surface format.");
let surface_capabilities = surface_loader
.get_physical_device_surface_capabilities_khr(physical_device, surface)
.unwrap();
let mut desired_image_count = surface_capabilities.min_image_count + 1;
if surface_capabilities.max_image_count > 0
&& desired_image_count > surface_capabilities.max_image_count
{
desired_image_count = surface_capabilities.max_image_count;
}
let surface_resolution = match surface_capabilities.current_extent.width {
std::u32::MAX => vk::Extent2D {
width: WIDTH as u32,
height: HEIGHT as u32,
},
_ => surface_capabilities.current_extent,
};
let pre_transform = if surface_capabilities
.supported_transforms
.subset(vk::SURFACE_TRANSFORM_IDENTITY_BIT_KHR)
{
vk::SURFACE_TRANSFORM_IDENTITY_BIT_KHR
} else {
surface_capabilities.current_transform
};
let present_modes = surface_loader
.get_physical_device_surface_present_modes_khr(physical_device, surface)
.unwrap();
let present_mode = present_modes
.iter()
.cloned()
.find(|&mode| mode == vk::PresentModeKHR::Mailbox)
.unwrap_or(vk::PresentModeKHR::Fifo);
let swapchain_create_info = vk::SwapchainCreateInfoKHR {
s_type: vk::StructureType::SwapchainCreateInfoKhr,
p_next: ptr::null(),
flags: Default::default(),
surface: surface,
min_image_count: desired_image_count,
image_color_space: surface_format.color_space,
image_format: surface_format.format,
image_extent: surface_resolution.clone(),
image_usage: vk::IMAGE_USAGE_COLOR_ATTACHMENT_BIT,
image_sharing_mode: vk::SharingMode::Exclusive,
pre_transform: pre_transform,
composite_alpha: vk::COMPOSITE_ALPHA_OPAQUE_BIT_KHR,
present_mode: present_mode,
clipped: 1,
old_swapchain: vk::SwapchainKHR::null(),
image_array_layers: 1,
p_queue_family_indices: ptr::null(),
queue_family_index_count: 0,
};
let swapchain_loader = Swapchain::new(instance, device).expect("Unable to load swapchain");
let swapchain = swapchain_loader
.create_swapchain_khr(&swapchain_create_info, None)
.unwrap();
Ok((swapchain_loader, swapchain))
}
unsafe fn get_present_images(
swapchain_loader: &Swapchain,
swapchain: SwapchainKHR,
) -> Result<Vec<Image>, vk::Result> {
swapchain_loader.get_swapchain_images_khr(swapchain)
}
unsafe fn create_semaphore(device: &Device<V1_0>) -> Result<Semaphore, vk::Result> { | let semaphore_create_info = vk::SemaphoreCreateInfo {
s_type: vk::StructureType::SemaphoreCreateInfo,
p_next: ptr::null(),
flags: Default::default(),
};
device.create_semaphore(&semaphore_create_info, None)
}
unsafe extern "system" fn vulkan_debug_callback(
_: vk::DebugReportFlagsEXT,
_: vk::DebugReportObjectTypeEXT,
_: vk::uint64_t,
_: vk::size_t,
_: vk::int32_t,
_: *const vk::c_char,
p_message: *const vk::c_char,
_: *mut vk::c_void,
) -> u32 {
println!("{:?}", CStr::from_ptr(p_message));
vk::VK_FALSE
} | random_line_split | |
main.rs | use ash::extensions::{DebugReport, Surface, Swapchain};
#[cfg(all(unix, not(target_os = "android"), not(target_os = "macos")))]
use ash::extensions::{WaylandSurface, XlibSurface};
use ash::version::{DeviceV1_0, EntryV1_0, InstanceV1_0, V1_0};
use ash::vk::Image;
use ash::vk::PhysicalDevice;
use ash::vk::Semaphore;
use ash::vk::SwapchainKHR;
use ash::Entry;
use ash::{vk, vk_make_version, Device, Instance};
use std::ffi::{CStr, CString};
use std::ptr;
const WIDTH: f64 = 800.0;
const HEIGHT: f64 = 600.0;
fn main() {
let entry = create_entry();
let instance = create_instance(&entry);
let physical_device = pick_physical_device(&instance);
let props = instance.get_physical_device_properties(physical_device);
println!("GPU chosen: {:?}", &unsafe {
CStr::from_ptr(&props.device_name[0])
});
let device = create_device(&instance, &physical_device);
let queue_family_index: u32 = 0;
let present_queue = unsafe { device.get_device_queue(queue_family_index, 0) };
let mut events_loop = winit::EventsLoop::new();
let window = winit::WindowBuilder::new()
.with_title("Ash - Example")
.with_dimensions(winit::dpi::LogicalSize {
width: WIDTH,
height: HEIGHT,
})
.build(&events_loop)
.unwrap();
let (swapchain_loader, swapchain) =
unsafe { create_swapchain(&entry, &instance, &window, physical_device, &device).unwrap() };
let present_images = unsafe { get_present_images(&swapchain_loader, swapchain).unwrap() };
let present_complete_semaphore = unsafe { create_semaphore(&device).unwrap() };
let rendering_complete_semaphore = unsafe { create_semaphore(&device).unwrap() };
let mut closed = false;
while !closed {
events_loop.poll_events(|event| match event {
winit::Event::WindowEvent { event, .. } => match event {
winit::WindowEvent::CloseRequested => closed = true,
_ => {}
},
_ => {}
});
let present_index = unsafe {
swapchain_loader
.acquire_next_image_khr(
swapchain,
std::u64::MAX,
present_complete_semaphore,
vk::Fence::null(),
)
.unwrap()
};
let present_info = vk::PresentInfoKHR {
s_type: vk::StructureType::PresentInfoKhr,
p_next: ptr::null(),
wait_semaphore_count: 0,
// p_wait_semaphores: &rendering_complete_semaphore,
p_wait_semaphores: ptr::null(),
swapchain_count: 1,
p_swapchains: &swapchain,
p_image_indices: &present_index,
p_results: ptr::null_mut(),
};
unsafe {
swapchain_loader
.queue_present_khr(present_queue, &present_info)
.unwrap();
}
}
}
fn create_entry() -> Entry<V1_0> |
fn create_instance(entry: &Entry<V1_0>) -> Instance<V1_0> {
let app_name = CString::new("Niagara-rs").unwrap();
let raw_name = app_name.as_ptr();
let appinfo = vk::ApplicationInfo {
s_type: vk::StructureType::ApplicationInfo,
api_version: vk_make_version!(1, 0, 36),
p_application_name: raw_name,
p_engine_name: raw_name,
application_version: 0,
engine_version: 0,
p_next: ptr::null(),
};
let layer_names = [CString::new("VK_LAYER_LUNARG_standard_validation").unwrap()];
let layers_names_raw: Vec<*const i8> = layer_names
.iter()
.map(|raw_name| raw_name.as_ptr())
.collect();
let extension_names_raw = extension_names();
let create_info = vk::InstanceCreateInfo {
s_type: vk::StructureType::InstanceCreateInfo,
p_next: ptr::null(),
flags: Default::default(),
p_application_info: &appinfo,
pp_enabled_layer_names: layers_names_raw.as_ptr(),
enabled_layer_count: layers_names_raw.len() as u32,
pp_enabled_extension_names: extension_names_raw.as_ptr(),
enabled_extension_count: extension_names_raw.len() as u32,
};
unsafe {
let instance = entry
.create_instance(&create_info, None)
.expect("Instance creation error");
let debug_info = vk::DebugReportCallbackCreateInfoEXT {
s_type: vk::StructureType::DebugReportCallbackCreateInfoExt,
p_next: ptr::null(),
flags: vk::DEBUG_REPORT_ERROR_BIT_EXT
| vk::DEBUG_REPORT_WARNING_BIT_EXT
| vk::DEBUG_REPORT_PERFORMANCE_WARNING_BIT_EXT,
pfn_callback: vulkan_debug_callback,
p_user_data: ptr::null_mut(),
};
let debug_report_loader =
DebugReport::new(entry, &instance).expect("Unable to load debug report");
let _debug_call_back = debug_report_loader
.create_debug_report_callback_ext(&debug_info, None)
.unwrap();
return instance;
}
}
fn pick_physical_device(instance: &Instance<V1_0>) -> vk::PhysicalDevice {
let physical_devices = instance
.enumerate_physical_devices()
.expect("Physical device error");
if physical_devices.len() == 0 {
panic!("No GPU found!");
}
let physical_device = physical_devices
.iter()
.max_by_key(|physical_device| {
let props = instance.get_physical_device_properties(**physical_device);
match props.device_type {
vk::PhysicalDeviceType::DiscreteGpu => 2,
vk::PhysicalDeviceType::IntegratedGpu => 1,
_ => 0,
}
})
.expect("No suitable device found!");
return *physical_device;
}
#[cfg(all(unix, not(target_os = "android"), not(target_os = "macos")))]
fn extension_names() -> Vec<*const i8> {
vec![
Surface::name().as_ptr(),
XlibSurface::name().as_ptr(),
DebugReport::name().as_ptr(),
]
}
fn create_device(instance: &Instance<V1_0>, physical_device: &vk::PhysicalDevice) -> Device<V1_0> {
let queue_family_index = 0 as u32;
let priorities = [1.0];
let queue_info = vk::types::DeviceQueueCreateInfo {
s_type: vk::StructureType::DeviceQueueCreateInfo,
p_next: ptr::null(),
flags: Default::default(),
queue_family_index: queue_family_index as u32,
p_queue_priorities: priorities.as_ptr(),
queue_count: priorities.len() as u32,
};
let device_extension_names_raw = [Swapchain::name().as_ptr()];
let features = vk::PhysicalDeviceFeatures {
shader_clip_distance: 1,
..Default::default()
};
let device_create_info = vk::DeviceCreateInfo {
s_type: vk::StructureType::DeviceCreateInfo,
p_next: ptr::null(),
flags: Default::default(),
p_queue_create_infos: &queue_info,
queue_create_info_count: 1,
pp_enabled_layer_names: ptr::null(),
enabled_layer_count: 0,
pp_enabled_extension_names: device_extension_names_raw.as_ptr(),
enabled_extension_count: device_extension_names_raw.len() as u32,
p_enabled_features: &features,
};
unsafe {
let device: Device<V1_0> = instance
.create_device(*physical_device, &device_create_info, None)
.unwrap();
return device;
}
}
#[cfg(all(unix, not(target_os = "android"), not(target_os = "macos")))]
unsafe fn create_surface<E: EntryV1_0, I: InstanceV1_0>(
entry: &E,
instance: &I,
window: &winit::Window,
) -> Result<vk::SurfaceKHR, vk::Result> {
use winit::os::unix::WindowExt;
let x11_display = window.get_xlib_display().unwrap();
let x11_window = window.get_xlib_window().unwrap();
let x11_create_info = vk::XlibSurfaceCreateInfoKHR {
s_type: vk::StructureType::XlibSurfaceCreateInfoKhr,
p_next: ptr::null(),
flags: Default::default(),
window: x11_window as vk::Window,
dpy: x11_display as *mut vk::Display,
};
let xlib_surface_loader =
XlibSurface::new(entry, instance).expect("Unable to load xlib surface");
xlib_surface_loader.create_xlib_surface_khr(&x11_create_info, None)
}
unsafe fn create_swapchain(
entry: &Entry<V1_0>,
instance: &Instance<V1_0>,
window: &winit::Window,
physical_device: PhysicalDevice,
device: &Device<V1_0>,
) -> Result<(Swapchain, SwapchainKHR), vk::Result> {
let surface = create_surface(entry, instance, window).unwrap();
let surface_loader =
Surface::new(entry, instance).expect("Unable to load the Surface extension");
let surface_formats = surface_loader
.get_physical_device_surface_formats_khr(physical_device, surface)
.unwrap();
let surface_format = surface_formats
.iter()
.map(|sfmt| match sfmt.format {
vk::Format::Undefined => vk::SurfaceFormatKHR {
format: vk::Format::B8g8r8Unorm,
color_space: sfmt.color_space,
},
_ => sfmt.clone(),
})
.nth(0)
.expect("Unable to find suitable surface format.");
let surface_capabilities = surface_loader
.get_physical_device_surface_capabilities_khr(physical_device, surface)
.unwrap();
let mut desired_image_count = surface_capabilities.min_image_count + 1;
if surface_capabilities.max_image_count > 0
&& desired_image_count > surface_capabilities.max_image_count
{
desired_image_count = surface_capabilities.max_image_count;
}
let surface_resolution = match surface_capabilities.current_extent.width {
std::u32::MAX => vk::Extent2D {
width: WIDTH as u32,
height: HEIGHT as u32,
},
_ => surface_capabilities.current_extent,
};
let pre_transform = if surface_capabilities
.supported_transforms
.subset(vk::SURFACE_TRANSFORM_IDENTITY_BIT_KHR)
{
vk::SURFACE_TRANSFORM_IDENTITY_BIT_KHR
} else {
surface_capabilities.current_transform
};
let present_modes = surface_loader
.get_physical_device_surface_present_modes_khr(physical_device, surface)
.unwrap();
let present_mode = present_modes
.iter()
.cloned()
.find(|&mode| mode == vk::PresentModeKHR::Mailbox)
.unwrap_or(vk::PresentModeKHR::Fifo);
let swapchain_create_info = vk::SwapchainCreateInfoKHR {
s_type: vk::StructureType::SwapchainCreateInfoKhr,
p_next: ptr::null(),
flags: Default::default(),
surface: surface,
min_image_count: desired_image_count,
image_color_space: surface_format.color_space,
image_format: surface_format.format,
image_extent: surface_resolution.clone(),
image_usage: vk::IMAGE_USAGE_COLOR_ATTACHMENT_BIT,
image_sharing_mode: vk::SharingMode::Exclusive,
pre_transform: pre_transform,
composite_alpha: vk::COMPOSITE_ALPHA_OPAQUE_BIT_KHR,
present_mode: present_mode,
clipped: 1,
old_swapchain: vk::SwapchainKHR::null(),
image_array_layers: 1,
p_queue_family_indices: ptr::null(),
queue_family_index_count: 0,
};
let swapchain_loader = Swapchain::new(instance, device).expect("Unable to load swapchain");
let swapchain = swapchain_loader
.create_swapchain_khr(&swapchain_create_info, None)
.unwrap();
Ok((swapchain_loader, swapchain))
}
unsafe fn get_present_images(
swapchain_loader: &Swapchain,
swapchain: SwapchainKHR,
) -> Result<Vec<Image>, vk::Result> {
swapchain_loader.get_swapchain_images_khr(swapchain)
}
unsafe fn create_semaphore(device: &Device<V1_0>) -> Result<Semaphore, vk::Result> {
let semaphore_create_info = vk::SemaphoreCreateInfo {
s_type: vk::StructureType::SemaphoreCreateInfo,
p_next: ptr::null(),
flags: Default::default(),
};
device.create_semaphore(&semaphore_create_info, None)
}
unsafe extern "system" fn vulkan_debug_callback(
_: vk::DebugReportFlagsEXT,
_: vk::DebugReportObjectTypeEXT,
_: vk::uint64_t,
_: vk::size_t,
_: vk::int32_t,
_: *const vk::c_char,
p_message: *const vk::c_char,
_: *mut vk::c_void,
) -> u32 {
println!("{:?}", CStr::from_ptr(p_message));
vk::VK_FALSE
}
| {
Entry::new().unwrap()
} | identifier_body |
tweetnacl.rs | use core::ops::{Add, AddAssign, Mul, MulAssign, Neg, Sub, SubAssign};
use subtle::{Choice, ConditionallySelectable, ConstantTimeEq};
use zeroize::Zeroize;
use super::FieldImplementation;
pub type Limbs = [i64; 16];
/// Element of the base field of the elliptic curve
#[derive(Clone, Copy, Debug, Default, Zeroize)]
pub struct FieldElement(pub Limbs);
impl ConditionallySelectable for FieldElement {
fn conditional_select(a: &Self, b: &Self, choice: Choice) -> Self {
let mut selection = Self::default();
for i in 0..16 {
selection.0[i] = i64::conditional_select(&a.0[i], &b.0[i], choice);
}
selection
}
fn | (a: &mut Self, b: &mut Self, choice: Choice) {
// what TweetNacl originally does
// let mask: i64 = !(b - 1);
// TweetNacl translated to Choice language
// let mask: i64 = !(choice.unwrap_u8() as i64) - 1);
// `subtle` definition, which is equivalent
// let mask: i64 = -(choice.unwrap_u8() as i64);
for (ai, bi) in a.0.iter_mut().zip(b.0.iter_mut()) {
// let t = mask & (*ai ^ *bi);
// *ai ^= t;
// *bi ^= t;
i64::conditional_swap(ai, bi, choice);
}
}
}
impl FieldImplementation for FieldElement {
type Limbs = Limbs;
const ZERO: Self = Self([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]);
const ONE: Self = Self([1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]);
const D: Self = Self([
0x78a3, 0x1359, 0x4dca, 0x75eb, 0xd8ab, 0x4141, 0x0a4d, 0x0070, 0xe898, 0x7779, 0x4079,
0x8cc7, 0xfe73, 0x2b6f, 0x6cee, 0x5203,
]);
const D2: Self = Self([
0xf159, 0x26b2, 0x9b94, 0xebd6, 0xb156, 0x8283, 0x149a, 0x00e0, 0xd130, 0xeef3, 0x80f2,
0x198e, 0xfce7, 0x56df, 0xd9dc, 0x2406,
]);
const EDWARDS_BASEPOINT_X: Self = Self([
0xd51a, 0x8f25, 0x2d60, 0xc956, 0xa7b2, 0x9525, 0xc760, 0x692c, 0xdc5c, 0xfdd6, 0xe231,
0xc0a4, 0x53fe, 0xcd6e, 0x36d3, 0x2169,
]);
const EDWARDS_BASEPOINT_Y: Self = Self([
0x6658, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666,
0x6666, 0x6666, 0x6666, 0x6666, 0x6666,
]);
const I: Self = Self([
0xa0b0, 0x4a0e, 0x1b27, 0xc4ee, 0xe478, 0xad2f, 0x1806, 0x2f43, 0xd7a7, 0x3dfb, 0x0099,
0x2b4d, 0xdf0b, 0x4fc1, 0x2480, 0x2b83,
]);
const APLUS2_OVER_FOUR: Self = Self([121666, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]);
const MONTGOMERY_BASEPOINT_U: Self = Self([9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]);
fn to_bytes(&self) -> [u8; 32] {
// make our own private copy
let mut fe = *self;
// three times' the charm??
// TODO: figure out why :)
fe.carry();
fe.carry();
fe.carry();
// let m_buf: FieldElementBuffer = Default::default();
// let mut m: FieldElement = FieldElement(m_buf);
let mut m: Limbs = Default::default();
for _j in 0..2 {
m[0] = fe.0[0] - 0xffed;
for i in 1..15 {
m[i] = fe.0[i] - 0xffff - ((m[i - 1] >> 16) & 1);
m[i - 1] &= 0xffff;
}
m[15] = fe.0[15] - 0x7fff - ((m[14] >> 16) & 1);
let b = (m[15] >> 16) & 1;
m[14] &= 0xffff;
FieldElement::conditional_swap(&mut fe, &mut FieldElement(m), ((1 - b) as u8).into());
}
let mut bytes: [u8; 32] = Default::default();
for i in 0..16 {
bytes[2 * i] = fe.0[i] as u8; //& 0xff;
bytes[2 * i + 1] = (fe.0[i] >> 8) as u8;
}
bytes
}
fn from_bytes_unchecked(bytes: &[u8; 32]) -> FieldElement {
let mut limbs = Limbs::default();
for i in 0..16 {
limbs[i] = (bytes[2 * i] as i64) + ((bytes[2 * i + 1] as i64) << 8);
}
// some kind of safety check
// but: also clears the x-coordinate sign bit
limbs[15] &= 0x7fff;
FieldElement(limbs)
}
// sv inv25519(gf o,const gf i)
// {
// // want: o = 1/i in base field
// gf c;
// int a;
// FOR(a,16) c[a]=i[a];
// // exponentiate with 2^255 - 21
// // same as inversion by Fermat's little theorem
// for(a=253;a>=0;a--) {
// S(c,c);
// if(a!=2&&a!=4) M(c,c,i);
// }
// FOR(a,16) o[a]=c[a];
// }
fn inverse(&self) -> FieldElement {
// TODO: possibly assert! that fe != 0?
// make our own private copy
let mut inverse = *self;
// exponentiate with 2**255 - 21,
// which by Fermat's little theorem is the same as inversion
for i in (0..=253).rev() {
inverse = inverse.squared();
if i != 2 && i != 4 {
inverse = &inverse * self;
}
}
inverse
}
// sv pow2523(gf o,const gf i)
// // the naming here means "to the power of 2^252 - 3
// // again by Fermat's little theorem, this is the same
// // as taking the square root, which is needed for
// // point decompression
// {
// gf c;
// int a;
// FOR(a,16) c[a]=i[a];
// for(a=250;a>=0;a--) {
// S(c,c);
// if(a!=1) M(c,c,i);
// }
// FOR(a,16) o[a]=c[a];
// }
/// TODO: figure out why this doesn't pass the test at the end
fn pow2523(&self) -> FieldElement {
let mut sqrt = *self;
for i in (0..=250).rev() {
sqrt = sqrt.squared();
if i != 1 {
sqrt = &sqrt * self;
}
}
sqrt
}
}
impl ConstantTimeEq for FieldElement {
fn ct_eq(&self, other: &Self) -> Choice {
let canonical_self = self.to_bytes();
let canonical_other = other.to_bytes();
canonical_self.ct_eq(&canonical_other)
}
}
impl PartialEq for FieldElement {
fn eq(&self, other: &Self) -> bool {
bool::from(self.ct_eq(other))
}
}
impl<'a, 'b> Add<&'b FieldElement> for &'a FieldElement {
type Output = FieldElement;
// TODO: TweetNaCl doesn't do any reduction here, why not?
/// Addition of field elements
fn add(self, other: &'b FieldElement) -> FieldElement {
let mut sum = *self;
sum += other;
sum
}
}
impl<'b> AddAssign<&'b FieldElement> for FieldElement {
fn add_assign(&mut self, other: &'b FieldElement) {
for (x, y) in self.0.iter_mut().zip(other.0.iter()) {
*x += y;
}
}
}
impl<'a> Neg for &'a FieldElement {
type Output = FieldElement;
/// Subition of field elements
fn neg(self) -> FieldElement {
let mut negation = *self;
for (i, xi) in self.0.iter().enumerate() {
negation.0[i] = -xi;
}
negation
}
}
impl<'a, 'b> Sub<&'b FieldElement> for &'a FieldElement {
type Output = FieldElement;
// TODO: TweetNaCl doesn't do any reduction here, why not?
/// Subition of field elements
fn sub(self, other: &'b FieldElement) -> FieldElement {
let mut difference = *self;
difference -= other;
difference
}
}
impl<'b> SubAssign<&'b FieldElement> for FieldElement {
fn sub_assign(&mut self, other: &'b FieldElement) {
for (x, y) in self.0.iter_mut().zip(other.0.iter()) {
*x -= y;
}
}
}
impl<'a, 'b> Mul<&'b FieldElement> for &'a FieldElement {
type Output = FieldElement;
fn mul(self, other: &'b FieldElement) -> FieldElement {
// start with so-called "schoolbook multiplication"
// TODO: nicer way to do this with iterators?
let mut pre_product: [i64; 31] = Default::default();
for i in 0..16 {
for j in 0..16 {
pre_product[i + j] += self.0[i] * other.0[j];
}
}
// reduce modulo 2**256 - 38
// (en route to reduction modulo 2**255 - 19)
for i in 0..15 {
pre_product[i] += 38 * pre_product[i + 16];
}
// ble, would prefer to call pre_product just product,
// but the two-step initialize then copy doesn't seem
// to work syntactically.
// also: really hope the initialization of `product`
// is optimized away...
let mut product: Limbs = Default::default();
product.copy_from_slice(&pre_product[..16]);
let mut fe = FieldElement(product);
// normalize such that all limbs lie in [0, 2^16)
// TODO: why twice? why is twice enough?
fe.carry();
fe.carry();
fe
}
}
impl<'b> MulAssign<&'b FieldElement> for FieldElement {
fn mul_assign(&mut self, other: &'b FieldElement) {
let result = (self as &FieldElement) * other;
self.0 = result.0;
}
}
impl FieldElement {
fn carry(&mut self) {
// TODO: multiplication calls this twice!!
// TODO: to_bytes calls this thrice!!!
//
// What exactly are the guarantees here?
// Why don't we do this twice or thrice if it's needed?
for i in 0..16 {
// add 2**16
self.0[i] += 1 << 16;
// "carry" part, everything over radix 2**16
let carry = self.0[i] >> 16;
// a) i < 15: add carry bit, subtract 1 to compensate addition of 2^16
// --> o[i + 1] += c - 1 // add carry bit, subtract
// b) i == 15: wraps around to index 0 via 2^256 = 38
// --> o[0] += 38 * (c - 1)
self.0[(i + 1) * ((i < 15) as usize)] +=
carry - 1 + 37 * (carry - 1) * ((i == 15) as i64);
// get rid of carry bit
// TODO: why not get rid of it immediately. kinda clearer
self.0[i] -= carry << 16;
}
}
}
#[cfg(test)]
mod tests {
use super::FieldElement;
use crate::field::FieldImplementation;
use subtle::ConstantTimeEq;
#[test]
fn test_one_plus_one() {
let one = FieldElement::ONE;
let two = &one + &one;
let expected = FieldElement([2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]);
// TODO: Implement PartialEq (hopefully in constant time!)
assert_eq!(two.0, expected.0);
assert!(bool::from(two.ct_eq(&expected)))
}
#[test]
fn test_one_times_zero() {
let one = FieldElement::ONE;
let zero = FieldElement::ZERO;
let result = &one * &zero;
// TODO: Implement PartialEq (hopefully in constant time!)
assert_eq!(result.0, zero.0);
assert!(bool::from(result.ct_eq(&zero)))
}
#[test]
fn test_two_times_three_is_six() {
let one = FieldElement::ONE;
let two = &one + &one;
let three = &two + &one;
let two_times_three = &two * &three;
// no multiplications, just sum up ONEs
let six = (1..=6).fold(FieldElement::ZERO, |partial_sum, _| {
&partial_sum + &FieldElement::ONE
});
assert_eq!(two_times_three.to_bytes(), six.to_bytes());
assert!(bool::from(two_times_three.ct_eq(&six)));
}
#[test]
fn test_negation() {
let d2 = FieldElement::D2;
let minus_d2 = -&d2;
let maybe_zero = &d2 + &minus_d2;
assert_eq!(FieldElement::ZERO.to_bytes(), maybe_zero.to_bytes());
}
#[test]
fn test_inversion() {
let d2 = FieldElement::D2;
let maybe_inverse = d2.inverse();
let maybe_one = &d2 * &maybe_inverse;
assert_eq!(maybe_one.to_bytes(), FieldElement::ONE.to_bytes());
assert!(bool::from(maybe_one.ct_eq(&FieldElement::ONE)));
assert_eq!(maybe_one, FieldElement::ONE);
}
#[test]
fn test_imaginary() {
let minus_one = -&FieldElement::ONE;
let i_squared = &FieldElement::I * &FieldElement::I;
assert_eq!(minus_one, i_squared);
}
#[test]
fn test_square_roots() {
let two = &FieldElement::ONE + &FieldElement::ONE;
// four has Legendre symbol of minus one
let four = &two * &two;
let sqrt_minus_four = &four.pow2523() * &four;
assert_eq!(&sqrt_minus_four * &sqrt_minus_four, -&four);
let sqrt_four = &FieldElement::I * &sqrt_minus_four;
assert_eq!(&sqrt_four * &sqrt_four, four);
let three = &two + &FieldElement::ONE;
// nine has Legendre symbol of one
let nine = &three * &three;
let sqrt_nine = &nine.pow2523() * &nine;
assert_eq!(&sqrt_nine * &sqrt_nine, nine);
}
}
| conditional_swap | identifier_name |
tweetnacl.rs | use core::ops::{Add, AddAssign, Mul, MulAssign, Neg, Sub, SubAssign};
use subtle::{Choice, ConditionallySelectable, ConstantTimeEq};
use zeroize::Zeroize;
use super::FieldImplementation;
pub type Limbs = [i64; 16];
/// Element of the base field of the elliptic curve
#[derive(Clone, Copy, Debug, Default, Zeroize)]
pub struct FieldElement(pub Limbs);
impl ConditionallySelectable for FieldElement {
fn conditional_select(a: &Self, b: &Self, choice: Choice) -> Self {
let mut selection = Self::default();
for i in 0..16 {
selection.0[i] = i64::conditional_select(&a.0[i], &b.0[i], choice);
}
selection
}
fn conditional_swap(a: &mut Self, b: &mut Self, choice: Choice) {
// what TweetNacl originally does
// let mask: i64 = !(b - 1);
// TweetNacl translated to Choice language
// let mask: i64 = !(choice.unwrap_u8() as i64) - 1);
// `subtle` definition, which is equivalent
// let mask: i64 = -(choice.unwrap_u8() as i64);
for (ai, bi) in a.0.iter_mut().zip(b.0.iter_mut()) {
// let t = mask & (*ai ^ *bi);
// *ai ^= t;
// *bi ^= t;
i64::conditional_swap(ai, bi, choice);
}
}
}
impl FieldImplementation for FieldElement {
type Limbs = Limbs;
const ZERO: Self = Self([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]);
const ONE: Self = Self([1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]);
const D: Self = Self([
0x78a3, 0x1359, 0x4dca, 0x75eb, 0xd8ab, 0x4141, 0x0a4d, 0x0070, 0xe898, 0x7779, 0x4079,
0x8cc7, 0xfe73, 0x2b6f, 0x6cee, 0x5203,
]);
const D2: Self = Self([
0xf159, 0x26b2, 0x9b94, 0xebd6, 0xb156, 0x8283, 0x149a, 0x00e0, 0xd130, 0xeef3, 0x80f2,
0x198e, 0xfce7, 0x56df, 0xd9dc, 0x2406,
]);
const EDWARDS_BASEPOINT_X: Self = Self([
0xd51a, 0x8f25, 0x2d60, 0xc956, 0xa7b2, 0x9525, 0xc760, 0x692c, 0xdc5c, 0xfdd6, 0xe231,
0xc0a4, 0x53fe, 0xcd6e, 0x36d3, 0x2169,
]);
const EDWARDS_BASEPOINT_Y: Self = Self([
0x6658, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666,
0x6666, 0x6666, 0x6666, 0x6666, 0x6666,
]);
const I: Self = Self([
0xa0b0, 0x4a0e, 0x1b27, 0xc4ee, 0xe478, 0xad2f, 0x1806, 0x2f43, 0xd7a7, 0x3dfb, 0x0099,
0x2b4d, 0xdf0b, 0x4fc1, 0x2480, 0x2b83,
]);
const APLUS2_OVER_FOUR: Self = Self([121666, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]);
const MONTGOMERY_BASEPOINT_U: Self = Self([9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]);
fn to_bytes(&self) -> [u8; 32] {
// make our own private copy
let mut fe = *self;
// three times' the charm??
// TODO: figure out why :)
fe.carry();
fe.carry();
fe.carry();
// let m_buf: FieldElementBuffer = Default::default();
// let mut m: FieldElement = FieldElement(m_buf);
let mut m: Limbs = Default::default();
for _j in 0..2 {
m[0] = fe.0[0] - 0xffed;
for i in 1..15 {
m[i] = fe.0[i] - 0xffff - ((m[i - 1] >> 16) & 1);
m[i - 1] &= 0xffff;
}
m[15] = fe.0[15] - 0x7fff - ((m[14] >> 16) & 1);
let b = (m[15] >> 16) & 1;
m[14] &= 0xffff;
FieldElement::conditional_swap(&mut fe, &mut FieldElement(m), ((1 - b) as u8).into());
}
let mut bytes: [u8; 32] = Default::default();
for i in 0..16 {
bytes[2 * i] = fe.0[i] as u8; //& 0xff;
bytes[2 * i + 1] = (fe.0[i] >> 8) as u8;
}
bytes
}
fn from_bytes_unchecked(bytes: &[u8; 32]) -> FieldElement {
let mut limbs = Limbs::default();
for i in 0..16 {
limbs[i] = (bytes[2 * i] as i64) + ((bytes[2 * i + 1] as i64) << 8);
}
// some kind of safety check
// but: also clears the x-coordinate sign bit
limbs[15] &= 0x7fff;
FieldElement(limbs)
}
// sv inv25519(gf o,const gf i)
// {
// // want: o = 1/i in base field
// gf c;
// int a;
// FOR(a,16) c[a]=i[a];
// // exponentiate with 2^255 - 21
// // same as inversion by Fermat's little theorem
// for(a=253;a>=0;a--) {
// S(c,c);
// if(a!=2&&a!=4) M(c,c,i);
// }
// FOR(a,16) o[a]=c[a];
// }
fn inverse(&self) -> FieldElement {
// TODO: possibly assert! that fe != 0?
// make our own private copy
let mut inverse = *self;
// exponentiate with 2**255 - 21,
// which by Fermat's little theorem is the same as inversion
for i in (0..=253).rev() {
inverse = inverse.squared();
if i != 2 && i != 4 {
inverse = &inverse * self;
}
}
inverse
}
// sv pow2523(gf o,const gf i)
// // the naming here means "to the power of 2^252 - 3
// // again by Fermat's little theorem, this is the same
// // as taking the square root, which is needed for
// // point decompression
// {
// gf c;
// int a;
// FOR(a,16) c[a]=i[a];
// for(a=250;a>=0;a--) {
// S(c,c);
// if(a!=1) M(c,c,i);
// }
// FOR(a,16) o[a]=c[a];
// }
/// TODO: figure out why this doesn't pass the test at the end
fn pow2523(&self) -> FieldElement {
let mut sqrt = *self;
for i in (0..=250).rev() {
sqrt = sqrt.squared();
if i != 1 {
sqrt = &sqrt * self;
}
}
sqrt
}
}
impl ConstantTimeEq for FieldElement {
fn ct_eq(&self, other: &Self) -> Choice {
let canonical_self = self.to_bytes();
let canonical_other = other.to_bytes();
canonical_self.ct_eq(&canonical_other)
}
}
impl PartialEq for FieldElement {
fn eq(&self, other: &Self) -> bool {
bool::from(self.ct_eq(other))
}
}
impl<'a, 'b> Add<&'b FieldElement> for &'a FieldElement {
type Output = FieldElement;
// TODO: TweetNaCl doesn't do any reduction here, why not?
/// Addition of field elements
fn add(self, other: &'b FieldElement) -> FieldElement {
let mut sum = *self;
sum += other;
sum
}
}
impl<'b> AddAssign<&'b FieldElement> for FieldElement {
fn add_assign(&mut self, other: &'b FieldElement) {
for (x, y) in self.0.iter_mut().zip(other.0.iter()) {
*x += y;
}
}
}
impl<'a> Neg for &'a FieldElement {
type Output = FieldElement;
/// Subition of field elements
fn neg(self) -> FieldElement {
let mut negation = *self;
for (i, xi) in self.0.iter().enumerate() {
negation.0[i] = -xi;
}
negation
}
}
impl<'a, 'b> Sub<&'b FieldElement> for &'a FieldElement {
type Output = FieldElement;
// TODO: TweetNaCl doesn't do any reduction here, why not?
/// Subition of field elements
fn sub(self, other: &'b FieldElement) -> FieldElement {
let mut difference = *self;
difference -= other;
difference
}
}
impl<'b> SubAssign<&'b FieldElement> for FieldElement {
fn sub_assign(&mut self, other: &'b FieldElement) {
for (x, y) in self.0.iter_mut().zip(other.0.iter()) {
*x -= y;
}
}
}
impl<'a, 'b> Mul<&'b FieldElement> for &'a FieldElement {
type Output = FieldElement;
fn mul(self, other: &'b FieldElement) -> FieldElement {
// start with so-called "schoolbook multiplication"
// TODO: nicer way to do this with iterators?
let mut pre_product: [i64; 31] = Default::default();
for i in 0..16 {
for j in 0..16 {
pre_product[i + j] += self.0[i] * other.0[j];
}
}
// reduce modulo 2**256 - 38
// (en route to reduction modulo 2**255 - 19)
for i in 0..15 {
pre_product[i] += 38 * pre_product[i + 16];
}
// ble, would prefer to call pre_product just product,
// but the two-step initialize then copy doesn't seem
// to work syntactically.
// also: really hope the initialization of `product`
// is optimized away...
let mut product: Limbs = Default::default();
product.copy_from_slice(&pre_product[..16]);
let mut fe = FieldElement(product);
// normalize such that all limbs lie in [0, 2^16)
// TODO: why twice? why is twice enough?
fe.carry();
fe.carry();
fe
}
}
impl<'b> MulAssign<&'b FieldElement> for FieldElement {
fn mul_assign(&mut self, other: &'b FieldElement) {
let result = (self as &FieldElement) * other;
self.0 = result.0;
}
}
impl FieldElement {
fn carry(&mut self) {
// TODO: multiplication calls this twice!!
// TODO: to_bytes calls this thrice!!!
//
// What exactly are the guarantees here?
// Why don't we do this twice or thrice if it's needed?
for i in 0..16 {
// add 2**16
self.0[i] += 1 << 16;
// "carry" part, everything over radix 2**16
let carry = self.0[i] >> 16;
// a) i < 15: add carry bit, subtract 1 to compensate addition of 2^16
// --> o[i + 1] += c - 1 // add carry bit, subtract
// b) i == 15: wraps around to index 0 via 2^256 = 38
// --> o[0] += 38 * (c - 1)
self.0[(i + 1) * ((i < 15) as usize)] +=
carry - 1 + 37 * (carry - 1) * ((i == 15) as i64);
// get rid of carry bit
// TODO: why not get rid of it immediately. kinda clearer
self.0[i] -= carry << 16;
}
}
}
#[cfg(test)]
mod tests {
use super::FieldElement;
use crate::field::FieldImplementation;
use subtle::ConstantTimeEq;
#[test]
fn test_one_plus_one() {
let one = FieldElement::ONE;
let two = &one + &one;
let expected = FieldElement([2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]);
// TODO: Implement PartialEq (hopefully in constant time!)
assert_eq!(two.0, expected.0);
assert!(bool::from(two.ct_eq(&expected)))
}
#[test]
fn test_one_times_zero() {
let one = FieldElement::ONE;
let zero = FieldElement::ZERO;
let result = &one * &zero;
// TODO: Implement PartialEq (hopefully in constant time!)
assert_eq!(result.0, zero.0);
assert!(bool::from(result.ct_eq(&zero)))
}
#[test]
fn test_two_times_three_is_six() {
let one = FieldElement::ONE;
let two = &one + &one;
let three = &two + &one;
let two_times_three = &two * &three;
// no multiplications, just sum up ONEs
let six = (1..=6).fold(FieldElement::ZERO, |partial_sum, _| {
&partial_sum + &FieldElement::ONE
});
assert_eq!(two_times_three.to_bytes(), six.to_bytes());
assert!(bool::from(two_times_three.ct_eq(&six)));
}
#[test]
fn test_negation() {
let d2 = FieldElement::D2;
let minus_d2 = -&d2;
let maybe_zero = &d2 + &minus_d2;
assert_eq!(FieldElement::ZERO.to_bytes(), maybe_zero.to_bytes());
}
#[test]
fn test_inversion() {
let d2 = FieldElement::D2;
let maybe_inverse = d2.inverse();
let maybe_one = &d2 * &maybe_inverse; | assert!(bool::from(maybe_one.ct_eq(&FieldElement::ONE)));
assert_eq!(maybe_one, FieldElement::ONE);
}
#[test]
fn test_imaginary() {
let minus_one = -&FieldElement::ONE;
let i_squared = &FieldElement::I * &FieldElement::I;
assert_eq!(minus_one, i_squared);
}
#[test]
fn test_square_roots() {
let two = &FieldElement::ONE + &FieldElement::ONE;
// four has Legendre symbol of minus one
let four = &two * &two;
let sqrt_minus_four = &four.pow2523() * &four;
assert_eq!(&sqrt_minus_four * &sqrt_minus_four, -&four);
let sqrt_four = &FieldElement::I * &sqrt_minus_four;
assert_eq!(&sqrt_four * &sqrt_four, four);
let three = &two + &FieldElement::ONE;
// nine has Legendre symbol of one
let nine = &three * &three;
let sqrt_nine = &nine.pow2523() * &nine;
assert_eq!(&sqrt_nine * &sqrt_nine, nine);
}
} | assert_eq!(maybe_one.to_bytes(), FieldElement::ONE.to_bytes()); | random_line_split |
tweetnacl.rs | use core::ops::{Add, AddAssign, Mul, MulAssign, Neg, Sub, SubAssign};
use subtle::{Choice, ConditionallySelectable, ConstantTimeEq};
use zeroize::Zeroize;
use super::FieldImplementation;
pub type Limbs = [i64; 16];
/// Element of the base field of the elliptic curve
#[derive(Clone, Copy, Debug, Default, Zeroize)]
pub struct FieldElement(pub Limbs);
impl ConditionallySelectable for FieldElement {
fn conditional_select(a: &Self, b: &Self, choice: Choice) -> Self {
let mut selection = Self::default();
for i in 0..16 {
selection.0[i] = i64::conditional_select(&a.0[i], &b.0[i], choice);
}
selection
}
fn conditional_swap(a: &mut Self, b: &mut Self, choice: Choice) {
// what TweetNacl originally does
// let mask: i64 = !(b - 1);
// TweetNacl translated to Choice language
// let mask: i64 = !(choice.unwrap_u8() as i64) - 1);
// `subtle` definition, which is equivalent
// let mask: i64 = -(choice.unwrap_u8() as i64);
for (ai, bi) in a.0.iter_mut().zip(b.0.iter_mut()) {
// let t = mask & (*ai ^ *bi);
// *ai ^= t;
// *bi ^= t;
i64::conditional_swap(ai, bi, choice);
}
}
}
impl FieldImplementation for FieldElement {
type Limbs = Limbs;
const ZERO: Self = Self([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]);
const ONE: Self = Self([1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]);
const D: Self = Self([
0x78a3, 0x1359, 0x4dca, 0x75eb, 0xd8ab, 0x4141, 0x0a4d, 0x0070, 0xe898, 0x7779, 0x4079,
0x8cc7, 0xfe73, 0x2b6f, 0x6cee, 0x5203,
]);
const D2: Self = Self([
0xf159, 0x26b2, 0x9b94, 0xebd6, 0xb156, 0x8283, 0x149a, 0x00e0, 0xd130, 0xeef3, 0x80f2,
0x198e, 0xfce7, 0x56df, 0xd9dc, 0x2406,
]);
const EDWARDS_BASEPOINT_X: Self = Self([
0xd51a, 0x8f25, 0x2d60, 0xc956, 0xa7b2, 0x9525, 0xc760, 0x692c, 0xdc5c, 0xfdd6, 0xe231,
0xc0a4, 0x53fe, 0xcd6e, 0x36d3, 0x2169,
]);
const EDWARDS_BASEPOINT_Y: Self = Self([
0x6658, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666,
0x6666, 0x6666, 0x6666, 0x6666, 0x6666,
]);
const I: Self = Self([
0xa0b0, 0x4a0e, 0x1b27, 0xc4ee, 0xe478, 0xad2f, 0x1806, 0x2f43, 0xd7a7, 0x3dfb, 0x0099,
0x2b4d, 0xdf0b, 0x4fc1, 0x2480, 0x2b83,
]);
const APLUS2_OVER_FOUR: Self = Self([121666, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]);
const MONTGOMERY_BASEPOINT_U: Self = Self([9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]);
fn to_bytes(&self) -> [u8; 32] {
// make our own private copy
let mut fe = *self;
// three times' the charm??
// TODO: figure out why :)
fe.carry();
fe.carry();
fe.carry();
// let m_buf: FieldElementBuffer = Default::default();
// let mut m: FieldElement = FieldElement(m_buf);
let mut m: Limbs = Default::default();
for _j in 0..2 {
m[0] = fe.0[0] - 0xffed;
for i in 1..15 {
m[i] = fe.0[i] - 0xffff - ((m[i - 1] >> 16) & 1);
m[i - 1] &= 0xffff;
}
m[15] = fe.0[15] - 0x7fff - ((m[14] >> 16) & 1);
let b = (m[15] >> 16) & 1;
m[14] &= 0xffff;
FieldElement::conditional_swap(&mut fe, &mut FieldElement(m), ((1 - b) as u8).into());
}
let mut bytes: [u8; 32] = Default::default();
for i in 0..16 {
bytes[2 * i] = fe.0[i] as u8; //& 0xff;
bytes[2 * i + 1] = (fe.0[i] >> 8) as u8;
}
bytes
}
fn from_bytes_unchecked(bytes: &[u8; 32]) -> FieldElement {
let mut limbs = Limbs::default();
for i in 0..16 {
limbs[i] = (bytes[2 * i] as i64) + ((bytes[2 * i + 1] as i64) << 8);
}
// some kind of safety check
// but: also clears the x-coordinate sign bit
limbs[15] &= 0x7fff;
FieldElement(limbs)
}
// sv inv25519(gf o,const gf i)
// {
// // want: o = 1/i in base field
// gf c;
// int a;
// FOR(a,16) c[a]=i[a];
// // exponentiate with 2^255 - 21
// // same as inversion by Fermat's little theorem
// for(a=253;a>=0;a--) {
// S(c,c);
// if(a!=2&&a!=4) M(c,c,i);
// }
// FOR(a,16) o[a]=c[a];
// }
fn inverse(&self) -> FieldElement {
// TODO: possibly assert! that fe != 0?
// make our own private copy
let mut inverse = *self;
// exponentiate with 2**255 - 21,
// which by Fermat's little theorem is the same as inversion
for i in (0..=253).rev() {
inverse = inverse.squared();
if i != 2 && i != 4 {
inverse = &inverse * self;
}
}
inverse
}
// sv pow2523(gf o,const gf i)
// // the naming here means "to the power of 2^252 - 3
// // again by Fermat's little theorem, this is the same
// // as taking the square root, which is needed for
// // point decompression
// {
// gf c;
// int a;
// FOR(a,16) c[a]=i[a];
// for(a=250;a>=0;a--) {
// S(c,c);
// if(a!=1) M(c,c,i);
// }
// FOR(a,16) o[a]=c[a];
// }
/// TODO: figure out why this doesn't pass the test at the end
fn pow2523(&self) -> FieldElement {
let mut sqrt = *self;
for i in (0..=250).rev() {
sqrt = sqrt.squared();
if i != 1 |
}
sqrt
}
}
impl ConstantTimeEq for FieldElement {
fn ct_eq(&self, other: &Self) -> Choice {
let canonical_self = self.to_bytes();
let canonical_other = other.to_bytes();
canonical_self.ct_eq(&canonical_other)
}
}
impl PartialEq for FieldElement {
fn eq(&self, other: &Self) -> bool {
bool::from(self.ct_eq(other))
}
}
impl<'a, 'b> Add<&'b FieldElement> for &'a FieldElement {
type Output = FieldElement;
// TODO: TweetNaCl doesn't do any reduction here, why not?
/// Addition of field elements
fn add(self, other: &'b FieldElement) -> FieldElement {
let mut sum = *self;
sum += other;
sum
}
}
impl<'b> AddAssign<&'b FieldElement> for FieldElement {
fn add_assign(&mut self, other: &'b FieldElement) {
for (x, y) in self.0.iter_mut().zip(other.0.iter()) {
*x += y;
}
}
}
impl<'a> Neg for &'a FieldElement {
type Output = FieldElement;
/// Subition of field elements
fn neg(self) -> FieldElement {
let mut negation = *self;
for (i, xi) in self.0.iter().enumerate() {
negation.0[i] = -xi;
}
negation
}
}
impl<'a, 'b> Sub<&'b FieldElement> for &'a FieldElement {
type Output = FieldElement;
// TODO: TweetNaCl doesn't do any reduction here, why not?
/// Subition of field elements
fn sub(self, other: &'b FieldElement) -> FieldElement {
let mut difference = *self;
difference -= other;
difference
}
}
impl<'b> SubAssign<&'b FieldElement> for FieldElement {
fn sub_assign(&mut self, other: &'b FieldElement) {
for (x, y) in self.0.iter_mut().zip(other.0.iter()) {
*x -= y;
}
}
}
impl<'a, 'b> Mul<&'b FieldElement> for &'a FieldElement {
type Output = FieldElement;
fn mul(self, other: &'b FieldElement) -> FieldElement {
// start with so-called "schoolbook multiplication"
// TODO: nicer way to do this with iterators?
let mut pre_product: [i64; 31] = Default::default();
for i in 0..16 {
for j in 0..16 {
pre_product[i + j] += self.0[i] * other.0[j];
}
}
// reduce modulo 2**256 - 38
// (en route to reduction modulo 2**255 - 19)
for i in 0..15 {
pre_product[i] += 38 * pre_product[i + 16];
}
// ble, would prefer to call pre_product just product,
// but the two-step initialize then copy doesn't seem
// to work syntactically.
// also: really hope the initialization of `product`
// is optimized away...
let mut product: Limbs = Default::default();
product.copy_from_slice(&pre_product[..16]);
let mut fe = FieldElement(product);
// normalize such that all limbs lie in [0, 2^16)
// TODO: why twice? why is twice enough?
fe.carry();
fe.carry();
fe
}
}
impl<'b> MulAssign<&'b FieldElement> for FieldElement {
fn mul_assign(&mut self, other: &'b FieldElement) {
let result = (self as &FieldElement) * other;
self.0 = result.0;
}
}
impl FieldElement {
fn carry(&mut self) {
// TODO: multiplication calls this twice!!
// TODO: to_bytes calls this thrice!!!
//
// What exactly are the guarantees here?
// Why don't we do this twice or thrice if it's needed?
for i in 0..16 {
// add 2**16
self.0[i] += 1 << 16;
// "carry" part, everything over radix 2**16
let carry = self.0[i] >> 16;
// a) i < 15: add carry bit, subtract 1 to compensate addition of 2^16
// --> o[i + 1] += c - 1 // add carry bit, subtract
// b) i == 15: wraps around to index 0 via 2^256 = 38
// --> o[0] += 38 * (c - 1)
self.0[(i + 1) * ((i < 15) as usize)] +=
carry - 1 + 37 * (carry - 1) * ((i == 15) as i64);
// get rid of carry bit
// TODO: why not get rid of it immediately. kinda clearer
self.0[i] -= carry << 16;
}
}
}
#[cfg(test)]
mod tests {
use super::FieldElement;
use crate::field::FieldImplementation;
use subtle::ConstantTimeEq;
#[test]
fn test_one_plus_one() {
let one = FieldElement::ONE;
let two = &one + &one;
let expected = FieldElement([2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]);
// TODO: Implement PartialEq (hopefully in constant time!)
assert_eq!(two.0, expected.0);
assert!(bool::from(two.ct_eq(&expected)))
}
#[test]
fn test_one_times_zero() {
let one = FieldElement::ONE;
let zero = FieldElement::ZERO;
let result = &one * &zero;
// TODO: Implement PartialEq (hopefully in constant time!)
assert_eq!(result.0, zero.0);
assert!(bool::from(result.ct_eq(&zero)))
}
#[test]
fn test_two_times_three_is_six() {
let one = FieldElement::ONE;
let two = &one + &one;
let three = &two + &one;
let two_times_three = &two * &three;
// no multiplications, just sum up ONEs
let six = (1..=6).fold(FieldElement::ZERO, |partial_sum, _| {
&partial_sum + &FieldElement::ONE
});
assert_eq!(two_times_three.to_bytes(), six.to_bytes());
assert!(bool::from(two_times_three.ct_eq(&six)));
}
#[test]
fn test_negation() {
let d2 = FieldElement::D2;
let minus_d2 = -&d2;
let maybe_zero = &d2 + &minus_d2;
assert_eq!(FieldElement::ZERO.to_bytes(), maybe_zero.to_bytes());
}
#[test]
fn test_inversion() {
let d2 = FieldElement::D2;
let maybe_inverse = d2.inverse();
let maybe_one = &d2 * &maybe_inverse;
assert_eq!(maybe_one.to_bytes(), FieldElement::ONE.to_bytes());
assert!(bool::from(maybe_one.ct_eq(&FieldElement::ONE)));
assert_eq!(maybe_one, FieldElement::ONE);
}
#[test]
fn test_imaginary() {
let minus_one = -&FieldElement::ONE;
let i_squared = &FieldElement::I * &FieldElement::I;
assert_eq!(minus_one, i_squared);
}
#[test]
fn test_square_roots() {
let two = &FieldElement::ONE + &FieldElement::ONE;
// four has Legendre symbol of minus one
let four = &two * &two;
let sqrt_minus_four = &four.pow2523() * &four;
assert_eq!(&sqrt_minus_four * &sqrt_minus_four, -&four);
let sqrt_four = &FieldElement::I * &sqrt_minus_four;
assert_eq!(&sqrt_four * &sqrt_four, four);
let three = &two + &FieldElement::ONE;
// nine has Legendre symbol of one
let nine = &three * &three;
let sqrt_nine = &nine.pow2523() * &nine;
assert_eq!(&sqrt_nine * &sqrt_nine, nine);
}
}
| {
sqrt = &sqrt * self;
} | conditional_block |
tweetnacl.rs | use core::ops::{Add, AddAssign, Mul, MulAssign, Neg, Sub, SubAssign};
use subtle::{Choice, ConditionallySelectable, ConstantTimeEq};
use zeroize::Zeroize;
use super::FieldImplementation;
pub type Limbs = [i64; 16];
/// Element of the base field of the elliptic curve
#[derive(Clone, Copy, Debug, Default, Zeroize)]
pub struct FieldElement(pub Limbs);
impl ConditionallySelectable for FieldElement {
fn conditional_select(a: &Self, b: &Self, choice: Choice) -> Self {
let mut selection = Self::default();
for i in 0..16 {
selection.0[i] = i64::conditional_select(&a.0[i], &b.0[i], choice);
}
selection
}
fn conditional_swap(a: &mut Self, b: &mut Self, choice: Choice) {
// what TweetNacl originally does
// let mask: i64 = !(b - 1);
// TweetNacl translated to Choice language
// let mask: i64 = !(choice.unwrap_u8() as i64) - 1);
// `subtle` definition, which is equivalent
// let mask: i64 = -(choice.unwrap_u8() as i64);
for (ai, bi) in a.0.iter_mut().zip(b.0.iter_mut()) {
// let t = mask & (*ai ^ *bi);
// *ai ^= t;
// *bi ^= t;
i64::conditional_swap(ai, bi, choice);
}
}
}
impl FieldImplementation for FieldElement {
type Limbs = Limbs;
const ZERO: Self = Self([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]);
const ONE: Self = Self([1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]);
const D: Self = Self([
0x78a3, 0x1359, 0x4dca, 0x75eb, 0xd8ab, 0x4141, 0x0a4d, 0x0070, 0xe898, 0x7779, 0x4079,
0x8cc7, 0xfe73, 0x2b6f, 0x6cee, 0x5203,
]);
const D2: Self = Self([
0xf159, 0x26b2, 0x9b94, 0xebd6, 0xb156, 0x8283, 0x149a, 0x00e0, 0xd130, 0xeef3, 0x80f2,
0x198e, 0xfce7, 0x56df, 0xd9dc, 0x2406,
]);
const EDWARDS_BASEPOINT_X: Self = Self([
0xd51a, 0x8f25, 0x2d60, 0xc956, 0xa7b2, 0x9525, 0xc760, 0x692c, 0xdc5c, 0xfdd6, 0xe231,
0xc0a4, 0x53fe, 0xcd6e, 0x36d3, 0x2169,
]);
const EDWARDS_BASEPOINT_Y: Self = Self([
0x6658, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666,
0x6666, 0x6666, 0x6666, 0x6666, 0x6666,
]);
const I: Self = Self([
0xa0b0, 0x4a0e, 0x1b27, 0xc4ee, 0xe478, 0xad2f, 0x1806, 0x2f43, 0xd7a7, 0x3dfb, 0x0099,
0x2b4d, 0xdf0b, 0x4fc1, 0x2480, 0x2b83,
]);
const APLUS2_OVER_FOUR: Self = Self([121666, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]);
const MONTGOMERY_BASEPOINT_U: Self = Self([9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]);
fn to_bytes(&self) -> [u8; 32] {
// make our own private copy
let mut fe = *self;
// three times' the charm??
// TODO: figure out why :)
fe.carry();
fe.carry();
fe.carry();
// let m_buf: FieldElementBuffer = Default::default();
// let mut m: FieldElement = FieldElement(m_buf);
let mut m: Limbs = Default::default();
for _j in 0..2 {
m[0] = fe.0[0] - 0xffed;
for i in 1..15 {
m[i] = fe.0[i] - 0xffff - ((m[i - 1] >> 16) & 1);
m[i - 1] &= 0xffff;
}
m[15] = fe.0[15] - 0x7fff - ((m[14] >> 16) & 1);
let b = (m[15] >> 16) & 1;
m[14] &= 0xffff;
FieldElement::conditional_swap(&mut fe, &mut FieldElement(m), ((1 - b) as u8).into());
}
let mut bytes: [u8; 32] = Default::default();
for i in 0..16 {
bytes[2 * i] = fe.0[i] as u8; //& 0xff;
bytes[2 * i + 1] = (fe.0[i] >> 8) as u8;
}
bytes
}
fn from_bytes_unchecked(bytes: &[u8; 32]) -> FieldElement {
let mut limbs = Limbs::default();
for i in 0..16 {
limbs[i] = (bytes[2 * i] as i64) + ((bytes[2 * i + 1] as i64) << 8);
}
// some kind of safety check
// but: also clears the x-coordinate sign bit
limbs[15] &= 0x7fff;
FieldElement(limbs)
}
// sv inv25519(gf o,const gf i)
// {
// // want: o = 1/i in base field
// gf c;
// int a;
// FOR(a,16) c[a]=i[a];
// // exponentiate with 2^255 - 21
// // same as inversion by Fermat's little theorem
// for(a=253;a>=0;a--) {
// S(c,c);
// if(a!=2&&a!=4) M(c,c,i);
// }
// FOR(a,16) o[a]=c[a];
// }
fn inverse(&self) -> FieldElement {
// TODO: possibly assert! that fe != 0?
// make our own private copy
let mut inverse = *self;
// exponentiate with 2**255 - 21,
// which by Fermat's little theorem is the same as inversion
for i in (0..=253).rev() {
inverse = inverse.squared();
if i != 2 && i != 4 {
inverse = &inverse * self;
}
}
inverse
}
// sv pow2523(gf o,const gf i)
// // the naming here means "to the power of 2^252 - 3
// // again by Fermat's little theorem, this is the same
// // as taking the square root, which is needed for
// // point decompression
// {
// gf c;
// int a;
// FOR(a,16) c[a]=i[a];
// for(a=250;a>=0;a--) {
// S(c,c);
// if(a!=1) M(c,c,i);
// }
// FOR(a,16) o[a]=c[a];
// }
/// TODO: figure out why this doesn't pass the test at the end
fn pow2523(&self) -> FieldElement {
let mut sqrt = *self;
for i in (0..=250).rev() {
sqrt = sqrt.squared();
if i != 1 {
sqrt = &sqrt * self;
}
}
sqrt
}
}
impl ConstantTimeEq for FieldElement {
fn ct_eq(&self, other: &Self) -> Choice {
let canonical_self = self.to_bytes();
let canonical_other = other.to_bytes();
canonical_self.ct_eq(&canonical_other)
}
}
impl PartialEq for FieldElement {
fn eq(&self, other: &Self) -> bool {
bool::from(self.ct_eq(other))
}
}
impl<'a, 'b> Add<&'b FieldElement> for &'a FieldElement {
type Output = FieldElement;
// TODO: TweetNaCl doesn't do any reduction here, why not?
/// Addition of field elements
fn add(self, other: &'b FieldElement) -> FieldElement {
let mut sum = *self;
sum += other;
sum
}
}
impl<'b> AddAssign<&'b FieldElement> for FieldElement {
fn add_assign(&mut self, other: &'b FieldElement) {
for (x, y) in self.0.iter_mut().zip(other.0.iter()) {
*x += y;
}
}
}
impl<'a> Neg for &'a FieldElement {
type Output = FieldElement;
/// Subition of field elements
fn neg(self) -> FieldElement {
let mut negation = *self;
for (i, xi) in self.0.iter().enumerate() {
negation.0[i] = -xi;
}
negation
}
}
impl<'a, 'b> Sub<&'b FieldElement> for &'a FieldElement {
type Output = FieldElement;
// TODO: TweetNaCl doesn't do any reduction here, why not?
/// Subition of field elements
fn sub(self, other: &'b FieldElement) -> FieldElement {
let mut difference = *self;
difference -= other;
difference
}
}
impl<'b> SubAssign<&'b FieldElement> for FieldElement {
fn sub_assign(&mut self, other: &'b FieldElement) |
}
impl<'a, 'b> Mul<&'b FieldElement> for &'a FieldElement {
type Output = FieldElement;
fn mul(self, other: &'b FieldElement) -> FieldElement {
// start with so-called "schoolbook multiplication"
// TODO: nicer way to do this with iterators?
let mut pre_product: [i64; 31] = Default::default();
for i in 0..16 {
for j in 0..16 {
pre_product[i + j] += self.0[i] * other.0[j];
}
}
// reduce modulo 2**256 - 38
// (en route to reduction modulo 2**255 - 19)
for i in 0..15 {
pre_product[i] += 38 * pre_product[i + 16];
}
// ble, would prefer to call pre_product just product,
// but the two-step initialize then copy doesn't seem
// to work syntactically.
// also: really hope the initialization of `product`
// is optimized away...
let mut product: Limbs = Default::default();
product.copy_from_slice(&pre_product[..16]);
let mut fe = FieldElement(product);
// normalize such that all limbs lie in [0, 2^16)
// TODO: why twice? why is twice enough?
fe.carry();
fe.carry();
fe
}
}
impl<'b> MulAssign<&'b FieldElement> for FieldElement {
fn mul_assign(&mut self, other: &'b FieldElement) {
let result = (self as &FieldElement) * other;
self.0 = result.0;
}
}
impl FieldElement {
fn carry(&mut self) {
// TODO: multiplication calls this twice!!
// TODO: to_bytes calls this thrice!!!
//
// What exactly are the guarantees here?
// Why don't we do this twice or thrice if it's needed?
for i in 0..16 {
// add 2**16
self.0[i] += 1 << 16;
// "carry" part, everything over radix 2**16
let carry = self.0[i] >> 16;
// a) i < 15: add carry bit, subtract 1 to compensate addition of 2^16
// --> o[i + 1] += c - 1 // add carry bit, subtract
// b) i == 15: wraps around to index 0 via 2^256 = 38
// --> o[0] += 38 * (c - 1)
self.0[(i + 1) * ((i < 15) as usize)] +=
carry - 1 + 37 * (carry - 1) * ((i == 15) as i64);
// get rid of carry bit
// TODO: why not get rid of it immediately. kinda clearer
self.0[i] -= carry << 16;
}
}
}
#[cfg(test)]
mod tests {
use super::FieldElement;
use crate::field::FieldImplementation;
use subtle::ConstantTimeEq;
#[test]
fn test_one_plus_one() {
let one = FieldElement::ONE;
let two = &one + &one;
let expected = FieldElement([2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]);
// TODO: Implement PartialEq (hopefully in constant time!)
assert_eq!(two.0, expected.0);
assert!(bool::from(two.ct_eq(&expected)))
}
#[test]
fn test_one_times_zero() {
let one = FieldElement::ONE;
let zero = FieldElement::ZERO;
let result = &one * &zero;
// TODO: Implement PartialEq (hopefully in constant time!)
assert_eq!(result.0, zero.0);
assert!(bool::from(result.ct_eq(&zero)))
}
#[test]
fn test_two_times_three_is_six() {
let one = FieldElement::ONE;
let two = &one + &one;
let three = &two + &one;
let two_times_three = &two * &three;
// no multiplications, just sum up ONEs
let six = (1..=6).fold(FieldElement::ZERO, |partial_sum, _| {
&partial_sum + &FieldElement::ONE
});
assert_eq!(two_times_three.to_bytes(), six.to_bytes());
assert!(bool::from(two_times_three.ct_eq(&six)));
}
#[test]
fn test_negation() {
let d2 = FieldElement::D2;
let minus_d2 = -&d2;
let maybe_zero = &d2 + &minus_d2;
assert_eq!(FieldElement::ZERO.to_bytes(), maybe_zero.to_bytes());
}
#[test]
fn test_inversion() {
let d2 = FieldElement::D2;
let maybe_inverse = d2.inverse();
let maybe_one = &d2 * &maybe_inverse;
assert_eq!(maybe_one.to_bytes(), FieldElement::ONE.to_bytes());
assert!(bool::from(maybe_one.ct_eq(&FieldElement::ONE)));
assert_eq!(maybe_one, FieldElement::ONE);
}
#[test]
fn test_imaginary() {
let minus_one = -&FieldElement::ONE;
let i_squared = &FieldElement::I * &FieldElement::I;
assert_eq!(minus_one, i_squared);
}
#[test]
fn test_square_roots() {
let two = &FieldElement::ONE + &FieldElement::ONE;
// four has Legendre symbol of minus one
let four = &two * &two;
let sqrt_minus_four = &four.pow2523() * &four;
assert_eq!(&sqrt_minus_four * &sqrt_minus_four, -&four);
let sqrt_four = &FieldElement::I * &sqrt_minus_four;
assert_eq!(&sqrt_four * &sqrt_four, four);
let three = &two + &FieldElement::ONE;
// nine has Legendre symbol of one
let nine = &three * &three;
let sqrt_nine = &nine.pow2523() * &nine;
assert_eq!(&sqrt_nine * &sqrt_nine, nine);
}
}
| {
for (x, y) in self.0.iter_mut().zip(other.0.iter()) {
*x -= y;
}
} | identifier_body |
control.rs | use crossbeam_utils::thread::scope;
use cursive::{
backend::Backend as CursiveBackend,
backends::crossterm,
event::Key,
traits::Nameable,
view::ViewWrapper,
views::{LayerPosition, NamedView},
View,
};
use cursive::{traits::Resizable, views::ResizedView, Cursive};
use cursive_buffered_backend::BufferedBackend;
use dirs::config_dir;
use serde::{Deserialize, Serialize};
use crate::{
align::{AlignAlgorithm, AlignMode},
backend::{send_cross_actions, Action, Cross, Dummy},
cursor::CursorState,
dialog,
doublehex::DoubleHexContext,
file::FileState,
style::Style,
view::{self, Aligned, AlignedMessage},
};
use std::{
error::Error,
fs::read_to_string,
ops::Range,
path::PathBuf,
sync::mpsc::{channel, Receiver, Sender},
};
type CursiveCallback = Box<dyn Fn(&mut Cursive) + 'static + Send>;
/// This is the main loop, here we switch between our custom backend and the cursive backend
/// when opening dialog boxes. This is done because initially, the cursive backend was too flickery.
/// However, this was fixed by using cursive_buffered_backend, so now this is only a minor optimization.
pub fn run(x: FileState, y: FileState) {
let mut settings = Settings::from_config().unwrap_or_default();
let digits = x.address_digits().max(y.address_digits());
settings.style.addr_width = digits;
let mut hv = HexView::new(x, y);
loop {
*match hv {
HexView::Aligned(ref mut v, _, _) => &mut v.dh.style,
HexView::Unaligned(ref mut v) => &mut v.dh.style,
} = settings.style;
let mut cross = Cross::init();
let (hv_new, quit) = hv.process_cross(&mut cross, &settings);
hv = hv_new;
cross.uninit();
// the column setting can be changed during the non-dialog,
// so we need to keep it updated here
settings.style = match &hv {
HexView::Aligned(v, _, _) => v.dh.style,
HexView::Unaligned(v) => v.dh.style,
};
let (hv_new, settings_new) = match quit {
DelegateEvent::Quit => break,
DelegateEvent::OpenDialog(dia) => hv.show_dialog(dia, settings),
_ => (hv, settings),
};
hv = hv_new;
settings = settings_new;
}
}
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
pub struct Settings {
pub algo: AlignAlgorithm,
pub style: Style,
}
impl Settings {
fn config_path() -> Result<PathBuf, std::io::Error> {
match std::env::var_os("BIODIFF_CONFIG_DIR") {
Some(p) => Ok(PathBuf::from(p)),
None => match config_dir() {
Some(mut p) => {
p.push("biodiff");
Ok(p)
}
None => Err(std::io::Error::new(
std::io::ErrorKind::NotFound,
"Could not find configuration directory",
)),
},
}
}
fn settings_file() -> Result<PathBuf, std::io::Error> {
let mut path = Self::config_path()?;
path.push("config.json");
Ok(path)
}
pub fn from_config() -> Option<Self> {
let config = read_to_string(Self::settings_file().ok()?).ok()?;
serde_json::from_str(&config).ok()
}
pub fn save_config(&self) -> Result<(), Box<dyn Error + 'static>> {
let config = serde_json::to_string(self)?;
let r = std::fs::create_dir_all(Self::config_path()?);
if let Err(ref e) = r {
match e.kind() {
std::io::ErrorKind::AlreadyExists => (),
_ => r?,
}
}
std::fs::write(Self::settings_file()?, config)?;
Ok(())
}
}
/// An enum containing either an aligned or unaligned hexview, without
/// a backend for painting.
/// The aligned view also contains a channel for messages, as the alignment
/// algorithms need to dynamically append/prepend new blocks to the view
/// and the crossbeam backend also sends user events over that.
pub enum HexView {
Aligned(
view::Aligned,
Sender<AlignedMessage>,
Receiver<AlignedMessage>,
),
Unaligned(view::Unaligned),
}
impl HexView {
/// Creates a new unaligned view from two files with given indexes and cursor
/// size 16x16.
pub fn new(left: FileState, right: FileState) -> Self {
HexView::Unaligned(view::Unaligned::new(
left,
right,
DoubleHexContext::new((16, 16)),
))
}
/// Turns a hexview into an aligned view using the given algorithm parameters
fn into_aligned(self, algo: &AlignAlgorithm, select: [Option<Range<usize>>; 2]) -> HexView {
let (send, recv) = channel();
match match self {
// first destruct our old hexview into its parts
HexView::Aligned(a, send, recv) => {
a.destruct().map_err(|a| HexView::Aligned(a, send, recv))
}
HexView::Unaligned(u) => u.destruct().map_err(HexView::Unaligned),
} {
// if the cursor was not placed on any index, we currently do nothing
// maybe one could think up some better values to align at here or something
Err(hv) => hv,
Ok((left, right, mut dh)) => {
if matches!(algo.mode, AlignMode::Local | AlignMode::Global) {
dh.cursor = CursorState::new((dh.cursor.get_size_x(), dh.cursor.get_size_y()))
};
HexView::Aligned(
view::Aligned::new(left, right, dh, algo, select, send.clone()),
send,
recv,
)
}
}
}
/// Turns a hexview into an unaligned view at the current cursor
fn into_unaligned(self) -> HexView {
match self {
HexView::Aligned(a, send, recv) => match a.destruct() {
Ok((left, right, cursor)) => {
HexView::Unaligned(view::Unaligned::new(left, right, cursor))
}
Err(a) => HexView::Aligned(a, send, recv),
},
// we don't need to change anything for unaligned views
HexView::Unaligned(_) => self,
}
}
/// Call the relevant event processing functions for the crossterm backend
fn event_proc(&mut self, cross: &mut Cross) -> DelegateEvent {
match self {
HexView::Aligned(ref mut a, ref mut send, ref mut recv) => {
aligned_cross(a, cross, send, recv)
}
HexView::Unaligned(ref mut u) => unaligned_cross(u, cross),
}
}
fn selection(&self) -> [Option<Range<usize>>; 2] {
match self {
HexView::Aligned(a, _, _) => a.selection_file_ranges(),
HexView::Unaligned(u) => u.selection_file_ranges(),
}
}
/// control loop for crossbeam backend, switches the view between aligned and unaligned when
/// requested and runs event loops
fn process_cross(self, cross: &mut Cross, settings: &Settings) -> (Self, DelegateEvent) {
let mut view = self;
let mut quit;
let quit_reason = loop {
let q = view.event_proc(cross);
view = match q {
// delegate to top-level control loop
DelegateEvent::Quit | DelegateEvent::OpenDialog(_) => {
quit = match &mut view {
HexView::Aligned(v, _, _) => !v.process_escape(cross),
HexView::Unaligned(v) => !v.process_escape(cross),
}
.then_some(q);
view
}
DelegateEvent::SwitchToAlign => {
quit = None;
let select = view.selection();
view.into_aligned(&settings.algo, select)
}
DelegateEvent::SwitchToUnalign => {
quit = None;
view.into_unaligned()
}
};
if let Some(q) = quit {
break q;
}
};
(view, quit_reason)
}
/// Setup a cursive instance and shows a dialog constructed through the callback given in `dialog`.
///
/// Note that the settings are placed into the user_data of the cursive instace and can be modified
/// by the callback.
fn show_dialog(self, dialog: CursiveCallback, settings: Settings) -> (Self, Settings) {
let mut siv = cursive::default();
// this theme is the default theme except that the background color is black
siv.set_theme(cursiv_theme());
siv.add_global_callback(Key::Esc, dialog::close_top_maybe_quit);
siv.set_user_data(settings);
match self {
HexView::Aligned(a, send, mut recv) => {
siv.add_fullscreen_layer(a.with_name("aligned").full_screen());
let mut sink = siv.cb_sink().clone();
// we create a new thread that converts the `AlignedMessage`s coming from
// the alignment threads to callbacks on the cursive instance, so this case
// is a bit more complicated than the unaligned one.
scope(|s| {
let join_handle = s.spawn(|_| cursiv_align_relay(&mut recv, &mut sink));
dialog(&mut siv);
siv.try_run_with(|| {
// use the buffered backend as it involves way less flickering
crossterm::Backend::init()
.map(|x| Box::new(BufferedBackend::new(x)) as Box<dyn CursiveBackend>)
})
.expect("Could not run");
// misuse the Action::Quit as a signal for the thread to exit
send.send(AlignedMessage::UserEvent(Action::Quit))
.expect("Could not tell align relay thread to quit");
join_handle
.join()
.expect("Could not join align relay thread");
})
.expect("Could not join align relay thread");
// extract the view from the cursive instance
match peel_onion(&mut siv) {
Some(x) => (
HexView::Aligned(x, send, recv),
siv.take_user_data().unwrap(),
),
None => panic!("Internal error, could not downcast view"),
}
}
HexView::Unaligned(u) => {
siv.add_fullscreen_layer(u.with_name("unaligned").full_screen());
dialog(&mut siv);
siv.try_run_with(|| {
crossterm::Backend::init()
.map(|x| Box::new(BufferedBackend::new(x)) as Box<dyn CursiveBackend>)
})
.expect("Could not run");
// extract the view from the cursive instance
match peel_onion(&mut siv) {
Some(v) => (HexView::Unaligned(v), siv.take_user_data().unwrap()),
None => panic!("Internal error, could not downcast view"),
}
}
}
}
}
// this one causes tears to come from my eyes
fn peel_onion<V: View>(siv: &mut Cursive) -> Option<V> {
siv.screen_mut()
.remove_layer(LayerPosition::FromBack(0))
.downcast::<ResizedView<NamedView<V>>>()
.ok()
.and_then(|view| view.into_inner().ok())
.and_then(|view| view.into_inner().ok())
}
/// Default Cursive theme except that the background color is black
fn cursiv_theme() -> cursive::theme::Theme {
use cursive::theme::{BaseColor::*, Color::*, PaletteColor::*};
let mut cursiv_theme = cursive::theme::load_default();
cursiv_theme.palette[Background] = Dark(Black);
cursiv_theme
}
/// Forwards `AlignedMessage`s from the alignment thread into callbacks for the cursive instance
fn cursiv_align_relay(recv: &mut Receiver<AlignedMessage>, sink: &mut cursive::CbSink) {
for ev in recv.iter() {
match ev {
AlignedMessage::UserEvent(Action::Quit) => break,
otherwise => {
sink.send(Box::new(|siv: &mut Cursive| {
siv.call_on_name("aligned", |view: &mut Aligned| {
view.process_action(&mut Dummy, otherwise);
})
.expect("Could not send new data to view");
}))
.expect("Could not send event to view");
}
}
}
}
/// This enum is used for delegating actions to higher level event loops.
enum DelegateEvent {
Quit,
SwitchToAlign,
SwitchToUnalign,
OpenDialog(CursiveCallback),
}
/// Converts an event to a delegation
fn delegate_action(action: Action) -> Option<DelegateEvent> {
match action {
Action::Quit => Some(DelegateEvent::Quit),
Action::Align => Some(DelegateEvent::SwitchToAlign),
Action::Unalign => Some(DelegateEvent::SwitchToUnalign),
Action::Algorithm => Some(DelegateEvent::OpenDialog(Box::new(dialog::settings))),
Action::Goto => Some(DelegateEvent::OpenDialog(Box::new(dialog::goto))),
Action::Search => Some(DelegateEvent::OpenDialog(Box::new(dialog::search))),
Action::SetOffset => Some(DelegateEvent::OpenDialog(Box::new(dialog::set_offset))),
Action::Help => Some(DelegateEvent::OpenDialog(Box::new(dialog::help_window(
dialog::MAIN_HELP,
)))),
_otherwise => None,
}
}
/// This function is the one that processes actions sent by the event reader loop
/// setup in `unaligned_cross`. Note that the event reader loop has to stay in the same
/// thread, so this process is chosen to not be in the main thread instead.
fn unaligned_cross_recv(
unaligned: &mut view::Unaligned,
cross: &mut Cross,
recv: Receiver<Action>,
) -> DelegateEvent {
unaligned.refresh(cross);
for action in recv.iter() {
if let Some(q) = delegate_action(action) {
return q;
}
unaligned.process_action(cross, action);
}
DelegateEvent::Quit
}
/// This setups the event processing thread for the crossterm backend and reads crossterm's events
fn unaligned_cross(unaligned: &mut view::Unaligned, cross: &mut Cross) -> DelegateEvent {
unaligned.refresh(cross);
let (mut send, recv) = channel();
let mut quit = DelegateEvent::Quit;
scope(|s| {
// both this thread and the send_cross_actions function determine when to quit by
// checking the output of delegate_action, so make sure this is the same
let receiver_thread = s.spawn(|_| unaligned_cross_recv(unaligned, cross, recv));
send_cross_actions(|action| delegate_action(action).is_some(), &mut send);
quit = receiver_thread.join().unwrap();
})
.unwrap();
quit
}
/// This function is the one that processes actions sent by the event reader loop
/// setup in `aligned_cross`, and also the ones sent by the alignment process.
/// Note that the event reader loop has to stay in the same thread, so this
/// process is chosen to not be in the main thread instead.
fn aligned_cross_recv(
aligned: &mut view::Aligned,
cross: &mut Cross,
recv: &mut Receiver<AlignedMessage>,
) -> DelegateEvent {
for msg in recv.iter() {
let msg = match msg {
AlignedMessage::UserEvent(action) => {
if let Some(q) = delegate_action(action) {
return q;
}
msg
}
_ => msg,
};
aligned.process_action(cross, msg);
}
DelegateEvent::Quit
}
/// Using the existing message channel (send, recv), setup a thread that
/// processes the messages and also read the crossterm events in the main thread.
/// The channel should be the same one used when setting up the Aligned view.
fn aligned_cross(
aligned: &mut view::Aligned,
cross: &mut Cross,
send: &mut Sender<AlignedMessage>,
recv: &mut Receiver<AlignedMessage>,
) -> DelegateEvent {
aligned.refresh(cross);
let mut quit = DelegateEvent::Quit;
scope(|s| {
// both the thread and the send_cross_actions function determine when to quit by
// checking the output of delegate_action, so make sure this is the same.
let receiver_thread = s.spawn(|_| aligned_cross_recv(aligned, cross, recv));
send_cross_actions(|action| delegate_action(action).is_some(), send);
quit = receiver_thread.join().unwrap();
})
.unwrap();
quit | } | random_line_split | |
control.rs | use crossbeam_utils::thread::scope;
use cursive::{
backend::Backend as CursiveBackend,
backends::crossterm,
event::Key,
traits::Nameable,
view::ViewWrapper,
views::{LayerPosition, NamedView},
View,
};
use cursive::{traits::Resizable, views::ResizedView, Cursive};
use cursive_buffered_backend::BufferedBackend;
use dirs::config_dir;
use serde::{Deserialize, Serialize};
use crate::{
align::{AlignAlgorithm, AlignMode},
backend::{send_cross_actions, Action, Cross, Dummy},
cursor::CursorState,
dialog,
doublehex::DoubleHexContext,
file::FileState,
style::Style,
view::{self, Aligned, AlignedMessage},
};
use std::{
error::Error,
fs::read_to_string,
ops::Range,
path::PathBuf,
sync::mpsc::{channel, Receiver, Sender},
};
type CursiveCallback = Box<dyn Fn(&mut Cursive) + 'static + Send>;
/// This is the main loop, here we switch between our custom backend and the cursive backend
/// when opening dialog boxes. This is done because initially, the cursive backend was too flickery.
/// However, this was fixed by using cursive_buffered_backend, so now this is only a minor optimization.
pub fn run(x: FileState, y: FileState) {
let mut settings = Settings::from_config().unwrap_or_default();
let digits = x.address_digits().max(y.address_digits());
settings.style.addr_width = digits;
let mut hv = HexView::new(x, y);
loop {
*match hv {
HexView::Aligned(ref mut v, _, _) => &mut v.dh.style,
HexView::Unaligned(ref mut v) => &mut v.dh.style,
} = settings.style;
let mut cross = Cross::init();
let (hv_new, quit) = hv.process_cross(&mut cross, &settings);
hv = hv_new;
cross.uninit();
// the column setting can be changed during the non-dialog,
// so we need to keep it updated here
settings.style = match &hv {
HexView::Aligned(v, _, _) => v.dh.style,
HexView::Unaligned(v) => v.dh.style,
};
let (hv_new, settings_new) = match quit {
DelegateEvent::Quit => break,
DelegateEvent::OpenDialog(dia) => hv.show_dialog(dia, settings),
_ => (hv, settings),
};
hv = hv_new;
settings = settings_new;
}
}
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
pub struct Settings {
pub algo: AlignAlgorithm,
pub style: Style,
}
impl Settings {
fn config_path() -> Result<PathBuf, std::io::Error> {
match std::env::var_os("BIODIFF_CONFIG_DIR") {
Some(p) => Ok(PathBuf::from(p)),
None => match config_dir() {
Some(mut p) => {
p.push("biodiff");
Ok(p)
}
None => Err(std::io::Error::new(
std::io::ErrorKind::NotFound,
"Could not find configuration directory",
)),
},
}
}
fn settings_file() -> Result<PathBuf, std::io::Error> {
let mut path = Self::config_path()?;
path.push("config.json");
Ok(path)
}
pub fn from_config() -> Option<Self> {
let config = read_to_string(Self::settings_file().ok()?).ok()?;
serde_json::from_str(&config).ok()
}
pub fn save_config(&self) -> Result<(), Box<dyn Error + 'static>> {
let config = serde_json::to_string(self)?;
let r = std::fs::create_dir_all(Self::config_path()?);
if let Err(ref e) = r {
match e.kind() {
std::io::ErrorKind::AlreadyExists => (),
_ => r?,
}
}
std::fs::write(Self::settings_file()?, config)?;
Ok(())
}
}
/// An enum containing either an aligned or unaligned hexview, without
/// a backend for painting.
/// The aligned view also contains a channel for messages, as the alignment
/// algorithms need to dynamically append/prepend new blocks to the view
/// and the crossbeam backend also sends user events over that.
pub enum HexView {
Aligned(
view::Aligned,
Sender<AlignedMessage>,
Receiver<AlignedMessage>,
),
Unaligned(view::Unaligned),
}
impl HexView {
/// Creates a new unaligned view from two files with given indexes and cursor
/// size 16x16.
pub fn new(left: FileState, right: FileState) -> Self {
HexView::Unaligned(view::Unaligned::new(
left,
right,
DoubleHexContext::new((16, 16)),
))
}
/// Turns a hexview into an aligned view using the given algorithm parameters
fn into_aligned(self, algo: &AlignAlgorithm, select: [Option<Range<usize>>; 2]) -> HexView {
let (send, recv) = channel();
match match self {
// first destruct our old hexview into its parts
HexView::Aligned(a, send, recv) => {
a.destruct().map_err(|a| HexView::Aligned(a, send, recv))
}
HexView::Unaligned(u) => u.destruct().map_err(HexView::Unaligned),
} {
// if the cursor was not placed on any index, we currently do nothing
// maybe one could think up some better values to align at here or something
Err(hv) => hv,
Ok((left, right, mut dh)) => {
if matches!(algo.mode, AlignMode::Local | AlignMode::Global) {
dh.cursor = CursorState::new((dh.cursor.get_size_x(), dh.cursor.get_size_y()))
};
HexView::Aligned(
view::Aligned::new(left, right, dh, algo, select, send.clone()),
send,
recv,
)
}
}
}
/// Turns a hexview into an unaligned view at the current cursor
fn into_unaligned(self) -> HexView {
match self {
HexView::Aligned(a, send, recv) => match a.destruct() {
Ok((left, right, cursor)) => {
HexView::Unaligned(view::Unaligned::new(left, right, cursor))
}
Err(a) => HexView::Aligned(a, send, recv),
},
// we don't need to change anything for unaligned views
HexView::Unaligned(_) => self,
}
}
/// Call the relevant event processing functions for the crossterm backend
fn event_proc(&mut self, cross: &mut Cross) -> DelegateEvent {
match self {
HexView::Aligned(ref mut a, ref mut send, ref mut recv) => {
aligned_cross(a, cross, send, recv)
}
HexView::Unaligned(ref mut u) => unaligned_cross(u, cross),
}
}
fn selection(&self) -> [Option<Range<usize>>; 2] {
match self {
HexView::Aligned(a, _, _) => a.selection_file_ranges(),
HexView::Unaligned(u) => u.selection_file_ranges(),
}
}
/// control loop for crossbeam backend, switches the view between aligned and unaligned when
/// requested and runs event loops
fn process_cross(self, cross: &mut Cross, settings: &Settings) -> (Self, DelegateEvent) {
let mut view = self;
let mut quit;
let quit_reason = loop {
let q = view.event_proc(cross);
view = match q {
// delegate to top-level control loop
DelegateEvent::Quit | DelegateEvent::OpenDialog(_) => {
quit = match &mut view {
HexView::Aligned(v, _, _) => !v.process_escape(cross),
HexView::Unaligned(v) => !v.process_escape(cross),
}
.then_some(q);
view
}
DelegateEvent::SwitchToAlign => {
quit = None;
let select = view.selection();
view.into_aligned(&settings.algo, select)
}
DelegateEvent::SwitchToUnalign => {
quit = None;
view.into_unaligned()
}
};
if let Some(q) = quit {
break q;
}
};
(view, quit_reason)
}
/// Setup a cursive instance and shows a dialog constructed through the callback given in `dialog`.
///
/// Note that the settings are placed into the user_data of the cursive instace and can be modified
/// by the callback.
fn show_dialog(self, dialog: CursiveCallback, settings: Settings) -> (Self, Settings) {
let mut siv = cursive::default();
// this theme is the default theme except that the background color is black
siv.set_theme(cursiv_theme());
siv.add_global_callback(Key::Esc, dialog::close_top_maybe_quit);
siv.set_user_data(settings);
match self {
HexView::Aligned(a, send, mut recv) => {
siv.add_fullscreen_layer(a.with_name("aligned").full_screen());
let mut sink = siv.cb_sink().clone();
// we create a new thread that converts the `AlignedMessage`s coming from
// the alignment threads to callbacks on the cursive instance, so this case
// is a bit more complicated than the unaligned one.
scope(|s| {
let join_handle = s.spawn(|_| cursiv_align_relay(&mut recv, &mut sink));
dialog(&mut siv);
siv.try_run_with(|| {
// use the buffered backend as it involves way less flickering
crossterm::Backend::init()
.map(|x| Box::new(BufferedBackend::new(x)) as Box<dyn CursiveBackend>)
})
.expect("Could not run");
// misuse the Action::Quit as a signal for the thread to exit
send.send(AlignedMessage::UserEvent(Action::Quit))
.expect("Could not tell align relay thread to quit");
join_handle
.join()
.expect("Could not join align relay thread");
})
.expect("Could not join align relay thread");
// extract the view from the cursive instance
match peel_onion(&mut siv) {
Some(x) => (
HexView::Aligned(x, send, recv),
siv.take_user_data().unwrap(),
),
None => panic!("Internal error, could not downcast view"),
}
}
HexView::Unaligned(u) => {
siv.add_fullscreen_layer(u.with_name("unaligned").full_screen());
dialog(&mut siv);
siv.try_run_with(|| {
crossterm::Backend::init()
.map(|x| Box::new(BufferedBackend::new(x)) as Box<dyn CursiveBackend>)
})
.expect("Could not run");
// extract the view from the cursive instance
match peel_onion(&mut siv) {
Some(v) => (HexView::Unaligned(v), siv.take_user_data().unwrap()),
None => panic!("Internal error, could not downcast view"),
}
}
}
}
}
// this one causes tears to come from my eyes
fn peel_onion<V: View>(siv: &mut Cursive) -> Option<V> {
siv.screen_mut()
.remove_layer(LayerPosition::FromBack(0))
.downcast::<ResizedView<NamedView<V>>>()
.ok()
.and_then(|view| view.into_inner().ok())
.and_then(|view| view.into_inner().ok())
}
/// Default Cursive theme except that the background color is black
fn cursiv_theme() -> cursive::theme::Theme {
use cursive::theme::{BaseColor::*, Color::*, PaletteColor::*};
let mut cursiv_theme = cursive::theme::load_default();
cursiv_theme.palette[Background] = Dark(Black);
cursiv_theme
}
/// Forwards `AlignedMessage`s from the alignment thread into callbacks for the cursive instance
fn cursiv_align_relay(recv: &mut Receiver<AlignedMessage>, sink: &mut cursive::CbSink) {
for ev in recv.iter() {
match ev {
AlignedMessage::UserEvent(Action::Quit) => break,
otherwise => |
}
}
}
/// This enum is used for delegating actions to higher level event loops.
enum DelegateEvent {
Quit,
SwitchToAlign,
SwitchToUnalign,
OpenDialog(CursiveCallback),
}
/// Converts an event to a delegation
fn delegate_action(action: Action) -> Option<DelegateEvent> {
match action {
Action::Quit => Some(DelegateEvent::Quit),
Action::Align => Some(DelegateEvent::SwitchToAlign),
Action::Unalign => Some(DelegateEvent::SwitchToUnalign),
Action::Algorithm => Some(DelegateEvent::OpenDialog(Box::new(dialog::settings))),
Action::Goto => Some(DelegateEvent::OpenDialog(Box::new(dialog::goto))),
Action::Search => Some(DelegateEvent::OpenDialog(Box::new(dialog::search))),
Action::SetOffset => Some(DelegateEvent::OpenDialog(Box::new(dialog::set_offset))),
Action::Help => Some(DelegateEvent::OpenDialog(Box::new(dialog::help_window(
dialog::MAIN_HELP,
)))),
_otherwise => None,
}
}
/// This function is the one that processes actions sent by the event reader loop
/// setup in `unaligned_cross`. Note that the event reader loop has to stay in the same
/// thread, so this process is chosen to not be in the main thread instead.
fn unaligned_cross_recv(
unaligned: &mut view::Unaligned,
cross: &mut Cross,
recv: Receiver<Action>,
) -> DelegateEvent {
unaligned.refresh(cross);
for action in recv.iter() {
if let Some(q) = delegate_action(action) {
return q;
}
unaligned.process_action(cross, action);
}
DelegateEvent::Quit
}
/// This setups the event processing thread for the crossterm backend and reads crossterm's events
fn unaligned_cross(unaligned: &mut view::Unaligned, cross: &mut Cross) -> DelegateEvent {
unaligned.refresh(cross);
let (mut send, recv) = channel();
let mut quit = DelegateEvent::Quit;
scope(|s| {
// both this thread and the send_cross_actions function determine when to quit by
// checking the output of delegate_action, so make sure this is the same
let receiver_thread = s.spawn(|_| unaligned_cross_recv(unaligned, cross, recv));
send_cross_actions(|action| delegate_action(action).is_some(), &mut send);
quit = receiver_thread.join().unwrap();
})
.unwrap();
quit
}
/// This function is the one that processes actions sent by the event reader loop
/// setup in `aligned_cross`, and also the ones sent by the alignment process.
/// Note that the event reader loop has to stay in the same thread, so this
/// process is chosen to not be in the main thread instead.
fn aligned_cross_recv(
aligned: &mut view::Aligned,
cross: &mut Cross,
recv: &mut Receiver<AlignedMessage>,
) -> DelegateEvent {
for msg in recv.iter() {
let msg = match msg {
AlignedMessage::UserEvent(action) => {
if let Some(q) = delegate_action(action) {
return q;
}
msg
}
_ => msg,
};
aligned.process_action(cross, msg);
}
DelegateEvent::Quit
}
/// Using the existing message channel (send, recv), setup a thread that
/// processes the messages and also read the crossterm events in the main thread.
/// The channel should be the same one used when setting up the Aligned view.
fn aligned_cross(
aligned: &mut view::Aligned,
cross: &mut Cross,
send: &mut Sender<AlignedMessage>,
recv: &mut Receiver<AlignedMessage>,
) -> DelegateEvent {
aligned.refresh(cross);
let mut quit = DelegateEvent::Quit;
scope(|s| {
// both the thread and the send_cross_actions function determine when to quit by
// checking the output of delegate_action, so make sure this is the same.
let receiver_thread = s.spawn(|_| aligned_cross_recv(aligned, cross, recv));
send_cross_actions(|action| delegate_action(action).is_some(), send);
quit = receiver_thread.join().unwrap();
})
.unwrap();
quit
}
| {
sink.send(Box::new(|siv: &mut Cursive| {
siv.call_on_name("aligned", |view: &mut Aligned| {
view.process_action(&mut Dummy, otherwise);
})
.expect("Could not send new data to view");
}))
.expect("Could not send event to view");
} | conditional_block |
control.rs | use crossbeam_utils::thread::scope;
use cursive::{
backend::Backend as CursiveBackend,
backends::crossterm,
event::Key,
traits::Nameable,
view::ViewWrapper,
views::{LayerPosition, NamedView},
View,
};
use cursive::{traits::Resizable, views::ResizedView, Cursive};
use cursive_buffered_backend::BufferedBackend;
use dirs::config_dir;
use serde::{Deserialize, Serialize};
use crate::{
align::{AlignAlgorithm, AlignMode},
backend::{send_cross_actions, Action, Cross, Dummy},
cursor::CursorState,
dialog,
doublehex::DoubleHexContext,
file::FileState,
style::Style,
view::{self, Aligned, AlignedMessage},
};
use std::{
error::Error,
fs::read_to_string,
ops::Range,
path::PathBuf,
sync::mpsc::{channel, Receiver, Sender},
};
type CursiveCallback = Box<dyn Fn(&mut Cursive) + 'static + Send>;
/// This is the main loop, here we switch between our custom backend and the cursive backend
/// when opening dialog boxes. This is done because initially, the cursive backend was too flickery.
/// However, this was fixed by using cursive_buffered_backend, so now this is only a minor optimization.
pub fn run(x: FileState, y: FileState) {
let mut settings = Settings::from_config().unwrap_or_default();
let digits = x.address_digits().max(y.address_digits());
settings.style.addr_width = digits;
let mut hv = HexView::new(x, y);
loop {
*match hv {
HexView::Aligned(ref mut v, _, _) => &mut v.dh.style,
HexView::Unaligned(ref mut v) => &mut v.dh.style,
} = settings.style;
let mut cross = Cross::init();
let (hv_new, quit) = hv.process_cross(&mut cross, &settings);
hv = hv_new;
cross.uninit();
// the column setting can be changed during the non-dialog,
// so we need to keep it updated here
settings.style = match &hv {
HexView::Aligned(v, _, _) => v.dh.style,
HexView::Unaligned(v) => v.dh.style,
};
let (hv_new, settings_new) = match quit {
DelegateEvent::Quit => break,
DelegateEvent::OpenDialog(dia) => hv.show_dialog(dia, settings),
_ => (hv, settings),
};
hv = hv_new;
settings = settings_new;
}
}
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
pub struct Settings {
pub algo: AlignAlgorithm,
pub style: Style,
}
impl Settings {
fn config_path() -> Result<PathBuf, std::io::Error> {
match std::env::var_os("BIODIFF_CONFIG_DIR") {
Some(p) => Ok(PathBuf::from(p)),
None => match config_dir() {
Some(mut p) => {
p.push("biodiff");
Ok(p)
}
None => Err(std::io::Error::new(
std::io::ErrorKind::NotFound,
"Could not find configuration directory",
)),
},
}
}
fn settings_file() -> Result<PathBuf, std::io::Error> {
let mut path = Self::config_path()?;
path.push("config.json");
Ok(path)
}
pub fn from_config() -> Option<Self> {
let config = read_to_string(Self::settings_file().ok()?).ok()?;
serde_json::from_str(&config).ok()
}
pub fn save_config(&self) -> Result<(), Box<dyn Error + 'static>> {
let config = serde_json::to_string(self)?;
let r = std::fs::create_dir_all(Self::config_path()?);
if let Err(ref e) = r {
match e.kind() {
std::io::ErrorKind::AlreadyExists => (),
_ => r?,
}
}
std::fs::write(Self::settings_file()?, config)?;
Ok(())
}
}
/// An enum containing either an aligned or unaligned hexview, without
/// a backend for painting.
/// The aligned view also contains a channel for messages, as the alignment
/// algorithms need to dynamically append/prepend new blocks to the view
/// and the crossbeam backend also sends user events over that.
pub enum HexView {
Aligned(
view::Aligned,
Sender<AlignedMessage>,
Receiver<AlignedMessage>,
),
Unaligned(view::Unaligned),
}
impl HexView {
/// Creates a new unaligned view from two files with given indexes and cursor
/// size 16x16.
pub fn new(left: FileState, right: FileState) -> Self {
HexView::Unaligned(view::Unaligned::new(
left,
right,
DoubleHexContext::new((16, 16)),
))
}
/// Turns a hexview into an aligned view using the given algorithm parameters
fn into_aligned(self, algo: &AlignAlgorithm, select: [Option<Range<usize>>; 2]) -> HexView {
let (send, recv) = channel();
match match self {
// first destruct our old hexview into its parts
HexView::Aligned(a, send, recv) => {
a.destruct().map_err(|a| HexView::Aligned(a, send, recv))
}
HexView::Unaligned(u) => u.destruct().map_err(HexView::Unaligned),
} {
// if the cursor was not placed on any index, we currently do nothing
// maybe one could think up some better values to align at here or something
Err(hv) => hv,
Ok((left, right, mut dh)) => {
if matches!(algo.mode, AlignMode::Local | AlignMode::Global) {
dh.cursor = CursorState::new((dh.cursor.get_size_x(), dh.cursor.get_size_y()))
};
HexView::Aligned(
view::Aligned::new(left, right, dh, algo, select, send.clone()),
send,
recv,
)
}
}
}
/// Turns a hexview into an unaligned view at the current cursor
fn into_unaligned(self) -> HexView {
match self {
HexView::Aligned(a, send, recv) => match a.destruct() {
Ok((left, right, cursor)) => {
HexView::Unaligned(view::Unaligned::new(left, right, cursor))
}
Err(a) => HexView::Aligned(a, send, recv),
},
// we don't need to change anything for unaligned views
HexView::Unaligned(_) => self,
}
}
/// Call the relevant event processing functions for the crossterm backend
fn event_proc(&mut self, cross: &mut Cross) -> DelegateEvent {
match self {
HexView::Aligned(ref mut a, ref mut send, ref mut recv) => {
aligned_cross(a, cross, send, recv)
}
HexView::Unaligned(ref mut u) => unaligned_cross(u, cross),
}
}
fn selection(&self) -> [Option<Range<usize>>; 2] {
match self {
HexView::Aligned(a, _, _) => a.selection_file_ranges(),
HexView::Unaligned(u) => u.selection_file_ranges(),
}
}
/// control loop for crossbeam backend, switches the view between aligned and unaligned when
/// requested and runs event loops
fn process_cross(self, cross: &mut Cross, settings: &Settings) -> (Self, DelegateEvent) {
let mut view = self;
let mut quit;
let quit_reason = loop {
let q = view.event_proc(cross);
view = match q {
// delegate to top-level control loop
DelegateEvent::Quit | DelegateEvent::OpenDialog(_) => {
quit = match &mut view {
HexView::Aligned(v, _, _) => !v.process_escape(cross),
HexView::Unaligned(v) => !v.process_escape(cross),
}
.then_some(q);
view
}
DelegateEvent::SwitchToAlign => {
quit = None;
let select = view.selection();
view.into_aligned(&settings.algo, select)
}
DelegateEvent::SwitchToUnalign => {
quit = None;
view.into_unaligned()
}
};
if let Some(q) = quit {
break q;
}
};
(view, quit_reason)
}
/// Setup a cursive instance and shows a dialog constructed through the callback given in `dialog`.
///
/// Note that the settings are placed into the user_data of the cursive instace and can be modified
/// by the callback.
fn show_dialog(self, dialog: CursiveCallback, settings: Settings) -> (Self, Settings) {
let mut siv = cursive::default();
// this theme is the default theme except that the background color is black
siv.set_theme(cursiv_theme());
siv.add_global_callback(Key::Esc, dialog::close_top_maybe_quit);
siv.set_user_data(settings);
match self {
HexView::Aligned(a, send, mut recv) => {
siv.add_fullscreen_layer(a.with_name("aligned").full_screen());
let mut sink = siv.cb_sink().clone();
// we create a new thread that converts the `AlignedMessage`s coming from
// the alignment threads to callbacks on the cursive instance, so this case
// is a bit more complicated than the unaligned one.
scope(|s| {
let join_handle = s.spawn(|_| cursiv_align_relay(&mut recv, &mut sink));
dialog(&mut siv);
siv.try_run_with(|| {
// use the buffered backend as it involves way less flickering
crossterm::Backend::init()
.map(|x| Box::new(BufferedBackend::new(x)) as Box<dyn CursiveBackend>)
})
.expect("Could not run");
// misuse the Action::Quit as a signal for the thread to exit
send.send(AlignedMessage::UserEvent(Action::Quit))
.expect("Could not tell align relay thread to quit");
join_handle
.join()
.expect("Could not join align relay thread");
})
.expect("Could not join align relay thread");
// extract the view from the cursive instance
match peel_onion(&mut siv) {
Some(x) => (
HexView::Aligned(x, send, recv),
siv.take_user_data().unwrap(),
),
None => panic!("Internal error, could not downcast view"),
}
}
HexView::Unaligned(u) => {
siv.add_fullscreen_layer(u.with_name("unaligned").full_screen());
dialog(&mut siv);
siv.try_run_with(|| {
crossterm::Backend::init()
.map(|x| Box::new(BufferedBackend::new(x)) as Box<dyn CursiveBackend>)
})
.expect("Could not run");
// extract the view from the cursive instance
match peel_onion(&mut siv) {
Some(v) => (HexView::Unaligned(v), siv.take_user_data().unwrap()),
None => panic!("Internal error, could not downcast view"),
}
}
}
}
}
// this one causes tears to come from my eyes
fn peel_onion<V: View>(siv: &mut Cursive) -> Option<V> {
siv.screen_mut()
.remove_layer(LayerPosition::FromBack(0))
.downcast::<ResizedView<NamedView<V>>>()
.ok()
.and_then(|view| view.into_inner().ok())
.and_then(|view| view.into_inner().ok())
}
/// Default Cursive theme except that the background color is black
fn | () -> cursive::theme::Theme {
use cursive::theme::{BaseColor::*, Color::*, PaletteColor::*};
let mut cursiv_theme = cursive::theme::load_default();
cursiv_theme.palette[Background] = Dark(Black);
cursiv_theme
}
/// Forwards `AlignedMessage`s from the alignment thread into callbacks for the cursive instance
fn cursiv_align_relay(recv: &mut Receiver<AlignedMessage>, sink: &mut cursive::CbSink) {
for ev in recv.iter() {
match ev {
AlignedMessage::UserEvent(Action::Quit) => break,
otherwise => {
sink.send(Box::new(|siv: &mut Cursive| {
siv.call_on_name("aligned", |view: &mut Aligned| {
view.process_action(&mut Dummy, otherwise);
})
.expect("Could not send new data to view");
}))
.expect("Could not send event to view");
}
}
}
}
/// This enum is used for delegating actions to higher level event loops.
enum DelegateEvent {
Quit,
SwitchToAlign,
SwitchToUnalign,
OpenDialog(CursiveCallback),
}
/// Converts an event to a delegation
fn delegate_action(action: Action) -> Option<DelegateEvent> {
match action {
Action::Quit => Some(DelegateEvent::Quit),
Action::Align => Some(DelegateEvent::SwitchToAlign),
Action::Unalign => Some(DelegateEvent::SwitchToUnalign),
Action::Algorithm => Some(DelegateEvent::OpenDialog(Box::new(dialog::settings))),
Action::Goto => Some(DelegateEvent::OpenDialog(Box::new(dialog::goto))),
Action::Search => Some(DelegateEvent::OpenDialog(Box::new(dialog::search))),
Action::SetOffset => Some(DelegateEvent::OpenDialog(Box::new(dialog::set_offset))),
Action::Help => Some(DelegateEvent::OpenDialog(Box::new(dialog::help_window(
dialog::MAIN_HELP,
)))),
_otherwise => None,
}
}
/// This function is the one that processes actions sent by the event reader loop
/// setup in `unaligned_cross`. Note that the event reader loop has to stay in the same
/// thread, so this process is chosen to not be in the main thread instead.
fn unaligned_cross_recv(
unaligned: &mut view::Unaligned,
cross: &mut Cross,
recv: Receiver<Action>,
) -> DelegateEvent {
unaligned.refresh(cross);
for action in recv.iter() {
if let Some(q) = delegate_action(action) {
return q;
}
unaligned.process_action(cross, action);
}
DelegateEvent::Quit
}
/// This setups the event processing thread for the crossterm backend and reads crossterm's events
fn unaligned_cross(unaligned: &mut view::Unaligned, cross: &mut Cross) -> DelegateEvent {
unaligned.refresh(cross);
let (mut send, recv) = channel();
let mut quit = DelegateEvent::Quit;
scope(|s| {
// both this thread and the send_cross_actions function determine when to quit by
// checking the output of delegate_action, so make sure this is the same
let receiver_thread = s.spawn(|_| unaligned_cross_recv(unaligned, cross, recv));
send_cross_actions(|action| delegate_action(action).is_some(), &mut send);
quit = receiver_thread.join().unwrap();
})
.unwrap();
quit
}
/// This function is the one that processes actions sent by the event reader loop
/// setup in `aligned_cross`, and also the ones sent by the alignment process.
/// Note that the event reader loop has to stay in the same thread, so this
/// process is chosen to not be in the main thread instead.
fn aligned_cross_recv(
aligned: &mut view::Aligned,
cross: &mut Cross,
recv: &mut Receiver<AlignedMessage>,
) -> DelegateEvent {
for msg in recv.iter() {
let msg = match msg {
AlignedMessage::UserEvent(action) => {
if let Some(q) = delegate_action(action) {
return q;
}
msg
}
_ => msg,
};
aligned.process_action(cross, msg);
}
DelegateEvent::Quit
}
/// Using the existing message channel (send, recv), setup a thread that
/// processes the messages and also read the crossterm events in the main thread.
/// The channel should be the same one used when setting up the Aligned view.
fn aligned_cross(
aligned: &mut view::Aligned,
cross: &mut Cross,
send: &mut Sender<AlignedMessage>,
recv: &mut Receiver<AlignedMessage>,
) -> DelegateEvent {
aligned.refresh(cross);
let mut quit = DelegateEvent::Quit;
scope(|s| {
// both the thread and the send_cross_actions function determine when to quit by
// checking the output of delegate_action, so make sure this is the same.
let receiver_thread = s.spawn(|_| aligned_cross_recv(aligned, cross, recv));
send_cross_actions(|action| delegate_action(action).is_some(), send);
quit = receiver_thread.join().unwrap();
})
.unwrap();
quit
}
| cursiv_theme | identifier_name |
print_test.py | # -*- coding: utf-8 -*-
"""
Created on Wed Aug 8 17:26:44 2018
@author: dell
"""
import tensorflow as tf
import numpy as np
from PIL import Image
"""
im = Image.open('D://Deeplearning_Demo//Data_original//Data_im//train_im//IMG_1_B.jpg')
im.show()
im_array = np.array(im)
print(im_array.shape)
"""
from PIL import Image
from dilated_resnet import *
import random
import pickle as p
import os
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.image as plimg
label_path='IMG_output_1_0.npy'
#label_path=tf.convert_to_tensor(label_path)
#定义定义的参数的存储位置在cpu还是在GPu上 tf.contrib.layers.xavier_initializer()
def create_variables(name,shape,initializer=tf.truncated_normal_initializer(),is_fc_layers=False):
'''
:param name: A string. The name of the new variable
:param shape: A list of dimensions
:param initializer: User Xavier as default.
:param is_fc_layer: Want to create fc layer variable? May use different weight_decay for fc
layers.
:return: The created variable
'''
## TODO: to allow different weight decay to fully connected layer and conv layer
regularizer = tf.contrib.layers.l2_regularizer(scale=0.0002)
#new_variables = tf.get_variable(name, shape=shape, initializer=initializer,
# regularizer=regularizer)
new_variables = tf.get_variable(name, shape=shape, initializer=initializer
)
return new_variables
# 这里先构建一个批归一化层的函数,方便后续使用,训练和测试的时候需要改变一下把?
def batch_normalization_layer(input_layer, dimension):
'''
Helper function to do batch normalziation
:param input_layer: 4D tensor
:param dimension: input_layer.get_shape().as_list()[-1]. The depth of the 4D tensor
:return: the 4D tensor after being normalized
'''
mean, varience = tf.nn.moments(input_layer, axes=[0, 1, 2])
beta = tf.get_variable('beta', dimension, tf.float32,
initializer=tf.constant_initializer(0.0, tf.float32))
gamma = tf.get_variable('gamma', dimension, tf.float32,
initializer=tf.constant_initializer(1.0, tf.float32))
bn_layer = tf.nn.batch_normalization(input_layer, mean, varience, beta, gamma, BN_EPSILON)
return bn_layer
# 在这里进行相应的修改操作吧?
def conv_bn_relu_layer(input_layer, filter_shape, stride, dilation=1):
'''
A helper function to conv, batch normalize and relu the input tensor sequentially
:param input_layer: 4D tensor
:param filter_shape: list. [filter_height, filter_width, filter_depth, filter_number]
:param stride: stride size for conv
:return: 4D tensor. Y = Relu(batch_normalize(conv(X)))
'''
out_channel = filter_shape[-1]
filter = create_variables(name='conv', shape=filter_shape)
if dilation == 1:
conv_layer = tf.nn.conv2d(input_layer, filter, strides=[1, stride, stride, 1], padding='SAME')
elif dilation == 2:
conv_layer = tf.nn.atrous_conv2d(value=input_layer, filters=filter, rate=2, padding='SAME')
elif dilation == 4:
conv_layer = tf.nn.atrous_conv2d(value=input_layer, filters=filter, rate=4, padding='SAME')
else:
raise ValueError('no dilation is choosen!!!')
bn_layer = batch_normalization_layer(conv_layer, out_channel)
output = tf.nn.relu(bn_layer)
return output
# 我们采用这个基础网络结构
def bn_relu_conv_layer(input_layer, filter_shape, stride=1, dilation=1):
'''
A helper function to batch normalize, relu and conv the input layer sequentially
:param input_layer: 4D tensor
:param filter_shape: list. [filter_height, filter_width, filter_depth, filter_number]
:param stride: stride size for conv
:return: 4D tensor. Y = conv(Relu(batch_normalize(X)))
'''
in_channel = input_layer.get_shape().as_list()[-1]
bn_layer = batch_normalization_layer(input_layer, in_channel)
relu_layer = tf.nn.relu(bn_layer)
filter = create_variables(name='conv', shape=filter_shape)
# 这里进行卷积操作的一个很重要的部分,选择卷积的方式是什么,其中有1,2,4
if dilation == 1:
conv_layer = tf.nn.conv2d(relu_layer, filter, strides=[1, stride, stride, 1], padding='SAME')
elif dilation == 2:
conv_layer = tf.nn.atrous_conv2d(value=relu_layer, filters=filter, rate=2, padding='SAME')
elif dilation == 4:
conv_layer = tf.nn.atrous_conv2d(value=relu_layer, filters=filter, rate=4, padding='SAME')
else:
raise ValueError('no dilation is choosen!!!')
return conv_layer
# 开始构造block的结构过程
def residual_block(input_layer, output_channel, dilation=1, stride=1, first_block=False):
'''
Defines a residual block in ResNet
:param input_layer: 4D tensor
:param output_channel: int. return_tensor.get_shape().as_list()[-1] = output_channel
:param first_block: if this is the first residual block of the whole network
:return: 4D tensor.
'''
input_channel = input_layer.get_shape().as_list()[-1]
# 按照正常的网络结构
# 我们选择先bath 然后进行卷积和relu的操作
# Y = conv(Relu(batch_normalize(X)))
# bn_relu_conv_layer(input_layer,filter_shape,stride,dilation=1)
'''
设置残差网络的模板的第一层
'''
# 这里进行查看输入输出维度以及深度是否相同,这里没考虑网络卷积之后的大小是否跟原始大小一样的!
with tf.variable_scope('conv1_in_block'):
if first_block:
filter = create_variables(name='conv', shape=[3, 3, input_channel, output_channel])
conv1 = tf.nn.conv2d(input_layer, filter, strides=[1, stride, stride, 1], padding='SAME')
else:
conv1 = bn_relu_conv_layer(input_layer, [3, 3, input_channel, output_channel], stride, dilation)
with tf.variable_scope('conv2_in_block'):
conv2 = bn_relu_conv_layer(conv1, [3, 3, output_channel, output_channel], stride, dilation)
# mid_layer=bn_relu_conv_layer(input_layer,[3,3],stride,dilation=dilation)
# out_layer=bn_relu_conv_layer(mid_layer,[3,3],stride,dilation=dilation)
if input_channel != output_channel:
filter = create_variables(name='Unichannel', shape=[1, 1, input_channel, output_channel])
input_layer = tf.nn.conv2d(input_layer, filter, strides=[1, 1, 1, 1], padding='SAME')
result = tf.add(input_layer, conv2)
return result
def inference(input_layer):
#下面按照那个结构进行相应的搭建框架的结构如下所示:[batch,h,w,3]出去的时候也应该是[batch,h,w,3]
"""
这下面的数字以后会改的
"""
input_channel=input_layer.get_shape().as_list()[-1]
input_w=input_layer.get_shape().as_list()[2]
input_h=input_layer.get_shape().as_list()[1]
#[7,7,16]
with tf.variable_scope('DRN_1'):
filter=create_variables(name='DRN_1_va',shape=[7,7,input_channel,16])
DRN_1=tf.nn.conv2d(input_layer,filter,strides=[1,1,1,1],padding='SAME')
DRN_1=tf.nn.relu(DRN_1)
with tf.variable_scope('DRN_2'):
DRN_2=residual_block(DRN_1,16,dilation=1,stride=1,first_block=False)
# [3,3,32]+[3,3,32]的残差网络的设,stride设计为2相当于进行了降采样的操作
with tf.variable_scope('DRN_3'):
| DRN_5=residual_block(DRN_4,128,dilation=1,stride=1,first_block=False)
with tf.variable_scope('DRN_5_2'):
DRN_5=residual_block(DRN_5,128,dilation=1,stride=1,first_block=False)
# [3,3,256]+[3,3,256]的残差网络的设,stride设计为2相当于进行了降采样的操作
with tf.variable_scope('DRN_6_1'):
DRN_6 = residual_block(DRN_5, 256, dilation=2, stride=1, first_block=False)
with tf.variable_scope('DRN_6_2'):
DRN_6 = residual_block(DRN_5, 256, dilation=2, stride=1, first_block=False)
#DRN_6=tf.nn.sigmoid(DRN_6)
return DRN_6
# -*- coding: utf-8 -*-
"""
Created on Fri Aug 10 21:39:20 2018
@author: dell
"""
tf.reset_default_graph()
# image_path = r'D:/Deeplearning_Demo/image/IMG_1_0.jpg'#绝对路径
# label_path=r'IMG_output_1_0.npy'
# xia_path="ddddd"
Image_File_dir = "D:/Deeplearning_Demo/image"
Label_File_dir = "D:/Deeplearning_Demo/label"
"""
Image_File_dir = "D:/Deeplearning_Demo/TensorFlow_demo/Ours_crowd_counting/output/crop_image"
Label_File_dir = "D:/Deeplearning_Demo/TensorFlow_demo/Ours_crowd_counting/output/crop_groundtruth"
"""
Image_list = []
Label_list = []
learning_rate = 0.01
# 这里为什么会出问题?
# batch_size=2
each_step = 10
# 定义存储路径
ckpt_dir = "./model"
if not os.path.exists(ckpt_dir):
os.makedirs(ckpt_dir)
# 得到了一些相应的文件名称,便于下一次调用
def get_files(file_dir, label_dir):
for file in os.listdir(file_dir):
Image_list.append(file_dir + '/' + file)
print(Image_list)
for file in os.listdir(label_dir):
Label_list.append(label_dir + '/' + file)
# 损失函数的计算方法是什么,这里我们进行相应的改进比如可以改进成一些方差的计算方法等等
def loss(y, pred_y):
loss = tf.reduce_sum(tf.square(y - pred_y))
return loss
get_files(Image_File_dir, Label_File_dir)
image_path = tf.convert_to_tensor(Image_list)
label_path = tf.convert_to_tensor(Label_list)
print("start")
# file_queue = tf.train.string_input_producer([image_path]) #创建输入队列
file_queue = tf.train.slice_input_producer([image_path, label_path], shuffle=False)
# image = tf.train.slice_input_producer([[image_path] ])
file_queue = tf.convert_to_tensor(file_queue)
# file_queue[0]= tf.convert_to_tensor(file_queue[0])
# reader = tf.WholeFileReader()
# key,image = reader.read(file_queue)
"""
图像数据
"""
image = tf.read_file(file_queue[0]) # reader读取序列
image = tf.image.decode_jpeg(image, channels=3) # 解码,tensor
image = tf.image.resize_images(image, [240, 240])
image = tf.image.per_image_standardization(image)
"""
标签数据
"""
label = tf.read_file(file_queue[1]) # reader读取序列
# 读出的 value 是 string,现在转换为 uint8 型的向量
record_bytes = tf.decode_raw(label, tf.float32)
depth_major = tf.reshape(tf.slice(record_bytes, [20], [240 * 240 * 1]),
[1, 240, 240]) # depth, height, width
print("done")
uint8image = tf.transpose(depth_major, [1, 2, 0])
label = tf.cast(uint8image, tf.float32)/30000
"""这里需要用参数进行设计"""
image_batch, label_batch = tf.train.batch([image, label],
batch_size=batch_size,
num_threads=1,
capacity=10000)
predict_map= inference(image_batch)
print("验证的结果:", predict_map, label_batch)
# saving and loading networks
# 保存模型的参数等等
with tf.Session() as sess:
sess.run(tf.local_variables_initializer())
sess.run(tf.global_variables_initializer())
coord = tf.train.Coordinator() # 协同启动的线程
threads = tf.train.start_queue_runners(sess=sess, coord=coord) # 启动线程运行队列
# 保存模型
# 下面开始循环的过程
for i in range(100):
# 应用到的网络结构
print("i的数字为:", i)
#losses = sess.run(loss_result)
# saver.save(sess, ckpt_dir+"/my-model.ckpt", global_step=i)
# 接下来显示训练一段时间的测试结果如何,来判断这种方法是否应该用的
[image, label] = sess.run([image_batch, label_batch])
print(image.shape)
print(label.shape)
print("jieguo:", label[:, 1:10, 1:10, :])
print(type(image)) # tensor
# 转换了图片的类型
image = tf.squeeze(image[0:1, :, :, :]).eval()
print("image_type", type(image)) # ndarray
print("image:", image)
print(image.shape) # 240×320×3
image = tf.cast(image, tf.uint8).eval()
print("image.dtype:", image.dtype) # uint8
plt.figure(i)
plt.imshow(image)
plt.show()
# 现在要转换原始的label以及生成的结果
label = tf.squeeze(label[0:1, :, :, :]).eval()
print("label_type", type(label)) # ndarray
print(label.shape) # 240×320×3
# label = tf.cast(label, tf.float32).eval()
# print("label.dtype:", label.dtype) # uint8
# 开始转换一下生成结果
# 显示原始数据的分布是什么
i0 = Image.fromarray(label)
# plt.figure(i+1)
result = i0.show()
# 显示一下训练出来的数据是什么样子的
result_groundtruth= sess.run(predict_map)
print("ddd:",result_groundtruth)
result_groundtruth = tf.squeeze(result_groundtruth).eval()
print("形状为:", result_groundtruth.shape)
print("生成的结果:",result_groundtruth)
# 停止所有的线程
coord.request_stop()
coord.join(threads) | DRN_3 = residual_block(DRN_2, 32, dilation=1, stride=1, first_block=False)
with tf.variable_scope('DRN_4_2'):
DRN_4 = residual_block(DRN_3, 64, dilation=1, stride=1, first_block=False)
with tf.variable_scope('DRN_5_1'):
| random_line_split |
print_test.py | # -*- coding: utf-8 -*-
"""
Created on Wed Aug 8 17:26:44 2018
@author: dell
"""
import tensorflow as tf
import numpy as np
from PIL import Image
"""
im = Image.open('D://Deeplearning_Demo//Data_original//Data_im//train_im//IMG_1_B.jpg')
im.show()
im_array = np.array(im)
print(im_array.shape)
"""
from PIL import Image
from dilated_resnet import *
import random
import pickle as p
import os
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.image as plimg
label_path='IMG_output_1_0.npy'
#label_path=tf.convert_to_tensor(label_path)
#定义定义的参数的存储位置在cpu还是在GPu上 tf.contrib.layers.xavier_initializer()
def create_variables(name,shape,initializer=tf.truncated_normal_initializer(),is_fc_layers=False):
'''
:param name: A string. The name of the new variable
:param shape: A list of dimensions
:param initializer: User Xavier as default.
:param is_fc_layer: Want to create fc layer variable? May use different weight_decay for fc
layers.
:return: The created variable
'''
## TODO: to allow different weight decay to fully connected layer and conv layer
regularizer = tf.contrib.layers.l2_regularizer(scale=0.0002)
#new_variables = tf.get_variable(name, shape=shape, initializer=initializer,
# regularizer=regularizer)
new_variables = tf.get_variable(name, shape=shape, initializer=initializer
)
return new_variables
# 这里先构建一个批归一化层的函数,方便后续使用,训练和测试的时候需要改变一下把?
def batch_normalization_layer(input_layer, dimension):
'''
Helper function to do batch normalziation
:param input_layer: 4D tensor
:param dimension: input_layer.get_shape().as_list()[-1]. The depth of the 4D tensor
:return: the 4D tensor after being normalized
'''
mean, varience = tf.nn.moments(input_layer, axes=[0, 1, 2])
beta = tf.get_variable('beta', dimension, tf.float32,
initializer=tf.constant_initializer(0.0, tf.float32))
gamma = tf.get_variable('gamma', dimension, tf.float32,
initializer=tf.constant_initializer(1.0, tf.float32))
bn_layer = tf.nn.batch_normalization(input_layer, mean, varience, beta, gamma, BN_EPSILON)
return bn_layer
# 在这里进行相应的修改操作吧?
def conv_bn_relu_layer(input_layer, filter_shape, stride, dilation=1):
'''
A helper function to conv, batch normalize and relu the input tensor sequentially
:param input_layer: 4D tensor
:param filter_shape: list. [filter_height, filter_width, filter_depth, filter_number]
:param stride: stride size for conv
:return: 4D tensor. Y = Relu(batch_normalize(conv(X)))
'''
out_channel = filter_shape[-1]
filter = create_variables(name='conv', shape=filter_shape)
if dilation == 1:
conv_layer = tf.nn.conv2d(input_layer, filter, strides=[1, stride, stride, 1], padding='SAME')
elif dilation == 2:
conv_layer = tf.nn.atrous_conv2d(value=input_layer, filters=filter, rate=2, padding='SAME')
elif dilation == 4:
conv_layer = tf.nn.atrous_conv2d(value=input_layer, filters=filter, rate=4, padding='SAME')
else:
raise ValueError('no dilation is choosen!!!')
bn_layer = batch_normalization_layer(conv_layer, out_channel)
output = tf.nn.relu(bn_layer)
return output
# 我们采用这个基础网络结构
def bn_relu_conv_layer(input_layer, filter_shape, stride=1, dilation=1):
'''
A helper function to batch normalize, relu and conv the input layer sequentially
:param input_layer: 4D tensor
:param filter_shape: list. [filter_height, filter_width, filter_depth, filter_number]
:param stride: stride size for conv
:return: 4D tensor. Y = conv(Relu(batch_normalize(X)))
'''
in_channel = input_layer.get_shape().as_list()[-1]
bn_layer = batch_normalization_layer(input_layer, in_channel)
relu_layer = tf.nn.relu(bn_layer)
filter = create_variables(name='conv', shape=filter_shape)
# 这里进行卷积操作的一个很重要的部分,选择卷积的方式是什么,其中有1,2,4
if dilation == 1:
conv_layer = tf.nn.conv2d(relu_layer, filter, strides=[1, stride, stride, 1], padding='SAME')
elif dilation == 2:
conv_layer = tf.nn.atrous_conv2d(value=relu_layer, filters=filter, rate=2, padding='SAME')
elif dilation == 4:
conv_layer = tf.nn.atrous_conv2d(value=relu_layer, filters=filter, rate=4, padding='SAME')
else:
raise ValueError('no dilation is choosen!!!')
return conv_layer
# 开始构造block的结构过程
def residual_block(input_layer, output_channel, dilation=1, stride=1, first_block=False):
'''
Defines a residual block in ResNet
:param input_layer: 4D tensor
:param output_channel: int. return_tensor.get_shape().as_list()[-1] = output_channel
:param first_block: if this is the first residual block of the whole network
:return: 4D tensor.
'''
input_channel = input_layer.get_shape().as_list()[-1]
# 按照正常的网络结构
# 我们选择先bath 然后进行卷积和relu的操作
# Y = conv(Relu(batch_normalize(X)))
# bn_relu_conv_layer(input_layer,filter_shape,stride,dilation=1)
'''
设置残差网络的模板的第一层
'''
# 这里进行查看输入输出维度以及深度是否相同,这里没考虑网络卷积之后的大小是否跟原始大小一样的!
with tf.variable_scope('conv1_in_block'):
if first_block:
filter = create_variables(name='conv', shape=[3, 3, input_channel, output_channel])
conv1 = tf.nn.conv2d(input_layer, filter, strides=[1, stride, stride, 1], padding='SAME')
else:
conv1 = bn_relu_conv_layer(input_layer, [3, 3, input_channel, output_channel], stride, dilation)
with tf.variable_scope('conv2_in_block'):
conv2 = bn_relu_conv_layer(conv1, [3, 3, output_channel, output_channel], stride, dilation)
# mid_layer=bn_relu_conv_layer(input_layer,[3,3],stride,dilation=dilation)
# out_layer=bn_relu_conv_layer(mid_layer,[3,3],stride,dilation=dilation)
if input_channel != output_channel:
filter = create_variables(name='Unichannel', shape=[1, 1, input_channel, output_channel])
input_layer = tf.nn.conv2d(input_layer, filter, strides=[1, 1, 1, 1], padding='SAME')
result = tf.add(input_layer, conv2)
return result
def inference(input_layer):
#下面按照那个结构进行相应的搭建框架的结构如下所示:[batch,h,w,3]出去的时候也应该是[batch,h,w,3]
"""
这下面的数字以后会改的
"""
input_channel=input_layer.get_shape().as_list()[-1]
input_w=input_layer.get_shape().as_list()[2]
input_h=input_layer.get_shape().as_list()[1]
#[7,7,16]
with tf.variable_scope('DRN_1'):
filter=create_variables(name='DRN_1_va',shape=[7,7,input_channel,16])
DRN_1=tf.nn.conv2d(input_layer,filter,strides=[1,1,1,1],padding='SAME')
DRN_1=tf.nn.relu(DRN_1)
with tf.variable_scope('DRN_2'):
DRN_2=residual_block(DRN_1,16,dilation=1,stride=1,first_block=False)
# [3,3,32]+[3,3,32]的残差网络的设,stride设计为2相当于进行了降采样的操作
with tf.variable_scope('DRN_3'):
DRN_3 = residual_block(DRN_2, 32, dilation=1, stride=1, first_block=False)
with tf.variable_scope('DRN_4_2'):
DRN_4 = residual_block(DRN_3, 64, dilation=1, stride=1, first_block=False)
with tf.variable_scope('DRN_5_1'):
DRN_5=residual_block(DRN_4,128,dilation=1,stride=1,first_block=False)
with tf.variable_scope('DRN_5_2'):
DRN_5=residual_block(DRN_5,128,dilation=1,stride=1,first_block=False)
# [3,3,256]+[3,3,256]的残差网络的设,stride设计为2相当于进行了降采样的操作
with tf.variable_scope('DRN_6_1'):
DRN_6 = residual_block(DRN_5, 256, dilation=2, stride=1, first_block=False)
with tf.variable_scope('DRN_6_2'):
DRN_6 = residual_block(DRN_5, 256, dilation=2, stride=1, first_block=False)
#DRN_6=tf.nn.sigmoid(DRN_6)
return DRN_6
# -*- coding: utf-8 -*-
"""
Created on Fri Aug 10 21:39:20 2018
@author: dell
"""
tf.reset_default_graph()
# image_path = r'D:/Deeplearning_Demo/image/IMG_1_0.jpg'#绝对路径
# label_path=r'IMG_output_1_0.npy'
# xia_path="ddddd"
Image_File_dir = "D:/Deeplearning_Demo/image"
Label_File_dir = "D:/Deeplearning_Demo/label"
"""
Image_File_dir = "D:/Deeplearning_Demo/TensorFlow_demo/Ours_crowd_counting/output/crop_image"
Label_File_dir = "D:/Deeplearning_Demo/TensorFlow_demo/Ours_crowd_counting/output/crop_groundtruth"
"""
Image_list = []
Label_list = []
learning_rate = 0.01
# 这里为什么会出问题?
# batch_size=2
each_step = 10
# 定义存储路径
ckpt_dir = "./model"
if not os.path.exists(ckpt_dir):
os.makedirs(ckpt_dir)
# 得到了一些相应的文件名称,便于下一次调用
def get_files(file_dir, label_dir):
for file in os.listdir(file_dir):
Image_list.append(file_dir + '/' + file)
print(Image_list)
for file in os.listdir(label_dir):
Label_list.append(label_dir + '/' + file)
# 损失函数的计算方法是什么,这里我们进行相应的改进比如可以改进成一些方差的计算方法等等
def loss(y, pred_y):
loss = tf.reduce_sum(tf.square(y - pred_y))
return loss
get_files(Image_File_dir, Label_File_dir)
image_path = tf.convert_to_tensor(Image_list)
label_path = tf.convert_to_tensor(Label_list)
print("start")
# file_queue = tf.train.string_input_producer([image_path]) #创建输入队列
file_queue = tf.train.slice_input_producer([image_path, label_path], shuffle=False)
# image = tf.train.slice_input_producer([[image_path] ])
file_queue = tf.convert_to_tensor(file_queue)
# file_queue[0]= tf.convert_to_tensor(file_queue[0])
# reader = tf.WholeFileReader()
# key,image = reader.read(file_queue)
"""
图像数据
"""
image = tf.read_file(file_queue[0]) # reader读取序列
image = tf.image.decode_jpeg(image, channels=3) # 解码,tensor
image = tf.image.resize_images(image, [240, 240])
image = tf.image.per_image_standardization(image)
"""
标签数据
"""
label = tf.read_file(file_queue[1]) # reader读取序列
# 读出的 value 是 string,现在转换为 uint8 型的向量
record_bytes = tf.decode_raw(label, tf.float32)
depth_major = tf.reshape(tf.slice(record_bytes, [20], [240 * 240 * 1]),
[1, 240, 240]) # depth, height, width
print("done")
uint8image = tf.transpose(depth_major, [1, 2, 0])
label = tf.cast(uint8image, tf.float32)/30000
"""这里需要用参数进行设计"""
image_batch, label_batch = tf.train.batch([image, label],
batch_size=batch_size,
num_threads=1,
capacity=10000)
predict_map= inference(image_batch)
print("验证的结果:", predict_map, label_batch)
# saving and loading networks
# 保存模型的参数等等
with tf.Session() as sess:
sess.run(tf.local_variables_initializer())
sess.run(tf.global_variables_initializer())
coord = tf.train.Coordinator() # 协同启动的线程
threads = tf.train.start_queue_runners(sess=sess, coord=coord) # 启动线程运行队列
# 保存模型
# 下面开始循环的过程
for i in range(100):
# 应用到的网络结构
print("i的数字为:", i)
#losses = sess.run(loss_result)
# saver.save(sess, ckpt_dir+"/my-model.ckpt", global_step=i)
# 接下来显示训练一段时间的测试结果如何,来判断这种方法是否应该用的
[image, label] = sess.run([image_batch, label_batch])
print(image.shape)
print(label.shape)
print("jieguo:", label[:, 1:10, 1:10, :])
print(type(image)) # tensor
# 转换了图片的类型
image = tf.squeeze(image[0:1, :, :, :]).eval()
print("image_type", type(image)) # ndarray
print("image:", image)
print(image.shape) # 240×320×3
image = tf.cast(image, tf.uint8).eval()
print("image.dtype:", image.dtype) # uint8
plt.figure(i)
plt.imshow(image)
plt.show()
# 现在要转换原始的label以及生成的结果
label = tf.squeeze(label[0:1, :, :, :]).eval()
print("label_type", type(label)) # ndarray
print(label.shape) # | 240×320×3
# label = tf.cast(label, tf.float32).eval()
# print("label.dtype:", label.dtype) # uint8
# 开始转换一下生成结果
# 显示原始数据的分布是什么
i0 = Image.fromarray(label)
# plt.figure(i+1)
result = i0.show()
# 显示一下训练出来的数据是什么样子的
result_groundtruth= sess.run(predict_map)
print("ddd:",result_groundtruth)
result_groundtruth = tf.squeeze(result_groundtruth).eval()
print("形状为:", result_groundtruth.shape)
print("生成的结果:",result_groundtruth)
# 停止所有的线程
coord.request_stop()
coord.join(threads)
| conditional_block | |
print_test.py | # -*- coding: utf-8 -*-
"""
Created on Wed Aug 8 17:26:44 2018
@author: dell
"""
import tensorflow as tf
import numpy as np
from PIL import Image
"""
im = Image.open('D://Deeplearning_Demo//Data_original//Data_im//train_im//IMG_1_B.jpg')
im.show()
im_array = np.array(im)
print(im_array.shape)
"""
from PIL import Image
from dilated_resnet import *
import random
import pickle as p
import os
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.image as plimg
label_path='IMG_output_1_0.npy'
#label_path=tf.convert_to_tensor(label_path)
#定义定义的参数的存储位置在cpu还是在GPu上 tf.contrib.layers.xavier_initializer()
def create_variables(name,shape,initializer=tf.truncated_normal_initializer(),is_fc_layers=False):
'''
:param name: A string. The name of the new variable
:param shape: A list of dimensions
:param initializer: User Xavier as default.
:param is_fc_layer: Want to create fc layer variable? May use different weight_decay for fc
layers.
:return: The created variable
'''
## TODO: to allow different weight decay to fully connected layer and conv layer
regularizer = tf.contrib.layers.l2_regularizer(scale=0.0002)
#new_variables = tf.get_variable(name, shape=shape, initializer=initializer,
# regularizer=regularizer)
new_variables = tf.get_variable(name, shape=shape, initializer=initializer
)
return new_variables
# 这里先构建一个批归一化层的函数,方便后续使用,训练和测试的时候需要改变一下把?
def batch_normalization_layer(input_layer, dimension):
'''
Helper function to do batch normalziation
:param input_layer: 4D tensor
:param dimension: input_layer.get_shape().as_list()[-1]. The depth of the 4D tensor
:return: the 4D tensor after being normalized
'''
mean, varience = tf.nn.moments(input_layer, axes=[0, 1, 2])
beta = tf.get_variable('beta', dimension, tf.float32,
initializer=tf.constant_initializer(0.0, tf.float32))
gamma = tf.get_variable('gamma', dimension, tf.float32,
initializer=tf.constant_initializer(1.0, tf.float32))
bn_layer = tf.nn.batch_normalization(input_layer, mean, varience, beta, gamma, BN_EPSILON)
return bn_layer
# 在这里进行相应的修改操作吧?
def conv_bn_relu_layer(input_layer, filter_shape, stride, dilation=1):
'''
A helper function to conv, batch normalize and relu the input tensor sequentially
:param input_layer: 4D tensor
:param filter_shape: list. [filter_height, filter_width, filter_depth, filter_number]
:param stride: stride size for conv
:return: 4D tensor. Y = Relu(batch_normalize(conv(X)))
'''
out_channel = filter_shape[-1]
filter = create_variables(name='conv', shape=filter_shape)
if dilation == 1:
conv_layer = tf.nn.conv2d(input_layer, filter, strides=[1, stride, stride, 1], padding='SAME')
elif dilation == 2:
conv_layer = tf.nn.atrous_conv2d(value=input_layer, filters=filter, rate=2, padding='SAME')
elif dilation == 4:
conv_layer = tf.nn.atrous_conv2d(value=input_layer, filters=filter, rate=4, padding='SAME')
else:
raise ValueError('no dilation is choosen!!!')
bn_layer = batch_normalization_layer(conv_layer, out_channel)
output = tf.nn.relu(bn_layer)
return output
# 我们采用这个基础网络结构
def bn_relu_conv_layer(input_layer, filter_shape, stride=1, dilation=1):
'''
A helper function to batch normalize, relu and conv the input layer sequentially
:param input_layer: 4D tensor
:param filter_shape: list. [filter_height, filter_width, filter_depth, filter_number]
:param stride: stride size for conv
:return: 4D tensor. Y = conv(Relu(batch_normalize(X)))
'''
in_channel = input_layer.get_shape().as_list()[-1]
bn_layer = batch_normalization_layer(input_layer, in_channel)
relu_layer = tf.nn.relu(bn_layer)
filter = create_variables(name='conv', shape=filter_shape)
# 这里进行卷积操作的一个很重要的部分,选择卷积的方式是什么,其中有1,2,4
if dilation == 1:
conv_layer = tf.nn.conv2d(relu_layer, filter, strides=[1, stride, stride, 1], padding='SAME')
elif dilation == 2:
conv_layer = tf.nn.atrous_conv2d(value=relu_layer, filters=filter, rate=2, padding='SAME')
elif dilation == 4:
conv_layer = tf.nn.atrous_conv2d(value=relu_layer, filters=filter, rate=4, padding='SAME')
else:
raise ValueError('no dilation is choosen!!!')
return conv_layer
# 开始构造block的结构过程
def residual_block(input_layer, output_channel, dilation=1, stride=1, first_block=False):
'''
Defines a residual block in ResNet
:param input_layer: 4D tensor
:param output_channel: int. return_tensor.get_shape().as_list()[-1] = output_channel
:param first_block: if this is the first residual block of the whole network
:return: 4D tensor.
'''
input_channel = input_layer.get_shape().as_list()[-1]
# 按照正常的网络结构
# 我们选择先bath 然后进行卷积和relu的操作
# Y = conv(Relu(batch_normalize(X)))
# bn_relu_conv_layer(input_layer,filter_shape,stride,dilation=1)
'''
设置残差网络的模板的第一层
'''
# 这里进行查看输入输出维度以及深度是否相同,这里没考虑网络卷积之后的大小是否跟原始大小一样的!
with tf.variable_scope('conv1_in_block'):
if first_block:
filter = create_variables(name='conv', shape=[3, 3, input_channel, output_channel])
conv1 = tf.nn.conv2d(input_layer, filter, strides=[1, stride, stride, 1], padding='SAME')
else:
conv1 = bn_relu_conv_layer(input_layer, [3, 3, input_channel, output_channel], stride, dilation)
with tf.variable_scope('conv2_in_block'):
conv2 = bn_relu_conv_layer(conv1, [3, 3, output_channel, output_channel], stride, dilation)
# mid_layer=bn_relu_conv_layer(input_layer,[3,3],stride,dilation=dilation)
# out_layer=bn_relu_conv_layer(mid_layer,[3,3],stride,dilation=dilation)
if input_channel != output_channel:
filter = create_variables(name='Unichannel', shape=[1, 1, input_channel, output_channel])
input_layer = tf.nn.conv2d(input_layer, filter, strides=[1, 1, 1, 1], padding='SAME')
result = tf.add(input_layer, conv2)
return result
def inference(input_layer):
#下面按照那个结构进行相应的搭建框架的结构如下所示:[batch,h,w,3]出去的时候也应该是[batch,h,w,3]
"""
这下面的数字以后会改的
"""
input_channel=input_layer.get_shape().as_list()[-1]
input_w=input_layer.get_shape().as_list()[2]
input_h=input_layer.get_shape().as_list()[1]
#[7,7,16]
with tf.variable_scope('DRN_1'):
filter=create_variables(name='DRN_1_va',shape=[7,7,input_channel,16])
DRN_1=tf.nn.conv2d(input_layer,filter,strides=[1,1,1,1],padding='SAME')
DRN_1=tf.nn.relu(DRN_1)
with tf.variable_scope('DRN_2'):
DRN_2=residual_block(DRN_1,16,dilation=1,stride=1,first_block=False)
# [3,3,32]+[3,3,32]的残差网络的设,stride设计为2相当于进行了降采样的操作
with tf.variable_scope('DRN_3'):
DRN_3 = residual_block(DRN_2, 32, dilation=1, stride=1, first_block=False)
with tf.variable_scope('DRN_4_2'):
DRN_4 = residual_block(DRN_3, 64, dilation=1, stride=1, first_block=False)
with tf.variable_scope('DRN_5_1'):
DRN_5=residual_block(DRN_4,128,dilation=1,stride=1,first_block=False)
with tf.variable_scope('DRN_5_2'):
DRN_5=residual_block(DRN_5,128,dilation=1,stride=1,first_block=False)
# [3,3,256]+[3,3,256]的残差网络的设,stride设计为2相当于进行了降采样的操作
with tf.variable_scope('DRN_6_1'):
DRN_6 = residual_block(DRN_5, 256, dilation=2, stride=1, first_block=False)
with tf.variable_scope('DRN_6_2'):
DRN_6 = residual_block(DRN_5, 256, dilation=2, stride=1, first_block=False)
#DRN_6=tf.nn.sigmoid(DRN_6)
return DRN_6
# -*- coding: utf-8 -*-
"""
Created on Fri Aug 10 21:39:20 2018
@author: dell
"""
tf.reset_default_graph()
# image_path = r'D:/Deeplearning_Demo/image/IMG_1_0.jpg'#绝对路径
# label_path=r'IMG_output_1_0.npy'
# xia_path="ddddd"
Image_File_dir = "D:/Deeplearning_Demo/image"
Label_File_dir = "D:/Deeplearning_Demo/label"
"""
Image_File_dir = "D:/Deeplearning_Demo/TensorFlow_demo/Ours_crowd_counting/output/crop_image"
Label_File_dir = "D:/Deeplearning_Demo/TensorFlow_demo/Ours_crowd_counting/output/crop_groundtruth"
"""
Image_list = []
Label_list = []
learning_rate = 0.01
# 这里为什么会出问题?
# batch_size=2
each_step = 10
# 定义存储路径
ckpt_dir = "./model"
if not os.path.exists(ckpt_dir):
os.makedirs(ckpt_dir)
# 得到了一些相应的文件名称,便于下一次调用
def get_files(file_dir, label_dir):
for file in os.listdir(file_dir):
Image_list.append(file_dir + '/' + file)
print(Image_list)
for file in os.listdir(label_dir):
Label_list.append(label_dir + '/' + file)
# 损失函数的计算方法是什么,这里我们进行相应的改进比如可以改进成一些方差的计算方法等等
def loss(y, pred_y):
loss = tf.reduce_sum(tf.square(y - pred_y))
return loss
get_files(Image_File_dir, Label_File_dir)
image_path = tf.convert_to_tensor(Image_list)
label_path = tf.convert_to_tensor(Label_list)
print("start")
# file_queue = tf.train.string_input_producer([image_path]) #创建输入队列
file_queue = tf.train.slice_input_producer([image_path, label_path], shuffle=False)
# image = tf.train.slice_input_producer([[image_path] ])
file_queue = tf.convert_to_tensor(file_queue)
# file_queue[0]= tf.convert_to_tensor(file_queue[0])
# reader = tf.WholeFileReader()
# key,image = reader.read(file_queue)
"""
图像数据
"""
image = tf.read_file(file_queue[0]) # reader读取序列
image = tf.image.decode_jpeg(image, channels=3) | ,tensor
image = tf.image.resize_images(image, [240, 240])
image = tf.image.per_image_standardization(image)
"""
标签数据
"""
label = tf.read_file(file_queue[1]) # reader读取序列
# 读出的 value 是 string,现在转换为 uint8 型的向量
record_bytes = tf.decode_raw(label, tf.float32)
depth_major = tf.reshape(tf.slice(record_bytes, [20], [240 * 240 * 1]),
[1, 240, 240]) # depth, height, width
print("done")
uint8image = tf.transpose(depth_major, [1, 2, 0])
label = tf.cast(uint8image, tf.float32)/30000
"""这里需要用参数进行设计"""
image_batch, label_batch = tf.train.batch([image, label],
batch_size=batch_size,
num_threads=1,
capacity=10000)
predict_map= inference(image_batch)
print("验证的结果:", predict_map, label_batch)
# saving and loading networks
# 保存模型的参数等等
with tf.Session() as sess:
sess.run(tf.local_variables_initializer())
sess.run(tf.global_variables_initializer())
coord = tf.train.Coordinator() # 协同启动的线程
threads = tf.train.start_queue_runners(sess=sess, coord=coord) # 启动线程运行队列
# 保存模型
# 下面开始循环的过程
for i in range(100):
# 应用到的网络结构
print("i的数字为:", i)
#losses = sess.run(loss_result)
# saver.save(sess, ckpt_dir+"/my-model.ckpt", global_step=i)
# 接下来显示训练一段时间的测试结果如何,来判断这种方法是否应该用的
[image, label] = sess.run([image_batch, label_batch])
print(image.shape)
print(label.shape)
print("jieguo:", label[:, 1:10, 1:10, :])
print(type(image)) # tensor
# 转换了图片的类型
image = tf.squeeze(image[0:1, :, :, :]).eval()
print("image_type", type(image)) # ndarray
print("image:", image)
print(image.shape) # 240×320×3
image = tf.cast(image, tf.uint8).eval()
print("image.dtype:", image.dtype) # uint8
plt.figure(i)
plt.imshow(image)
plt.show()
# 现在要转换原始的label以及生成的结果
label = tf.squeeze(label[0:1, :, :, :]).eval()
print("label_type", type(label)) # ndarray
print(label.shape) # 240×320×3
# label = tf.cast(label, tf.float32).eval()
# print("label.dtype:", label.dtype) # uint8
# 开始转换一下生成结果
# 显示原始数据的分布是什么
i0 = Image.fromarray(label)
# plt.figure(i+1)
result = i0.show()
# 显示一下训练出来的数据是什么样子的
result_groundtruth= sess.run(predict_map)
print("ddd:",result_groundtruth)
result_groundtruth = tf.squeeze(result_groundtruth).eval()
print("形状为:", result_groundtruth.shape)
print("生成的结果:",result_groundtruth)
# 停止所有的线程
coord.request_stop()
coord.join(threads)
| # 解码 | identifier_name |
print_test.py | # -*- coding: utf-8 -*-
"""
Created on Wed Aug 8 17:26:44 2018
@author: dell
"""
import tensorflow as tf
import numpy as np
from PIL import Image
"""
im = Image.open('D://Deeplearning_Demo//Data_original//Data_im//train_im//IMG_1_B.jpg')
im.show()
im_array = np.array(im)
print(im_array.shape)
"""
from PIL import Image
from dilated_resnet import *
import random
import pickle as p
import os
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.image as plimg
label_path='IMG_output_1_0.npy'
#label_path=tf.convert_to_tensor(label_path)
#定义定义的参数的存储位置在cpu还是在GPu上 tf.contrib.layers.xavier_initializer()
def create_variables(name,shape,initializer=tf.truncated_normal_initializer(),is_fc_layers=False):
'''
:param name: A string. The name of the new variable
:param shape: A list of dimensions
:param initializer: User Xavier as default.
:param is_fc_layer: Want to create fc layer variable? May use different weight_decay for fc
layers.
:return: The created variable
'''
## TODO: to allow different weight decay to fully connected layer and conv layer
regularizer = tf.contrib.layers.l2_regularizer(scale=0.0002)
#new_variables = tf.get_variable(name, shape=shape, initializer=initializer,
# regularizer=regularizer)
new_variables = tf.get_variable(name, shape=shape, initializer=initializer
)
return new_variables
# 这里先构建一个批归一化层的函数,方便后续使用,训练和测试的时候需要改变一下把?
def batch_normalization_layer(input_layer, dimension):
'''
Helper function to do batch normalziation
:param input_layer: 4D tensor
:param dimension: input_layer.get_shape().as_list()[-1]. The depth of the 4D tensor
:return: the 4D tensor after being normalized
'''
mean, varience = tf.nn.moments(input_layer, axes=[0, 1, 2])
beta = tf.get_variable('beta', dimension, tf.float32,
initializer=tf.constant_initializer(0.0, tf.float32))
gamma = tf.get_variable('gamma', dimension, tf.float32,
initializer=tf.constant_initializer(1.0, tf.float32))
bn_layer = tf.nn.batch_normalization(input_layer, mean, varience, beta, gamma, BN_EPSILON)
return bn_layer
# 在这里进行相应的修改操作吧?
def conv_bn_relu_layer(input_layer, filter_shape, stride, dilation=1):
'''
A helper function to conv, batch normalize and relu the input tensor sequentially
:param input_layer: 4D tensor
:param filter_shape: list. [filter_height, filter_width, filter_depth, filter_number]
:param stride: stride size for conv
:return: 4D tensor. Y = Relu(batch_normalize(conv(X)))
'''
out_channel = filter_shape[-1]
filter = create_variables(name='conv', shape=filter_shape)
if dilation == 1:
conv_layer = tf.nn.conv2d(input_layer, filter, strides=[1, stride, stride, 1], padding='SAME')
elif dilation == 2:
conv_layer = tf.nn.atrous_conv2d(value=input_layer, filters=filter, rate=2, padding='SAME')
elif dilation == 4:
conv_layer = tf.nn.atrous_conv2d(value=input_layer, filters=filter, rate=4, padding='SAME')
else:
raise ValueError('no dilation is choosen!!!')
bn_layer = batch_normalization_layer(conv_layer, out_channel)
output = tf.nn.relu(bn_layer)
return output
# 我们采用这个基础网络结构
def bn_relu_conv_layer(input_layer, filter_shape, stride=1, dilation=1):
'''
A helper function to batch normalize, relu and conv the input layer sequentially
:param input_layer: 4D tensor
:param filter_shape: list. [filter_height, filter_width, filter_depth, filter_number]
:param stride: stride size for conv
:return: 4D tensor. Y = conv(Relu(batch_normalize(X)))
'''
in_channel = input_layer.get_shape().as_list()[-1]
bn_layer = batch_normalization_layer(input_layer, in_channel)
relu_layer = tf.nn.relu(bn_layer)
filter = create_variables(name='conv', shape=filter_shape)
# 这里进行卷积操作的一个很重要的部分,选择卷积的方式是什么,其中有1,2,4
if dilation == 1:
conv_layer = tf.nn.conv2d(relu_layer, filter, strides=[1, stride, stride, 1], padding='SAME')
elif dilation == 2:
conv_layer = tf.nn.atrous_conv2d(value=relu_layer, filters=filter, rate=2, padding='SAME')
elif dilation == 4:
conv_layer = tf.nn.atrous_conv2d(value=relu_layer, filters=filter, rate=4, padding='SAME')
else:
raise ValueError('no dilation is choosen!!!')
return conv_layer
# 开始构造block的结构过程
def residual_block(input_layer, output_channel, dilation=1, stride=1, first_block=False):
'''
Defines a residual block in ResNet
:param input_layer: 4D tensor
:param output_channel: int. return_tensor.get_shape().as_list()[-1] = output_channel
:param first_block: if this is the first residual block of the whole n | 7,input_channel,16])
DRN_1=tf.nn.conv2d(input_layer,filter,strides=[1,1,1,1],padding='SAME')
DRN_1=tf.nn.relu(DRN_1)
with tf.variable_scope('DRN_2'):
DRN_2=residual_block(DRN_1,16,dilation=1,stride=1,first_block=False)
# [3,3,32]+[3,3,32]的残差网络的设,stride设计为2相当于进行了降采样的操作
with tf.variable_scope('DRN_3'):
DRN_3 = residual_block(DRN_2, 32, dilation=1, stride=1, first_block=False)
with tf.variable_scope('DRN_4_2'):
DRN_4 = residual_block(DRN_3, 64, dilation=1, stride=1, first_block=False)
with tf.variable_scope('DRN_5_1'):
DRN_5=residual_block(DRN_4,128,dilation=1,stride=1,first_block=False)
with tf.variable_scope('DRN_5_2'):
DRN_5=residual_block(DRN_5,128,dilation=1,stride=1,first_block=False)
# [3,3,256]+[3,3,256]的残差网络的设,stride设计为2相当于进行了降采样的操作
with tf.variable_scope('DRN_6_1'):
DRN_6 = residual_block(DRN_5, 256, dilation=2, stride=1, first_block=False)
with tf.variable_scope('DRN_6_2'):
DRN_6 = residual_block(DRN_5, 256, dilation=2, stride=1, first_block=False)
#DRN_6=tf.nn.sigmoid(DRN_6)
return DRN_6
# -*- coding: utf-8 -*-
"""
Created on Fri Aug 10 21:39:20 2018
@author: dell
"""
tf.reset_default_graph()
# image_path = r'D:/Deeplearning_Demo/image/IMG_1_0.jpg'#绝对路径
# label_path=r'IMG_output_1_0.npy'
# xia_path="ddddd"
Image_File_dir = "D:/Deeplearning_Demo/image"
Label_File_dir = "D:/Deeplearning_Demo/label"
"""
Image_File_dir = "D:/Deeplearning_Demo/TensorFlow_demo/Ours_crowd_counting/output/crop_image"
Label_File_dir = "D:/Deeplearning_Demo/TensorFlow_demo/Ours_crowd_counting/output/crop_groundtruth"
"""
Image_list = []
Label_list = []
learning_rate = 0.01
# 这里为什么会出问题?
# batch_size=2
each_step = 10
# 定义存储路径
ckpt_dir = "./model"
if not os.path.exists(ckpt_dir):
os.makedirs(ckpt_dir)
# 得到了一些相应的文件名称,便于下一次调用
def get_files(file_dir, label_dir):
for file in os.listdir(file_dir):
Image_list.append(file_dir + '/' + file)
print(Image_list)
for file in os.listdir(label_dir):
Label_list.append(label_dir + '/' + file)
# 损失函数的计算方法是什么,这里我们进行相应的改进比如可以改进成一些方差的计算方法等等
def loss(y, pred_y):
loss = tf.reduce_sum(tf.square(y - pred_y))
return loss
get_files(Image_File_dir, Label_File_dir)
image_path = tf.convert_to_tensor(Image_list)
label_path = tf.convert_to_tensor(Label_list)
print("start")
# file_queue = tf.train.string_input_producer([image_path]) #创建输入队列
file_queue = tf.train.slice_input_producer([image_path, label_path], shuffle=False)
# image = tf.train.slice_input_producer([[image_path] ])
file_queue = tf.convert_to_tensor(file_queue)
# file_queue[0]= tf.convert_to_tensor(file_queue[0])
# reader = tf.WholeFileReader()
# key,image = reader.read(file_queue)
"""
图像数据
"""
image = tf.read_file(file_queue[0]) # reader读取序列
image = tf.image.decode_jpeg(image, channels=3) # 解码,tensor
image = tf.image.resize_images(image, [240, 240])
image = tf.image.per_image_standardization(image)
"""
标签数据
"""
label = tf.read_file(file_queue[1]) # reader读取序列
# 读出的 value 是 string,现在转换为 uint8 型的向量
record_bytes = tf.decode_raw(label, tf.float32)
depth_major = tf.reshape(tf.slice(record_bytes, [20], [240 * 240 * 1]),
[1, 240, 240]) # depth, height, width
print("done")
uint8image = tf.transpose(depth_major, [1, 2, 0])
label = tf.cast(uint8image, tf.float32)/30000
"""这里需要用参数进行设计"""
image_batch, label_batch = tf.train.batch([image, label],
batch_size=batch_size,
num_threads=1,
capacity=10000)
predict_map= inference(image_batch)
print("验证的结果:", predict_map, label_batch)
# saving and loading networks
# 保存模型的参数等等
with tf.Session() as sess:
sess.run(tf.local_variables_initializer())
sess.run(tf.global_variables_initializer())
coord = tf.train.Coordinator() # 协同启动的线程
threads = tf.train.start_queue_runners(sess=sess, coord=coord) # 启动线程运行队列
# 保存模型
# 下面开始循环的过程
for i in range(100):
# 应用到的网络结构
print("i的数字为:", i)
#losses = sess.run(loss_result)
# saver.save(sess, ckpt_dir+"/my-model.ckpt", global_step=i)
# 接下来显示训练一段时间的测试结果如何,来判断这种方法是否应该用的
[image, label] = sess.run([image_batch, label_batch])
print(image.shape)
print(label.shape)
print("jieguo:", label[:, 1:10, 1:10, :])
print(type(image)) # tensor
# 转换了图片的类型
image = tf.squeeze(image[0:1, :, :, :]).eval()
print("image_type", type(image)) # ndarray
print("image:", image)
print(image.shape) # 240×320×3
image = tf.cast(image, tf.uint8).eval()
print("image.dtype:", image.dtype) # uint8
plt.figure(i)
plt.imshow(image)
plt.show()
# 现在要转换原始的label以及生成的结果
label = tf.squeeze(label[0:1, :, :, :]).eval()
print("label_type", type(label)) # ndarray
print(label.shape) # 240×320×3
# label = tf.cast(label, tf.float32).eval()
# print("label.dtype:", label.dtype) # uint8
# 开始转换一下生成结果
# 显示原始数据的分布是什么
i0 = Image.fromarray(label)
# plt.figure(i+1)
result = i0.show()
# 显示一下训练出来的数据是什么样子的
result_groundtruth= sess.run(predict_map)
print("ddd:",result_groundtruth)
result_groundtruth = tf.squeeze(result_groundtruth).eval()
print("形状为:", result_groundtruth.shape)
print("生成的结果:",result_groundtruth)
# 停止所有的线程
coord.request_stop()
coord.join(threads)
| etwork
:return: 4D tensor.
'''
input_channel = input_layer.get_shape().as_list()[-1]
# 按照正常的网络结构
# 我们选择先bath 然后进行卷积和relu的操作
# Y = conv(Relu(batch_normalize(X)))
# bn_relu_conv_layer(input_layer,filter_shape,stride,dilation=1)
'''
设置残差网络的模板的第一层
'''
# 这里进行查看输入输出维度以及深度是否相同,这里没考虑网络卷积之后的大小是否跟原始大小一样的!
with tf.variable_scope('conv1_in_block'):
if first_block:
filter = create_variables(name='conv', shape=[3, 3, input_channel, output_channel])
conv1 = tf.nn.conv2d(input_layer, filter, strides=[1, stride, stride, 1], padding='SAME')
else:
conv1 = bn_relu_conv_layer(input_layer, [3, 3, input_channel, output_channel], stride, dilation)
with tf.variable_scope('conv2_in_block'):
conv2 = bn_relu_conv_layer(conv1, [3, 3, output_channel, output_channel], stride, dilation)
# mid_layer=bn_relu_conv_layer(input_layer,[3,3],stride,dilation=dilation)
# out_layer=bn_relu_conv_layer(mid_layer,[3,3],stride,dilation=dilation)
if input_channel != output_channel:
filter = create_variables(name='Unichannel', shape=[1, 1, input_channel, output_channel])
input_layer = tf.nn.conv2d(input_layer, filter, strides=[1, 1, 1, 1], padding='SAME')
result = tf.add(input_layer, conv2)
return result
def inference(input_layer):
#下面按照那个结构进行相应的搭建框架的结构如下所示:[batch,h,w,3]出去的时候也应该是[batch,h,w,3]
"""
这下面的数字以后会改的
"""
input_channel=input_layer.get_shape().as_list()[-1]
input_w=input_layer.get_shape().as_list()[2]
input_h=input_layer.get_shape().as_list()[1]
#[7,7,16]
with tf.variable_scope('DRN_1'):
filter=create_variables(name='DRN_1_va',shape=[7, | identifier_body |
push_active_set.rs | use {
crate::weighted_shuffle::WeightedShuffle,
indexmap::IndexMap,
rand::Rng,
solana_bloom::bloom::{AtomicBloom, Bloom},
solana_sdk::{native_token::LAMPORTS_PER_SOL, pubkey::Pubkey},
std::collections::HashMap,
};
const NUM_PUSH_ACTIVE_SET_ENTRIES: usize = 25;
// Each entry corresponds to a stake bucket for
// min stake of { this node, crds value owner }
// The entry represents set of gossip nodes to actively
// push to for crds values belonging to the bucket.
#[derive(Default)]
pub(crate) struct PushActiveSet([PushActiveSetEntry; NUM_PUSH_ACTIVE_SET_ENTRIES]);
// Keys are gossip nodes to push messages to.
// Values are which origins the node has pruned.
#[derive(Default)]
struct PushActiveSetEntry(IndexMap</*node:*/ Pubkey, /*origins:*/ AtomicBloom<Pubkey>>);
impl PushActiveSet {
#[cfg(debug_assertions)]
const MIN_NUM_BLOOM_ITEMS: usize = 512;
#[cfg(not(debug_assertions))]
const MIN_NUM_BLOOM_ITEMS: usize = crate::cluster_info::CRDS_UNIQUE_PUBKEY_CAPACITY;
pub(crate) fn get_nodes<'a>(
&'a self,
pubkey: &Pubkey, // This node.
origin: &'a Pubkey, // CRDS value owner.
// If true forces gossip push even if the node has pruned the origin.
should_force_push: impl FnMut(&Pubkey) -> bool + 'a,
stakes: &HashMap<Pubkey, u64>,
) -> impl Iterator<Item = &Pubkey> + 'a {
let stake = stakes.get(pubkey).min(stakes.get(origin));
self.get_entry(stake).get_nodes(origin, should_force_push)
}
// Prunes origins for the given gossip node.
// We will stop pushing messages from the specified origins to the node.
pub(crate) fn prune(
&self,
pubkey: &Pubkey, // This node.
node: &Pubkey, // Gossip node.
origins: &[Pubkey], // CRDS value owners.
stakes: &HashMap<Pubkey, u64>,
) {
let stake = stakes.get(pubkey);
for origin in origins {
if origin == pubkey {
continue;
}
let stake = stake.min(stakes.get(origin));
self.get_entry(stake).prune(node, origin)
}
}
pub(crate) fn rotate<R: Rng>(
&mut self,
rng: &mut R,
size: usize, // Number of nodes to retain in each active-set entry.
cluster_size: usize,
// Gossip nodes to be sampled for each push active set.
nodes: &[Pubkey],
stakes: &HashMap<Pubkey, u64>,
) {
let num_bloom_filter_items = cluster_size.max(Self::MIN_NUM_BLOOM_ITEMS);
// Active set of nodes to push to are sampled from these gossip nodes,
// using sampling probabilities obtained from the stake bucket of each
// node.
let buckets: Vec<_> = nodes
.iter()
.map(|node| get_stake_bucket(stakes.get(node)))
.collect();
// (k, entry) represents push active set where the stake bucket of
// min stake of {this node, crds value owner}
// is equal to `k`. The `entry` maintains set of gossip nodes to
// actively push to for crds values belonging to this bucket.
for (k, entry) in self.0.iter_mut().enumerate() {
let weights: Vec<u64> = buckets
.iter()
.map(|&bucket| {
// bucket <- get_stake_bucket(min stake of {
// this node, crds value owner and gossip peer
// })
// weight <- (bucket + 1)^2
// min stake of {...} is a proxy for how much we care about
// the link, and tries to mirror similar logic on the
// receiving end when pruning incoming links:
// https://github.com/solana-labs/solana/blob/81394cf92/gossip/src/received_cache.rs#L100-L105
let bucket = bucket.min(k) as u64;
bucket.saturating_add(1).saturating_pow(2)
})
.collect();
entry.rotate(rng, size, num_bloom_filter_items, nodes, &weights);
}
}
fn get_entry(&self, stake: Option<&u64>) -> &PushActiveSetEntry |
}
impl PushActiveSetEntry {
const BLOOM_FALSE_RATE: f64 = 0.1;
const BLOOM_MAX_BITS: usize = 1024 * 8 * 4;
fn get_nodes<'a>(
&'a self,
origin: &'a Pubkey,
// If true forces gossip push even if the node has pruned the origin.
mut should_force_push: impl FnMut(&Pubkey) -> bool + 'a,
) -> impl Iterator<Item = &Pubkey> + 'a {
self.0
.iter()
.filter(move |(node, bloom_filter)| {
!bloom_filter.contains(origin) || should_force_push(node)
})
.map(|(node, _bloom_filter)| node)
}
fn prune(
&self,
node: &Pubkey, // Gossip node.
origin: &Pubkey, // CRDS value owner
) {
if let Some(bloom_filter) = self.0.get(node) {
bloom_filter.add(origin);
}
}
fn rotate<R: Rng>(
&mut self,
rng: &mut R,
size: usize, // Number of nodes to retain.
num_bloom_filter_items: usize,
nodes: &[Pubkey],
weights: &[u64],
) {
debug_assert_eq!(nodes.len(), weights.len());
debug_assert!(weights.iter().all(|&weight| weight != 0u64));
let shuffle = WeightedShuffle::new("rotate-active-set", weights).shuffle(rng);
for node in shuffle.map(|k| &nodes[k]) {
// We intend to discard the oldest/first entry in the index-map.
if self.0.len() > size {
break;
}
if self.0.contains_key(node) {
continue;
}
let bloom = AtomicBloom::from(Bloom::random(
num_bloom_filter_items,
Self::BLOOM_FALSE_RATE,
Self::BLOOM_MAX_BITS,
));
bloom.add(node);
self.0.insert(*node, bloom);
}
// Drop the oldest entry while preserving the ordering of others.
while self.0.len() > size {
self.0.shift_remove_index(0);
}
}
}
// Maps stake to bucket index.
fn get_stake_bucket(stake: Option<&u64>) -> usize {
let stake = stake.copied().unwrap_or_default() / LAMPORTS_PER_SOL;
let bucket = u64::BITS - stake.leading_zeros();
(bucket as usize).min(NUM_PUSH_ACTIVE_SET_ENTRIES - 1)
}
#[cfg(test)]
mod tests {
use {super::*, rand::SeedableRng, rand_chacha::ChaChaRng, std::iter::repeat_with};
#[test]
fn test_get_stake_bucket() {
assert_eq!(get_stake_bucket(None), 0);
let buckets = [0, 1, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 5, 5];
for (k, bucket) in buckets.into_iter().enumerate() {
let stake = (k as u64) * LAMPORTS_PER_SOL;
assert_eq!(get_stake_bucket(Some(&stake)), bucket);
}
for (stake, bucket) in [
(4_194_303, 22),
(4_194_304, 23),
(8_388_607, 23),
(8_388_608, 24),
] {
let stake = stake * LAMPORTS_PER_SOL;
assert_eq!(get_stake_bucket(Some(&stake)), bucket);
}
assert_eq!(
get_stake_bucket(Some(&u64::MAX)),
NUM_PUSH_ACTIVE_SET_ENTRIES - 1
);
}
#[test]
fn test_push_active_set() {
const CLUSTER_SIZE: usize = 117;
const MAX_STAKE: u64 = (1 << 20) * LAMPORTS_PER_SOL;
let mut rng = ChaChaRng::from_seed([189u8; 32]);
let pubkey = Pubkey::new_unique();
let nodes: Vec<_> = repeat_with(Pubkey::new_unique).take(20).collect();
let stakes = repeat_with(|| rng.gen_range(1..MAX_STAKE));
let mut stakes: HashMap<_, _> = nodes.iter().copied().zip(stakes).collect();
stakes.insert(pubkey, rng.gen_range(1..MAX_STAKE));
let mut active_set = PushActiveSet::default();
assert!(active_set.0.iter().all(|entry| entry.0.is_empty()));
active_set.rotate(&mut rng, 5, CLUSTER_SIZE, &nodes, &stakes);
assert!(active_set.0.iter().all(|entry| entry.0.len() == 5));
// Assert that for all entries, each filter already prunes the key.
for entry in &active_set.0 {
for (node, filter) in entry.0.iter() {
assert!(filter.contains(node));
}
}
let other = &nodes[5];
let origin = &nodes[17];
assert!(active_set
.get_nodes(&pubkey, origin, |_| false, &stakes)
.eq([13, 5, 18, 16, 0].into_iter().map(|k| &nodes[k])));
assert!(active_set
.get_nodes(&pubkey, other, |_| false, &stakes)
.eq([13, 18, 16, 0].into_iter().map(|k| &nodes[k])));
active_set.prune(&pubkey, &nodes[5], &[*origin], &stakes);
active_set.prune(&pubkey, &nodes[3], &[*origin], &stakes);
active_set.prune(&pubkey, &nodes[16], &[*origin], &stakes);
assert!(active_set
.get_nodes(&pubkey, origin, |_| false, &stakes)
.eq([13, 18, 0].into_iter().map(|k| &nodes[k])));
assert!(active_set
.get_nodes(&pubkey, other, |_| false, &stakes)
.eq([13, 18, 16, 0].into_iter().map(|k| &nodes[k])));
active_set.rotate(&mut rng, 7, CLUSTER_SIZE, &nodes, &stakes);
assert!(active_set.0.iter().all(|entry| entry.0.len() == 7));
assert!(active_set
.get_nodes(&pubkey, origin, |_| false, &stakes)
.eq([18, 0, 7, 15, 11].into_iter().map(|k| &nodes[k])));
assert!(active_set
.get_nodes(&pubkey, other, |_| false, &stakes)
.eq([18, 16, 0, 7, 15, 11].into_iter().map(|k| &nodes[k])));
let origins = [*origin, *other];
active_set.prune(&pubkey, &nodes[18], &origins, &stakes);
active_set.prune(&pubkey, &nodes[0], &origins, &stakes);
active_set.prune(&pubkey, &nodes[15], &origins, &stakes);
assert!(active_set
.get_nodes(&pubkey, origin, |_| false, &stakes)
.eq([7, 11].into_iter().map(|k| &nodes[k])));
assert!(active_set
.get_nodes(&pubkey, other, |_| false, &stakes)
.eq([16, 7, 11].into_iter().map(|k| &nodes[k])));
}
#[test]
fn test_push_active_set_entry() {
const NUM_BLOOM_FILTER_ITEMS: usize = 100;
let mut rng = ChaChaRng::from_seed([147u8; 32]);
let nodes: Vec<_> = repeat_with(Pubkey::new_unique).take(20).collect();
let weights: Vec<_> = repeat_with(|| rng.gen_range(1..1000)).take(20).collect();
let mut entry = PushActiveSetEntry::default();
entry.rotate(
&mut rng,
5, // size
NUM_BLOOM_FILTER_ITEMS,
&nodes,
&weights,
);
assert_eq!(entry.0.len(), 5);
let keys = [&nodes[16], &nodes[11], &nodes[17], &nodes[14], &nodes[5]];
assert!(entry.0.keys().eq(keys));
for origin in &nodes {
if !keys.contains(&origin) {
assert!(entry.get_nodes(origin, |_| false).eq(keys));
} else {
assert!(entry.get_nodes(origin, |_| true).eq(keys));
assert!(entry
.get_nodes(origin, |_| false)
.eq(keys.into_iter().filter(|&key| key != origin)));
}
}
// Assert that each filter already prunes the key.
for (node, filter) in entry.0.iter() {
assert!(filter.contains(node));
}
for origin in keys {
assert!(entry.get_nodes(origin, |_| true).eq(keys));
assert!(entry
.get_nodes(origin, |_| false)
.eq(keys.into_iter().filter(|&node| node != origin)));
}
// Assert that prune excludes node from get.
let origin = &nodes[3];
entry.prune(&nodes[11], origin);
entry.prune(&nodes[14], origin);
entry.prune(&nodes[19], origin);
assert!(entry.get_nodes(origin, |_| true).eq(keys));
assert!(entry.get_nodes(origin, |_| false).eq(keys
.into_iter()
.filter(|&&node| node != nodes[11] && node != nodes[14])));
// Assert that rotate adds new nodes.
entry.rotate(&mut rng, 5, NUM_BLOOM_FILTER_ITEMS, &nodes, &weights);
let keys = [&nodes[11], &nodes[17], &nodes[14], &nodes[5], &nodes[7]];
assert!(entry.0.keys().eq(keys));
entry.rotate(&mut rng, 6, NUM_BLOOM_FILTER_ITEMS, &nodes, &weights);
let keys = [
&nodes[17], &nodes[14], &nodes[5], &nodes[7], &nodes[1], &nodes[13],
];
assert!(entry.0.keys().eq(keys));
entry.rotate(&mut rng, 4, NUM_BLOOM_FILTER_ITEMS, &nodes, &weights);
let keys = [&nodes[5], &nodes[7], &nodes[1], &nodes[13]];
assert!(entry.0.keys().eq(keys));
}
}
| {
&self.0[get_stake_bucket(stake)]
} | identifier_body |
push_active_set.rs | use {
crate::weighted_shuffle::WeightedShuffle,
indexmap::IndexMap,
rand::Rng,
solana_bloom::bloom::{AtomicBloom, Bloom},
solana_sdk::{native_token::LAMPORTS_PER_SOL, pubkey::Pubkey},
std::collections::HashMap,
};
const NUM_PUSH_ACTIVE_SET_ENTRIES: usize = 25;
// Each entry corresponds to a stake bucket for
// min stake of { this node, crds value owner }
// The entry represents set of gossip nodes to actively
// push to for crds values belonging to the bucket.
#[derive(Default)]
pub(crate) struct PushActiveSet([PushActiveSetEntry; NUM_PUSH_ACTIVE_SET_ENTRIES]);
// Keys are gossip nodes to push messages to.
// Values are which origins the node has pruned.
#[derive(Default)]
struct PushActiveSetEntry(IndexMap</*node:*/ Pubkey, /*origins:*/ AtomicBloom<Pubkey>>);
impl PushActiveSet {
#[cfg(debug_assertions)]
const MIN_NUM_BLOOM_ITEMS: usize = 512;
#[cfg(not(debug_assertions))]
const MIN_NUM_BLOOM_ITEMS: usize = crate::cluster_info::CRDS_UNIQUE_PUBKEY_CAPACITY;
pub(crate) fn get_nodes<'a>(
&'a self,
pubkey: &Pubkey, // This node.
origin: &'a Pubkey, // CRDS value owner.
// If true forces gossip push even if the node has pruned the origin.
should_force_push: impl FnMut(&Pubkey) -> bool + 'a,
stakes: &HashMap<Pubkey, u64>,
) -> impl Iterator<Item = &Pubkey> + 'a {
let stake = stakes.get(pubkey).min(stakes.get(origin));
self.get_entry(stake).get_nodes(origin, should_force_push)
}
// Prunes origins for the given gossip node.
// We will stop pushing messages from the specified origins to the node.
pub(crate) fn prune(
&self,
pubkey: &Pubkey, // This node.
node: &Pubkey, // Gossip node.
origins: &[Pubkey], // CRDS value owners.
stakes: &HashMap<Pubkey, u64>,
) {
let stake = stakes.get(pubkey);
for origin in origins {
if origin == pubkey {
continue;
}
let stake = stake.min(stakes.get(origin));
self.get_entry(stake).prune(node, origin)
}
}
pub(crate) fn rotate<R: Rng>(
&mut self,
rng: &mut R,
size: usize, // Number of nodes to retain in each active-set entry.
cluster_size: usize,
// Gossip nodes to be sampled for each push active set.
nodes: &[Pubkey],
stakes: &HashMap<Pubkey, u64>,
) {
let num_bloom_filter_items = cluster_size.max(Self::MIN_NUM_BLOOM_ITEMS);
// Active set of nodes to push to are sampled from these gossip nodes,
// using sampling probabilities obtained from the stake bucket of each
// node.
let buckets: Vec<_> = nodes
.iter()
.map(|node| get_stake_bucket(stakes.get(node)))
.collect();
// (k, entry) represents push active set where the stake bucket of
// min stake of {this node, crds value owner}
// is equal to `k`. The `entry` maintains set of gossip nodes to
// actively push to for crds values belonging to this bucket.
for (k, entry) in self.0.iter_mut().enumerate() {
let weights: Vec<u64> = buckets
.iter()
.map(|&bucket| {
// bucket <- get_stake_bucket(min stake of {
// this node, crds value owner and gossip peer
// })
// weight <- (bucket + 1)^2
// min stake of {...} is a proxy for how much we care about
// the link, and tries to mirror similar logic on the
// receiving end when pruning incoming links:
// https://github.com/solana-labs/solana/blob/81394cf92/gossip/src/received_cache.rs#L100-L105
let bucket = bucket.min(k) as u64;
bucket.saturating_add(1).saturating_pow(2)
})
.collect();
entry.rotate(rng, size, num_bloom_filter_items, nodes, &weights);
}
}
fn get_entry(&self, stake: Option<&u64>) -> &PushActiveSetEntry {
&self.0[get_stake_bucket(stake)]
}
}
impl PushActiveSetEntry {
const BLOOM_FALSE_RATE: f64 = 0.1;
const BLOOM_MAX_BITS: usize = 1024 * 8 * 4;
fn get_nodes<'a>(
&'a self,
origin: &'a Pubkey,
// If true forces gossip push even if the node has pruned the origin.
mut should_force_push: impl FnMut(&Pubkey) -> bool + 'a,
) -> impl Iterator<Item = &Pubkey> + 'a {
self.0
.iter()
.filter(move |(node, bloom_filter)| {
!bloom_filter.contains(origin) || should_force_push(node)
})
.map(|(node, _bloom_filter)| node)
}
fn | (
&self,
node: &Pubkey, // Gossip node.
origin: &Pubkey, // CRDS value owner
) {
if let Some(bloom_filter) = self.0.get(node) {
bloom_filter.add(origin);
}
}
fn rotate<R: Rng>(
&mut self,
rng: &mut R,
size: usize, // Number of nodes to retain.
num_bloom_filter_items: usize,
nodes: &[Pubkey],
weights: &[u64],
) {
debug_assert_eq!(nodes.len(), weights.len());
debug_assert!(weights.iter().all(|&weight| weight != 0u64));
let shuffle = WeightedShuffle::new("rotate-active-set", weights).shuffle(rng);
for node in shuffle.map(|k| &nodes[k]) {
// We intend to discard the oldest/first entry in the index-map.
if self.0.len() > size {
break;
}
if self.0.contains_key(node) {
continue;
}
let bloom = AtomicBloom::from(Bloom::random(
num_bloom_filter_items,
Self::BLOOM_FALSE_RATE,
Self::BLOOM_MAX_BITS,
));
bloom.add(node);
self.0.insert(*node, bloom);
}
// Drop the oldest entry while preserving the ordering of others.
while self.0.len() > size {
self.0.shift_remove_index(0);
}
}
}
// Maps stake to bucket index.
fn get_stake_bucket(stake: Option<&u64>) -> usize {
let stake = stake.copied().unwrap_or_default() / LAMPORTS_PER_SOL;
let bucket = u64::BITS - stake.leading_zeros();
(bucket as usize).min(NUM_PUSH_ACTIVE_SET_ENTRIES - 1)
}
#[cfg(test)]
mod tests {
use {super::*, rand::SeedableRng, rand_chacha::ChaChaRng, std::iter::repeat_with};
#[test]
fn test_get_stake_bucket() {
assert_eq!(get_stake_bucket(None), 0);
let buckets = [0, 1, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 5, 5];
for (k, bucket) in buckets.into_iter().enumerate() {
let stake = (k as u64) * LAMPORTS_PER_SOL;
assert_eq!(get_stake_bucket(Some(&stake)), bucket);
}
for (stake, bucket) in [
(4_194_303, 22),
(4_194_304, 23),
(8_388_607, 23),
(8_388_608, 24),
] {
let stake = stake * LAMPORTS_PER_SOL;
assert_eq!(get_stake_bucket(Some(&stake)), bucket);
}
assert_eq!(
get_stake_bucket(Some(&u64::MAX)),
NUM_PUSH_ACTIVE_SET_ENTRIES - 1
);
}
#[test]
fn test_push_active_set() {
const CLUSTER_SIZE: usize = 117;
const MAX_STAKE: u64 = (1 << 20) * LAMPORTS_PER_SOL;
let mut rng = ChaChaRng::from_seed([189u8; 32]);
let pubkey = Pubkey::new_unique();
let nodes: Vec<_> = repeat_with(Pubkey::new_unique).take(20).collect();
let stakes = repeat_with(|| rng.gen_range(1..MAX_STAKE));
let mut stakes: HashMap<_, _> = nodes.iter().copied().zip(stakes).collect();
stakes.insert(pubkey, rng.gen_range(1..MAX_STAKE));
let mut active_set = PushActiveSet::default();
assert!(active_set.0.iter().all(|entry| entry.0.is_empty()));
active_set.rotate(&mut rng, 5, CLUSTER_SIZE, &nodes, &stakes);
assert!(active_set.0.iter().all(|entry| entry.0.len() == 5));
// Assert that for all entries, each filter already prunes the key.
for entry in &active_set.0 {
for (node, filter) in entry.0.iter() {
assert!(filter.contains(node));
}
}
let other = &nodes[5];
let origin = &nodes[17];
assert!(active_set
.get_nodes(&pubkey, origin, |_| false, &stakes)
.eq([13, 5, 18, 16, 0].into_iter().map(|k| &nodes[k])));
assert!(active_set
.get_nodes(&pubkey, other, |_| false, &stakes)
.eq([13, 18, 16, 0].into_iter().map(|k| &nodes[k])));
active_set.prune(&pubkey, &nodes[5], &[*origin], &stakes);
active_set.prune(&pubkey, &nodes[3], &[*origin], &stakes);
active_set.prune(&pubkey, &nodes[16], &[*origin], &stakes);
assert!(active_set
.get_nodes(&pubkey, origin, |_| false, &stakes)
.eq([13, 18, 0].into_iter().map(|k| &nodes[k])));
assert!(active_set
.get_nodes(&pubkey, other, |_| false, &stakes)
.eq([13, 18, 16, 0].into_iter().map(|k| &nodes[k])));
active_set.rotate(&mut rng, 7, CLUSTER_SIZE, &nodes, &stakes);
assert!(active_set.0.iter().all(|entry| entry.0.len() == 7));
assert!(active_set
.get_nodes(&pubkey, origin, |_| false, &stakes)
.eq([18, 0, 7, 15, 11].into_iter().map(|k| &nodes[k])));
assert!(active_set
.get_nodes(&pubkey, other, |_| false, &stakes)
.eq([18, 16, 0, 7, 15, 11].into_iter().map(|k| &nodes[k])));
let origins = [*origin, *other];
active_set.prune(&pubkey, &nodes[18], &origins, &stakes);
active_set.prune(&pubkey, &nodes[0], &origins, &stakes);
active_set.prune(&pubkey, &nodes[15], &origins, &stakes);
assert!(active_set
.get_nodes(&pubkey, origin, |_| false, &stakes)
.eq([7, 11].into_iter().map(|k| &nodes[k])));
assert!(active_set
.get_nodes(&pubkey, other, |_| false, &stakes)
.eq([16, 7, 11].into_iter().map(|k| &nodes[k])));
}
#[test]
fn test_push_active_set_entry() {
const NUM_BLOOM_FILTER_ITEMS: usize = 100;
let mut rng = ChaChaRng::from_seed([147u8; 32]);
let nodes: Vec<_> = repeat_with(Pubkey::new_unique).take(20).collect();
let weights: Vec<_> = repeat_with(|| rng.gen_range(1..1000)).take(20).collect();
let mut entry = PushActiveSetEntry::default();
entry.rotate(
&mut rng,
5, // size
NUM_BLOOM_FILTER_ITEMS,
&nodes,
&weights,
);
assert_eq!(entry.0.len(), 5);
let keys = [&nodes[16], &nodes[11], &nodes[17], &nodes[14], &nodes[5]];
assert!(entry.0.keys().eq(keys));
for origin in &nodes {
if !keys.contains(&origin) {
assert!(entry.get_nodes(origin, |_| false).eq(keys));
} else {
assert!(entry.get_nodes(origin, |_| true).eq(keys));
assert!(entry
.get_nodes(origin, |_| false)
.eq(keys.into_iter().filter(|&key| key != origin)));
}
}
// Assert that each filter already prunes the key.
for (node, filter) in entry.0.iter() {
assert!(filter.contains(node));
}
for origin in keys {
assert!(entry.get_nodes(origin, |_| true).eq(keys));
assert!(entry
.get_nodes(origin, |_| false)
.eq(keys.into_iter().filter(|&node| node != origin)));
}
// Assert that prune excludes node from get.
let origin = &nodes[3];
entry.prune(&nodes[11], origin);
entry.prune(&nodes[14], origin);
entry.prune(&nodes[19], origin);
assert!(entry.get_nodes(origin, |_| true).eq(keys));
assert!(entry.get_nodes(origin, |_| false).eq(keys
.into_iter()
.filter(|&&node| node != nodes[11] && node != nodes[14])));
// Assert that rotate adds new nodes.
entry.rotate(&mut rng, 5, NUM_BLOOM_FILTER_ITEMS, &nodes, &weights);
let keys = [&nodes[11], &nodes[17], &nodes[14], &nodes[5], &nodes[7]];
assert!(entry.0.keys().eq(keys));
entry.rotate(&mut rng, 6, NUM_BLOOM_FILTER_ITEMS, &nodes, &weights);
let keys = [
&nodes[17], &nodes[14], &nodes[5], &nodes[7], &nodes[1], &nodes[13],
];
assert!(entry.0.keys().eq(keys));
entry.rotate(&mut rng, 4, NUM_BLOOM_FILTER_ITEMS, &nodes, &weights);
let keys = [&nodes[5], &nodes[7], &nodes[1], &nodes[13]];
assert!(entry.0.keys().eq(keys));
}
}
| prune | identifier_name |
push_active_set.rs | use {
crate::weighted_shuffle::WeightedShuffle,
indexmap::IndexMap,
rand::Rng,
solana_bloom::bloom::{AtomicBloom, Bloom},
solana_sdk::{native_token::LAMPORTS_PER_SOL, pubkey::Pubkey},
std::collections::HashMap,
};
const NUM_PUSH_ACTIVE_SET_ENTRIES: usize = 25;
// Each entry corresponds to a stake bucket for
// min stake of { this node, crds value owner }
// The entry represents set of gossip nodes to actively
// push to for crds values belonging to the bucket.
#[derive(Default)]
pub(crate) struct PushActiveSet([PushActiveSetEntry; NUM_PUSH_ACTIVE_SET_ENTRIES]);
// Keys are gossip nodes to push messages to.
// Values are which origins the node has pruned.
#[derive(Default)]
struct PushActiveSetEntry(IndexMap</*node:*/ Pubkey, /*origins:*/ AtomicBloom<Pubkey>>);
impl PushActiveSet {
#[cfg(debug_assertions)]
const MIN_NUM_BLOOM_ITEMS: usize = 512;
#[cfg(not(debug_assertions))]
const MIN_NUM_BLOOM_ITEMS: usize = crate::cluster_info::CRDS_UNIQUE_PUBKEY_CAPACITY;
pub(crate) fn get_nodes<'a>(
&'a self,
pubkey: &Pubkey, // This node.
origin: &'a Pubkey, // CRDS value owner.
// If true forces gossip push even if the node has pruned the origin.
should_force_push: impl FnMut(&Pubkey) -> bool + 'a,
stakes: &HashMap<Pubkey, u64>,
) -> impl Iterator<Item = &Pubkey> + 'a {
let stake = stakes.get(pubkey).min(stakes.get(origin));
self.get_entry(stake).get_nodes(origin, should_force_push)
}
// Prunes origins for the given gossip node.
// We will stop pushing messages from the specified origins to the node.
pub(crate) fn prune(
&self,
pubkey: &Pubkey, // This node.
node: &Pubkey, // Gossip node.
origins: &[Pubkey], // CRDS value owners.
stakes: &HashMap<Pubkey, u64>,
) {
let stake = stakes.get(pubkey);
for origin in origins {
if origin == pubkey {
continue;
}
let stake = stake.min(stakes.get(origin));
self.get_entry(stake).prune(node, origin)
}
}
pub(crate) fn rotate<R: Rng>(
&mut self,
rng: &mut R,
size: usize, // Number of nodes to retain in each active-set entry.
cluster_size: usize,
// Gossip nodes to be sampled for each push active set.
nodes: &[Pubkey],
stakes: &HashMap<Pubkey, u64>,
) {
let num_bloom_filter_items = cluster_size.max(Self::MIN_NUM_BLOOM_ITEMS);
// Active set of nodes to push to are sampled from these gossip nodes,
// using sampling probabilities obtained from the stake bucket of each
// node.
let buckets: Vec<_> = nodes
.iter()
.map(|node| get_stake_bucket(stakes.get(node)))
.collect();
// (k, entry) represents push active set where the stake bucket of
// min stake of {this node, crds value owner}
// is equal to `k`. The `entry` maintains set of gossip nodes to
// actively push to for crds values belonging to this bucket.
for (k, entry) in self.0.iter_mut().enumerate() {
let weights: Vec<u64> = buckets
.iter()
.map(|&bucket| {
// bucket <- get_stake_bucket(min stake of {
// this node, crds value owner and gossip peer
// })
// weight <- (bucket + 1)^2
// min stake of {...} is a proxy for how much we care about
// the link, and tries to mirror similar logic on the
// receiving end when pruning incoming links:
// https://github.com/solana-labs/solana/blob/81394cf92/gossip/src/received_cache.rs#L100-L105
let bucket = bucket.min(k) as u64;
bucket.saturating_add(1).saturating_pow(2)
})
.collect();
entry.rotate(rng, size, num_bloom_filter_items, nodes, &weights);
}
}
fn get_entry(&self, stake: Option<&u64>) -> &PushActiveSetEntry {
&self.0[get_stake_bucket(stake)]
}
}
impl PushActiveSetEntry {
const BLOOM_FALSE_RATE: f64 = 0.1;
const BLOOM_MAX_BITS: usize = 1024 * 8 * 4;
fn get_nodes<'a>(
&'a self,
origin: &'a Pubkey,
// If true forces gossip push even if the node has pruned the origin.
mut should_force_push: impl FnMut(&Pubkey) -> bool + 'a,
) -> impl Iterator<Item = &Pubkey> + 'a {
self.0
.iter()
.filter(move |(node, bloom_filter)| {
!bloom_filter.contains(origin) || should_force_push(node)
})
.map(|(node, _bloom_filter)| node)
}
fn prune(
&self,
node: &Pubkey, // Gossip node.
origin: &Pubkey, // CRDS value owner
) {
if let Some(bloom_filter) = self.0.get(node) {
bloom_filter.add(origin);
}
}
fn rotate<R: Rng>(
&mut self,
rng: &mut R,
size: usize, // Number of nodes to retain.
num_bloom_filter_items: usize,
nodes: &[Pubkey],
weights: &[u64],
) {
debug_assert_eq!(nodes.len(), weights.len());
debug_assert!(weights.iter().all(|&weight| weight != 0u64));
let shuffle = WeightedShuffle::new("rotate-active-set", weights).shuffle(rng);
for node in shuffle.map(|k| &nodes[k]) {
// We intend to discard the oldest/first entry in the index-map.
if self.0.len() > size {
break;
}
if self.0.contains_key(node) {
continue;
}
let bloom = AtomicBloom::from(Bloom::random(
num_bloom_filter_items,
Self::BLOOM_FALSE_RATE,
Self::BLOOM_MAX_BITS,
));
bloom.add(node);
self.0.insert(*node, bloom);
}
// Drop the oldest entry while preserving the ordering of others.
while self.0.len() > size {
self.0.shift_remove_index(0);
}
}
}
// Maps stake to bucket index.
fn get_stake_bucket(stake: Option<&u64>) -> usize {
let stake = stake.copied().unwrap_or_default() / LAMPORTS_PER_SOL;
let bucket = u64::BITS - stake.leading_zeros();
(bucket as usize).min(NUM_PUSH_ACTIVE_SET_ENTRIES - 1)
}
#[cfg(test)]
mod tests {
use {super::*, rand::SeedableRng, rand_chacha::ChaChaRng, std::iter::repeat_with};
#[test]
fn test_get_stake_bucket() {
assert_eq!(get_stake_bucket(None), 0);
let buckets = [0, 1, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 5, 5];
for (k, bucket) in buckets.into_iter().enumerate() {
let stake = (k as u64) * LAMPORTS_PER_SOL;
assert_eq!(get_stake_bucket(Some(&stake)), bucket);
}
for (stake, bucket) in [
(4_194_303, 22),
(4_194_304, 23),
(8_388_607, 23),
(8_388_608, 24),
] {
let stake = stake * LAMPORTS_PER_SOL;
assert_eq!(get_stake_bucket(Some(&stake)), bucket);
}
assert_eq!(
get_stake_bucket(Some(&u64::MAX)),
NUM_PUSH_ACTIVE_SET_ENTRIES - 1
);
}
#[test]
fn test_push_active_set() {
const CLUSTER_SIZE: usize = 117;
const MAX_STAKE: u64 = (1 << 20) * LAMPORTS_PER_SOL;
let mut rng = ChaChaRng::from_seed([189u8; 32]);
let pubkey = Pubkey::new_unique();
let nodes: Vec<_> = repeat_with(Pubkey::new_unique).take(20).collect();
let stakes = repeat_with(|| rng.gen_range(1..MAX_STAKE));
let mut stakes: HashMap<_, _> = nodes.iter().copied().zip(stakes).collect();
stakes.insert(pubkey, rng.gen_range(1..MAX_STAKE));
let mut active_set = PushActiveSet::default();
assert!(active_set.0.iter().all(|entry| entry.0.is_empty()));
active_set.rotate(&mut rng, 5, CLUSTER_SIZE, &nodes, &stakes);
assert!(active_set.0.iter().all(|entry| entry.0.len() == 5));
// Assert that for all entries, each filter already prunes the key.
for entry in &active_set.0 {
for (node, filter) in entry.0.iter() {
assert!(filter.contains(node));
}
}
let other = &nodes[5];
let origin = &nodes[17];
assert!(active_set
.get_nodes(&pubkey, origin, |_| false, &stakes)
.eq([13, 5, 18, 16, 0].into_iter().map(|k| &nodes[k])));
assert!(active_set
.get_nodes(&pubkey, other, |_| false, &stakes)
.eq([13, 18, 16, 0].into_iter().map(|k| &nodes[k])));
active_set.prune(&pubkey, &nodes[5], &[*origin], &stakes);
active_set.prune(&pubkey, &nodes[3], &[*origin], &stakes);
active_set.prune(&pubkey, &nodes[16], &[*origin], &stakes);
assert!(active_set
.get_nodes(&pubkey, origin, |_| false, &stakes)
.eq([13, 18, 0].into_iter().map(|k| &nodes[k])));
assert!(active_set
.get_nodes(&pubkey, other, |_| false, &stakes)
.eq([13, 18, 16, 0].into_iter().map(|k| &nodes[k])));
active_set.rotate(&mut rng, 7, CLUSTER_SIZE, &nodes, &stakes);
assert!(active_set.0.iter().all(|entry| entry.0.len() == 7));
assert!(active_set
.get_nodes(&pubkey, origin, |_| false, &stakes)
.eq([18, 0, 7, 15, 11].into_iter().map(|k| &nodes[k])));
assert!(active_set
.get_nodes(&pubkey, other, |_| false, &stakes)
.eq([18, 16, 0, 7, 15, 11].into_iter().map(|k| &nodes[k])));
let origins = [*origin, *other];
active_set.prune(&pubkey, &nodes[18], &origins, &stakes);
active_set.prune(&pubkey, &nodes[0], &origins, &stakes);
active_set.prune(&pubkey, &nodes[15], &origins, &stakes);
assert!(active_set
.get_nodes(&pubkey, origin, |_| false, &stakes)
.eq([7, 11].into_iter().map(|k| &nodes[k])));
assert!(active_set
.get_nodes(&pubkey, other, |_| false, &stakes)
.eq([16, 7, 11].into_iter().map(|k| &nodes[k])));
}
| #[test]
fn test_push_active_set_entry() {
const NUM_BLOOM_FILTER_ITEMS: usize = 100;
let mut rng = ChaChaRng::from_seed([147u8; 32]);
let nodes: Vec<_> = repeat_with(Pubkey::new_unique).take(20).collect();
let weights: Vec<_> = repeat_with(|| rng.gen_range(1..1000)).take(20).collect();
let mut entry = PushActiveSetEntry::default();
entry.rotate(
&mut rng,
5, // size
NUM_BLOOM_FILTER_ITEMS,
&nodes,
&weights,
);
assert_eq!(entry.0.len(), 5);
let keys = [&nodes[16], &nodes[11], &nodes[17], &nodes[14], &nodes[5]];
assert!(entry.0.keys().eq(keys));
for origin in &nodes {
if !keys.contains(&origin) {
assert!(entry.get_nodes(origin, |_| false).eq(keys));
} else {
assert!(entry.get_nodes(origin, |_| true).eq(keys));
assert!(entry
.get_nodes(origin, |_| false)
.eq(keys.into_iter().filter(|&key| key != origin)));
}
}
// Assert that each filter already prunes the key.
for (node, filter) in entry.0.iter() {
assert!(filter.contains(node));
}
for origin in keys {
assert!(entry.get_nodes(origin, |_| true).eq(keys));
assert!(entry
.get_nodes(origin, |_| false)
.eq(keys.into_iter().filter(|&node| node != origin)));
}
// Assert that prune excludes node from get.
let origin = &nodes[3];
entry.prune(&nodes[11], origin);
entry.prune(&nodes[14], origin);
entry.prune(&nodes[19], origin);
assert!(entry.get_nodes(origin, |_| true).eq(keys));
assert!(entry.get_nodes(origin, |_| false).eq(keys
.into_iter()
.filter(|&&node| node != nodes[11] && node != nodes[14])));
// Assert that rotate adds new nodes.
entry.rotate(&mut rng, 5, NUM_BLOOM_FILTER_ITEMS, &nodes, &weights);
let keys = [&nodes[11], &nodes[17], &nodes[14], &nodes[5], &nodes[7]];
assert!(entry.0.keys().eq(keys));
entry.rotate(&mut rng, 6, NUM_BLOOM_FILTER_ITEMS, &nodes, &weights);
let keys = [
&nodes[17], &nodes[14], &nodes[5], &nodes[7], &nodes[1], &nodes[13],
];
assert!(entry.0.keys().eq(keys));
entry.rotate(&mut rng, 4, NUM_BLOOM_FILTER_ITEMS, &nodes, &weights);
let keys = [&nodes[5], &nodes[7], &nodes[1], &nodes[13]];
assert!(entry.0.keys().eq(keys));
}
} | random_line_split | |
push_active_set.rs | use {
crate::weighted_shuffle::WeightedShuffle,
indexmap::IndexMap,
rand::Rng,
solana_bloom::bloom::{AtomicBloom, Bloom},
solana_sdk::{native_token::LAMPORTS_PER_SOL, pubkey::Pubkey},
std::collections::HashMap,
};
const NUM_PUSH_ACTIVE_SET_ENTRIES: usize = 25;
// Each entry corresponds to a stake bucket for
// min stake of { this node, crds value owner }
// The entry represents set of gossip nodes to actively
// push to for crds values belonging to the bucket.
#[derive(Default)]
pub(crate) struct PushActiveSet([PushActiveSetEntry; NUM_PUSH_ACTIVE_SET_ENTRIES]);
// Keys are gossip nodes to push messages to.
// Values are which origins the node has pruned.
#[derive(Default)]
struct PushActiveSetEntry(IndexMap</*node:*/ Pubkey, /*origins:*/ AtomicBloom<Pubkey>>);
impl PushActiveSet {
#[cfg(debug_assertions)]
const MIN_NUM_BLOOM_ITEMS: usize = 512;
#[cfg(not(debug_assertions))]
const MIN_NUM_BLOOM_ITEMS: usize = crate::cluster_info::CRDS_UNIQUE_PUBKEY_CAPACITY;
pub(crate) fn get_nodes<'a>(
&'a self,
pubkey: &Pubkey, // This node.
origin: &'a Pubkey, // CRDS value owner.
// If true forces gossip push even if the node has pruned the origin.
should_force_push: impl FnMut(&Pubkey) -> bool + 'a,
stakes: &HashMap<Pubkey, u64>,
) -> impl Iterator<Item = &Pubkey> + 'a {
let stake = stakes.get(pubkey).min(stakes.get(origin));
self.get_entry(stake).get_nodes(origin, should_force_push)
}
// Prunes origins for the given gossip node.
// We will stop pushing messages from the specified origins to the node.
pub(crate) fn prune(
&self,
pubkey: &Pubkey, // This node.
node: &Pubkey, // Gossip node.
origins: &[Pubkey], // CRDS value owners.
stakes: &HashMap<Pubkey, u64>,
) {
let stake = stakes.get(pubkey);
for origin in origins {
if origin == pubkey {
continue;
}
let stake = stake.min(stakes.get(origin));
self.get_entry(stake).prune(node, origin)
}
}
pub(crate) fn rotate<R: Rng>(
&mut self,
rng: &mut R,
size: usize, // Number of nodes to retain in each active-set entry.
cluster_size: usize,
// Gossip nodes to be sampled for each push active set.
nodes: &[Pubkey],
stakes: &HashMap<Pubkey, u64>,
) {
let num_bloom_filter_items = cluster_size.max(Self::MIN_NUM_BLOOM_ITEMS);
// Active set of nodes to push to are sampled from these gossip nodes,
// using sampling probabilities obtained from the stake bucket of each
// node.
let buckets: Vec<_> = nodes
.iter()
.map(|node| get_stake_bucket(stakes.get(node)))
.collect();
// (k, entry) represents push active set where the stake bucket of
// min stake of {this node, crds value owner}
// is equal to `k`. The `entry` maintains set of gossip nodes to
// actively push to for crds values belonging to this bucket.
for (k, entry) in self.0.iter_mut().enumerate() {
let weights: Vec<u64> = buckets
.iter()
.map(|&bucket| {
// bucket <- get_stake_bucket(min stake of {
// this node, crds value owner and gossip peer
// })
// weight <- (bucket + 1)^2
// min stake of {...} is a proxy for how much we care about
// the link, and tries to mirror similar logic on the
// receiving end when pruning incoming links:
// https://github.com/solana-labs/solana/blob/81394cf92/gossip/src/received_cache.rs#L100-L105
let bucket = bucket.min(k) as u64;
bucket.saturating_add(1).saturating_pow(2)
})
.collect();
entry.rotate(rng, size, num_bloom_filter_items, nodes, &weights);
}
}
fn get_entry(&self, stake: Option<&u64>) -> &PushActiveSetEntry {
&self.0[get_stake_bucket(stake)]
}
}
impl PushActiveSetEntry {
const BLOOM_FALSE_RATE: f64 = 0.1;
const BLOOM_MAX_BITS: usize = 1024 * 8 * 4;
fn get_nodes<'a>(
&'a self,
origin: &'a Pubkey,
// If true forces gossip push even if the node has pruned the origin.
mut should_force_push: impl FnMut(&Pubkey) -> bool + 'a,
) -> impl Iterator<Item = &Pubkey> + 'a {
self.0
.iter()
.filter(move |(node, bloom_filter)| {
!bloom_filter.contains(origin) || should_force_push(node)
})
.map(|(node, _bloom_filter)| node)
}
fn prune(
&self,
node: &Pubkey, // Gossip node.
origin: &Pubkey, // CRDS value owner
) {
if let Some(bloom_filter) = self.0.get(node) {
bloom_filter.add(origin);
}
}
fn rotate<R: Rng>(
&mut self,
rng: &mut R,
size: usize, // Number of nodes to retain.
num_bloom_filter_items: usize,
nodes: &[Pubkey],
weights: &[u64],
) {
debug_assert_eq!(nodes.len(), weights.len());
debug_assert!(weights.iter().all(|&weight| weight != 0u64));
let shuffle = WeightedShuffle::new("rotate-active-set", weights).shuffle(rng);
for node in shuffle.map(|k| &nodes[k]) {
// We intend to discard the oldest/first entry in the index-map.
if self.0.len() > size {
break;
}
if self.0.contains_key(node) {
continue;
}
let bloom = AtomicBloom::from(Bloom::random(
num_bloom_filter_items,
Self::BLOOM_FALSE_RATE,
Self::BLOOM_MAX_BITS,
));
bloom.add(node);
self.0.insert(*node, bloom);
}
// Drop the oldest entry while preserving the ordering of others.
while self.0.len() > size {
self.0.shift_remove_index(0);
}
}
}
// Maps stake to bucket index.
fn get_stake_bucket(stake: Option<&u64>) -> usize {
let stake = stake.copied().unwrap_or_default() / LAMPORTS_PER_SOL;
let bucket = u64::BITS - stake.leading_zeros();
(bucket as usize).min(NUM_PUSH_ACTIVE_SET_ENTRIES - 1)
}
#[cfg(test)]
mod tests {
use {super::*, rand::SeedableRng, rand_chacha::ChaChaRng, std::iter::repeat_with};
#[test]
fn test_get_stake_bucket() {
assert_eq!(get_stake_bucket(None), 0);
let buckets = [0, 1, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 5, 5];
for (k, bucket) in buckets.into_iter().enumerate() {
let stake = (k as u64) * LAMPORTS_PER_SOL;
assert_eq!(get_stake_bucket(Some(&stake)), bucket);
}
for (stake, bucket) in [
(4_194_303, 22),
(4_194_304, 23),
(8_388_607, 23),
(8_388_608, 24),
] {
let stake = stake * LAMPORTS_PER_SOL;
assert_eq!(get_stake_bucket(Some(&stake)), bucket);
}
assert_eq!(
get_stake_bucket(Some(&u64::MAX)),
NUM_PUSH_ACTIVE_SET_ENTRIES - 1
);
}
#[test]
fn test_push_active_set() {
const CLUSTER_SIZE: usize = 117;
const MAX_STAKE: u64 = (1 << 20) * LAMPORTS_PER_SOL;
let mut rng = ChaChaRng::from_seed([189u8; 32]);
let pubkey = Pubkey::new_unique();
let nodes: Vec<_> = repeat_with(Pubkey::new_unique).take(20).collect();
let stakes = repeat_with(|| rng.gen_range(1..MAX_STAKE));
let mut stakes: HashMap<_, _> = nodes.iter().copied().zip(stakes).collect();
stakes.insert(pubkey, rng.gen_range(1..MAX_STAKE));
let mut active_set = PushActiveSet::default();
assert!(active_set.0.iter().all(|entry| entry.0.is_empty()));
active_set.rotate(&mut rng, 5, CLUSTER_SIZE, &nodes, &stakes);
assert!(active_set.0.iter().all(|entry| entry.0.len() == 5));
// Assert that for all entries, each filter already prunes the key.
for entry in &active_set.0 {
for (node, filter) in entry.0.iter() {
assert!(filter.contains(node));
}
}
let other = &nodes[5];
let origin = &nodes[17];
assert!(active_set
.get_nodes(&pubkey, origin, |_| false, &stakes)
.eq([13, 5, 18, 16, 0].into_iter().map(|k| &nodes[k])));
assert!(active_set
.get_nodes(&pubkey, other, |_| false, &stakes)
.eq([13, 18, 16, 0].into_iter().map(|k| &nodes[k])));
active_set.prune(&pubkey, &nodes[5], &[*origin], &stakes);
active_set.prune(&pubkey, &nodes[3], &[*origin], &stakes);
active_set.prune(&pubkey, &nodes[16], &[*origin], &stakes);
assert!(active_set
.get_nodes(&pubkey, origin, |_| false, &stakes)
.eq([13, 18, 0].into_iter().map(|k| &nodes[k])));
assert!(active_set
.get_nodes(&pubkey, other, |_| false, &stakes)
.eq([13, 18, 16, 0].into_iter().map(|k| &nodes[k])));
active_set.rotate(&mut rng, 7, CLUSTER_SIZE, &nodes, &stakes);
assert!(active_set.0.iter().all(|entry| entry.0.len() == 7));
assert!(active_set
.get_nodes(&pubkey, origin, |_| false, &stakes)
.eq([18, 0, 7, 15, 11].into_iter().map(|k| &nodes[k])));
assert!(active_set
.get_nodes(&pubkey, other, |_| false, &stakes)
.eq([18, 16, 0, 7, 15, 11].into_iter().map(|k| &nodes[k])));
let origins = [*origin, *other];
active_set.prune(&pubkey, &nodes[18], &origins, &stakes);
active_set.prune(&pubkey, &nodes[0], &origins, &stakes);
active_set.prune(&pubkey, &nodes[15], &origins, &stakes);
assert!(active_set
.get_nodes(&pubkey, origin, |_| false, &stakes)
.eq([7, 11].into_iter().map(|k| &nodes[k])));
assert!(active_set
.get_nodes(&pubkey, other, |_| false, &stakes)
.eq([16, 7, 11].into_iter().map(|k| &nodes[k])));
}
#[test]
fn test_push_active_set_entry() {
const NUM_BLOOM_FILTER_ITEMS: usize = 100;
let mut rng = ChaChaRng::from_seed([147u8; 32]);
let nodes: Vec<_> = repeat_with(Pubkey::new_unique).take(20).collect();
let weights: Vec<_> = repeat_with(|| rng.gen_range(1..1000)).take(20).collect();
let mut entry = PushActiveSetEntry::default();
entry.rotate(
&mut rng,
5, // size
NUM_BLOOM_FILTER_ITEMS,
&nodes,
&weights,
);
assert_eq!(entry.0.len(), 5);
let keys = [&nodes[16], &nodes[11], &nodes[17], &nodes[14], &nodes[5]];
assert!(entry.0.keys().eq(keys));
for origin in &nodes {
if !keys.contains(&origin) | else {
assert!(entry.get_nodes(origin, |_| true).eq(keys));
assert!(entry
.get_nodes(origin, |_| false)
.eq(keys.into_iter().filter(|&key| key != origin)));
}
}
// Assert that each filter already prunes the key.
for (node, filter) in entry.0.iter() {
assert!(filter.contains(node));
}
for origin in keys {
assert!(entry.get_nodes(origin, |_| true).eq(keys));
assert!(entry
.get_nodes(origin, |_| false)
.eq(keys.into_iter().filter(|&node| node != origin)));
}
// Assert that prune excludes node from get.
let origin = &nodes[3];
entry.prune(&nodes[11], origin);
entry.prune(&nodes[14], origin);
entry.prune(&nodes[19], origin);
assert!(entry.get_nodes(origin, |_| true).eq(keys));
assert!(entry.get_nodes(origin, |_| false).eq(keys
.into_iter()
.filter(|&&node| node != nodes[11] && node != nodes[14])));
// Assert that rotate adds new nodes.
entry.rotate(&mut rng, 5, NUM_BLOOM_FILTER_ITEMS, &nodes, &weights);
let keys = [&nodes[11], &nodes[17], &nodes[14], &nodes[5], &nodes[7]];
assert!(entry.0.keys().eq(keys));
entry.rotate(&mut rng, 6, NUM_BLOOM_FILTER_ITEMS, &nodes, &weights);
let keys = [
&nodes[17], &nodes[14], &nodes[5], &nodes[7], &nodes[1], &nodes[13],
];
assert!(entry.0.keys().eq(keys));
entry.rotate(&mut rng, 4, NUM_BLOOM_FILTER_ITEMS, &nodes, &weights);
let keys = [&nodes[5], &nodes[7], &nodes[1], &nodes[13]];
assert!(entry.0.keys().eq(keys));
}
}
| {
assert!(entry.get_nodes(origin, |_| false).eq(keys));
} | conditional_block |
tag_tweets_py2.py | #!/usr/bin/env python
# -*- coding: UTF-8 -*-
import json
import sys
import re
import os
import multiprocessing
import nltk.tokenize.casual as NLTK
from nltk.corpus import stopwords
import string
PUNCTUATION = list(string.punctuation)
STOP = stopwords.words('english') + ['rt', 'via']
##########################################
# These are the core regular expressions.
# Copied from nltk.tokenize.casual, but separate to different types.
##########################################
EMOTICONS = NLTK.EMOTICONS
EMOJIS = r"""[\U00010000-\U0010ffff]"""
URLS = NLTK.URLS
Phone_numbers = r"""
(?:
(?: # (international)
\+?[01]
[\-\s.]*
)?
(?: # (area code)
[\(]?
\d{3}
[\-\s.\)]*
)?
\d{3} # exchange
[\-\s.]*
\d{4} # base
)"""
Username = r"""
(?:@[\w_]+)"""
Hashtags = r"""
(?:\#+[\w_]+[\w\'_\-]*[\w_]+)"""
Email = r"""
[\w.+-]+@[\w-]+\.(?:[\w-]\.?)+[\w-]"""
# The components of the tokenizer:
REGEXPS = NLTK.REGEXPS
# Modified from nltk regexps. Separated different types.
NormWords = (
# HTML tags:
r"""<[^>\s]+>"""
,
# ASCII Arrows
r"""[\-]+>|<[\-]+"""
,
# Remaining word types:
r"""
(?:[^\W\d_](?:[^\W\d_]|['\-_])+[^\W\d_]) # Words with apostrophes or dashes.
|
(?:[+\-]?\d+[,/.:-]\d+[+\-]?) # Numbers, including fractions, decimals.
|
(?:[\w_]+) # Words without apostrophes or dashes.
|
(?:\.(?:\s*\.){1,}) # Ellipsis dots.
|
(?:\S) # Everything else that isn't whitespace.
"""
)
######################################################################
# This is the core tokenizing regex:
WORD_RE = re.compile(r"""(%s)""" % "|".join(REGEXPS), re.VERBOSE | re.I
| re.UNICODE)
# WORD_RE performs poorly on these patterns:
HANG_RE = re.compile(r"""([^a-zA-Z0-9])\1{3,}""")
# The emoticon string gets its own regex so that we can preserve case for
# them as needed:
EMOTICON_RE = re.compile(EMOTICONS, re.VERBOSE | re.I | re.UNICODE)
# These regex are added
EMOJI_RE = re.compile(EMOJIS, re.UNICODE)
URLS_RE = re.compile(URLS, re.VERBOSE | re.I | re.UNICODE)
PHONUM_RE = re.compile(Phone_numbers, re.VERBOSE | re.I | re.UNICODE)
USERNAME_RE = re.compile(Username, re.VERBOSE | re.I | re.UNICODE)
HASHTAG_RE = re.compile(Hashtags, re.VERBOSE | re.I | re.UNICODE)
EMAIL_RE = re.compile(Email, re.VERBOSE | re.I | re.UNICODE)
NORMAL_RE = re.compile(r"""(%s)""" % "|".join(NormWords), re.VERBOSE | re.I | re.UNICODE)
class MyTweetTokenizer:
r"""
Modified from nltk TweetTokenizer
If type argument is set to be True,
Return a tuple for each token, with the token and its type.
Otherwise,
Return the original nltk TweetTokenizer results.
Type codes:
N: normal words
E: emoticons or emojis
U: urls or emails
PN: phone number
USR: user names
H: hashtags
S: stopwords
PUNC: punctuations
"""
def __init__(self, type_include=True):
self.type_include = type_include
def clean(self, text):
if not self.type_include:
|
# Fix HTML character entities:
text = NLTK._replace_html_entities(text)
# Shorten problematic sequences of characters
safe_text = NLTK.HANG_RE.sub(r'\1\1\1', text)
# Tokenize:
words = WORD_RE.findall(safe_text)
clean_text = text
# # Possibly alter the case, but avoid changing emoticons like :D into :d:
for i, x in enumerate(words[:]):
# if EMOTICON_RE.match(x) or EMOJI_RE.match(x):
# text.decode('utf8')
if URLS_RE.match(x) or EMAIL_RE.match(x):
# print "url"
clean_text = clean_text.replace(x, '')
elif USERNAME_RE.match(x):
# print "Username"
clean_text = clean_text.replace(x, '')
elif HASHTAG_RE.match(x):
# print "tag"
clean_text = clean_text.replace(x, '')
elif PHONUM_RE.match(x):
# print "phone"
clean_text = clean_text.replace(x, '')
# elif x.lower() in STOP:
# print "stop"
# clean_text = clean_text.replace(x, '')
# elif EMOJI_RE.match(x):
# clean_text = clean_text.replace(x, '')
else:
continue
return clean_text
emoji_pattern = re.compile(
u"(\ud83d[\ude00-\ude4f])|" # emoticons
u"(\ud83d[\u0000-\uddff])|" # symbols & pictographs (2 of 2)
u"(\ud83d[\ude80-\udeff])|" # transport & map symbols
u"(\uD83E[\uDD00-\uDDFF])|"
u"(\ud83c[\udf00-\uffff])|" # symbols & pictographs (1 of 2)
u"(\ud83c[\udde0-\uddff])|" # flags (iOS)
u"([\u2934\u2935]\uFE0F?)|"
u"([\u3030\u303D]\uFE0F?)|"
u"([\u3297\u3299]\uFE0F?)|"
u"([\u203C\u2049]\uFE0F?)|"
u"([\u00A9\u00AE]\uFE0F?)|"
u"([\u2122\u2139]\uFE0F?)|"
u"(\uD83C\uDC04\uFE0F?)|"
u"(\uD83C\uDCCF\uFE0F?)|"
u"([\u0023\u002A\u0030-\u0039]\uFE0F?\u20E3)|"
u"(\u24C2\uFE0F?|[\u2B05-\u2B07\u2B1B\u2B1C\u2B50\u2B55]\uFE0F?)|"
u"([\u2600-\u26FF]\uFE0F?)|"
u"([\u2700-\u27BF]\uFE0F?)"
"+", flags=re.UNICODE)
# input_file: str
# output_file: str
def read_tweets(input_file):
happy_emoji = [' :‑) ', ' :) ', ' :))', ' :)))', ' :-] ', ' :]', ' :-3', ':->', ':>', ' 8-)', ':-}', ':}', ' :o)', ' :c)', ' :^)', ' =]', ' =)',
' :‑D', ' :D', ' 8‑D', ' 8D ', ' x‑D', ' xD ', ' X‑D ', ' XD ', ' =D ', ' =3', ':-))', ':-)))', ':\'‑)', ':\')',
' :-*', ':*', ' :×', ' ;‑)', ' ;)', ' *-)', ' *)', ';‑]', ' ;]', ' ;^)', ' :‑,', ' ;D', ' :‑P', ' :P', ' X‑P', ' x‑p',
' :‑p', ' :p ', ' :b', ' d:', ' =p', '^_^', '^^', '^ ^', '(^_^)/', '(^O^)/', '(^o^)/', '(^^)/', '>^_^<', '^/^', '(*^_^*)',
'(^.^)', '(^·^)', '(^.^)', '(^_^)', '(^^)', '^_^', '(*^.^*)', '(#^.^#)', '(*^0^*)', '\(^o^)/', '!(^^)!', '(^v^)',
'(^u^)', '( ^)o(^ )', '(^O^)', '(^o^)', ')^o^(', 'ヽ(´▽`)/', '≧∇≦', '^ω^', '^▽^',
'\xF0\x9F\x98\x81', '\xF0\x9F\x98\x82', '\xF0\x9F\x98\x83', '\xF0\x9F\x98\x84', '\xF0\x9F\x98\x86', '\xF0\x9F\x98\x89',
'\xF0\x9F\x98\x8A', '\xF0\x9F\x98\x8B', '\xF0\x9F\x98\x8C', '\xF0\x9F\x98\x8D', '\xF0\x9F\x98\x8F', '\xF0\x9F\x98\x97', '\xF0\x9F\x98\x98',
'\xF0\x9F\x98\x99', '\xF0\x9F\x98\x9A', '\xF0\x9F\x98\x9B', '\xF0\x9F\x98\x9C', '\xF0\x9F\x98\x9D', '\xF0\x9F\x98\xB8', '\xF0\x9F\x98\xB9', '\xF0\x9F\x98\xBA',
'\xF0\x9F\x98\xBB', '\xF0\x9F\x98\xBD', '\xF0\x9F\x99\x8B', '\xF0\x9F\x99\x8C', '\xF0\x9F\x98\x80', '\xF0\x9F\x98\x87',
'\xF0\x9F\x98\x88', '\xF0\x9F\x98\x8E',
'\xF0\x9F\x92\x8B', '\xF0\x9F\x92\x8F', '\xF0\x9F\x92\x91', '\xF0\x9F\x92\x95', '\xF0\x9F\x92\x96', '\xF0\x9F\x92\x97', '\xF0\x9F\x92\x98',
'\xF0\x9F\x92\x9D',
'\xF0\x9F\x8C\xB9', '\xF0\x9F\x8E\x80', '\xF0\x9F\x8E\x81', '\xF0\x9F\x8E\x82', '\xF0\x9F\x8E\x86', '\xF0\x9F\x8E\x87', '\xF0\x9F\x8E\x89',
'\xF0\x9F\x8E\x8A',
'\xE2\x9C\x8C', '\xE2\x9D\xA4', '\xE2\x98\xBA', '\xE2\x99\xA5', '\xE3\x8A\x97']
sad_emoji = [' :‑(', ' :(', ' :‑c', ' :c', ' :‑<', ' :<', ' :‑[', ' :[', ' :-||', ' >:[', ' :{', ' :@', ' >:(', ' :\'‑(', ' :\'(',
' DX ', ' D= ', ' D; ', ' D: ', ' D:<', ' D‑\':', ' >:O', ' :-0', ' :‑o', ' :o ', ' :‑O', ' :O ', ' :‑/', ' :‑.',
' >:\\', ' >:/', ' :\\', ' =/', ' =\\', ' :L', ' =L', ' :S', ' :‑|', ' :|', ' :$ ', '(-_-;)', ' Q_Q', ' TnT', 'T.T', 'Q.Q', ';;',
' ;n;', ' ;-;', ' ;_;', '(T_T)', '(;_:)', '(ToT)', '(ー_ー)!!', '(-.-)', '(-_-)', '(=_=)', '(-"-)', '(ーー;)', '(* ̄m ̄)', '(#゚Д゚)',
'(´;ω;`)', 'ヽ(`Д´)ノ', '( ´,_ゝ`)',
'\xF0\x9F\x98\x91', '\xF0\x9F\x98\x92', '\xF0\x9F\x98\x93', '\xF0\x9F\x98\x94', '\xF0\x9F\x98\x95', '\xF0\x9F\x98\x96', '\xF0\x9F\x98\x9E', '\xF0\x9F\x98\x9F',
'\xF0\x9F\x98\xA0', '\xF0\x9F\x98\xA1', '\xF0\x9F\x98\xA2', '\xF0\x9F\x98\xA3', '\xF0\x9F\x98\xA4', '\xF0\x9F\x98\xA5', '\xF0\x9F\x98\xA6', '\xF0\x9F\x98\xA7', '\xF0\x9F\x98\xA8',
'\xF0\x9F\x98\xA9', '\xF0\x9F\x98\xAB', '\xF0\x9F\x98\xAD', '\xF0\x9F\x98\xB1', '\xF0\x9F\x98\xBE', '\xF0\x9F\x99\x8D',
'\xF0\x9F\x92\x94', '\xF0\x9F\x92\xA2'
]
output = {}
print("input_file: {}".format(input_file))
with open(input_file, 'r') as inf:
tweets = MyTweetTokenizer()
output_file = "tagged/{}.txt".format(input_file.split("/")[-1])
with open(output_file, 'w', 100) as outf:
for line in inf:
if is_json(line):
record = json.loads(line)
if u'text' in record:
unicode_text = record[u'text']
if len(unicode_text) < 20:
continue
utf8text = unicode_text.encode("utf-8")
is_happy, happy_tag, happy_clean_text = find_emoji(utf8text, happy_emoji)
is_sad, sad_tag, sad_clean_text = find_emoji(utf8text, sad_emoji)
if is_happy and not is_sad:
clean_emoji_text = remove_emoji(happy_clean_text) # remove emoji
clean_text = tweets.clean(clean_emoji_text) # remove others
clean_text = clean_text.replace("http://","").replace("https://","")
if len(clean_text) >= 20:
output = {'text': clean_text, 'label': '1', 'emoji': happy_tag}
outf.write(json.dumps(output) + '\n')
else:
continue
elif not is_happy and is_sad:
clean_emoji_text = remove_emoji(sad_clean_text)
clean_text = tweets.clean(clean_emoji_text)
clean_text = clean_text.replace("http://","").replace("https://","")
if len(clean_text) >= 20:
output = {'text': clean_text, 'label': '0', 'emoji': sad_tag}
outf.write(json.dumps(output) + '\n')
else:
continue
else:
continue
# text: str
# emoji: list
# return: bool
def find_emoji(text, emoji):
flag = False
flag_emoji = []
clean_text = text
for e in emoji:
if e in text:
clean_text = clean_text.replace(e, '')
flag = True
flag_emoji.append(e)
return flag, flag_emoji, clean_text
def remove_emoji(text):
# print type(text), "first" # str
text = text.decode('utf8')
# print type(text), "second" # unicode
text = emoji_pattern.sub(r'', text).encode('utf8')
return
def is_json(myjson):
try:
json_object = json.loads(myjson)
except ValueError, e:
return False
return True
def run(data_dir):
files = [os.path.join(data_dir, f) for f in os.listdir(data_dir)]
start = time.time()
pool = multiprocessing.Pool(4)
results = pool.map_async(read_tweets, files)
pool.close()
pool.join()
print(time.time()-start)
if __name__ == '__main__':
run("/home/p8shi/tweets_english")
| tknzr = NLTK.TweetTokenizer()
return tknzr.tokenize(text) | conditional_block |
tag_tweets_py2.py | #!/usr/bin/env python
# -*- coding: UTF-8 -*-
import json
import sys
import re
import os
import multiprocessing
import nltk.tokenize.casual as NLTK
from nltk.corpus import stopwords
import string
PUNCTUATION = list(string.punctuation)
STOP = stopwords.words('english') + ['rt', 'via']
##########################################
# These are the core regular expressions.
# Copied from nltk.tokenize.casual, but separate to different types.
##########################################
EMOTICONS = NLTK.EMOTICONS
EMOJIS = r"""[\U00010000-\U0010ffff]"""
URLS = NLTK.URLS
Phone_numbers = r"""
(?:
(?: # (international)
\+?[01]
[\-\s.]*
)?
(?: # (area code)
[\(]?
\d{3}
[\-\s.\)]*
)?
\d{3} # exchange
[\-\s.]*
\d{4} # base
)"""
Username = r"""
(?:@[\w_]+)"""
Hashtags = r"""
(?:\#+[\w_]+[\w\'_\-]*[\w_]+)"""
Email = r"""
[\w.+-]+@[\w-]+\.(?:[\w-]\.?)+[\w-]"""
# The components of the tokenizer:
REGEXPS = NLTK.REGEXPS
# Modified from nltk regexps. Separated different types.
NormWords = (
# HTML tags:
r"""<[^>\s]+>"""
,
# ASCII Arrows
r"""[\-]+>|<[\-]+"""
,
# Remaining word types:
r"""
(?:[^\W\d_](?:[^\W\d_]|['\-_])+[^\W\d_]) # Words with apostrophes or dashes.
|
(?:[+\-]?\d+[,/.:-]\d+[+\-]?) # Numbers, including fractions, decimals.
|
(?:[\w_]+) # Words without apostrophes or dashes.
|
(?:\.(?:\s*\.){1,}) # Ellipsis dots.
|
(?:\S) # Everything else that isn't whitespace.
"""
)
######################################################################
# This is the core tokenizing regex:
WORD_RE = re.compile(r"""(%s)""" % "|".join(REGEXPS), re.VERBOSE | re.I
| re.UNICODE)
# WORD_RE performs poorly on these patterns:
HANG_RE = re.compile(r"""([^a-zA-Z0-9])\1{3,}""")
# The emoticon string gets its own regex so that we can preserve case for
# them as needed:
EMOTICON_RE = re.compile(EMOTICONS, re.VERBOSE | re.I | re.UNICODE)
# These regex are added
EMOJI_RE = re.compile(EMOJIS, re.UNICODE)
URLS_RE = re.compile(URLS, re.VERBOSE | re.I | re.UNICODE)
PHONUM_RE = re.compile(Phone_numbers, re.VERBOSE | re.I | re.UNICODE)
USERNAME_RE = re.compile(Username, re.VERBOSE | re.I | re.UNICODE)
HASHTAG_RE = re.compile(Hashtags, re.VERBOSE | re.I | re.UNICODE)
EMAIL_RE = re.compile(Email, re.VERBOSE | re.I | re.UNICODE)
NORMAL_RE = re.compile(r"""(%s)""" % "|".join(NormWords), re.VERBOSE | re.I | re.UNICODE)
class MyTweetTokenizer:
r"""
Modified from nltk TweetTokenizer
If type argument is set to be True,
Return a tuple for each token, with the token and its type.
Otherwise,
Return the original nltk TweetTokenizer results.
Type codes:
N: normal words
E: emoticons or emojis
U: urls or emails
PN: phone number
USR: user names
H: hashtags
S: stopwords
PUNC: punctuations
"""
def __init__(self, type_include=True):
self.type_include = type_include
def clean(self, text):
if not self.type_include:
tknzr = NLTK.TweetTokenizer()
return tknzr.tokenize(text)
# Fix HTML character entities:
text = NLTK._replace_html_entities(text)
# Shorten problematic sequences of characters
safe_text = NLTK.HANG_RE.sub(r'\1\1\1', text)
# Tokenize:
words = WORD_RE.findall(safe_text)
clean_text = text
# # Possibly alter the case, but avoid changing emoticons like :D into :d:
for i, x in enumerate(words[:]):
# if EMOTICON_RE.match(x) or EMOJI_RE.match(x):
# text.decode('utf8')
if URLS_RE.match(x) or EMAIL_RE.match(x):
# print "url"
clean_text = clean_text.replace(x, '')
elif USERNAME_RE.match(x):
# print "Username"
clean_text = clean_text.replace(x, '')
elif HASHTAG_RE.match(x):
# print "tag"
clean_text = clean_text.replace(x, '')
elif PHONUM_RE.match(x):
# print "phone"
clean_text = clean_text.replace(x, '')
# elif x.lower() in STOP:
# print "stop"
# clean_text = clean_text.replace(x, '')
# elif EMOJI_RE.match(x):
# clean_text = clean_text.replace(x, '')
else:
continue
return clean_text
emoji_pattern = re.compile(
u"(\ud83d[\ude00-\ude4f])|" # emoticons
u"(\ud83d[\u0000-\uddff])|" # symbols & pictographs (2 of 2)
u"(\ud83d[\ude80-\udeff])|" # transport & map symbols
u"(\uD83E[\uDD00-\uDDFF])|"
u"(\ud83c[\udf00-\uffff])|" # symbols & pictographs (1 of 2)
u"(\ud83c[\udde0-\uddff])|" # flags (iOS)
u"([\u2934\u2935]\uFE0F?)|"
u"([\u3030\u303D]\uFE0F?)|"
u"([\u3297\u3299]\uFE0F?)|"
u"([\u203C\u2049]\uFE0F?)|"
u"([\u00A9\u00AE]\uFE0F?)|"
u"([\u2122\u2139]\uFE0F?)|"
u"(\uD83C\uDC04\uFE0F?)|"
u"(\uD83C\uDCCF\uFE0F?)|"
u"([\u0023\u002A\u0030-\u0039]\uFE0F?\u20E3)|"
u"(\u24C2\uFE0F?|[\u2B05-\u2B07\u2B1B\u2B1C\u2B50\u2B55]\uFE0F?)|"
u"([\u2600-\u26FF]\uFE0F?)|"
u"([\u2700-\u27BF]\uFE0F?)"
"+", flags=re.UNICODE)
# input_file: str
# output_file: str
def read_tweets(input_file):
happy_emoji = [' :‑) ', ' :) ', ' :))', ' :)))', ' :-] ', ' :]', ' :-3', ':->', ':>', ' 8-)', ':-}', ':}', ' :o)', ' :c)', ' :^)', ' =]', ' =)',
' :‑D', ' :D', ' 8‑D', ' 8D ', ' x‑D', ' xD ', ' X‑D ', ' XD ', ' =D ', ' =3', ':-))', ':-)))', ':\'‑)', ':\')',
' :-*', ':*', ' :×', ' ;‑)', ' ;)', ' *-)', ' *)', ';‑]', ' ;]', ' ;^)', ' :‑,', ' ;D', ' :‑P', ' :P', ' X‑P', ' x‑p',
' :‑p', ' :p ', ' :b', ' d:', ' =p', '^_^', '^^', '^ ^', '(^_^)/', '(^O^)/', '(^o^)/', '(^^)/', '>^_^<', '^/^', '(*^_^*)',
'(^.^)', '(^·^)', '(^.^)', '(^_^)', '(^^)', '^_^', '(*^.^*)', '(#^.^#)', '(*^0^*)', '\(^o^)/', '!(^^)!', '(^v^)',
'(^u^)', '( ^)o(^ )', '(^O^)', '(^o^)', ')^o^(', 'ヽ(´▽`)/', '≧∇≦', '^ω^', '^▽^',
'\xF0\x9F\x98\x81', '\xF0\x9F\x98\x82', '\xF0\x9F\x98\x83', '\xF0\x9F\x98\x84', '\xF0\x9F\x98\x86', '\xF0\x9F\x98\x89',
'\xF0\x9F\x98\x8A', '\xF0\x9F\x98\x8B', '\xF0\x9F\x98\x8C', '\xF0\x9F\x98\x8D', '\xF0\x9F\x98\x8F', '\xF0\x9F\x98\x97', '\xF0\x9F\x98\x98',
'\xF0\x9F\x98\x99', '\xF0\x9F\x98\x9A', '\xF0\x9F\x98\x9B', '\xF0\x9F\x98\x9C', '\xF0\x9F\x98\x9D', '\xF0\x9F\x98\xB8', '\xF0\x9F\x98\xB9', '\xF0\x9F\x98\xBA',
'\xF0\x9F\x98\xBB', '\xF0\x9F\x98\xBD', '\xF0\x9F\x99\x8B', '\xF0\x9F\x99\x8C', '\xF0\x9F\x98\x80', '\xF0\x9F\x98\x87',
'\xF0\x9F\x98\x88', '\xF0\x9F\x98\x8E',
'\xF0\x9F\x92\x8B', '\xF0\x9F\x92\x8F', '\xF0\x9F\x92\x91', '\xF0\x9F\x92\x95', '\xF0\x9F\x92\x96', '\xF0\x9F\x92\x97', '\xF0\x9F\x92\x98',
'\xF0\x9F\x92\x9D',
'\xF0\x9F\x8C\xB9', '\xF0\x9F\x8E\x80', '\xF0\x9F\x8E\x81', '\xF0\x9F\x8E\x82', '\xF0\x9F\x8E\x86', '\xF0\x9F\x8E\x87', '\xF0\x9F\x8E\x89',
'\xF0\x9F\x8E\x8A',
'\xE2\x9C\x8C', '\xE2\x9D\xA4', '\xE2\x98\xBA', '\xE2\x99\xA5', '\xE3\x8A\x97']
sad_emoji = [' :‑(', ' :(', ' :‑c', ' :c', ' :‑<', ' :<', ' :‑[', ' :[', ' :-||', ' >:[', ' :{', ' :@', ' >:(', ' :\'‑(', ' :\'(',
' DX ', ' D= ', ' D; ', ' D: ', ' D:<', ' D‑\':', ' >:O', ' :-0', ' :‑o', ' :o ', ' :‑O', ' :O ', ' :‑/', ' :‑.',
' >:\\', ' >:/', ' :\\', ' =/', ' =\\', ' :L', ' =L', ' :S', ' :‑|', ' :|', ' :$ ', '(-_-;)', ' Q_Q', ' TnT', 'T.T', 'Q.Q', ';;',
' ;n;', ' ;-;', ' ;_;', '(T_T)', '(;_:)', '(ToT)', '(ー_ー)!!', '(-.-)', '(-_-)', '(=_=)', '(-"-)', '(ーー;)', '(* ̄m ̄)', '(#゚Д゚)',
'(´;ω;`)', 'ヽ(`Д´)ノ', '( ´,_ゝ`)',
'\xF0\x9F\x98\x91', '\xF0\x9F\x98\x92', '\xF0\x9F\x98\x93', '\xF0\x9F\x98\x94', '\xF0\x9F\x98\x95', '\xF0\x9F\x98\x96', '\xF0\x9F\x98\x9E', '\xF0\x9F\x98\x9F',
'\xF0\x9F\x98\xA0', '\xF0\x9F\x98\xA1', '\xF0\x9F\x98\xA2', '\xF0\x9F\x98\xA3', '\xF0\x9F\x98\xA4', '\xF0\x9F\x98\xA5', '\xF0\x9F\x98\xA6', '\xF0\x9F\x98\xA7', '\xF0\x9F\x98\xA8',
'\xF0\x9F\x98\xA9', '\xF0\x9F\x98\xAB', '\xF0\x9F\x98\xAD', '\xF0\x9F\x98\xB1', '\xF0\x9F\x98\xBE', '\xF0\x9F\x99\x8D',
'\xF0\x9F\x92\x94', '\xF0\x9F\x92\xA2'
]
output = {}
print("input_file: {}".format(input_file))
with open(input_file, 'r') as inf:
tweets = MyTweetTokenizer()
output_file = "tagged/{}.txt".format(input_file.split("/")[-1])
with open(output_file, 'w', 100) as outf:
for line in inf:
if is_json(line):
record = json.loads(line)
if u'text' in record:
unicode_text = record[u'text']
if len(unicode_text) < 20:
continue
utf8text = unicode_text.encode("utf-8")
is_happy, happy_tag, happy_clean_text = find_emoji(utf8text, happy_emoji)
is_sad, sad_tag, sad_clean_text = find_emoji(utf8text, sad_emoji)
if is_happy and not is_sad:
clean_emoji_text = remove_emoji(happy_clean_text) # remove emoji
clean_text = tweets.clean(clean_emoji_text) # remove others
clean_text = clean_text.replace("http://","").replace("https://","")
if len(clean_text) >= 20:
output = {'text': clean_text, 'label': '1', 'emoji': happy_tag}
outf.write(json.dumps(output) + '\n')
else:
continue
elif not is_happy and is_sad:
clean_emoji_text = remove_emoji(sad_clean_text)
clean_text = tweets.clean(clean_emoji_text)
clean_text = clean_text.replace("http://","").replace("https://","")
if len(clean_text) >= 20:
output = {'text': clean_text, 'label': '0', 'emoji': sad_tag}
outf.write(json.dumps(output) + '\n')
else:
continue
else:
continue
# text: str
# emoji: list
# return: bool
def find_emoji(text, emoji):
flag = False
flag_emoji = []
clean_text = text
for e in emoji:
if e in text:
clean_text = clean_text.replace(e, '')
flag = True
flag_emoji.append(e)
return flag, flag_emoji, clean_text
def remove_emoji(text):
# print type(text), "first" # str
text = text.decode('utf8')
# print type(text), "second" # unicode
text = emoji_pattern.sub(r'', text).encode('utf8')
| f run(data_dir):
files = [os.path.join(data_dir, f) for f in os.listdir(data_dir)]
start = time.time()
pool = multiprocessing.Pool(4)
results = pool.map_async(read_tweets, files)
pool.close()
pool.join()
print(time.time()-start)
if __name__ == '__main__':
run("/home/p8shi/tweets_english")
| return
def is_json(myjson):
try:
json_object = json.loads(myjson)
except ValueError, e:
return False
return True
de | identifier_body |
tag_tweets_py2.py | #!/usr/bin/env python
# -*- coding: UTF-8 -*-
import json
import sys
import re
import os
import multiprocessing
import nltk.tokenize.casual as NLTK
from nltk.corpus import stopwords
import string
PUNCTUATION = list(string.punctuation)
STOP = stopwords.words('english') + ['rt', 'via']
##########################################
# These are the core regular expressions.
# Copied from nltk.tokenize.casual, but separate to different types.
##########################################
EMOTICONS = NLTK.EMOTICONS
EMOJIS = r"""[\U00010000-\U0010ffff]"""
URLS = NLTK.URLS
Phone_numbers = r"""
(?:
(?: # (international)
\+?[01]
[\-\s.]*
)?
(?: # (area code)
[\(]?
\d{3}
[\-\s.\)]*
)?
\d{3} # exchange
[\-\s.]*
\d{4} # base
)"""
Username = r"""
(?:@[\w_]+)"""
Hashtags = r"""
(?:\#+[\w_]+[\w\'_\-]*[\w_]+)"""
Email = r"""
[\w.+-]+@[\w-]+\.(?:[\w-]\.?)+[\w-]"""
# The components of the tokenizer:
REGEXPS = NLTK.REGEXPS
# Modified from nltk regexps. Separated different types.
NormWords = (
# HTML tags:
r"""<[^>\s]+>"""
,
# ASCII Arrows
r"""[\-]+>|<[\-]+"""
,
# Remaining word types:
r"""
(?:[^\W\d_](?:[^\W\d_]|['\-_])+[^\W\d_]) # Words with apostrophes or dashes.
|
(?:[+\-]?\d+[,/.:-]\d+[+\-]?) # Numbers, including fractions, decimals.
|
(?:[\w_]+) # Words without apostrophes or dashes.
|
(?:\.(?:\s*\.){1,}) # Ellipsis dots.
|
(?:\S) # Everything else that isn't whitespace.
"""
)
######################################################################
# This is the core tokenizing regex:
| # WORD_RE performs poorly on these patterns:
HANG_RE = re.compile(r"""([^a-zA-Z0-9])\1{3,}""")
# The emoticon string gets its own regex so that we can preserve case for
# them as needed:
EMOTICON_RE = re.compile(EMOTICONS, re.VERBOSE | re.I | re.UNICODE)
# These regex are added
EMOJI_RE = re.compile(EMOJIS, re.UNICODE)
URLS_RE = re.compile(URLS, re.VERBOSE | re.I | re.UNICODE)
PHONUM_RE = re.compile(Phone_numbers, re.VERBOSE | re.I | re.UNICODE)
USERNAME_RE = re.compile(Username, re.VERBOSE | re.I | re.UNICODE)
HASHTAG_RE = re.compile(Hashtags, re.VERBOSE | re.I | re.UNICODE)
EMAIL_RE = re.compile(Email, re.VERBOSE | re.I | re.UNICODE)
NORMAL_RE = re.compile(r"""(%s)""" % "|".join(NormWords), re.VERBOSE | re.I | re.UNICODE)
class MyTweetTokenizer:
r"""
Modified from nltk TweetTokenizer
If type argument is set to be True,
Return a tuple for each token, with the token and its type.
Otherwise,
Return the original nltk TweetTokenizer results.
Type codes:
N: normal words
E: emoticons or emojis
U: urls or emails
PN: phone number
USR: user names
H: hashtags
S: stopwords
PUNC: punctuations
"""
def __init__(self, type_include=True):
self.type_include = type_include
def clean(self, text):
if not self.type_include:
tknzr = NLTK.TweetTokenizer()
return tknzr.tokenize(text)
# Fix HTML character entities:
text = NLTK._replace_html_entities(text)
# Shorten problematic sequences of characters
safe_text = NLTK.HANG_RE.sub(r'\1\1\1', text)
# Tokenize:
words = WORD_RE.findall(safe_text)
clean_text = text
# # Possibly alter the case, but avoid changing emoticons like :D into :d:
for i, x in enumerate(words[:]):
# if EMOTICON_RE.match(x) or EMOJI_RE.match(x):
# text.decode('utf8')
if URLS_RE.match(x) or EMAIL_RE.match(x):
# print "url"
clean_text = clean_text.replace(x, '')
elif USERNAME_RE.match(x):
# print "Username"
clean_text = clean_text.replace(x, '')
elif HASHTAG_RE.match(x):
# print "tag"
clean_text = clean_text.replace(x, '')
elif PHONUM_RE.match(x):
# print "phone"
clean_text = clean_text.replace(x, '')
# elif x.lower() in STOP:
# print "stop"
# clean_text = clean_text.replace(x, '')
# elif EMOJI_RE.match(x):
# clean_text = clean_text.replace(x, '')
else:
continue
return clean_text
emoji_pattern = re.compile(
u"(\ud83d[\ude00-\ude4f])|" # emoticons
u"(\ud83d[\u0000-\uddff])|" # symbols & pictographs (2 of 2)
u"(\ud83d[\ude80-\udeff])|" # transport & map symbols
u"(\uD83E[\uDD00-\uDDFF])|"
u"(\ud83c[\udf00-\uffff])|" # symbols & pictographs (1 of 2)
u"(\ud83c[\udde0-\uddff])|" # flags (iOS)
u"([\u2934\u2935]\uFE0F?)|"
u"([\u3030\u303D]\uFE0F?)|"
u"([\u3297\u3299]\uFE0F?)|"
u"([\u203C\u2049]\uFE0F?)|"
u"([\u00A9\u00AE]\uFE0F?)|"
u"([\u2122\u2139]\uFE0F?)|"
u"(\uD83C\uDC04\uFE0F?)|"
u"(\uD83C\uDCCF\uFE0F?)|"
u"([\u0023\u002A\u0030-\u0039]\uFE0F?\u20E3)|"
u"(\u24C2\uFE0F?|[\u2B05-\u2B07\u2B1B\u2B1C\u2B50\u2B55]\uFE0F?)|"
u"([\u2600-\u26FF]\uFE0F?)|"
u"([\u2700-\u27BF]\uFE0F?)"
"+", flags=re.UNICODE)
# input_file: str
# output_file: str
def read_tweets(input_file):
happy_emoji = [' :‑) ', ' :) ', ' :))', ' :)))', ' :-] ', ' :]', ' :-3', ':->', ':>', ' 8-)', ':-}', ':}', ' :o)', ' :c)', ' :^)', ' =]', ' =)',
' :‑D', ' :D', ' 8‑D', ' 8D ', ' x‑D', ' xD ', ' X‑D ', ' XD ', ' =D ', ' =3', ':-))', ':-)))', ':\'‑)', ':\')',
' :-*', ':*', ' :×', ' ;‑)', ' ;)', ' *-)', ' *)', ';‑]', ' ;]', ' ;^)', ' :‑,', ' ;D', ' :‑P', ' :P', ' X‑P', ' x‑p',
' :‑p', ' :p ', ' :b', ' d:', ' =p', '^_^', '^^', '^ ^', '(^_^)/', '(^O^)/', '(^o^)/', '(^^)/', '>^_^<', '^/^', '(*^_^*)',
'(^.^)', '(^·^)', '(^.^)', '(^_^)', '(^^)', '^_^', '(*^.^*)', '(#^.^#)', '(*^0^*)', '\(^o^)/', '!(^^)!', '(^v^)',
'(^u^)', '( ^)o(^ )', '(^O^)', '(^o^)', ')^o^(', 'ヽ(´▽`)/', '≧∇≦', '^ω^', '^▽^',
'\xF0\x9F\x98\x81', '\xF0\x9F\x98\x82', '\xF0\x9F\x98\x83', '\xF0\x9F\x98\x84', '\xF0\x9F\x98\x86', '\xF0\x9F\x98\x89',
'\xF0\x9F\x98\x8A', '\xF0\x9F\x98\x8B', '\xF0\x9F\x98\x8C', '\xF0\x9F\x98\x8D', '\xF0\x9F\x98\x8F', '\xF0\x9F\x98\x97', '\xF0\x9F\x98\x98',
'\xF0\x9F\x98\x99', '\xF0\x9F\x98\x9A', '\xF0\x9F\x98\x9B', '\xF0\x9F\x98\x9C', '\xF0\x9F\x98\x9D', '\xF0\x9F\x98\xB8', '\xF0\x9F\x98\xB9', '\xF0\x9F\x98\xBA',
'\xF0\x9F\x98\xBB', '\xF0\x9F\x98\xBD', '\xF0\x9F\x99\x8B', '\xF0\x9F\x99\x8C', '\xF0\x9F\x98\x80', '\xF0\x9F\x98\x87',
'\xF0\x9F\x98\x88', '\xF0\x9F\x98\x8E',
'\xF0\x9F\x92\x8B', '\xF0\x9F\x92\x8F', '\xF0\x9F\x92\x91', '\xF0\x9F\x92\x95', '\xF0\x9F\x92\x96', '\xF0\x9F\x92\x97', '\xF0\x9F\x92\x98',
'\xF0\x9F\x92\x9D',
'\xF0\x9F\x8C\xB9', '\xF0\x9F\x8E\x80', '\xF0\x9F\x8E\x81', '\xF0\x9F\x8E\x82', '\xF0\x9F\x8E\x86', '\xF0\x9F\x8E\x87', '\xF0\x9F\x8E\x89',
'\xF0\x9F\x8E\x8A',
'\xE2\x9C\x8C', '\xE2\x9D\xA4', '\xE2\x98\xBA', '\xE2\x99\xA5', '\xE3\x8A\x97']
sad_emoji = [' :‑(', ' :(', ' :‑c', ' :c', ' :‑<', ' :<', ' :‑[', ' :[', ' :-||', ' >:[', ' :{', ' :@', ' >:(', ' :\'‑(', ' :\'(',
' DX ', ' D= ', ' D; ', ' D: ', ' D:<', ' D‑\':', ' >:O', ' :-0', ' :‑o', ' :o ', ' :‑O', ' :O ', ' :‑/', ' :‑.',
' >:\\', ' >:/', ' :\\', ' =/', ' =\\', ' :L', ' =L', ' :S', ' :‑|', ' :|', ' :$ ', '(-_-;)', ' Q_Q', ' TnT', 'T.T', 'Q.Q', ';;',
' ;n;', ' ;-;', ' ;_;', '(T_T)', '(;_:)', '(ToT)', '(ー_ー)!!', '(-.-)', '(-_-)', '(=_=)', '(-"-)', '(ーー;)', '(* ̄m ̄)', '(#゚Д゚)',
'(´;ω;`)', 'ヽ(`Д´)ノ', '( ´,_ゝ`)',
'\xF0\x9F\x98\x91', '\xF0\x9F\x98\x92', '\xF0\x9F\x98\x93', '\xF0\x9F\x98\x94', '\xF0\x9F\x98\x95', '\xF0\x9F\x98\x96', '\xF0\x9F\x98\x9E', '\xF0\x9F\x98\x9F',
'\xF0\x9F\x98\xA0', '\xF0\x9F\x98\xA1', '\xF0\x9F\x98\xA2', '\xF0\x9F\x98\xA3', '\xF0\x9F\x98\xA4', '\xF0\x9F\x98\xA5', '\xF0\x9F\x98\xA6', '\xF0\x9F\x98\xA7', '\xF0\x9F\x98\xA8',
'\xF0\x9F\x98\xA9', '\xF0\x9F\x98\xAB', '\xF0\x9F\x98\xAD', '\xF0\x9F\x98\xB1', '\xF0\x9F\x98\xBE', '\xF0\x9F\x99\x8D',
'\xF0\x9F\x92\x94', '\xF0\x9F\x92\xA2'
]
output = {}
print("input_file: {}".format(input_file))
with open(input_file, 'r') as inf:
tweets = MyTweetTokenizer()
output_file = "tagged/{}.txt".format(input_file.split("/")[-1])
with open(output_file, 'w', 100) as outf:
for line in inf:
if is_json(line):
record = json.loads(line)
if u'text' in record:
unicode_text = record[u'text']
if len(unicode_text) < 20:
continue
utf8text = unicode_text.encode("utf-8")
is_happy, happy_tag, happy_clean_text = find_emoji(utf8text, happy_emoji)
is_sad, sad_tag, sad_clean_text = find_emoji(utf8text, sad_emoji)
if is_happy and not is_sad:
clean_emoji_text = remove_emoji(happy_clean_text) # remove emoji
clean_text = tweets.clean(clean_emoji_text) # remove others
clean_text = clean_text.replace("http://","").replace("https://","")
if len(clean_text) >= 20:
output = {'text': clean_text, 'label': '1', 'emoji': happy_tag}
outf.write(json.dumps(output) + '\n')
else:
continue
elif not is_happy and is_sad:
clean_emoji_text = remove_emoji(sad_clean_text)
clean_text = tweets.clean(clean_emoji_text)
clean_text = clean_text.replace("http://","").replace("https://","")
if len(clean_text) >= 20:
output = {'text': clean_text, 'label': '0', 'emoji': sad_tag}
outf.write(json.dumps(output) + '\n')
else:
continue
else:
continue
# text: str
# emoji: list
# return: bool
def find_emoji(text, emoji):
flag = False
flag_emoji = []
clean_text = text
for e in emoji:
if e in text:
clean_text = clean_text.replace(e, '')
flag = True
flag_emoji.append(e)
return flag, flag_emoji, clean_text
def remove_emoji(text):
# print type(text), "first" # str
text = text.decode('utf8')
# print type(text), "second" # unicode
text = emoji_pattern.sub(r'', text).encode('utf8')
return
def is_json(myjson):
try:
json_object = json.loads(myjson)
except ValueError, e:
return False
return True
def run(data_dir):
files = [os.path.join(data_dir, f) for f in os.listdir(data_dir)]
start = time.time()
pool = multiprocessing.Pool(4)
results = pool.map_async(read_tweets, files)
pool.close()
pool.join()
print(time.time()-start)
if __name__ == '__main__':
run("/home/p8shi/tweets_english") | WORD_RE = re.compile(r"""(%s)""" % "|".join(REGEXPS), re.VERBOSE | re.I
| re.UNICODE)
| random_line_split |
tag_tweets_py2.py | #!/usr/bin/env python
# -*- coding: UTF-8 -*-
import json
import sys
import re
import os
import multiprocessing
import nltk.tokenize.casual as NLTK
from nltk.corpus import stopwords
import string
PUNCTUATION = list(string.punctuation)
STOP = stopwords.words('english') + ['rt', 'via']
##########################################
# These are the core regular expressions.
# Copied from nltk.tokenize.casual, but separate to different types.
##########################################
EMOTICONS = NLTK.EMOTICONS
EMOJIS = r"""[\U00010000-\U0010ffff]"""
URLS = NLTK.URLS
Phone_numbers = r"""
(?:
(?: # (international)
\+?[01]
[\-\s.]*
)?
(?: # (area code)
[\(]?
\d{3}
[\-\s.\)]*
)?
\d{3} # exchange
[\-\s.]*
\d{4} # base
)"""
Username = r"""
(?:@[\w_]+)"""
Hashtags = r"""
(?:\#+[\w_]+[\w\'_\-]*[\w_]+)"""
Email = r"""
[\w.+-]+@[\w-]+\.(?:[\w-]\.?)+[\w-]"""
# The components of the tokenizer:
REGEXPS = NLTK.REGEXPS
# Modified from nltk regexps. Separated different types.
NormWords = (
# HTML tags:
r"""<[^>\s]+>"""
,
# ASCII Arrows
r"""[\-]+>|<[\-]+"""
,
# Remaining word types:
r"""
(?:[^\W\d_](?:[^\W\d_]|['\-_])+[^\W\d_]) # Words with apostrophes or dashes.
|
(?:[+\-]?\d+[,/.:-]\d+[+\-]?) # Numbers, including fractions, decimals.
|
(?:[\w_]+) # Words without apostrophes or dashes.
|
(?:\.(?:\s*\.){1,}) # Ellipsis dots.
|
(?:\S) # Everything else that isn't whitespace.
"""
)
######################################################################
# This is the core tokenizing regex:
WORD_RE = re.compile(r"""(%s)""" % "|".join(REGEXPS), re.VERBOSE | re.I
| re.UNICODE)
# WORD_RE performs poorly on these patterns:
HANG_RE = re.compile(r"""([^a-zA-Z0-9])\1{3,}""")
# The emoticon string gets its own regex so that we can preserve case for
# them as needed:
EMOTICON_RE = re.compile(EMOTICONS, re.VERBOSE | re.I | re.UNICODE)
# These regex are added
EMOJI_RE = re.compile(EMOJIS, re.UNICODE)
URLS_RE = re.compile(URLS, re.VERBOSE | re.I | re.UNICODE)
PHONUM_RE = re.compile(Phone_numbers, re.VERBOSE | re.I | re.UNICODE)
USERNAME_RE = re.compile(Username, re.VERBOSE | re.I | re.UNICODE)
HASHTAG_RE = re.compile(Hashtags, re.VERBOSE | re.I | re.UNICODE)
EMAIL_RE = re.compile(Email, re.VERBOSE | re.I | re.UNICODE)
NORMAL_RE = re.compile(r"""(%s)""" % "|".join(NormWords), re.VERBOSE | re.I | re.UNICODE)
class MyTweetTokenizer:
r"""
Modified from nltk TweetTokenizer
If type argument is set to be True,
Return a tuple for each token, with the token and its type.
Otherwise,
Return the original nltk TweetTokenizer results.
Type codes:
N: normal words
E: emoticons or emojis
U: urls or emails
PN: phone number
USR: user names
H: hashtags
S: stopwords
PUNC: punctuations
"""
def __init__(self, type_include=True):
self.type_include = type_include
def clean(self, text):
if not self.type_include:
tknzr = NLTK.TweetTokenizer()
return tknzr.tokenize(text)
# Fix HTML character entities:
text = NLTK._replace_html_entities(text)
# Shorten problematic sequences of characters
safe_text = NLTK.HANG_RE.sub(r'\1\1\1', text)
# Tokenize:
words = WORD_RE.findall(safe_text)
clean_text = text
# # Possibly alter the case, but avoid changing emoticons like :D into :d:
for i, x in enumerate(words[:]):
# if EMOTICON_RE.match(x) or EMOJI_RE.match(x):
# text.decode('utf8')
if URLS_RE.match(x) or EMAIL_RE.match(x):
# print "url"
clean_text = clean_text.replace(x, '')
elif USERNAME_RE.match(x):
# print "Username"
clean_text = clean_text.replace(x, '')
elif HASHTAG_RE.match(x):
# print "tag"
clean_text = clean_text.replace(x, '')
elif PHONUM_RE.match(x):
# print "phone"
clean_text = clean_text.replace(x, '')
# elif x.lower() in STOP:
# print "stop"
# clean_text = clean_text.replace(x, '')
# elif EMOJI_RE.match(x):
# clean_text = clean_text.replace(x, '')
else:
continue
return clean_text
emoji_pattern = re.compile(
u"(\ud83d[\ude00-\ude4f])|" # emoticons
u"(\ud83d[\u0000-\uddff])|" # symbols & pictographs (2 of 2)
u"(\ud83d[\ude80-\udeff])|" # transport & map symbols
u"(\uD83E[\uDD00-\uDDFF])|"
u"(\ud83c[\udf00-\uffff])|" # symbols & pictographs (1 of 2)
u"(\ud83c[\udde0-\uddff])|" # flags (iOS)
u"([\u2934\u2935]\uFE0F?)|"
u"([\u3030\u303D]\uFE0F?)|"
u"([\u3297\u3299]\uFE0F?)|"
u"([\u203C\u2049]\uFE0F?)|"
u"([\u00A9\u00AE]\uFE0F?)|"
u"([\u2122\u2139]\uFE0F?)|"
u"(\uD83C\uDC04\uFE0F?)|"
u"(\uD83C\uDCCF\uFE0F?)|"
u"([\u0023\u002A\u0030-\u0039]\uFE0F?\u20E3)|"
u"(\u24C2\uFE0F?|[\u2B05-\u2B07\u2B1B\u2B1C\u2B50\u2B55]\uFE0F?)|"
u"([\u2600-\u26FF]\uFE0F?)|"
u"([\u2700-\u27BF]\uFE0F?)"
"+", flags=re.UNICODE)
# input_file: str
# output_file: str
def read_tweets(input_file):
happy_emoji = [' :‑) ', ' :) ', ' :))', ' :)))', ' :-] ', ' :]', ' :-3', ':->', ':>', ' 8-)', ':-}', ':}', ' :o)', ' :c)', ' :^)', ' =]', ' =)',
' :‑D', ' :D', ' 8‑D', ' 8D ', ' x‑D', ' xD ', ' X‑D ', ' XD ', ' =D ', ' =3', ':-))', ':-)))', ':\'‑)', ':\')',
' :-*', ':*', ' :×', ' ;‑)', ' ;)', ' *-)', ' *)', ';‑]', ' ;]', ' ;^)', ' :‑,', ' ;D', ' :‑P', ' :P', ' X‑P', ' x‑p',
' :‑p', ' :p ', ' :b', ' d:', ' =p', '^_^', '^^', '^ ^', '(^_^)/', '(^O^)/', '(^o^)/', '(^^)/', '>^_^<', '^/^', '(*^_^*)',
'(^.^)', '(^·^)', '(^.^)', '(^_^)', '(^^)', '^_^', '(*^.^*)', '(#^.^#)', '(*^0^*)', '\(^o^)/', '!(^^)!', '(^v^)',
'(^u^)', '( ^)o(^ )', '(^O^)', '(^o^)', ')^o^(', 'ヽ(´▽`)/', '≧∇≦', '^ω^', '^▽^',
'\xF0\x9F\x98\x81', '\xF0\x9F\x98\x82', '\xF0\x9F\x98\x83', '\xF0\x9F\x98\x84', '\xF0\x9F\x98\x86', '\xF0\x9F\x98\x89',
'\xF0\x9F\x98\x8A', '\xF0\x9F\x98\x8B', '\xF0\x9F\x98\x8C', '\xF0\x9F\x98\x8D', '\xF0\x9F\x98\x8F', '\xF0\x9F\x98\x97', '\xF0\x9F\x98\x98',
'\xF0\x9F\x98\x99', '\xF0\x9F\x98\x9A', '\xF0\x9F\x98\x9B', '\xF0\x9F\x98\x9C', '\xF0\x9F\x98\x9D', '\xF0\x9F\x98\xB8', '\xF0\x9F\x98\xB9', '\xF0\x9F\x98\xBA',
'\xF0\x9F\x98\xBB', '\xF0\x9F\x98\xBD', '\xF0\x9F\x99\x8B', '\xF0\x9F\x99\x8C', '\xF0\x9F\x98\x80', '\xF0\x9F\x98\x87',
'\xF0\x9F\x98\x88', '\xF0\x9F\x98\x8E',
'\xF0\x9F\x92\x8B', '\xF0\x9F\x92\x8F', '\xF0\x9F\x92\x91', '\xF0\x9F\x92\x95', '\xF0\x9F\x92\x96', '\xF0\x9F\x92\x97', '\xF0\x9F\x92\x98',
'\xF0\x9F\x92\x9D',
'\xF0\x9F\x8C\xB9', '\xF0\x9F\x8E\x80', '\xF0\x9F\x8E\x81', '\xF0\x9F\x8E\x82', '\xF0\x9F\x8E\x86', '\xF0\x9F\x8E\x87', '\xF0\x9F\x8E\x89',
'\xF0\x9F\x8E\x8A',
'\xE2\x9C\x8C', '\xE2\x9D\xA4', '\xE2\x98\xBA', '\xE2\x99\xA5', '\xE3\x8A\x97']
sad_emoji = [' :‑(', ' :(', ' :‑c', ' :c', ' :‑<', ' :<', ' :‑[', ' :[', ' :-||', ' >:[', ' :{', ' :@', ' >:(', ' :\'‑(', ' :\'(',
' DX ', ' D= ', ' D; ', ' D: ', ' D:<', ' D‑\':', ' >:O', ' :-0', ' :‑o', ' :o ', ' :‑O', ' :O ', ' :‑/', ' :‑.',
' >:\\', ' >:/', ' :\\', ' =/', ' =\\', ' :L', ' =L', ' :S', ' :‑|', ' :|', ' :$ ', '(-_-;)', ' Q_Q', ' TnT', 'T.T', 'Q.Q', ';;',
' ;n;', ' ;-;', ' ;_;', '(T_T)', '(;_:)', '(ToT)', '(ー_ー)!!', '(-.-)', '(-_-)', '(=_=)', '(-"-)', '(ーー;)', '(* ̄m ̄)', '(#゚Д゚)',
'(´;ω;`)', 'ヽ(`Д´)ノ', '( ´,_ゝ`)',
'\xF0\x9F\x98\x91', '\xF0\x9F\x98\x92', '\xF0\x9F\x98\x93', '\xF0\x9F\x98\x94', '\xF0\x9F\x98\x95', '\xF0\x9F\x98\x96', '\xF0\x9F\x98\x9E', '\xF0\x9F\x98\x9F',
'\xF0\x9F\x98\xA0', '\xF0\x9F\x98\xA1', '\xF0\x9F\x98\xA2', '\xF0\x9F\x98\xA3', '\xF0\x9F\x98\xA4', '\xF0\x9F\x98\xA5', '\xF0\x9F\x98\xA6', '\xF0\x9F\x98\xA7', '\xF0\x9F\x98\xA8',
'\xF0\x9F\x98\xA9', '\xF0\x9F\x98\xAB', '\xF0\x9F\x98\xAD', '\xF0\x9F\x98\xB1', '\xF0\x9F\x98\xBE', '\xF0\x9F\x99\x8D',
'\xF0\x9F\x92\x94', '\xF0\x9F\x92\xA2'
]
output = {}
print("input_file: {}".format(input_file))
with open(input_file, 'r') as inf:
tweets = MyTweetTokenizer()
output_file = "tagged/{}.txt".format(input_file.split("/")[-1])
with open(output_file, 'w', 100) as outf:
for line in inf:
if is_json(line):
record = json.loads(line)
if u'text' in record:
unicode_text = record[u'text']
if len(unicode_text) < 20:
continue
utf8text = unicode_text.encode("utf-8")
is_happy, happy_tag, happy_clean_text = find_emoji(utf8text, happy_emoji)
is_sad, sad_tag, sad_clean_text = find_emoji(utf8text, sad_emoji)
if is_happy and not is_sad:
clean_emoji_text = remove_emoji(happy_clean_text) # remove emoji
clean_text = tweets.clean(clean_emoji_text) # remove others
clean_text = clean_text.replace("http://","").replace("https://","")
if len(clean_text) >= 20:
output = {'text': clean_text, 'label': '1', 'emoji': happy_tag}
outf.write(json.dumps(output) + '\n')
else:
continue
elif not is_happy and is_sad:
clean_emoji_text = remove_emoji(sad_clean_text)
clean_text = tweets.clean(clean_emoji_text)
clean_text = clean_text.replace("http://","").replace("https://","")
if len(clean_text) >= 20:
output = {'text': clean_text, 'label': '0', 'emoji': sad_tag}
outf.write(json.dumps(output) + '\n')
else:
continue
else:
continue
# text: str
# emoji: list
# return: bool
def find_emoji(text, emoji):
flag = False
flag_emoji = []
clean_text = text
for e in emoji:
if e in text:
clean_text = clean_text.replace(e, '')
flag = True
flag_emoji.append(e)
return flag, flag_emoji, clean_text
def remove_emoji(text):
# print type(text), "first" # str
text = text.decode('utf8')
# print type(text), "second" # un | xt = emoji_pattern.sub(r'', text).encode('utf8')
return
def is_json(myjson):
try:
json_object = json.loads(myjson)
except ValueError, e:
return False
return True
def run(data_dir):
files = [os.path.join(data_dir, f) for f in os.listdir(data_dir)]
start = time.time()
pool = multiprocessing.Pool(4)
results = pool.map_async(read_tweets, files)
pool.close()
pool.join()
print(time.time()-start)
if __name__ == '__main__':
run("/home/p8shi/tweets_english")
| icode
te | identifier_name |
Conv_layer.py | __author__='Pabi'
import numpy as np
import pandas as pd
class Data(object):
"""
This class is used for all data storage purposes
Data is stored as 3D volumes. This includes wieghts and input data
"""
def __init__(self, width, height, depth, weight_init='undefined'):
self.width = width
self.height = height
self.depth = depth
n_weight_vals = self.height * self.width * self.depth
self.data_mtx = np.reshape(np.zeros(n_weight_vals), newshape=(self.depth, self.height, self.width))
self.delta_data_mtx = np.reshape(np.zeros(n_weight_vals), newshape=(self.depth, self.height, self.width))
self.vectorized_rand_norm = np.vectorize(self.generate_normal_rand, otypes=[np.float])
# weight initialization
# if weight initialization not set then use Xavier method for initializing weights
'TODO: provide link'
if weight_init != 'undefined':
weight_std = np.sqrt(n_weight_vals)
self.data_mtx = self.vectorized_rand_norm(self.data_mtx)
def get_data(self, width_indx, heigh_indx, depth_indx):
pass
# weight_patch=
def get_shape(self):
return self.data_mtx.shape
def set_data_elmt(self, i, j, depth, val):
self.data_mtx[depth, i, j] = val
def set_padded_mtx(self,input_mtx):
self.padded_mtx = input_mtx
self.depth , self.width,self.height = input_mtx.shape
self.delta_data_mtx = np.reshape(np.zeros(self.depth*self.height*self.width), newshape=(self.depth, self.height, self.width))
def set_data_mtx(self,input_mtx):
self.data_mtx = input_mtx
self.depth , self.width,self.height = input_mtx.shape
self.delta_data_mtx = np.reshape(np.zeros(self.depth*self.height*self.width), newshape=(self.depth, self.height, self.width))
def get_gradient(self, x, y, depth):
return self.delta_data_mtx[depth, x, y]
def set_gradient(self, x, y, depth, grad_val):
self.delta_data_mtx[depth, x, y] = grad_val
def add_gradient(self, x, y, depth, grad_val):
self.delta_data_mtx += grad_val
def generate_normal_rand(self, matx_elmt):
n_weight_vals = self.height * self.depth * self.depth
return np.float(matx_elmt + np.random.normal(loc=0, scale=np.sqrt(n_weight_vals), size=1))
class Naive_Conv_NeuralNet_Layer(object):
"""
A numpy based, naive implementation of a vanilla convolutional neural net layer.
Multiple Conv layers + pooling(optional) + some final output transformations define a full Conv Net
Details of the mathematics can be found at the from textbook 'Deep Learning' by Goodman, Bengio et al.
Implementation based also on stanford convolutional networks course work:
http://cs231n.github.io/convolutional-networks/#conv
Code is inspired by karpathy's javascript implementation of a different deep learning layers. Its amazing. So check it out.
All(most since I looked at alot of different code in coming to try understand this stuff) goes to ya. Thanks for making your code public dude
https://github.com/karpathy/convnetjs
"""
def __init__(self, input_volume, no_filters, filter_map_dim=3, stride_len=1, zero_padding=1,weight_init='False'):
"""
:param input_feature_map_dim:
:param no_filters:
:param filter_map_dim:
:param stride_len:
:param zero_padding:
:return:
"""
self.num_channels_D, self.width_X, self.height_Y= input_volume.get_shape()
self.n_filters = no_filters
self.input_vol = input_volume # need to change this to a copy of the input in the future .copy()
self.filter_size = filter_map_dim
self.stride_len = stride_len
self.zero_padding = zero_padding
self.filter_map = [Data(width=self.filter_size, height=self.filter_size, depth=self.input_vol.depth,weight_init='normal') for i in
range(self.n_filters)]
self.bias_vol = [Data(width=1, height=1, depth=1) for i in range(self.n_filters)]
self.zero_pad_image() # zero pad once since zero pad parm > 0
# Initialize weights to be applied to input_feature_map. Sample from N(0,1) as intialization weights
if weight_init == 'True':
pass
# Output volume sizes
# TODO: write a function to check if output dim are int types. If not adjust with appropriate zero padding
while (self.width_X-self.filter_size+ 2 * self.zero_padding)/self.stride_len % 1 != 0.0:
print('yay')
self.zero_pad_image()
else:
self.Output_Width = int((self.width_X - self.filter_size + 2 * self.zero_padding) / (self.stride_len) + 1)
self.Output_Height = int((self.height_Y - self.filter_size + 2 * self.zero_padding) / (self.stride_len) + 1)
self.output_Tensor = Data(width=self.Output_Width, height=self.Output_Height, depth=self.n_filters)
def filter_val_init(self,filter_vol):
for filter_indx in range(len(self.filter_map)):
self.filter_map[filter_indx].set_data_mtx(filter_vol[filter_indx,:,:])
| def im2col(self, X):
"""
:param X: filter_dim X filter_dim area of current image to be converted to 1 X filter_dim^2 vector
:param filter_dim:
:return: vector of dimension 1 by filter_dim^2
"""
flat_vect = np.reshape(X, -1)
return flat_vect
def convolution_op(self, image_col, filter_col):
conv_result = np.sum(np.dot(image_col, filter_col))
return conv_result
def zero_pad(self,x):
return np.pad(x,pad_width=(1,1),mode='constant',constant_values=0)
def zero_pad_image(self):
input_img =self.input_vol.data_mtx.copy()
input_img_list = input_img.tolist()
padded = False
while self.zero_padding < self.filter_size and padded==False:
if (self.width_X-self.filter_size+ 2 * self.zero_padding)/self.stride_len % 1 == 0.0 :
for j in range(0,input_img.shape[0]):
input_img_list[j] = self.zero_pad(input_img_list[j])
print(input_img_list)
padded = True
else:
self.zero_padding += 1
self.input_vol.set_padded_mtx(np.asarray(input_img_list))
def set_weights(self,input_vol):
for j in range(len(self.filter_map)):
self.filter_map[j].set_data_mtx(input_vol[j,:,:,:])
def Naive_forwardpass(self):
"""
Forward pass of conv net implementing output map generating function.
Returns an tensor of self.Output_Width X self.Output_Height X self.n_filters. Which is happily sent off to the
next poor bugger layer of the CNN architecture
Not happy too(livid actually) with the efficiency and endless loops but c'est la vie. This is for education purposes.
:param X: Image/feature map from previous layer/(just the picture I guess)
:return: tensor of vol : self.Output_Width X self.Output_Height X self.n_filters
"""
for filter_k in range(0, self.n_filters):
filter_col = self.im2col(self.filter_map[filter_k].data_mtx)
for hgt_indx in range(0, self.Output_Height):
for wdth_indx in range(0, self.Output_Width):
wdth_start_index = wdth_indx * self.stride_len
wdth_end_index= wdth_start_index + self.filter_size
hgt_start_index = hgt_indx * self.stride_len
hgt_end_index = hgt_start_index + self.filter_size
trn_img_area = self.input_vol.padded_mtx[:, wdth_start_index:wdth_end_index,
hgt_start_index:hgt_end_index]
trn_img_col = self.im2col(trn_img_area)
self.output_Tensor.data_mtx[filter_k,wdth_indx , hgt_indx] = self.convolution_op(trn_img_col,
filter_col) + np.sum(self.bias_vol[filter_k].data_mtx)
return self.output_Tensor
# hopefully correct implementation of conv back prop
def Naive_backwardpass(self):
"""
:param X:
:return:
"""
# this fucking backward pass ...sigh
# need to make two backward pass gradient calculations
# gradient w.r.t filter weights which will be used for weight updates.
# gradient w.r.t current image representation/ current layer which will be used as gradient flow to lower layers
for filter_j in range(0, len(self.filter_map)):
filter_vol = self.filter_map[ filter_j] # fix a single filter,reference to a class object. Make sure that changes are inplace and not new copy object
for height_indx in range(0, self.Output_Height):
for width_indx in range(0,self.Output_Width): # fixes a single pixel , pixel i,j in layer L the output vol
upstream_grad = np.full(shape=(filter_vol.depth, self.filter_size, self.filter_size),
fill_value=self.output_Tensor.delta_data_mtx[
filter_j, width_indx, height_indx]) # get dE/d(x_{i,j}) . derivative of error w.r.t fixed pixel
w,h,s,f = width_indx,height_indx,self.stride_len,self.filter_size
filter_vol.delta_data_mtx[:, :, :] += self.input_vol.padded_mtx[:,w * s:w * s + f,h * s: h * s + f]\
* upstream_grad # element wise multiplication
self.input_vol.delta_data_mtx[:,w * s:w * s + f,h * s: h * s + f] += filter_vol.data_mtx[:, :,:] * upstream_grad
init_boarder_end = self.input_vol.delta_data_mtx.shape[1] - self.zero_padding
return self.input_vol.delta_data_mtx[:,self.zero_padding:init_boarder_end,self.zero_padding:init_boarder_end] # return image without zero padding | random_line_split | |
Conv_layer.py | __author__='Pabi'
import numpy as np
import pandas as pd
class Data(object):
"""
This class is used for all data storage purposes
Data is stored as 3D volumes. This includes wieghts and input data
"""
def __init__(self, width, height, depth, weight_init='undefined'):
self.width = width
self.height = height
self.depth = depth
n_weight_vals = self.height * self.width * self.depth
self.data_mtx = np.reshape(np.zeros(n_weight_vals), newshape=(self.depth, self.height, self.width))
self.delta_data_mtx = np.reshape(np.zeros(n_weight_vals), newshape=(self.depth, self.height, self.width))
self.vectorized_rand_norm = np.vectorize(self.generate_normal_rand, otypes=[np.float])
# weight initialization
# if weight initialization not set then use Xavier method for initializing weights
'TODO: provide link'
if weight_init != 'undefined':
weight_std = np.sqrt(n_weight_vals)
self.data_mtx = self.vectorized_rand_norm(self.data_mtx)
def get_data(self, width_indx, heigh_indx, depth_indx):
pass
# weight_patch=
def get_shape(self):
return self.data_mtx.shape
def set_data_elmt(self, i, j, depth, val):
self.data_mtx[depth, i, j] = val
def set_padded_mtx(self,input_mtx):
|
def set_data_mtx(self,input_mtx):
self.data_mtx = input_mtx
self.depth , self.width,self.height = input_mtx.shape
self.delta_data_mtx = np.reshape(np.zeros(self.depth*self.height*self.width), newshape=(self.depth, self.height, self.width))
def get_gradient(self, x, y, depth):
return self.delta_data_mtx[depth, x, y]
def set_gradient(self, x, y, depth, grad_val):
self.delta_data_mtx[depth, x, y] = grad_val
def add_gradient(self, x, y, depth, grad_val):
self.delta_data_mtx += grad_val
def generate_normal_rand(self, matx_elmt):
n_weight_vals = self.height * self.depth * self.depth
return np.float(matx_elmt + np.random.normal(loc=0, scale=np.sqrt(n_weight_vals), size=1))
class Naive_Conv_NeuralNet_Layer(object):
"""
A numpy based, naive implementation of a vanilla convolutional neural net layer.
Multiple Conv layers + pooling(optional) + some final output transformations define a full Conv Net
Details of the mathematics can be found at the from textbook 'Deep Learning' by Goodman, Bengio et al.
Implementation based also on stanford convolutional networks course work:
http://cs231n.github.io/convolutional-networks/#conv
Code is inspired by karpathy's javascript implementation of a different deep learning layers. Its amazing. So check it out.
All(most since I looked at alot of different code in coming to try understand this stuff) goes to ya. Thanks for making your code public dude
https://github.com/karpathy/convnetjs
"""
def __init__(self, input_volume, no_filters, filter_map_dim=3, stride_len=1, zero_padding=1,weight_init='False'):
"""
:param input_feature_map_dim:
:param no_filters:
:param filter_map_dim:
:param stride_len:
:param zero_padding:
:return:
"""
self.num_channels_D, self.width_X, self.height_Y= input_volume.get_shape()
self.n_filters = no_filters
self.input_vol = input_volume # need to change this to a copy of the input in the future .copy()
self.filter_size = filter_map_dim
self.stride_len = stride_len
self.zero_padding = zero_padding
self.filter_map = [Data(width=self.filter_size, height=self.filter_size, depth=self.input_vol.depth,weight_init='normal') for i in
range(self.n_filters)]
self.bias_vol = [Data(width=1, height=1, depth=1) for i in range(self.n_filters)]
self.zero_pad_image() # zero pad once since zero pad parm > 0
# Initialize weights to be applied to input_feature_map. Sample from N(0,1) as intialization weights
if weight_init == 'True':
pass
# Output volume sizes
# TODO: write a function to check if output dim are int types. If not adjust with appropriate zero padding
while (self.width_X-self.filter_size+ 2 * self.zero_padding)/self.stride_len % 1 != 0.0:
print('yay')
self.zero_pad_image()
else:
self.Output_Width = int((self.width_X - self.filter_size + 2 * self.zero_padding) / (self.stride_len) + 1)
self.Output_Height = int((self.height_Y - self.filter_size + 2 * self.zero_padding) / (self.stride_len) + 1)
self.output_Tensor = Data(width=self.Output_Width, height=self.Output_Height, depth=self.n_filters)
def filter_val_init(self,filter_vol):
for filter_indx in range(len(self.filter_map)):
self.filter_map[filter_indx].set_data_mtx(filter_vol[filter_indx,:,:])
def im2col(self, X):
"""
:param X: filter_dim X filter_dim area of current image to be converted to 1 X filter_dim^2 vector
:param filter_dim:
:return: vector of dimension 1 by filter_dim^2
"""
flat_vect = np.reshape(X, -1)
return flat_vect
def convolution_op(self, image_col, filter_col):
conv_result = np.sum(np.dot(image_col, filter_col))
return conv_result
def zero_pad(self,x):
return np.pad(x,pad_width=(1,1),mode='constant',constant_values=0)
def zero_pad_image(self):
input_img =self.input_vol.data_mtx.copy()
input_img_list = input_img.tolist()
padded = False
while self.zero_padding < self.filter_size and padded==False:
if (self.width_X-self.filter_size+ 2 * self.zero_padding)/self.stride_len % 1 == 0.0 :
for j in range(0,input_img.shape[0]):
input_img_list[j] = self.zero_pad(input_img_list[j])
print(input_img_list)
padded = True
else:
self.zero_padding += 1
self.input_vol.set_padded_mtx(np.asarray(input_img_list))
def set_weights(self,input_vol):
for j in range(len(self.filter_map)):
self.filter_map[j].set_data_mtx(input_vol[j,:,:,:])
def Naive_forwardpass(self):
"""
Forward pass of conv net implementing output map generating function.
Returns an tensor of self.Output_Width X self.Output_Height X self.n_filters. Which is happily sent off to the
next poor bugger layer of the CNN architecture
Not happy too(livid actually) with the efficiency and endless loops but c'est la vie. This is for education purposes.
:param X: Image/feature map from previous layer/(just the picture I guess)
:return: tensor of vol : self.Output_Width X self.Output_Height X self.n_filters
"""
for filter_k in range(0, self.n_filters):
filter_col = self.im2col(self.filter_map[filter_k].data_mtx)
for hgt_indx in range(0, self.Output_Height):
for wdth_indx in range(0, self.Output_Width):
wdth_start_index = wdth_indx * self.stride_len
wdth_end_index= wdth_start_index + self.filter_size
hgt_start_index = hgt_indx * self.stride_len
hgt_end_index = hgt_start_index + self.filter_size
trn_img_area = self.input_vol.padded_mtx[:, wdth_start_index:wdth_end_index,
hgt_start_index:hgt_end_index]
trn_img_col = self.im2col(trn_img_area)
self.output_Tensor.data_mtx[filter_k,wdth_indx , hgt_indx] = self.convolution_op(trn_img_col,
filter_col) + np.sum(self.bias_vol[filter_k].data_mtx)
return self.output_Tensor
# hopefully correct implementation of conv back prop
def Naive_backwardpass(self):
"""
:param X:
:return:
"""
# this fucking backward pass ...sigh
# need to make two backward pass gradient calculations
# gradient w.r.t filter weights which will be used for weight updates.
# gradient w.r.t current image representation/ current layer which will be used as gradient flow to lower layers
for filter_j in range(0, len(self.filter_map)):
filter_vol = self.filter_map[ filter_j] # fix a single filter,reference to a class object. Make sure that changes are inplace and not new copy object
for height_indx in range(0, self.Output_Height):
for width_indx in range(0,self.Output_Width): # fixes a single pixel , pixel i,j in layer L the output vol
upstream_grad = np.full(shape=(filter_vol.depth, self.filter_size, self.filter_size),
fill_value=self.output_Tensor.delta_data_mtx[
filter_j, width_indx, height_indx]) # get dE/d(x_{i,j}) . derivative of error w.r.t fixed pixel
w,h,s,f = width_indx,height_indx,self.stride_len,self.filter_size
filter_vol.delta_data_mtx[:, :, :] += self.input_vol.padded_mtx[:,w * s:w * s + f,h * s: h * s + f]\
* upstream_grad # element wise multiplication
self.input_vol.delta_data_mtx[:,w * s:w * s + f,h * s: h * s + f] += filter_vol.data_mtx[:, :,:] * upstream_grad
init_boarder_end = self.input_vol.delta_data_mtx.shape[1] - self.zero_padding
return self.input_vol.delta_data_mtx[:,self.zero_padding:init_boarder_end,self.zero_padding:init_boarder_end] # return image without zero padding
| self.padded_mtx = input_mtx
self.depth , self.width,self.height = input_mtx.shape
self.delta_data_mtx = np.reshape(np.zeros(self.depth*self.height*self.width), newshape=(self.depth, self.height, self.width)) | identifier_body |
Conv_layer.py | __author__='Pabi'
import numpy as np
import pandas as pd
class Data(object):
"""
This class is used for all data storage purposes
Data is stored as 3D volumes. This includes wieghts and input data
"""
def __init__(self, width, height, depth, weight_init='undefined'):
self.width = width
self.height = height
self.depth = depth
n_weight_vals = self.height * self.width * self.depth
self.data_mtx = np.reshape(np.zeros(n_weight_vals), newshape=(self.depth, self.height, self.width))
self.delta_data_mtx = np.reshape(np.zeros(n_weight_vals), newshape=(self.depth, self.height, self.width))
self.vectorized_rand_norm = np.vectorize(self.generate_normal_rand, otypes=[np.float])
# weight initialization
# if weight initialization not set then use Xavier method for initializing weights
'TODO: provide link'
if weight_init != 'undefined':
weight_std = np.sqrt(n_weight_vals)
self.data_mtx = self.vectorized_rand_norm(self.data_mtx)
def get_data(self, width_indx, heigh_indx, depth_indx):
pass
# weight_patch=
def get_shape(self):
return self.data_mtx.shape
def set_data_elmt(self, i, j, depth, val):
self.data_mtx[depth, i, j] = val
def set_padded_mtx(self,input_mtx):
self.padded_mtx = input_mtx
self.depth , self.width,self.height = input_mtx.shape
self.delta_data_mtx = np.reshape(np.zeros(self.depth*self.height*self.width), newshape=(self.depth, self.height, self.width))
def set_data_mtx(self,input_mtx):
self.data_mtx = input_mtx
self.depth , self.width,self.height = input_mtx.shape
self.delta_data_mtx = np.reshape(np.zeros(self.depth*self.height*self.width), newshape=(self.depth, self.height, self.width))
def get_gradient(self, x, y, depth):
return self.delta_data_mtx[depth, x, y]
def set_gradient(self, x, y, depth, grad_val):
self.delta_data_mtx[depth, x, y] = grad_val
def add_gradient(self, x, y, depth, grad_val):
self.delta_data_mtx += grad_val
def generate_normal_rand(self, matx_elmt):
n_weight_vals = self.height * self.depth * self.depth
return np.float(matx_elmt + np.random.normal(loc=0, scale=np.sqrt(n_weight_vals), size=1))
class Naive_Conv_NeuralNet_Layer(object):
"""
A numpy based, naive implementation of a vanilla convolutional neural net layer.
Multiple Conv layers + pooling(optional) + some final output transformations define a full Conv Net
Details of the mathematics can be found at the from textbook 'Deep Learning' by Goodman, Bengio et al.
Implementation based also on stanford convolutional networks course work:
http://cs231n.github.io/convolutional-networks/#conv
Code is inspired by karpathy's javascript implementation of a different deep learning layers. Its amazing. So check it out.
All(most since I looked at alot of different code in coming to try understand this stuff) goes to ya. Thanks for making your code public dude
https://github.com/karpathy/convnetjs
"""
def __init__(self, input_volume, no_filters, filter_map_dim=3, stride_len=1, zero_padding=1,weight_init='False'):
"""
:param input_feature_map_dim:
:param no_filters:
:param filter_map_dim:
:param stride_len:
:param zero_padding:
:return:
"""
self.num_channels_D, self.width_X, self.height_Y= input_volume.get_shape()
self.n_filters = no_filters
self.input_vol = input_volume # need to change this to a copy of the input in the future .copy()
self.filter_size = filter_map_dim
self.stride_len = stride_len
self.zero_padding = zero_padding
self.filter_map = [Data(width=self.filter_size, height=self.filter_size, depth=self.input_vol.depth,weight_init='normal') for i in
range(self.n_filters)]
self.bias_vol = [Data(width=1, height=1, depth=1) for i in range(self.n_filters)]
self.zero_pad_image() # zero pad once since zero pad parm > 0
# Initialize weights to be applied to input_feature_map. Sample from N(0,1) as intialization weights
if weight_init == 'True':
pass
# Output volume sizes
# TODO: write a function to check if output dim are int types. If not adjust with appropriate zero padding
while (self.width_X-self.filter_size+ 2 * self.zero_padding)/self.stride_len % 1 != 0.0:
print('yay')
self.zero_pad_image()
else:
self.Output_Width = int((self.width_X - self.filter_size + 2 * self.zero_padding) / (self.stride_len) + 1)
self.Output_Height = int((self.height_Y - self.filter_size + 2 * self.zero_padding) / (self.stride_len) + 1)
self.output_Tensor = Data(width=self.Output_Width, height=self.Output_Height, depth=self.n_filters)
def filter_val_init(self,filter_vol):
for filter_indx in range(len(self.filter_map)):
self.filter_map[filter_indx].set_data_mtx(filter_vol[filter_indx,:,:])
def im2col(self, X):
"""
:param X: filter_dim X filter_dim area of current image to be converted to 1 X filter_dim^2 vector
:param filter_dim:
:return: vector of dimension 1 by filter_dim^2
"""
flat_vect = np.reshape(X, -1)
return flat_vect
def convolution_op(self, image_col, filter_col):
conv_result = np.sum(np.dot(image_col, filter_col))
return conv_result
def zero_pad(self,x):
return np.pad(x,pad_width=(1,1),mode='constant',constant_values=0)
def zero_pad_image(self):
input_img =self.input_vol.data_mtx.copy()
input_img_list = input_img.tolist()
padded = False
while self.zero_padding < self.filter_size and padded==False:
|
self.input_vol.set_padded_mtx(np.asarray(input_img_list))
def set_weights(self,input_vol):
for j in range(len(self.filter_map)):
self.filter_map[j].set_data_mtx(input_vol[j,:,:,:])
def Naive_forwardpass(self):
"""
Forward pass of conv net implementing output map generating function.
Returns an tensor of self.Output_Width X self.Output_Height X self.n_filters. Which is happily sent off to the
next poor bugger layer of the CNN architecture
Not happy too(livid actually) with the efficiency and endless loops but c'est la vie. This is for education purposes.
:param X: Image/feature map from previous layer/(just the picture I guess)
:return: tensor of vol : self.Output_Width X self.Output_Height X self.n_filters
"""
for filter_k in range(0, self.n_filters):
filter_col = self.im2col(self.filter_map[filter_k].data_mtx)
for hgt_indx in range(0, self.Output_Height):
for wdth_indx in range(0, self.Output_Width):
wdth_start_index = wdth_indx * self.stride_len
wdth_end_index= wdth_start_index + self.filter_size
hgt_start_index = hgt_indx * self.stride_len
hgt_end_index = hgt_start_index + self.filter_size
trn_img_area = self.input_vol.padded_mtx[:, wdth_start_index:wdth_end_index,
hgt_start_index:hgt_end_index]
trn_img_col = self.im2col(trn_img_area)
self.output_Tensor.data_mtx[filter_k,wdth_indx , hgt_indx] = self.convolution_op(trn_img_col,
filter_col) + np.sum(self.bias_vol[filter_k].data_mtx)
return self.output_Tensor
# hopefully correct implementation of conv back prop
def Naive_backwardpass(self):
"""
:param X:
:return:
"""
# this fucking backward pass ...sigh
# need to make two backward pass gradient calculations
# gradient w.r.t filter weights which will be used for weight updates.
# gradient w.r.t current image representation/ current layer which will be used as gradient flow to lower layers
for filter_j in range(0, len(self.filter_map)):
filter_vol = self.filter_map[ filter_j] # fix a single filter,reference to a class object. Make sure that changes are inplace and not new copy object
for height_indx in range(0, self.Output_Height):
for width_indx in range(0,self.Output_Width): # fixes a single pixel , pixel i,j in layer L the output vol
upstream_grad = np.full(shape=(filter_vol.depth, self.filter_size, self.filter_size),
fill_value=self.output_Tensor.delta_data_mtx[
filter_j, width_indx, height_indx]) # get dE/d(x_{i,j}) . derivative of error w.r.t fixed pixel
w,h,s,f = width_indx,height_indx,self.stride_len,self.filter_size
filter_vol.delta_data_mtx[:, :, :] += self.input_vol.padded_mtx[:,w * s:w * s + f,h * s: h * s + f]\
* upstream_grad # element wise multiplication
self.input_vol.delta_data_mtx[:,w * s:w * s + f,h * s: h * s + f] += filter_vol.data_mtx[:, :,:] * upstream_grad
init_boarder_end = self.input_vol.delta_data_mtx.shape[1] - self.zero_padding
return self.input_vol.delta_data_mtx[:,self.zero_padding:init_boarder_end,self.zero_padding:init_boarder_end] # return image without zero padding
| if (self.width_X-self.filter_size+ 2 * self.zero_padding)/self.stride_len % 1 == 0.0 :
for j in range(0,input_img.shape[0]):
input_img_list[j] = self.zero_pad(input_img_list[j])
print(input_img_list)
padded = True
else:
self.zero_padding += 1 | conditional_block |
Conv_layer.py | __author__='Pabi'
import numpy as np
import pandas as pd
class Data(object):
"""
This class is used for all data storage purposes
Data is stored as 3D volumes. This includes wieghts and input data
"""
def __init__(self, width, height, depth, weight_init='undefined'):
self.width = width
self.height = height
self.depth = depth
n_weight_vals = self.height * self.width * self.depth
self.data_mtx = np.reshape(np.zeros(n_weight_vals), newshape=(self.depth, self.height, self.width))
self.delta_data_mtx = np.reshape(np.zeros(n_weight_vals), newshape=(self.depth, self.height, self.width))
self.vectorized_rand_norm = np.vectorize(self.generate_normal_rand, otypes=[np.float])
# weight initialization
# if weight initialization not set then use Xavier method for initializing weights
'TODO: provide link'
if weight_init != 'undefined':
weight_std = np.sqrt(n_weight_vals)
self.data_mtx = self.vectorized_rand_norm(self.data_mtx)
def get_data(self, width_indx, heigh_indx, depth_indx):
pass
# weight_patch=
def get_shape(self):
return self.data_mtx.shape
def set_data_elmt(self, i, j, depth, val):
self.data_mtx[depth, i, j] = val
def set_padded_mtx(self,input_mtx):
self.padded_mtx = input_mtx
self.depth , self.width,self.height = input_mtx.shape
self.delta_data_mtx = np.reshape(np.zeros(self.depth*self.height*self.width), newshape=(self.depth, self.height, self.width))
def set_data_mtx(self,input_mtx):
self.data_mtx = input_mtx
self.depth , self.width,self.height = input_mtx.shape
self.delta_data_mtx = np.reshape(np.zeros(self.depth*self.height*self.width), newshape=(self.depth, self.height, self.width))
def get_gradient(self, x, y, depth):
return self.delta_data_mtx[depth, x, y]
def set_gradient(self, x, y, depth, grad_val):
self.delta_data_mtx[depth, x, y] = grad_val
def add_gradient(self, x, y, depth, grad_val):
self.delta_data_mtx += grad_val
def generate_normal_rand(self, matx_elmt):
n_weight_vals = self.height * self.depth * self.depth
return np.float(matx_elmt + np.random.normal(loc=0, scale=np.sqrt(n_weight_vals), size=1))
class Naive_Conv_NeuralNet_Layer(object):
"""
A numpy based, naive implementation of a vanilla convolutional neural net layer.
Multiple Conv layers + pooling(optional) + some final output transformations define a full Conv Net
Details of the mathematics can be found at the from textbook 'Deep Learning' by Goodman, Bengio et al.
Implementation based also on stanford convolutional networks course work:
http://cs231n.github.io/convolutional-networks/#conv
Code is inspired by karpathy's javascript implementation of a different deep learning layers. Its amazing. So check it out.
All(most since I looked at alot of different code in coming to try understand this stuff) goes to ya. Thanks for making your code public dude
https://github.com/karpathy/convnetjs
"""
def __init__(self, input_volume, no_filters, filter_map_dim=3, stride_len=1, zero_padding=1,weight_init='False'):
"""
:param input_feature_map_dim:
:param no_filters:
:param filter_map_dim:
:param stride_len:
:param zero_padding:
:return:
"""
self.num_channels_D, self.width_X, self.height_Y= input_volume.get_shape()
self.n_filters = no_filters
self.input_vol = input_volume # need to change this to a copy of the input in the future .copy()
self.filter_size = filter_map_dim
self.stride_len = stride_len
self.zero_padding = zero_padding
self.filter_map = [Data(width=self.filter_size, height=self.filter_size, depth=self.input_vol.depth,weight_init='normal') for i in
range(self.n_filters)]
self.bias_vol = [Data(width=1, height=1, depth=1) for i in range(self.n_filters)]
self.zero_pad_image() # zero pad once since zero pad parm > 0
# Initialize weights to be applied to input_feature_map. Sample from N(0,1) as intialization weights
if weight_init == 'True':
pass
# Output volume sizes
# TODO: write a function to check if output dim are int types. If not adjust with appropriate zero padding
while (self.width_X-self.filter_size+ 2 * self.zero_padding)/self.stride_len % 1 != 0.0:
print('yay')
self.zero_pad_image()
else:
self.Output_Width = int((self.width_X - self.filter_size + 2 * self.zero_padding) / (self.stride_len) + 1)
self.Output_Height = int((self.height_Y - self.filter_size + 2 * self.zero_padding) / (self.stride_len) + 1)
self.output_Tensor = Data(width=self.Output_Width, height=self.Output_Height, depth=self.n_filters)
def filter_val_init(self,filter_vol):
for filter_indx in range(len(self.filter_map)):
self.filter_map[filter_indx].set_data_mtx(filter_vol[filter_indx,:,:])
def im2col(self, X):
"""
:param X: filter_dim X filter_dim area of current image to be converted to 1 X filter_dim^2 vector
:param filter_dim:
:return: vector of dimension 1 by filter_dim^2
"""
flat_vect = np.reshape(X, -1)
return flat_vect
def | (self, image_col, filter_col):
conv_result = np.sum(np.dot(image_col, filter_col))
return conv_result
def zero_pad(self,x):
return np.pad(x,pad_width=(1,1),mode='constant',constant_values=0)
def zero_pad_image(self):
input_img =self.input_vol.data_mtx.copy()
input_img_list = input_img.tolist()
padded = False
while self.zero_padding < self.filter_size and padded==False:
if (self.width_X-self.filter_size+ 2 * self.zero_padding)/self.stride_len % 1 == 0.0 :
for j in range(0,input_img.shape[0]):
input_img_list[j] = self.zero_pad(input_img_list[j])
print(input_img_list)
padded = True
else:
self.zero_padding += 1
self.input_vol.set_padded_mtx(np.asarray(input_img_list))
def set_weights(self,input_vol):
for j in range(len(self.filter_map)):
self.filter_map[j].set_data_mtx(input_vol[j,:,:,:])
def Naive_forwardpass(self):
"""
Forward pass of conv net implementing output map generating function.
Returns an tensor of self.Output_Width X self.Output_Height X self.n_filters. Which is happily sent off to the
next poor bugger layer of the CNN architecture
Not happy too(livid actually) with the efficiency and endless loops but c'est la vie. This is for education purposes.
:param X: Image/feature map from previous layer/(just the picture I guess)
:return: tensor of vol : self.Output_Width X self.Output_Height X self.n_filters
"""
for filter_k in range(0, self.n_filters):
filter_col = self.im2col(self.filter_map[filter_k].data_mtx)
for hgt_indx in range(0, self.Output_Height):
for wdth_indx in range(0, self.Output_Width):
wdth_start_index = wdth_indx * self.stride_len
wdth_end_index= wdth_start_index + self.filter_size
hgt_start_index = hgt_indx * self.stride_len
hgt_end_index = hgt_start_index + self.filter_size
trn_img_area = self.input_vol.padded_mtx[:, wdth_start_index:wdth_end_index,
hgt_start_index:hgt_end_index]
trn_img_col = self.im2col(trn_img_area)
self.output_Tensor.data_mtx[filter_k,wdth_indx , hgt_indx] = self.convolution_op(trn_img_col,
filter_col) + np.sum(self.bias_vol[filter_k].data_mtx)
return self.output_Tensor
# hopefully correct implementation of conv back prop
def Naive_backwardpass(self):
"""
:param X:
:return:
"""
# this fucking backward pass ...sigh
# need to make two backward pass gradient calculations
# gradient w.r.t filter weights which will be used for weight updates.
# gradient w.r.t current image representation/ current layer which will be used as gradient flow to lower layers
for filter_j in range(0, len(self.filter_map)):
filter_vol = self.filter_map[ filter_j] # fix a single filter,reference to a class object. Make sure that changes are inplace and not new copy object
for height_indx in range(0, self.Output_Height):
for width_indx in range(0,self.Output_Width): # fixes a single pixel , pixel i,j in layer L the output vol
upstream_grad = np.full(shape=(filter_vol.depth, self.filter_size, self.filter_size),
fill_value=self.output_Tensor.delta_data_mtx[
filter_j, width_indx, height_indx]) # get dE/d(x_{i,j}) . derivative of error w.r.t fixed pixel
w,h,s,f = width_indx,height_indx,self.stride_len,self.filter_size
filter_vol.delta_data_mtx[:, :, :] += self.input_vol.padded_mtx[:,w * s:w * s + f,h * s: h * s + f]\
* upstream_grad # element wise multiplication
self.input_vol.delta_data_mtx[:,w * s:w * s + f,h * s: h * s + f] += filter_vol.data_mtx[:, :,:] * upstream_grad
init_boarder_end = self.input_vol.delta_data_mtx.shape[1] - self.zero_padding
return self.input_vol.delta_data_mtx[:,self.zero_padding:init_boarder_end,self.zero_padding:init_boarder_end] # return image without zero padding
| convolution_op | identifier_name |
forms.py | # Copyright 2010 Jose Maria Zambrana Arze <contact@josezambrana.com>
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from google.appengine.ext.db import djangoforms
import logging
from django import forms
from django.conf import settings
from django.core.validators import validate_email
from django.template.defaultfilters import slugify
from django.utils.translation import ugettext_lazy as _
from django.utils.safestring import mark_safe
from common.models import Block, MenuItem, Theme, ConfigData, Comment
from common.widgets import SelectMultiple, SelectDateTimeWidget
from common import util
from recaptcha_django import ReCaptchaField
from users.models import User, UserDoesNotExist
from beautifulsoup.BeautifulSoup import BeautifulSoup
class ReCaptchaField(ReCaptchaField):
__metaclass__ = djangoforms.monkey_patch
def widget_attrs(self, widget):
return {'theme':'clean'}
class SelectDateTimeField(forms.DateTimeField):
widget = SelectDateTimeWidget
class BlobWidget(forms.FileInput):
pass
class BlobField(forms.FileField):
widget = BlobWidget
class DateTimeProperty(djangoforms.DateTimeProperty):
__metaclass__ = djangoforms.monkey_patch
def | (self, **kwargs):
if self.name == 'deleted_at' or self.auto_now or self.auto_now_add:
return None
defaults = {'form_class': SelectDateTimeField}
defaults.update(kwargs)
return super(DateTimeProperty, self).get_form_field(**defaults)
class StringListProperty(djangoforms.StringListProperty):
__metaclass__ = djangoforms.monkey_patch
def get_form_field(self, **kwargs):
defaults = {'widget': forms.Textarea,
'initial': '',
'required':False}
defaults.update(kwargs)
return super(StringListProperty, self).get_form_field(**defaults)
def get_value_for_form(self, instance):
value = super(StringListProperty, self).get_value_for_form(instance)
if not value:
return None
if isinstance(value, list):
value = ', '.join(value)
return value
def make_value_from_form(self, value):
if not value:
return []
if isinstance(value, basestring):
value = util.get_tags(value.lower())
return value
class MultiEmailField(forms.Field):
def to_python(self, value):
if not value:
return []
return util.get_tags(value.lower())
def validate(self, value):
super(MultiEmailField, self).validate(value)
for email in value:
validate_email(email)
class Input(forms.widgets.Input):
__metaclass__ = djangoforms.monkey_patch
def build_attrs(self, extra_attrs=None, **kwargs):
attrs = super(Input, self).build_attrs(extra_attrs=extra_attrs, **kwargs)
_class = attrs.get('class', '')
if _class:
_class = "%s %s" % (_class, self.input_type)
else:
_class = self.input_type
attrs.update({'class':_class})
return attrs
class Form(forms.Form):
__metaclass__ = djangoforms.monkey_patch
class ModelForm(djangoforms.ModelForm):
__metaclass__ = djangoforms.monkey_patch
class Meta:
exclude = ['uuid', 'slug', 'created_at', 'updated_at', 'deleted_at']
class CategoryForm(ModelForm):
def save(self):
if self.instance is None:
params = {'slug':unicode(slugify(self.cleaned_data['name']))}
self.cleaned_data.update(params)
return super(CategoryForm, self).save()
class BaseForm(ModelForm):
def __init__(self, *args, **kwargs):
ModelForm.__init__(self, *args, **kwargs)
def clean(self):
data = self.cleaned_data
if 'name' in data:
data['slug'] = unicode(slugify(data['name']))
else:
raise forms.ValidationError(_("Name is required"))
return data
def save(self):
if self.instance is None:
params = {'uuid':util.generate_uuid()}
self.cleaned_data.update(params)
return super(BaseForm, self).save()
class BaseContentForm(BaseForm):
class Meta:
exclude = BaseForm.Meta.exclude + ['plain_description']
def __init__(self, *args, **kwargs):
BaseForm.__init__(self, *args, **kwargs)
self.fields['tags'].widget = forms.TextInput()
self.fields['meta_desc'].widget = forms.Textarea(attrs={'class':'ckexclude'})
def save(self):
plain_description = ''
if 'description' in self.cleaned_data:
plain_description = mark_safe(''.join(BeautifulSoup(self.cleaned_data['description']).findAll(text=True)))
params = {"plain_description":plain_description}
self.cleaned_data.update(params)
return BaseForm.save(self)
class CommentForm(ModelForm):
class Meta:
model = Comment
exclude = ModelForm.Meta.exclude + ['author', 'owner', 'content', 'content_type']
def __init__(self, *args, **kwargs):
self.extra_params = {}
if "extra_params" in kwargs:
self.extra_params = kwargs.pop("extra_params")
super(CommentForm, self).__init__(*args, **kwargs)
def save(self):
self.cleaned_data.update(self.extra_params)
return ModelForm.save(self)
class UnloggedCommentForm(CommentForm):
class Meta(CommentForm.Meta):
pass
captcha = ReCaptchaField()
class BlockNewForm(BaseForm):
class Meta:
model = Block
exclude = ['uuid', 'slug', 'args', 'deleted_at', 'params']
def __init__(self, *args, **kwargs):
super(BlockNewForm, self).__init__(*args, **kwargs)
self.fields['menus'].widget = forms.RadioSelect(choices=settings.BLOCK_MENUS_OPTION.items(),
attrs={'class':'radioselect'})
attrs={'disabled':'disabled'}
self.fields['visibility'].widget = SelectMultiple(choices=MenuItem.get_choices(), attrs=attrs)
self.fields['model'].widget = forms.Select(choices=Block.get_models_choices())
def save(self):
if not self.cleaned_data['visibility'] == '[]':
self.cleaned_data['visibility'] = util.get_tags(self.cleaned_data['visibility'])
else:
self.cleaned_data['visibility'] = []
return super(BlockNewForm, self).save()
class BlockForm(BaseForm):
class Meta:
model = Block
exclude = ['uuid', 'slug', 'model', 'args', 'deleted_at', 'params']
def __init__(self, *args, **kwargs):
super(BlockForm, self).__init__(*args, **kwargs)
self.fields['menus'].widget = forms.RadioSelect(choices=settings.BLOCK_MENUS_OPTION.items(),
attrs={'class':'radioselect'})
attrs = {}
if self.instance.menus == 'all' or self.instance.menus == 'none':
attrs={'disabled':'disabled'}
self.fields['visibility'].widget = SelectMultiple(choices=MenuItem.get_choices(), attrs=attrs)
def save(self):
if not self.cleaned_data['visibility'] == '[]':
self.cleaned_data['visibility'] = util.get_tags(self.cleaned_data['visibility'])
else:
self.cleaned_data['visibility'] = []
return super(BlockForm, self).save()
class StaticBlockForm(BlockForm):
static_content = forms.CharField(widget=forms.Textarea, label=_("Static Content"))
class Meta:
model = Block
exclude = ['uuid', 'slug', 'model', 'args', 'deleted_at']
def __init__(self, *args, **kwargs):
logging.info("****** common.forms.StaticBlockForm")
super(StaticBlockForm, self).__init__(*args, **kwargs)
logging.info(" instance: %s " % self.instance)
logging.info(" params: %s " % self.instance.params)
self.fields['static_content'].initial = self.instance.params.get('content', '')
self.fields.keyOrder = ['name', 'position', 'menus', 'visibility', 'order', 'static_content']
def save(self):
logging.info("** common.forms.StaticBlockForm")
block_ref = super(StaticBlockForm, self).save()
block_ref.params['content'] = self.cleaned_data['static_content']
block_ref.put()
return block_ref
class AdminSiteForm(Form):
site_name = forms.CharField()
meta_description = forms.CharField(widget=forms.Textarea)
meta_keywords = forms.CharField(widget=forms.Textarea)
theme = forms.ChoiceField(choices=Theme.get_choices())
def __init__(self, *args, **kwargs):
logging.info(">> AdminSiteForm")
super(AdminSiteForm, self).__init__(*args, **kwargs)
self.fields['site_name'].initial = ConfigData.get_configdata('SITE_NAME')
self.fields['meta_description'].initial = ConfigData.get_configdata('SITE_DESCRIPTION')
self.fields['meta_keywords'].initial = ConfigData.get_configdata('SITE_KEYWORDS')
self.fields['theme'].choices = Theme.get_choices()
self.fields['theme'].widget = forms.Select(choices=Theme.get_choices())
self.fields['theme'].initial = Theme.get_active().uuid
def save(self):
ConfigData.set_configdata('SITE_NAME', self.cleaned_data['site_name'])
ConfigData.set_configdata('SITE_DESCRIPTION', self.cleaned_data['meta_description'])
ConfigData.set_configdata('SITE_KEYWORDS', self.cleaned_data['meta_keywords'])
Theme.check_for_duplicated_active_themes(self.cleaned_data['theme'])
return True
class InstallForm(AdminSiteForm):
username = forms.RegexField(label=_("Admin Username"), max_length=30, regex=r'^\w+$',
error_message = _("This value must contain only letters, numbers and underscores."))
first_name = forms.CharField(label=_("First Name"))
last_name = forms.CharField(label=_("Last Name"))
email = forms.EmailField(label=_("Email"))
password1 = forms.CharField(label=_("Password"), widget=forms.PasswordInput, min_length=5, max_length=15)
password2 = forms.CharField(label=_("Password confirmation"), widget=forms.PasswordInput)
class Meta:
fields = ("site_name", "meta_description", "meta_keywords", "theme",
"username", "first_name", "last_name", "email")
def __init__(self, *args, **kwargs):
super(InstallForm, self).__init__(*args, **kwargs)
self.fields['username'].initial = 'admin'
def clean_username(self):
username = self.cleaned_data["username"].lower()
try:
User.get(username=username)
except UserDoesNotExist:
return username.lower()
raise forms.ValidationError(_("A user with that username already exists."))
def clean_email(self):
email = self.cleaned_data["email"]
try:
User.get(email=email)
except UserDoesNotExist:
return email
raise forms.ValidationError(_("A user with that email already exists."))
def clean_password2(self):
password1 = self.cleaned_data.get("password1", "")
password2 = self.cleaned_data["password2"]
if password1 != password2:
raise forms.ValidationError(_("The two password fields didn't match."))
return password2
def save(self):
super(InstallForm, self).save()
params = {"username":self.cleaned_data["username"].lower(),
"first_name":self.cleaned_data["first_name"],
"last_name":self.cleaned_data["last_name"],
"email":self.cleaned_data["email"],
"active":True,
"superuser":True,
"roles":['authenticated', 'administrator']}
user = User(**params)
user.code = util.generate_uuid()
user.set_password(self.cleaned_data["password1"])
user.save()
ConfigData.set_configdata('ADMIN_USERNAME', user.username)
return user
| get_form_field | identifier_name |
forms.py | # Copyright 2010 Jose Maria Zambrana Arze <contact@josezambrana.com>
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from google.appengine.ext.db import djangoforms |
from django import forms
from django.conf import settings
from django.core.validators import validate_email
from django.template.defaultfilters import slugify
from django.utils.translation import ugettext_lazy as _
from django.utils.safestring import mark_safe
from common.models import Block, MenuItem, Theme, ConfigData, Comment
from common.widgets import SelectMultiple, SelectDateTimeWidget
from common import util
from recaptcha_django import ReCaptchaField
from users.models import User, UserDoesNotExist
from beautifulsoup.BeautifulSoup import BeautifulSoup
class ReCaptchaField(ReCaptchaField):
__metaclass__ = djangoforms.monkey_patch
def widget_attrs(self, widget):
return {'theme':'clean'}
class SelectDateTimeField(forms.DateTimeField):
widget = SelectDateTimeWidget
class BlobWidget(forms.FileInput):
pass
class BlobField(forms.FileField):
widget = BlobWidget
class DateTimeProperty(djangoforms.DateTimeProperty):
__metaclass__ = djangoforms.monkey_patch
def get_form_field(self, **kwargs):
if self.name == 'deleted_at' or self.auto_now or self.auto_now_add:
return None
defaults = {'form_class': SelectDateTimeField}
defaults.update(kwargs)
return super(DateTimeProperty, self).get_form_field(**defaults)
class StringListProperty(djangoforms.StringListProperty):
__metaclass__ = djangoforms.monkey_patch
def get_form_field(self, **kwargs):
defaults = {'widget': forms.Textarea,
'initial': '',
'required':False}
defaults.update(kwargs)
return super(StringListProperty, self).get_form_field(**defaults)
def get_value_for_form(self, instance):
value = super(StringListProperty, self).get_value_for_form(instance)
if not value:
return None
if isinstance(value, list):
value = ', '.join(value)
return value
def make_value_from_form(self, value):
if not value:
return []
if isinstance(value, basestring):
value = util.get_tags(value.lower())
return value
class MultiEmailField(forms.Field):
def to_python(self, value):
if not value:
return []
return util.get_tags(value.lower())
def validate(self, value):
super(MultiEmailField, self).validate(value)
for email in value:
validate_email(email)
class Input(forms.widgets.Input):
__metaclass__ = djangoforms.monkey_patch
def build_attrs(self, extra_attrs=None, **kwargs):
attrs = super(Input, self).build_attrs(extra_attrs=extra_attrs, **kwargs)
_class = attrs.get('class', '')
if _class:
_class = "%s %s" % (_class, self.input_type)
else:
_class = self.input_type
attrs.update({'class':_class})
return attrs
class Form(forms.Form):
__metaclass__ = djangoforms.monkey_patch
class ModelForm(djangoforms.ModelForm):
__metaclass__ = djangoforms.monkey_patch
class Meta:
exclude = ['uuid', 'slug', 'created_at', 'updated_at', 'deleted_at']
class CategoryForm(ModelForm):
def save(self):
if self.instance is None:
params = {'slug':unicode(slugify(self.cleaned_data['name']))}
self.cleaned_data.update(params)
return super(CategoryForm, self).save()
class BaseForm(ModelForm):
def __init__(self, *args, **kwargs):
ModelForm.__init__(self, *args, **kwargs)
def clean(self):
data = self.cleaned_data
if 'name' in data:
data['slug'] = unicode(slugify(data['name']))
else:
raise forms.ValidationError(_("Name is required"))
return data
def save(self):
if self.instance is None:
params = {'uuid':util.generate_uuid()}
self.cleaned_data.update(params)
return super(BaseForm, self).save()
class BaseContentForm(BaseForm):
class Meta:
exclude = BaseForm.Meta.exclude + ['plain_description']
def __init__(self, *args, **kwargs):
BaseForm.__init__(self, *args, **kwargs)
self.fields['tags'].widget = forms.TextInput()
self.fields['meta_desc'].widget = forms.Textarea(attrs={'class':'ckexclude'})
def save(self):
plain_description = ''
if 'description' in self.cleaned_data:
plain_description = mark_safe(''.join(BeautifulSoup(self.cleaned_data['description']).findAll(text=True)))
params = {"plain_description":plain_description}
self.cleaned_data.update(params)
return BaseForm.save(self)
class CommentForm(ModelForm):
class Meta:
model = Comment
exclude = ModelForm.Meta.exclude + ['author', 'owner', 'content', 'content_type']
def __init__(self, *args, **kwargs):
self.extra_params = {}
if "extra_params" in kwargs:
self.extra_params = kwargs.pop("extra_params")
super(CommentForm, self).__init__(*args, **kwargs)
def save(self):
self.cleaned_data.update(self.extra_params)
return ModelForm.save(self)
class UnloggedCommentForm(CommentForm):
class Meta(CommentForm.Meta):
pass
captcha = ReCaptchaField()
class BlockNewForm(BaseForm):
class Meta:
model = Block
exclude = ['uuid', 'slug', 'args', 'deleted_at', 'params']
def __init__(self, *args, **kwargs):
super(BlockNewForm, self).__init__(*args, **kwargs)
self.fields['menus'].widget = forms.RadioSelect(choices=settings.BLOCK_MENUS_OPTION.items(),
attrs={'class':'radioselect'})
attrs={'disabled':'disabled'}
self.fields['visibility'].widget = SelectMultiple(choices=MenuItem.get_choices(), attrs=attrs)
self.fields['model'].widget = forms.Select(choices=Block.get_models_choices())
def save(self):
if not self.cleaned_data['visibility'] == '[]':
self.cleaned_data['visibility'] = util.get_tags(self.cleaned_data['visibility'])
else:
self.cleaned_data['visibility'] = []
return super(BlockNewForm, self).save()
class BlockForm(BaseForm):
class Meta:
model = Block
exclude = ['uuid', 'slug', 'model', 'args', 'deleted_at', 'params']
def __init__(self, *args, **kwargs):
super(BlockForm, self).__init__(*args, **kwargs)
self.fields['menus'].widget = forms.RadioSelect(choices=settings.BLOCK_MENUS_OPTION.items(),
attrs={'class':'radioselect'})
attrs = {}
if self.instance.menus == 'all' or self.instance.menus == 'none':
attrs={'disabled':'disabled'}
self.fields['visibility'].widget = SelectMultiple(choices=MenuItem.get_choices(), attrs=attrs)
def save(self):
if not self.cleaned_data['visibility'] == '[]':
self.cleaned_data['visibility'] = util.get_tags(self.cleaned_data['visibility'])
else:
self.cleaned_data['visibility'] = []
return super(BlockForm, self).save()
class StaticBlockForm(BlockForm):
static_content = forms.CharField(widget=forms.Textarea, label=_("Static Content"))
class Meta:
model = Block
exclude = ['uuid', 'slug', 'model', 'args', 'deleted_at']
def __init__(self, *args, **kwargs):
logging.info("****** common.forms.StaticBlockForm")
super(StaticBlockForm, self).__init__(*args, **kwargs)
logging.info(" instance: %s " % self.instance)
logging.info(" params: %s " % self.instance.params)
self.fields['static_content'].initial = self.instance.params.get('content', '')
self.fields.keyOrder = ['name', 'position', 'menus', 'visibility', 'order', 'static_content']
def save(self):
logging.info("** common.forms.StaticBlockForm")
block_ref = super(StaticBlockForm, self).save()
block_ref.params['content'] = self.cleaned_data['static_content']
block_ref.put()
return block_ref
class AdminSiteForm(Form):
site_name = forms.CharField()
meta_description = forms.CharField(widget=forms.Textarea)
meta_keywords = forms.CharField(widget=forms.Textarea)
theme = forms.ChoiceField(choices=Theme.get_choices())
def __init__(self, *args, **kwargs):
logging.info(">> AdminSiteForm")
super(AdminSiteForm, self).__init__(*args, **kwargs)
self.fields['site_name'].initial = ConfigData.get_configdata('SITE_NAME')
self.fields['meta_description'].initial = ConfigData.get_configdata('SITE_DESCRIPTION')
self.fields['meta_keywords'].initial = ConfigData.get_configdata('SITE_KEYWORDS')
self.fields['theme'].choices = Theme.get_choices()
self.fields['theme'].widget = forms.Select(choices=Theme.get_choices())
self.fields['theme'].initial = Theme.get_active().uuid
def save(self):
ConfigData.set_configdata('SITE_NAME', self.cleaned_data['site_name'])
ConfigData.set_configdata('SITE_DESCRIPTION', self.cleaned_data['meta_description'])
ConfigData.set_configdata('SITE_KEYWORDS', self.cleaned_data['meta_keywords'])
Theme.check_for_duplicated_active_themes(self.cleaned_data['theme'])
return True
class InstallForm(AdminSiteForm):
username = forms.RegexField(label=_("Admin Username"), max_length=30, regex=r'^\w+$',
error_message = _("This value must contain only letters, numbers and underscores."))
first_name = forms.CharField(label=_("First Name"))
last_name = forms.CharField(label=_("Last Name"))
email = forms.EmailField(label=_("Email"))
password1 = forms.CharField(label=_("Password"), widget=forms.PasswordInput, min_length=5, max_length=15)
password2 = forms.CharField(label=_("Password confirmation"), widget=forms.PasswordInput)
class Meta:
fields = ("site_name", "meta_description", "meta_keywords", "theme",
"username", "first_name", "last_name", "email")
def __init__(self, *args, **kwargs):
super(InstallForm, self).__init__(*args, **kwargs)
self.fields['username'].initial = 'admin'
def clean_username(self):
username = self.cleaned_data["username"].lower()
try:
User.get(username=username)
except UserDoesNotExist:
return username.lower()
raise forms.ValidationError(_("A user with that username already exists."))
def clean_email(self):
email = self.cleaned_data["email"]
try:
User.get(email=email)
except UserDoesNotExist:
return email
raise forms.ValidationError(_("A user with that email already exists."))
def clean_password2(self):
password1 = self.cleaned_data.get("password1", "")
password2 = self.cleaned_data["password2"]
if password1 != password2:
raise forms.ValidationError(_("The two password fields didn't match."))
return password2
def save(self):
super(InstallForm, self).save()
params = {"username":self.cleaned_data["username"].lower(),
"first_name":self.cleaned_data["first_name"],
"last_name":self.cleaned_data["last_name"],
"email":self.cleaned_data["email"],
"active":True,
"superuser":True,
"roles":['authenticated', 'administrator']}
user = User(**params)
user.code = util.generate_uuid()
user.set_password(self.cleaned_data["password1"])
user.save()
ConfigData.set_configdata('ADMIN_USERNAME', user.username)
return user |
import logging | random_line_split |
forms.py | # Copyright 2010 Jose Maria Zambrana Arze <contact@josezambrana.com>
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from google.appengine.ext.db import djangoforms
import logging
from django import forms
from django.conf import settings
from django.core.validators import validate_email
from django.template.defaultfilters import slugify
from django.utils.translation import ugettext_lazy as _
from django.utils.safestring import mark_safe
from common.models import Block, MenuItem, Theme, ConfigData, Comment
from common.widgets import SelectMultiple, SelectDateTimeWidget
from common import util
from recaptcha_django import ReCaptchaField
from users.models import User, UserDoesNotExist
from beautifulsoup.BeautifulSoup import BeautifulSoup
class ReCaptchaField(ReCaptchaField):
__metaclass__ = djangoforms.monkey_patch
def widget_attrs(self, widget):
return {'theme':'clean'}
class SelectDateTimeField(forms.DateTimeField):
widget = SelectDateTimeWidget
class BlobWidget(forms.FileInput):
pass
class BlobField(forms.FileField):
widget = BlobWidget
class DateTimeProperty(djangoforms.DateTimeProperty):
__metaclass__ = djangoforms.monkey_patch
def get_form_field(self, **kwargs):
if self.name == 'deleted_at' or self.auto_now or self.auto_now_add:
return None
defaults = {'form_class': SelectDateTimeField}
defaults.update(kwargs)
return super(DateTimeProperty, self).get_form_field(**defaults)
class StringListProperty(djangoforms.StringListProperty):
__metaclass__ = djangoforms.monkey_patch
def get_form_field(self, **kwargs):
defaults = {'widget': forms.Textarea,
'initial': '',
'required':False}
defaults.update(kwargs)
return super(StringListProperty, self).get_form_field(**defaults)
def get_value_for_form(self, instance):
value = super(StringListProperty, self).get_value_for_form(instance)
if not value:
return None
if isinstance(value, list):
value = ', '.join(value)
return value
def make_value_from_form(self, value):
if not value:
return []
if isinstance(value, basestring):
value = util.get_tags(value.lower())
return value
class MultiEmailField(forms.Field):
def to_python(self, value):
if not value:
return []
return util.get_tags(value.lower())
def validate(self, value):
super(MultiEmailField, self).validate(value)
for email in value:
validate_email(email)
class Input(forms.widgets.Input):
__metaclass__ = djangoforms.monkey_patch
def build_attrs(self, extra_attrs=None, **kwargs):
attrs = super(Input, self).build_attrs(extra_attrs=extra_attrs, **kwargs)
_class = attrs.get('class', '')
if _class:
_class = "%s %s" % (_class, self.input_type)
else:
_class = self.input_type
attrs.update({'class':_class})
return attrs
class Form(forms.Form):
__metaclass__ = djangoforms.monkey_patch
class ModelForm(djangoforms.ModelForm):
__metaclass__ = djangoforms.monkey_patch
class Meta:
exclude = ['uuid', 'slug', 'created_at', 'updated_at', 'deleted_at']
class CategoryForm(ModelForm):
def save(self):
if self.instance is None:
params = {'slug':unicode(slugify(self.cleaned_data['name']))}
self.cleaned_data.update(params)
return super(CategoryForm, self).save()
class BaseForm(ModelForm):
def __init__(self, *args, **kwargs):
ModelForm.__init__(self, *args, **kwargs)
def clean(self):
data = self.cleaned_data
if 'name' in data:
data['slug'] = unicode(slugify(data['name']))
else:
raise forms.ValidationError(_("Name is required"))
return data
def save(self):
if self.instance is None:
params = {'uuid':util.generate_uuid()}
self.cleaned_data.update(params)
return super(BaseForm, self).save()
class BaseContentForm(BaseForm):
class Meta:
exclude = BaseForm.Meta.exclude + ['plain_description']
def __init__(self, *args, **kwargs):
BaseForm.__init__(self, *args, **kwargs)
self.fields['tags'].widget = forms.TextInput()
self.fields['meta_desc'].widget = forms.Textarea(attrs={'class':'ckexclude'})
def save(self):
plain_description = ''
if 'description' in self.cleaned_data:
plain_description = mark_safe(''.join(BeautifulSoup(self.cleaned_data['description']).findAll(text=True)))
params = {"plain_description":plain_description}
self.cleaned_data.update(params)
return BaseForm.save(self)
class CommentForm(ModelForm):
|
class UnloggedCommentForm(CommentForm):
class Meta(CommentForm.Meta):
pass
captcha = ReCaptchaField()
class BlockNewForm(BaseForm):
class Meta:
model = Block
exclude = ['uuid', 'slug', 'args', 'deleted_at', 'params']
def __init__(self, *args, **kwargs):
super(BlockNewForm, self).__init__(*args, **kwargs)
self.fields['menus'].widget = forms.RadioSelect(choices=settings.BLOCK_MENUS_OPTION.items(),
attrs={'class':'radioselect'})
attrs={'disabled':'disabled'}
self.fields['visibility'].widget = SelectMultiple(choices=MenuItem.get_choices(), attrs=attrs)
self.fields['model'].widget = forms.Select(choices=Block.get_models_choices())
def save(self):
if not self.cleaned_data['visibility'] == '[]':
self.cleaned_data['visibility'] = util.get_tags(self.cleaned_data['visibility'])
else:
self.cleaned_data['visibility'] = []
return super(BlockNewForm, self).save()
class BlockForm(BaseForm):
class Meta:
model = Block
exclude = ['uuid', 'slug', 'model', 'args', 'deleted_at', 'params']
def __init__(self, *args, **kwargs):
super(BlockForm, self).__init__(*args, **kwargs)
self.fields['menus'].widget = forms.RadioSelect(choices=settings.BLOCK_MENUS_OPTION.items(),
attrs={'class':'radioselect'})
attrs = {}
if self.instance.menus == 'all' or self.instance.menus == 'none':
attrs={'disabled':'disabled'}
self.fields['visibility'].widget = SelectMultiple(choices=MenuItem.get_choices(), attrs=attrs)
def save(self):
if not self.cleaned_data['visibility'] == '[]':
self.cleaned_data['visibility'] = util.get_tags(self.cleaned_data['visibility'])
else:
self.cleaned_data['visibility'] = []
return super(BlockForm, self).save()
class StaticBlockForm(BlockForm):
static_content = forms.CharField(widget=forms.Textarea, label=_("Static Content"))
class Meta:
model = Block
exclude = ['uuid', 'slug', 'model', 'args', 'deleted_at']
def __init__(self, *args, **kwargs):
logging.info("****** common.forms.StaticBlockForm")
super(StaticBlockForm, self).__init__(*args, **kwargs)
logging.info(" instance: %s " % self.instance)
logging.info(" params: %s " % self.instance.params)
self.fields['static_content'].initial = self.instance.params.get('content', '')
self.fields.keyOrder = ['name', 'position', 'menus', 'visibility', 'order', 'static_content']
def save(self):
logging.info("** common.forms.StaticBlockForm")
block_ref = super(StaticBlockForm, self).save()
block_ref.params['content'] = self.cleaned_data['static_content']
block_ref.put()
return block_ref
class AdminSiteForm(Form):
site_name = forms.CharField()
meta_description = forms.CharField(widget=forms.Textarea)
meta_keywords = forms.CharField(widget=forms.Textarea)
theme = forms.ChoiceField(choices=Theme.get_choices())
def __init__(self, *args, **kwargs):
logging.info(">> AdminSiteForm")
super(AdminSiteForm, self).__init__(*args, **kwargs)
self.fields['site_name'].initial = ConfigData.get_configdata('SITE_NAME')
self.fields['meta_description'].initial = ConfigData.get_configdata('SITE_DESCRIPTION')
self.fields['meta_keywords'].initial = ConfigData.get_configdata('SITE_KEYWORDS')
self.fields['theme'].choices = Theme.get_choices()
self.fields['theme'].widget = forms.Select(choices=Theme.get_choices())
self.fields['theme'].initial = Theme.get_active().uuid
def save(self):
ConfigData.set_configdata('SITE_NAME', self.cleaned_data['site_name'])
ConfigData.set_configdata('SITE_DESCRIPTION', self.cleaned_data['meta_description'])
ConfigData.set_configdata('SITE_KEYWORDS', self.cleaned_data['meta_keywords'])
Theme.check_for_duplicated_active_themes(self.cleaned_data['theme'])
return True
class InstallForm(AdminSiteForm):
username = forms.RegexField(label=_("Admin Username"), max_length=30, regex=r'^\w+$',
error_message = _("This value must contain only letters, numbers and underscores."))
first_name = forms.CharField(label=_("First Name"))
last_name = forms.CharField(label=_("Last Name"))
email = forms.EmailField(label=_("Email"))
password1 = forms.CharField(label=_("Password"), widget=forms.PasswordInput, min_length=5, max_length=15)
password2 = forms.CharField(label=_("Password confirmation"), widget=forms.PasswordInput)
class Meta:
fields = ("site_name", "meta_description", "meta_keywords", "theme",
"username", "first_name", "last_name", "email")
def __init__(self, *args, **kwargs):
super(InstallForm, self).__init__(*args, **kwargs)
self.fields['username'].initial = 'admin'
def clean_username(self):
username = self.cleaned_data["username"].lower()
try:
User.get(username=username)
except UserDoesNotExist:
return username.lower()
raise forms.ValidationError(_("A user with that username already exists."))
def clean_email(self):
email = self.cleaned_data["email"]
try:
User.get(email=email)
except UserDoesNotExist:
return email
raise forms.ValidationError(_("A user with that email already exists."))
def clean_password2(self):
password1 = self.cleaned_data.get("password1", "")
password2 = self.cleaned_data["password2"]
if password1 != password2:
raise forms.ValidationError(_("The two password fields didn't match."))
return password2
def save(self):
super(InstallForm, self).save()
params = {"username":self.cleaned_data["username"].lower(),
"first_name":self.cleaned_data["first_name"],
"last_name":self.cleaned_data["last_name"],
"email":self.cleaned_data["email"],
"active":True,
"superuser":True,
"roles":['authenticated', 'administrator']}
user = User(**params)
user.code = util.generate_uuid()
user.set_password(self.cleaned_data["password1"])
user.save()
ConfigData.set_configdata('ADMIN_USERNAME', user.username)
return user
| class Meta:
model = Comment
exclude = ModelForm.Meta.exclude + ['author', 'owner', 'content', 'content_type']
def __init__(self, *args, **kwargs):
self.extra_params = {}
if "extra_params" in kwargs:
self.extra_params = kwargs.pop("extra_params")
super(CommentForm, self).__init__(*args, **kwargs)
def save(self):
self.cleaned_data.update(self.extra_params)
return ModelForm.save(self) | identifier_body |
forms.py | # Copyright 2010 Jose Maria Zambrana Arze <contact@josezambrana.com>
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from google.appengine.ext.db import djangoforms
import logging
from django import forms
from django.conf import settings
from django.core.validators import validate_email
from django.template.defaultfilters import slugify
from django.utils.translation import ugettext_lazy as _
from django.utils.safestring import mark_safe
from common.models import Block, MenuItem, Theme, ConfigData, Comment
from common.widgets import SelectMultiple, SelectDateTimeWidget
from common import util
from recaptcha_django import ReCaptchaField
from users.models import User, UserDoesNotExist
from beautifulsoup.BeautifulSoup import BeautifulSoup
class ReCaptchaField(ReCaptchaField):
__metaclass__ = djangoforms.monkey_patch
def widget_attrs(self, widget):
return {'theme':'clean'}
class SelectDateTimeField(forms.DateTimeField):
widget = SelectDateTimeWidget
class BlobWidget(forms.FileInput):
pass
class BlobField(forms.FileField):
widget = BlobWidget
class DateTimeProperty(djangoforms.DateTimeProperty):
__metaclass__ = djangoforms.monkey_patch
def get_form_field(self, **kwargs):
if self.name == 'deleted_at' or self.auto_now or self.auto_now_add:
return None
defaults = {'form_class': SelectDateTimeField}
defaults.update(kwargs)
return super(DateTimeProperty, self).get_form_field(**defaults)
class StringListProperty(djangoforms.StringListProperty):
__metaclass__ = djangoforms.monkey_patch
def get_form_field(self, **kwargs):
defaults = {'widget': forms.Textarea,
'initial': '',
'required':False}
defaults.update(kwargs)
return super(StringListProperty, self).get_form_field(**defaults)
def get_value_for_form(self, instance):
value = super(StringListProperty, self).get_value_for_form(instance)
if not value:
return None
if isinstance(value, list):
value = ', '.join(value)
return value
def make_value_from_form(self, value):
if not value:
|
if isinstance(value, basestring):
value = util.get_tags(value.lower())
return value
class MultiEmailField(forms.Field):
def to_python(self, value):
if not value:
return []
return util.get_tags(value.lower())
def validate(self, value):
super(MultiEmailField, self).validate(value)
for email in value:
validate_email(email)
class Input(forms.widgets.Input):
__metaclass__ = djangoforms.monkey_patch
def build_attrs(self, extra_attrs=None, **kwargs):
attrs = super(Input, self).build_attrs(extra_attrs=extra_attrs, **kwargs)
_class = attrs.get('class', '')
if _class:
_class = "%s %s" % (_class, self.input_type)
else:
_class = self.input_type
attrs.update({'class':_class})
return attrs
class Form(forms.Form):
__metaclass__ = djangoforms.monkey_patch
class ModelForm(djangoforms.ModelForm):
__metaclass__ = djangoforms.monkey_patch
class Meta:
exclude = ['uuid', 'slug', 'created_at', 'updated_at', 'deleted_at']
class CategoryForm(ModelForm):
def save(self):
if self.instance is None:
params = {'slug':unicode(slugify(self.cleaned_data['name']))}
self.cleaned_data.update(params)
return super(CategoryForm, self).save()
class BaseForm(ModelForm):
def __init__(self, *args, **kwargs):
ModelForm.__init__(self, *args, **kwargs)
def clean(self):
data = self.cleaned_data
if 'name' in data:
data['slug'] = unicode(slugify(data['name']))
else:
raise forms.ValidationError(_("Name is required"))
return data
def save(self):
if self.instance is None:
params = {'uuid':util.generate_uuid()}
self.cleaned_data.update(params)
return super(BaseForm, self).save()
class BaseContentForm(BaseForm):
class Meta:
exclude = BaseForm.Meta.exclude + ['plain_description']
def __init__(self, *args, **kwargs):
BaseForm.__init__(self, *args, **kwargs)
self.fields['tags'].widget = forms.TextInput()
self.fields['meta_desc'].widget = forms.Textarea(attrs={'class':'ckexclude'})
def save(self):
plain_description = ''
if 'description' in self.cleaned_data:
plain_description = mark_safe(''.join(BeautifulSoup(self.cleaned_data['description']).findAll(text=True)))
params = {"plain_description":plain_description}
self.cleaned_data.update(params)
return BaseForm.save(self)
class CommentForm(ModelForm):
class Meta:
model = Comment
exclude = ModelForm.Meta.exclude + ['author', 'owner', 'content', 'content_type']
def __init__(self, *args, **kwargs):
self.extra_params = {}
if "extra_params" in kwargs:
self.extra_params = kwargs.pop("extra_params")
super(CommentForm, self).__init__(*args, **kwargs)
def save(self):
self.cleaned_data.update(self.extra_params)
return ModelForm.save(self)
class UnloggedCommentForm(CommentForm):
class Meta(CommentForm.Meta):
pass
captcha = ReCaptchaField()
class BlockNewForm(BaseForm):
class Meta:
model = Block
exclude = ['uuid', 'slug', 'args', 'deleted_at', 'params']
def __init__(self, *args, **kwargs):
super(BlockNewForm, self).__init__(*args, **kwargs)
self.fields['menus'].widget = forms.RadioSelect(choices=settings.BLOCK_MENUS_OPTION.items(),
attrs={'class':'radioselect'})
attrs={'disabled':'disabled'}
self.fields['visibility'].widget = SelectMultiple(choices=MenuItem.get_choices(), attrs=attrs)
self.fields['model'].widget = forms.Select(choices=Block.get_models_choices())
def save(self):
if not self.cleaned_data['visibility'] == '[]':
self.cleaned_data['visibility'] = util.get_tags(self.cleaned_data['visibility'])
else:
self.cleaned_data['visibility'] = []
return super(BlockNewForm, self).save()
class BlockForm(BaseForm):
class Meta:
model = Block
exclude = ['uuid', 'slug', 'model', 'args', 'deleted_at', 'params']
def __init__(self, *args, **kwargs):
super(BlockForm, self).__init__(*args, **kwargs)
self.fields['menus'].widget = forms.RadioSelect(choices=settings.BLOCK_MENUS_OPTION.items(),
attrs={'class':'radioselect'})
attrs = {}
if self.instance.menus == 'all' or self.instance.menus == 'none':
attrs={'disabled':'disabled'}
self.fields['visibility'].widget = SelectMultiple(choices=MenuItem.get_choices(), attrs=attrs)
def save(self):
if not self.cleaned_data['visibility'] == '[]':
self.cleaned_data['visibility'] = util.get_tags(self.cleaned_data['visibility'])
else:
self.cleaned_data['visibility'] = []
return super(BlockForm, self).save()
class StaticBlockForm(BlockForm):
static_content = forms.CharField(widget=forms.Textarea, label=_("Static Content"))
class Meta:
model = Block
exclude = ['uuid', 'slug', 'model', 'args', 'deleted_at']
def __init__(self, *args, **kwargs):
logging.info("****** common.forms.StaticBlockForm")
super(StaticBlockForm, self).__init__(*args, **kwargs)
logging.info(" instance: %s " % self.instance)
logging.info(" params: %s " % self.instance.params)
self.fields['static_content'].initial = self.instance.params.get('content', '')
self.fields.keyOrder = ['name', 'position', 'menus', 'visibility', 'order', 'static_content']
def save(self):
logging.info("** common.forms.StaticBlockForm")
block_ref = super(StaticBlockForm, self).save()
block_ref.params['content'] = self.cleaned_data['static_content']
block_ref.put()
return block_ref
class AdminSiteForm(Form):
site_name = forms.CharField()
meta_description = forms.CharField(widget=forms.Textarea)
meta_keywords = forms.CharField(widget=forms.Textarea)
theme = forms.ChoiceField(choices=Theme.get_choices())
def __init__(self, *args, **kwargs):
logging.info(">> AdminSiteForm")
super(AdminSiteForm, self).__init__(*args, **kwargs)
self.fields['site_name'].initial = ConfigData.get_configdata('SITE_NAME')
self.fields['meta_description'].initial = ConfigData.get_configdata('SITE_DESCRIPTION')
self.fields['meta_keywords'].initial = ConfigData.get_configdata('SITE_KEYWORDS')
self.fields['theme'].choices = Theme.get_choices()
self.fields['theme'].widget = forms.Select(choices=Theme.get_choices())
self.fields['theme'].initial = Theme.get_active().uuid
def save(self):
ConfigData.set_configdata('SITE_NAME', self.cleaned_data['site_name'])
ConfigData.set_configdata('SITE_DESCRIPTION', self.cleaned_data['meta_description'])
ConfigData.set_configdata('SITE_KEYWORDS', self.cleaned_data['meta_keywords'])
Theme.check_for_duplicated_active_themes(self.cleaned_data['theme'])
return True
class InstallForm(AdminSiteForm):
username = forms.RegexField(label=_("Admin Username"), max_length=30, regex=r'^\w+$',
error_message = _("This value must contain only letters, numbers and underscores."))
first_name = forms.CharField(label=_("First Name"))
last_name = forms.CharField(label=_("Last Name"))
email = forms.EmailField(label=_("Email"))
password1 = forms.CharField(label=_("Password"), widget=forms.PasswordInput, min_length=5, max_length=15)
password2 = forms.CharField(label=_("Password confirmation"), widget=forms.PasswordInput)
class Meta:
fields = ("site_name", "meta_description", "meta_keywords", "theme",
"username", "first_name", "last_name", "email")
def __init__(self, *args, **kwargs):
super(InstallForm, self).__init__(*args, **kwargs)
self.fields['username'].initial = 'admin'
def clean_username(self):
username = self.cleaned_data["username"].lower()
try:
User.get(username=username)
except UserDoesNotExist:
return username.lower()
raise forms.ValidationError(_("A user with that username already exists."))
def clean_email(self):
email = self.cleaned_data["email"]
try:
User.get(email=email)
except UserDoesNotExist:
return email
raise forms.ValidationError(_("A user with that email already exists."))
def clean_password2(self):
password1 = self.cleaned_data.get("password1", "")
password2 = self.cleaned_data["password2"]
if password1 != password2:
raise forms.ValidationError(_("The two password fields didn't match."))
return password2
def save(self):
super(InstallForm, self).save()
params = {"username":self.cleaned_data["username"].lower(),
"first_name":self.cleaned_data["first_name"],
"last_name":self.cleaned_data["last_name"],
"email":self.cleaned_data["email"],
"active":True,
"superuser":True,
"roles":['authenticated', 'administrator']}
user = User(**params)
user.code = util.generate_uuid()
user.set_password(self.cleaned_data["password1"])
user.save()
ConfigData.set_configdata('ADMIN_USERNAME', user.username)
return user
| return [] | conditional_block |
mod.rs | mod boundingbox;
mod material;
mod shape;
use crate::config::SimulationConfig;
use crate::fields::ScalarField;
use crate::greenfunctions::cosinebasis::{CosineBasis, Direction};
use crate::world::boundingbox::BoundingBox;
use crate::world::shape::Shape;
use nalgebra::*;
use pbr::ProgressBar;
use rayon::iter::*;
use serde::Deserialize;
use snafu::Snafu;
use std::io::Stdout;
use std::sync::{Arc, Mutex};
/// A struct representing the world.
#[derive(PartialEq, Clone, Debug, Deserialize)]
pub struct World {
/// The grid size corresponding to this world.
size: Vector3<usize>,
/// The list with the different shapes.
objects: Vec<Shape>,
/// The simulation configuration.
simulation_config: SimulationConfig,
#[serde(skip)]
use_progress_bar: bool,
}
/// A struct that iterates over the different forces of the objects.
pub struct ForceIterator<'a> {
i: usize,
world: &'a World,
}
impl<'a> Iterator for ForceIterator<'a> {
type Item = Vector3<f32>;
fn next(&mut self) -> Option<Vector3<f32>> {
if self.i < self.world.objects.len() {
let force = self.world.force_on(self.i);
self.i += 1;
Some(force)
} else {
None
}
}
}
/// These errors can be thrown when validating a world.
#[derive(Debug, Snafu)]
pub enum WorldError {
/// An error indicating that one of the shapes is too close too the edge, causing the bounding
/// box to cross the boundary.
#[snafu(display("shape {} too close to edge", index))]
ShapeTooCloseToEdge {
/// The index of the violating object.
index: usize,
},
/// An error indicating that the bounding boxes of two objects in this world intersect and
/// and therefore this world is invalid.
#[snafu(display("bounding boxes of shapes {} and {} intersect", index_1, index_2))]
ShapesIntersect {
/// The index of the first object intersecting with the second.
index_1: usize,
/// The index of the second object intersecting with the first.
index_2: usize,
},
}
impl World {
/// Enable or disable the progress bar for the simulation.
pub fn set_progress_bar(&mut self, enable: bool) {
self.use_progress_bar = enable;
}
/// Obtain a force iterator for all objects in this world.
pub fn forces(&self) -> ForceIterator<'_> {
ForceIterator { i: 0, world: &self }
}
/// Compute the force on the `i`'th object.
pub fn force_on(&self, i: usize) -> Vector3<f32> |
/// This function validates the geometry of the world. The function should be called, because it
/// guarantees overflows later on in the simulation.
///
/// # Errors
/// - If any of the shapes is too close to the world border, the simulation can't be run and a
/// `WorldError::ShapeTooCloseToEdge` will be returned. To fix this, move the object or increase
/// the grid size.
///
/// - If any of the objects are too close too eachother, their boundingboxes might intersect and
/// the results will be invalid. If this is the case, a `WorldError::ShapesIntersect` will be
/// returned. The violating shape indexes will be contained within. To fix this, move one or
/// both of the objects.
pub fn validate(&self) -> Result<(), WorldError> {
let bbox_world = BoundingBox::new(0, 0, 0, self.size.x, self.size.y, self.size.z);
let expanded_boxes = self
.objects
.iter()
.enumerate()
.map(|(index, obj)| {
obj.bbox()
.expanded(2)
.map_err(|_| WorldError::ShapeTooCloseToEdge { index })
})
.collect::<Result<Vec<_>, _>>()?;
for (i, bbox_1) in expanded_boxes.iter().enumerate() {
// Check for intersection with world
if !bbox_1.inside(&bbox_world) {
return Err(WorldError::ShapeTooCloseToEdge { index: i });
}
// Check for intersection with other objects
for (j, bbox_2) in expanded_boxes.iter().enumerate() {
if i < j && bbox_1.intersects(&bbox_2) {
return Err(WorldError::ShapesIntersect {
index_1: i,
index_2: j,
});
}
}
}
Ok(())
}
/// Performs a recursive integration between two frequencies. If the difference between the
/// midpoint force and the linear interpolation is too large, both sides of the domain will use
/// this function recursively to integrate the force.
pub fn integrate_force_between_frequencies(
&self,
i: usize,
start_frequency: f32,
end_frequency: f32,
start_value: Vector3<f32>,
end_value: Vector3<f32>,
max: f32,
) -> Vector3<f32> {
// Do a recursive integration. The function should be smooth.
let middle_frequency = 0.5 * (start_frequency + end_frequency);
let middle_value = self.force_on_for_freq(i, middle_frequency);
let average = (start_value + end_value) / 2.0;
if (average - middle_value).norm() * (end_frequency - start_frequency)
< self.simulation_config.frequency_threshold * max
{
// The change in area from the middle value vs extrapolation is less than the threshold
0.5 * (start_value + 2.0 * middle_value + end_value) * (end_frequency - start_frequency)
} else {
self.integrate_force_between_frequencies(
i,
start_frequency,
middle_frequency,
start_value,
middle_value,
max,
) + self.integrate_force_between_frequencies(
i,
middle_frequency,
end_frequency,
middle_value,
end_value,
max,
)
}
}
/// Compute the force on object `i` for a certain `frequency`. This method will also subtract
/// the error forces due to quantization by subtracting the force due to single objects.
fn force_on_for_freq(&self, i: usize, frequency: f32) -> Vector3<f32> {
// Progress bar
let bbox = &self.objects[i].bbox();
let dx = bbox.x1 - bbox.x0 + 4;
let dy = bbox.y1 - bbox.y0 + 4;
let dz = bbox.z1 - bbox.z0 + 4;
let count = 2 * (dx * dy + dy * dz + dz * dx) * (1 + self.objects.len());
let progress_bar = if self.use_progress_bar {
let progress_bar = Arc::new(Mutex::new(ProgressBar::new(count as u64)));
progress_bar.lock().unwrap().format("[=>~]");
progress_bar.lock().unwrap().tick();
Some(progress_bar)
} else {
None
};
let perm_all_geom = &self.permittivity_field_all_geometry(frequency);
let mut total_force =
self.force_on_for_freq_and_geometry(frequency, perm_all_geom, bbox, &progress_bar);
// Discretization gives rise to forces of an object on itself. Removing these gives more
// accurate results.
for other in &self.objects {
let perm = &self.permittivity_field(frequency, &[*other]);
total_force -=
self.force_on_for_freq_and_geometry(frequency, perm, bbox, &progress_bar);
}
if let Some(progress_bar) = progress_bar {
progress_bar.lock().unwrap().finish_println("");
}
println!(
"Force for frequency {}: ({}, {}, {})",
frequency, total_force.x, total_force.y, total_force.z
);
total_force
}
/// Compute the force on the geometry inside `BoundingBox`, for the given permittivity field
/// `perm` and `BoundingBox` `bbox`.
fn force_on_for_freq_and_geometry(
&self,
frequency: f32,
perm: &ScalarField,
bbox: &BoundingBox,
progress_bar: &Option<Arc<Mutex<ProgressBar<Stdout>>>>,
) -> Vector3<f32> {
(0..6)
.into_par_iter()
.map(|face| {
(match face {
0 => CosineBasis::new(
Point3::new(bbox.x0 - 2, bbox.y0 - 2, bbox.z0 - 2),
Point3::new(bbox.x1 + 2, bbox.y1 + 2, bbox.z0 - 2),
frequency,
perm,
&self.simulation_config,
Direction::NegZ,
),
1 => CosineBasis::new(
Point3::new(bbox.x0 - 2, bbox.y0 - 2, bbox.z1 + 2),
Point3::new(bbox.x1 + 2, bbox.y1 + 2, bbox.z1 + 2),
frequency,
perm,
&self.simulation_config,
Direction::Z,
),
2 => CosineBasis::new(
Point3::new(bbox.x0 - 2, bbox.y0 - 2, bbox.z0 - 2),
Point3::new(bbox.x1 + 2, bbox.y0 - 2, bbox.z1 + 2),
frequency,
perm,
&self.simulation_config,
Direction::NegY,
),
3 => CosineBasis::new(
Point3::new(bbox.x0 - 2, bbox.y1 + 2, bbox.z0 - 2),
Point3::new(bbox.x1 + 2, bbox.y1 + 2, bbox.z1 + 2),
frequency,
perm,
&self.simulation_config,
Direction::Y,
),
4 => CosineBasis::new(
Point3::new(bbox.x0 - 2, bbox.y0 - 2, bbox.z0 - 2),
Point3::new(bbox.x0 - 2, bbox.y1 + 2, bbox.z1 + 2),
frequency,
perm,
&self.simulation_config,
Direction::NegX,
),
5 => CosineBasis::new(
Point3::new(bbox.x1 + 2, bbox.y0 - 2, bbox.z0 - 2),
Point3::new(bbox.x1 + 2, bbox.y1 + 2, bbox.z1 + 2),
frequency,
perm,
&self.simulation_config,
Direction::X,
),
i => panic!("Face index out of bounds: {}", i),
})
.with_progress_bar(progress_bar.clone())
.force()
})
.sum()
}
/// Returns a scalar field representing the permittivity of a vector of bounding boxes.
fn permittivity_field(&self, freq: f32, objects: &[Shape]) -> ScalarField {
let mut permittivity_field = ScalarField::ones(self.size);
for shape in objects {
shape.draw_permittivity(&mut permittivity_field, freq);
}
permittivity_field
}
/// Returns a scalar field representing the permittivity of the entire geometry.
fn permittivity_field_all_geometry(&self, freq: f32) -> ScalarField {
self.permittivity_field(freq, &self.objects)
}
}
| {
println!("Geometry:");
println!(
"\tWorld size: ({}, {}, {})",
self.size.x, self.size.y, self.size.z
);
for (i, bbox) in self.objects.iter().enumerate() {
println!("\t{}: {}", i, bbox);
}
println!("{}", self.simulation_config);
// The maximum frequency is given by (speed of light) / (grid element size)
let start_freq = self.simulation_config.frequency_range[0];
let end_freq = self.simulation_config.frequency_range[1];
let start_force = self.force_on_for_freq(i, start_freq);
let end_force = self.force_on_for_freq(i, end_freq);
self.integrate_force_between_frequencies(
i,
start_freq,
end_freq,
start_force,
end_force,
start_force.norm(),
)
} | identifier_body |
mod.rs | mod boundingbox;
mod material;
mod shape;
use crate::config::SimulationConfig;
use crate::fields::ScalarField;
use crate::greenfunctions::cosinebasis::{CosineBasis, Direction};
use crate::world::boundingbox::BoundingBox;
use crate::world::shape::Shape;
use nalgebra::*;
use pbr::ProgressBar;
use rayon::iter::*;
use serde::Deserialize;
use snafu::Snafu;
use std::io::Stdout;
use std::sync::{Arc, Mutex};
/// A struct representing the world.
#[derive(PartialEq, Clone, Debug, Deserialize)]
pub struct World {
/// The grid size corresponding to this world.
size: Vector3<usize>,
/// The list with the different shapes.
objects: Vec<Shape>,
/// The simulation configuration.
simulation_config: SimulationConfig,
#[serde(skip)]
use_progress_bar: bool,
}
/// A struct that iterates over the different forces of the objects.
pub struct ForceIterator<'a> {
i: usize,
world: &'a World,
}
impl<'a> Iterator for ForceIterator<'a> {
type Item = Vector3<f32>;
fn next(&mut self) -> Option<Vector3<f32>> {
if self.i < self.world.objects.len() {
let force = self.world.force_on(self.i);
self.i += 1;
Some(force)
} else {
None
}
}
}
/// These errors can be thrown when validating a world.
#[derive(Debug, Snafu)]
pub enum WorldError {
/// An error indicating that one of the shapes is too close too the edge, causing the bounding
/// box to cross the boundary.
#[snafu(display("shape {} too close to edge", index))]
ShapeTooCloseToEdge {
/// The index of the violating object.
index: usize,
},
/// An error indicating that the bounding boxes of two objects in this world intersect and
/// and therefore this world is invalid.
#[snafu(display("bounding boxes of shapes {} and {} intersect", index_1, index_2))]
ShapesIntersect {
/// The index of the first object intersecting with the second.
index_1: usize,
/// The index of the second object intersecting with the first.
index_2: usize,
},
}
impl World {
/// Enable or disable the progress bar for the simulation.
pub fn set_progress_bar(&mut self, enable: bool) {
self.use_progress_bar = enable;
}
/// Obtain a force iterator for all objects in this world.
pub fn forces(&self) -> ForceIterator<'_> {
ForceIterator { i: 0, world: &self }
}
/// Compute the force on the `i`'th object.
pub fn force_on(&self, i: usize) -> Vector3<f32> {
println!("Geometry:");
println!(
"\tWorld size: ({}, {}, {})",
self.size.x, self.size.y, self.size.z
);
for (i, bbox) in self.objects.iter().enumerate() {
println!("\t{}: {}", i, bbox);
}
println!("{}", self.simulation_config);
// The maximum frequency is given by (speed of light) / (grid element size)
let start_freq = self.simulation_config.frequency_range[0];
let end_freq = self.simulation_config.frequency_range[1];
let start_force = self.force_on_for_freq(i, start_freq);
let end_force = self.force_on_for_freq(i, end_freq);
self.integrate_force_between_frequencies(
i,
start_freq,
end_freq,
start_force,
end_force,
start_force.norm(),
)
}
/// This function validates the geometry of the world. The function should be called, because it
/// guarantees overflows later on in the simulation.
///
/// # Errors
/// - If any of the shapes is too close to the world border, the simulation can't be run and a
/// `WorldError::ShapeTooCloseToEdge` will be returned. To fix this, move the object or increase
/// the grid size.
///
/// - If any of the objects are too close too eachother, their boundingboxes might intersect and
/// the results will be invalid. If this is the case, a `WorldError::ShapesIntersect` will be
/// returned. The violating shape indexes will be contained within. To fix this, move one or
/// both of the objects.
pub fn validate(&self) -> Result<(), WorldError> {
let bbox_world = BoundingBox::new(0, 0, 0, self.size.x, self.size.y, self.size.z);
let expanded_boxes = self
.objects
.iter()
.enumerate()
.map(|(index, obj)| {
obj.bbox()
.expanded(2)
.map_err(|_| WorldError::ShapeTooCloseToEdge { index })
})
.collect::<Result<Vec<_>, _>>()?;
for (i, bbox_1) in expanded_boxes.iter().enumerate() {
// Check for intersection with world
if !bbox_1.inside(&bbox_world) {
return Err(WorldError::ShapeTooCloseToEdge { index: i });
}
// Check for intersection with other objects
for (j, bbox_2) in expanded_boxes.iter().enumerate() {
if i < j && bbox_1.intersects(&bbox_2) {
return Err(WorldError::ShapesIntersect {
index_1: i,
index_2: j,
});
}
}
}
Ok(())
}
/// Performs a recursive integration between two frequencies. If the difference between the
/// midpoint force and the linear interpolation is too large, both sides of the domain will use
/// this function recursively to integrate the force.
pub fn integrate_force_between_frequencies(
&self,
i: usize,
start_frequency: f32,
end_frequency: f32,
start_value: Vector3<f32>,
end_value: Vector3<f32>,
max: f32,
) -> Vector3<f32> {
// Do a recursive integration. The function should be smooth.
let middle_frequency = 0.5 * (start_frequency + end_frequency);
let middle_value = self.force_on_for_freq(i, middle_frequency);
let average = (start_value + end_value) / 2.0;
if (average - middle_value).norm() * (end_frequency - start_frequency)
< self.simulation_config.frequency_threshold * max
{
// The change in area from the middle value vs extrapolation is less than the threshold
0.5 * (start_value + 2.0 * middle_value + end_value) * (end_frequency - start_frequency)
} else {
self.integrate_force_between_frequencies(
i,
start_frequency,
middle_frequency,
start_value,
middle_value,
max,
) + self.integrate_force_between_frequencies(
i,
middle_frequency,
end_frequency,
middle_value,
end_value,
max,
)
}
}
/// Compute the force on object `i` for a certain `frequency`. This method will also subtract
/// the error forces due to quantization by subtracting the force due to single objects.
fn | (&self, i: usize, frequency: f32) -> Vector3<f32> {
// Progress bar
let bbox = &self.objects[i].bbox();
let dx = bbox.x1 - bbox.x0 + 4;
let dy = bbox.y1 - bbox.y0 + 4;
let dz = bbox.z1 - bbox.z0 + 4;
let count = 2 * (dx * dy + dy * dz + dz * dx) * (1 + self.objects.len());
let progress_bar = if self.use_progress_bar {
let progress_bar = Arc::new(Mutex::new(ProgressBar::new(count as u64)));
progress_bar.lock().unwrap().format("[=>~]");
progress_bar.lock().unwrap().tick();
Some(progress_bar)
} else {
None
};
let perm_all_geom = &self.permittivity_field_all_geometry(frequency);
let mut total_force =
self.force_on_for_freq_and_geometry(frequency, perm_all_geom, bbox, &progress_bar);
// Discretization gives rise to forces of an object on itself. Removing these gives more
// accurate results.
for other in &self.objects {
let perm = &self.permittivity_field(frequency, &[*other]);
total_force -=
self.force_on_for_freq_and_geometry(frequency, perm, bbox, &progress_bar);
}
if let Some(progress_bar) = progress_bar {
progress_bar.lock().unwrap().finish_println("");
}
println!(
"Force for frequency {}: ({}, {}, {})",
frequency, total_force.x, total_force.y, total_force.z
);
total_force
}
/// Compute the force on the geometry inside `BoundingBox`, for the given permittivity field
/// `perm` and `BoundingBox` `bbox`.
fn force_on_for_freq_and_geometry(
&self,
frequency: f32,
perm: &ScalarField,
bbox: &BoundingBox,
progress_bar: &Option<Arc<Mutex<ProgressBar<Stdout>>>>,
) -> Vector3<f32> {
(0..6)
.into_par_iter()
.map(|face| {
(match face {
0 => CosineBasis::new(
Point3::new(bbox.x0 - 2, bbox.y0 - 2, bbox.z0 - 2),
Point3::new(bbox.x1 + 2, bbox.y1 + 2, bbox.z0 - 2),
frequency,
perm,
&self.simulation_config,
Direction::NegZ,
),
1 => CosineBasis::new(
Point3::new(bbox.x0 - 2, bbox.y0 - 2, bbox.z1 + 2),
Point3::new(bbox.x1 + 2, bbox.y1 + 2, bbox.z1 + 2),
frequency,
perm,
&self.simulation_config,
Direction::Z,
),
2 => CosineBasis::new(
Point3::new(bbox.x0 - 2, bbox.y0 - 2, bbox.z0 - 2),
Point3::new(bbox.x1 + 2, bbox.y0 - 2, bbox.z1 + 2),
frequency,
perm,
&self.simulation_config,
Direction::NegY,
),
3 => CosineBasis::new(
Point3::new(bbox.x0 - 2, bbox.y1 + 2, bbox.z0 - 2),
Point3::new(bbox.x1 + 2, bbox.y1 + 2, bbox.z1 + 2),
frequency,
perm,
&self.simulation_config,
Direction::Y,
),
4 => CosineBasis::new(
Point3::new(bbox.x0 - 2, bbox.y0 - 2, bbox.z0 - 2),
Point3::new(bbox.x0 - 2, bbox.y1 + 2, bbox.z1 + 2),
frequency,
perm,
&self.simulation_config,
Direction::NegX,
),
5 => CosineBasis::new(
Point3::new(bbox.x1 + 2, bbox.y0 - 2, bbox.z0 - 2),
Point3::new(bbox.x1 + 2, bbox.y1 + 2, bbox.z1 + 2),
frequency,
perm,
&self.simulation_config,
Direction::X,
),
i => panic!("Face index out of bounds: {}", i),
})
.with_progress_bar(progress_bar.clone())
.force()
})
.sum()
}
/// Returns a scalar field representing the permittivity of a vector of bounding boxes.
fn permittivity_field(&self, freq: f32, objects: &[Shape]) -> ScalarField {
let mut permittivity_field = ScalarField::ones(self.size);
for shape in objects {
shape.draw_permittivity(&mut permittivity_field, freq);
}
permittivity_field
}
/// Returns a scalar field representing the permittivity of the entire geometry.
fn permittivity_field_all_geometry(&self, freq: f32) -> ScalarField {
self.permittivity_field(freq, &self.objects)
}
}
| force_on_for_freq | identifier_name |
mod.rs | mod boundingbox;
mod material;
mod shape;
use crate::config::SimulationConfig;
use crate::fields::ScalarField;
use crate::greenfunctions::cosinebasis::{CosineBasis, Direction};
use crate::world::boundingbox::BoundingBox;
use crate::world::shape::Shape;
use nalgebra::*;
use pbr::ProgressBar;
use rayon::iter::*;
use serde::Deserialize;
use snafu::Snafu;
use std::io::Stdout;
use std::sync::{Arc, Mutex};
/// A struct representing the world.
#[derive(PartialEq, Clone, Debug, Deserialize)]
pub struct World {
/// The grid size corresponding to this world.
size: Vector3<usize>,
/// The list with the different shapes.
objects: Vec<Shape>,
/// The simulation configuration.
simulation_config: SimulationConfig,
#[serde(skip)]
use_progress_bar: bool,
}
/// A struct that iterates over the different forces of the objects.
pub struct ForceIterator<'a> {
i: usize,
world: &'a World,
}
impl<'a> Iterator for ForceIterator<'a> {
type Item = Vector3<f32>;
fn next(&mut self) -> Option<Vector3<f32>> {
if self.i < self.world.objects.len() {
let force = self.world.force_on(self.i);
self.i += 1;
Some(force)
} else {
None
}
}
}
/// These errors can be thrown when validating a world.
#[derive(Debug, Snafu)]
pub enum WorldError {
/// An error indicating that one of the shapes is too close too the edge, causing the bounding
/// box to cross the boundary.
#[snafu(display("shape {} too close to edge", index))]
ShapeTooCloseToEdge {
/// The index of the violating object.
index: usize,
},
/// An error indicating that the bounding boxes of two objects in this world intersect and
/// and therefore this world is invalid.
#[snafu(display("bounding boxes of shapes {} and {} intersect", index_1, index_2))]
ShapesIntersect {
/// The index of the first object intersecting with the second.
index_1: usize,
/// The index of the second object intersecting with the first.
index_2: usize,
},
}
impl World {
/// Enable or disable the progress bar for the simulation.
pub fn set_progress_bar(&mut self, enable: bool) {
self.use_progress_bar = enable;
}
/// Obtain a force iterator for all objects in this world.
pub fn forces(&self) -> ForceIterator<'_> {
ForceIterator { i: 0, world: &self }
}
/// Compute the force on the `i`'th object.
pub fn force_on(&self, i: usize) -> Vector3<f32> {
println!("Geometry:");
println!(
"\tWorld size: ({}, {}, {})",
self.size.x, self.size.y, self.size.z
);
for (i, bbox) in self.objects.iter().enumerate() {
println!("\t{}: {}", i, bbox);
}
println!("{}", self.simulation_config);
// The maximum frequency is given by (speed of light) / (grid element size)
let start_freq = self.simulation_config.frequency_range[0];
let end_freq = self.simulation_config.frequency_range[1];
let start_force = self.force_on_for_freq(i, start_freq);
let end_force = self.force_on_for_freq(i, end_freq);
self.integrate_force_between_frequencies(
i,
start_freq,
end_freq,
start_force,
end_force,
start_force.norm(),
)
}
/// This function validates the geometry of the world. The function should be called, because it
/// guarantees overflows later on in the simulation.
///
/// # Errors
/// - If any of the shapes is too close to the world border, the simulation can't be run and a
/// `WorldError::ShapeTooCloseToEdge` will be returned. To fix this, move the object or increase
/// the grid size.
///
/// - If any of the objects are too close too eachother, their boundingboxes might intersect and
/// the results will be invalid. If this is the case, a `WorldError::ShapesIntersect` will be
/// returned. The violating shape indexes will be contained within. To fix this, move one or
/// both of the objects.
pub fn validate(&self) -> Result<(), WorldError> {
let bbox_world = BoundingBox::new(0, 0, 0, self.size.x, self.size.y, self.size.z);
let expanded_boxes = self
.objects
.iter()
.enumerate()
.map(|(index, obj)| {
obj.bbox()
.expanded(2)
.map_err(|_| WorldError::ShapeTooCloseToEdge { index })
})
.collect::<Result<Vec<_>, _>>()?;
for (i, bbox_1) in expanded_boxes.iter().enumerate() {
// Check for intersection with world
if !bbox_1.inside(&bbox_world) {
return Err(WorldError::ShapeTooCloseToEdge { index: i });
}
| // Check for intersection with other objects
for (j, bbox_2) in expanded_boxes.iter().enumerate() {
if i < j && bbox_1.intersects(&bbox_2) {
return Err(WorldError::ShapesIntersect {
index_1: i,
index_2: j,
});
}
}
}
Ok(())
}
/// Performs a recursive integration between two frequencies. If the difference between the
/// midpoint force and the linear interpolation is too large, both sides of the domain will use
/// this function recursively to integrate the force.
pub fn integrate_force_between_frequencies(
&self,
i: usize,
start_frequency: f32,
end_frequency: f32,
start_value: Vector3<f32>,
end_value: Vector3<f32>,
max: f32,
) -> Vector3<f32> {
// Do a recursive integration. The function should be smooth.
let middle_frequency = 0.5 * (start_frequency + end_frequency);
let middle_value = self.force_on_for_freq(i, middle_frequency);
let average = (start_value + end_value) / 2.0;
if (average - middle_value).norm() * (end_frequency - start_frequency)
< self.simulation_config.frequency_threshold * max
{
// The change in area from the middle value vs extrapolation is less than the threshold
0.5 * (start_value + 2.0 * middle_value + end_value) * (end_frequency - start_frequency)
} else {
self.integrate_force_between_frequencies(
i,
start_frequency,
middle_frequency,
start_value,
middle_value,
max,
) + self.integrate_force_between_frequencies(
i,
middle_frequency,
end_frequency,
middle_value,
end_value,
max,
)
}
}
/// Compute the force on object `i` for a certain `frequency`. This method will also subtract
/// the error forces due to quantization by subtracting the force due to single objects.
fn force_on_for_freq(&self, i: usize, frequency: f32) -> Vector3<f32> {
// Progress bar
let bbox = &self.objects[i].bbox();
let dx = bbox.x1 - bbox.x0 + 4;
let dy = bbox.y1 - bbox.y0 + 4;
let dz = bbox.z1 - bbox.z0 + 4;
let count = 2 * (dx * dy + dy * dz + dz * dx) * (1 + self.objects.len());
let progress_bar = if self.use_progress_bar {
let progress_bar = Arc::new(Mutex::new(ProgressBar::new(count as u64)));
progress_bar.lock().unwrap().format("[=>~]");
progress_bar.lock().unwrap().tick();
Some(progress_bar)
} else {
None
};
let perm_all_geom = &self.permittivity_field_all_geometry(frequency);
let mut total_force =
self.force_on_for_freq_and_geometry(frequency, perm_all_geom, bbox, &progress_bar);
// Discretization gives rise to forces of an object on itself. Removing these gives more
// accurate results.
for other in &self.objects {
let perm = &self.permittivity_field(frequency, &[*other]);
total_force -=
self.force_on_for_freq_and_geometry(frequency, perm, bbox, &progress_bar);
}
if let Some(progress_bar) = progress_bar {
progress_bar.lock().unwrap().finish_println("");
}
println!(
"Force for frequency {}: ({}, {}, {})",
frequency, total_force.x, total_force.y, total_force.z
);
total_force
}
/// Compute the force on the geometry inside `BoundingBox`, for the given permittivity field
/// `perm` and `BoundingBox` `bbox`.
fn force_on_for_freq_and_geometry(
&self,
frequency: f32,
perm: &ScalarField,
bbox: &BoundingBox,
progress_bar: &Option<Arc<Mutex<ProgressBar<Stdout>>>>,
) -> Vector3<f32> {
(0..6)
.into_par_iter()
.map(|face| {
(match face {
0 => CosineBasis::new(
Point3::new(bbox.x0 - 2, bbox.y0 - 2, bbox.z0 - 2),
Point3::new(bbox.x1 + 2, bbox.y1 + 2, bbox.z0 - 2),
frequency,
perm,
&self.simulation_config,
Direction::NegZ,
),
1 => CosineBasis::new(
Point3::new(bbox.x0 - 2, bbox.y0 - 2, bbox.z1 + 2),
Point3::new(bbox.x1 + 2, bbox.y1 + 2, bbox.z1 + 2),
frequency,
perm,
&self.simulation_config,
Direction::Z,
),
2 => CosineBasis::new(
Point3::new(bbox.x0 - 2, bbox.y0 - 2, bbox.z0 - 2),
Point3::new(bbox.x1 + 2, bbox.y0 - 2, bbox.z1 + 2),
frequency,
perm,
&self.simulation_config,
Direction::NegY,
),
3 => CosineBasis::new(
Point3::new(bbox.x0 - 2, bbox.y1 + 2, bbox.z0 - 2),
Point3::new(bbox.x1 + 2, bbox.y1 + 2, bbox.z1 + 2),
frequency,
perm,
&self.simulation_config,
Direction::Y,
),
4 => CosineBasis::new(
Point3::new(bbox.x0 - 2, bbox.y0 - 2, bbox.z0 - 2),
Point3::new(bbox.x0 - 2, bbox.y1 + 2, bbox.z1 + 2),
frequency,
perm,
&self.simulation_config,
Direction::NegX,
),
5 => CosineBasis::new(
Point3::new(bbox.x1 + 2, bbox.y0 - 2, bbox.z0 - 2),
Point3::new(bbox.x1 + 2, bbox.y1 + 2, bbox.z1 + 2),
frequency,
perm,
&self.simulation_config,
Direction::X,
),
i => panic!("Face index out of bounds: {}", i),
})
.with_progress_bar(progress_bar.clone())
.force()
})
.sum()
}
/// Returns a scalar field representing the permittivity of a vector of bounding boxes.
fn permittivity_field(&self, freq: f32, objects: &[Shape]) -> ScalarField {
let mut permittivity_field = ScalarField::ones(self.size);
for shape in objects {
shape.draw_permittivity(&mut permittivity_field, freq);
}
permittivity_field
}
/// Returns a scalar field representing the permittivity of the entire geometry.
fn permittivity_field_all_geometry(&self, freq: f32) -> ScalarField {
self.permittivity_field(freq, &self.objects)
}
} | random_line_split | |
algorithm.rs | #![allow(unknown_lints)]
#![warn(clippy::all)]
extern crate ndarray;
extern crate petgraph;
extern crate rand;
extern crate sprs;
use crate::protocol_traits::graph::{Graph, GraphObject, Id, Metadata};
use crate::protocol_traits::ledger::LedgerView;
use crate::types::walk::{RandomWalk, RandomWalks, SeedSet};
use crate::types::Osrank;
use core::iter::Iterator;
use fraction::Fraction;
use num_traits::Zero;
use rand::distributions::WeightedError;
use rand::seq::SliceRandom;
use rand::{Rng, SeedableRng};
use std::hash::Hash;
#[derive(Debug)]
pub enum OsrankError {}
#[derive(Debug)]
pub struct WalkResult<G, I>
where
I: Eq + Hash,
{
network_view: G,
pub walks: RandomWalks<I>,
}
fn walks<'a, L, G: 'a, RNG>(
starting_nodes: impl Iterator<Item = &'a Id<G::Node>>,
network: &G,
ledger_view: &L,
mut rng: RNG,
get_weight: &dyn Fn(&<G::Edge as GraphObject>::Metadata) -> f64,
) -> RandomWalks<Id<G::Node>>
where
L: LedgerView,
G: Graph,
Id<G::Node>: Clone + Eq + Hash,
RNG: Rng + SeedableRng,
{
let mut walks = RandomWalks::new();
for i in starting_nodes {
for _ in 0..(*ledger_view.get_random_walks_num()) {
let mut walk = RandomWalk::new(i.clone());
let mut current_node = i;
// TODO distinguish account/project
// TODO Should there be a safeguard so this doesn't run forever?
while rng.gen::<f64>() < ledger_view.get_damping_factors().project {
let neighbors = network.neighbours(¤t_node);
match neighbors.choose_weighted(&mut rng, |item| {
network
.lookup_edge_metadata(&item.id)
.and_then(|m| Some(get_weight(m)))
.unwrap()
}) {
Ok(next_edge) => {
walk.add_next(next_edge.target.clone());
current_node = next_edge.target;
}
Err(WeightedError::NoItem) => break,
Err(error) => panic!("Problem with the neighbors: {:?}", error),
}
}
walks.add_walk(walk);
}
}
walks
}
// FIXME(adn) It should be possible to make this code parametric over
// Dependency<W>, for I have ran into a cryptic error about the SampleBorrow
// trait not be implemented, and wasn't able to immediately make the code
// typecheck.
pub fn random_walk<L, G, RNG>(
seed_set: Option<SeedSet<Id<G::Node>>>,
network: &G,
ledger_view: &L,
rng: RNG,
get_weight: &dyn Fn(&<G::Edge as GraphObject>::Metadata) -> f64,
) -> Result<WalkResult<G, <G::Node as GraphObject>::Id>, OsrankError>
where
L: LedgerView,
G: Graph + Clone,
Id<G::Node>: Clone + Eq + Hash,
RNG: Rng + SeedableRng,
{
match seed_set {
Some(seeds) => {
let walks = walks(seeds.seedset_iter(), network, ledger_view, rng, get_weight);
let mut trusted_node_ids: Vec<&Id<G::Node>> = Vec::new();
for node in network.nodes() {
if rank_node::<L, G>(&walks, node.id().clone(), ledger_view) > Osrank::zero() {
trusted_node_ids.push(&node.id());
}
}
Ok(WalkResult {
network_view: network.subgraph_by_nodes(trusted_node_ids),
walks,
})
}
None => {
let whole_network = (*network).clone(); // FIXME, terrible.
let all_node_ids = network.nodes().map(|n| n.id());
let res = WalkResult {
network_view: whole_network,
walks: walks(all_node_ids, network, ledger_view, rng, get_weight),
};
Ok(res)
}
}
}
/// Naive version of the algorithm that given a full Network and a precomputed
/// set W of random walks, iterates over each edge of the Network and computes
/// the osrank.
pub fn osrank_naive<L, G, RNG>(
seed_set: Option<SeedSet<Id<G::Node>>>,
network: &mut G,
ledger_view: &L,
initial_seed: <RNG as SeedableRng>::Seed,
get_weight: Box<dyn Fn(&<G::Edge as GraphObject>::Metadata) -> f64>,
from_osrank: Box<dyn Fn(&G::Node, Osrank) -> Metadata<G::Node>>,
) -> Result<(), OsrankError>
where
L: LedgerView,
G: Graph + Clone,
Id<G::Node>: Clone + Eq + Hash,
RNG: Rng + SeedableRng,
<RNG as SeedableRng>::Seed: Clone,
{
//NOTE(adn) The fact we are creating a new RNG every time we call
// `random_walk` is deliberate and something to think about. We probably
// want to "restart" the randomness from the initial seed every call to
// `random_walk`, which means this function has to consume the RNG.
match seed_set {
Some(_) => {
// Phase1, rank the network and produce a NetworkView.
let phase1 = random_walk(
seed_set,
&*network,
ledger_view,
RNG::from_seed(initial_seed.clone()),
&get_weight,
)?;
// Phase2, compute the osrank only on the NetworkView
let phase2 = random_walk(
None,
&phase1.network_view,
ledger_view,
RNG::from_seed(initial_seed.clone()),
&get_weight,
)?;
rank_network(&phase2.walks, &mut *network, ledger_view, &from_osrank)
}
None => {
// Compute osrank on the full NetworkView
let create_walks = random_walk(
None,
&*network,
ledger_view,
RNG::from_seed(initial_seed.clone()),
&get_weight,
)?;
rank_network(
&create_walks.walks,
&mut *network,
ledger_view,
&from_osrank,
)
}
}
}
fn rank_node<L, G>(
random_walks: &RandomWalks<Id<G::Node>>, | ledger_view: &L,
) -> Osrank
where
L: LedgerView,
G: Graph,
<G::Node as GraphObject>::Id: Eq + Clone + Hash,
{
let total_walks = random_walks.len();
let node_visits = random_walks.count_visits(&node_id);
Fraction::from(1.0 - ledger_view.get_damping_factors().project)
* Osrank::new(node_visits as u32, total_walks as u32)
}
pub fn rank_network<'a, L, G: 'a>(
random_walks: &RandomWalks<Id<G::Node>>,
network_view: &'a mut G,
ledger_view: &L,
from_osrank: &dyn Fn(&G::Node, Osrank) -> Metadata<G::Node>,
) -> Result<(), OsrankError>
where
L: LedgerView,
G: Graph,
<G::Node as GraphObject>::Id: Eq + Clone + Hash,
{
for node in network_view.nodes_mut() {
let rank = rank_node::<L, G>(&random_walks, node.id().clone(), ledger_view);
node.set_metadata(from_osrank(&node, rank))
}
Ok(())
}
#[cfg(test)]
mod tests {
extern crate rand;
extern crate rand_xorshift;
use super::*;
use crate::protocol_traits::ledger::MockLedger;
use crate::types::network::{Artifact, ArtifactType, DependencyType, Network};
use crate::types::Weight;
use num_traits::Zero;
use rand_xorshift::XorShiftRng;
type MockNetwork = Network<f64>;
#[test]
fn everything_ok() {
// build the example network
let mut network = Network::default();
for node in &["p1", "p2", "p3"] {
network.add_node(
node.to_string(),
ArtifactType::Project {
osrank: Zero::zero(),
},
)
}
// Create the seed set from all projects
let seed_set = SeedSet::from(vec!["p1".to_string(), "p2".to_string(), "p3".to_string()]);
for node in &["a1", "a2", "a3", "isle"] {
network.add_node(
node.to_string(),
ArtifactType::Account {
osrank: Zero::zero(),
},
)
}
let edges = [
("p1", "a1", Weight::new(3, 7)),
("a1", "p1", Weight::new(1, 1)),
("p1", "p2", Weight::new(4, 7)),
("p2", "a2", Weight::new(1, 1)),
("a2", "p2", Weight::new(1, 3)),
("a2", "p3", Weight::new(2, 3)),
("p3", "a2", Weight::new(11, 28)),
("p3", "a3", Weight::new(1, 28)),
("p3", "p1", Weight::new(2, 7)),
("p3", "p2", Weight::new(2, 7)),
("a3", "p3", Weight::new(1, 1)),
];
for edge in &edges {
network.add_edge(
&edge.0.to_string(),
&edge.1.to_string(),
2,
DependencyType::Influence(edge.2.as_f64().unwrap()),
)
}
let mock_ledger = MockLedger::default();
let get_weight = Box::new(|m: &DependencyType<f64>| *m.get_weight());
let set_osrank = Box::new(|node: &Artifact<String>, rank| match node.get_metadata() {
ArtifactType::Project { osrank: _ } => ArtifactType::Project { osrank: rank },
ArtifactType::Account { osrank: _ } => ArtifactType::Account { osrank: rank },
});
assert_eq!(network.edge_count(), 11);
// This is the insertion point of the Graph API. If we had a GraphAPI
// "handle" in scope here, we could extract the seed from some state
// and use it in the algorithm. Faking it for now.
let initial_seed = [0; 16];
assert_eq!(
osrank_naive::<MockLedger, MockNetwork, XorShiftRng>(
Some(seed_set),
&mut network,
&mock_ledger,
initial_seed,
get_weight,
set_osrank
)
.unwrap(),
()
);
assert_eq!(
network.nodes().fold(Vec::new(), |mut ranks, node| {
// let bla = *node.get_metadata();
ranks.push(format!("{}", *node));
ranks
}),
vec![
"id: p1 osrank: 0.1425",
"id: p2 osrank: 0.2225",
"id: p3 osrank: 0.1575",
"id: a1 osrank: 0.08",
"id: a2 osrank: 0.23",
"id: a3 osrank: 0.055",
"id: isle osrank: 0"
]
);
}
} | node_id: Id<G::Node>, | random_line_split |
algorithm.rs | #![allow(unknown_lints)]
#![warn(clippy::all)]
extern crate ndarray;
extern crate petgraph;
extern crate rand;
extern crate sprs;
use crate::protocol_traits::graph::{Graph, GraphObject, Id, Metadata};
use crate::protocol_traits::ledger::LedgerView;
use crate::types::walk::{RandomWalk, RandomWalks, SeedSet};
use crate::types::Osrank;
use core::iter::Iterator;
use fraction::Fraction;
use num_traits::Zero;
use rand::distributions::WeightedError;
use rand::seq::SliceRandom;
use rand::{Rng, SeedableRng};
use std::hash::Hash;
#[derive(Debug)]
pub enum OsrankError {}
#[derive(Debug)]
pub struct | <G, I>
where
I: Eq + Hash,
{
network_view: G,
pub walks: RandomWalks<I>,
}
fn walks<'a, L, G: 'a, RNG>(
starting_nodes: impl Iterator<Item = &'a Id<G::Node>>,
network: &G,
ledger_view: &L,
mut rng: RNG,
get_weight: &dyn Fn(&<G::Edge as GraphObject>::Metadata) -> f64,
) -> RandomWalks<Id<G::Node>>
where
L: LedgerView,
G: Graph,
Id<G::Node>: Clone + Eq + Hash,
RNG: Rng + SeedableRng,
{
let mut walks = RandomWalks::new();
for i in starting_nodes {
for _ in 0..(*ledger_view.get_random_walks_num()) {
let mut walk = RandomWalk::new(i.clone());
let mut current_node = i;
// TODO distinguish account/project
// TODO Should there be a safeguard so this doesn't run forever?
while rng.gen::<f64>() < ledger_view.get_damping_factors().project {
let neighbors = network.neighbours(¤t_node);
match neighbors.choose_weighted(&mut rng, |item| {
network
.lookup_edge_metadata(&item.id)
.and_then(|m| Some(get_weight(m)))
.unwrap()
}) {
Ok(next_edge) => {
walk.add_next(next_edge.target.clone());
current_node = next_edge.target;
}
Err(WeightedError::NoItem) => break,
Err(error) => panic!("Problem with the neighbors: {:?}", error),
}
}
walks.add_walk(walk);
}
}
walks
}
// FIXME(adn) It should be possible to make this code parametric over
// Dependency<W>, for I have ran into a cryptic error about the SampleBorrow
// trait not be implemented, and wasn't able to immediately make the code
// typecheck.
pub fn random_walk<L, G, RNG>(
seed_set: Option<SeedSet<Id<G::Node>>>,
network: &G,
ledger_view: &L,
rng: RNG,
get_weight: &dyn Fn(&<G::Edge as GraphObject>::Metadata) -> f64,
) -> Result<WalkResult<G, <G::Node as GraphObject>::Id>, OsrankError>
where
L: LedgerView,
G: Graph + Clone,
Id<G::Node>: Clone + Eq + Hash,
RNG: Rng + SeedableRng,
{
match seed_set {
Some(seeds) => {
let walks = walks(seeds.seedset_iter(), network, ledger_view, rng, get_weight);
let mut trusted_node_ids: Vec<&Id<G::Node>> = Vec::new();
for node in network.nodes() {
if rank_node::<L, G>(&walks, node.id().clone(), ledger_view) > Osrank::zero() {
trusted_node_ids.push(&node.id());
}
}
Ok(WalkResult {
network_view: network.subgraph_by_nodes(trusted_node_ids),
walks,
})
}
None => {
let whole_network = (*network).clone(); // FIXME, terrible.
let all_node_ids = network.nodes().map(|n| n.id());
let res = WalkResult {
network_view: whole_network,
walks: walks(all_node_ids, network, ledger_view, rng, get_weight),
};
Ok(res)
}
}
}
/// Naive version of the algorithm that given a full Network and a precomputed
/// set W of random walks, iterates over each edge of the Network and computes
/// the osrank.
pub fn osrank_naive<L, G, RNG>(
seed_set: Option<SeedSet<Id<G::Node>>>,
network: &mut G,
ledger_view: &L,
initial_seed: <RNG as SeedableRng>::Seed,
get_weight: Box<dyn Fn(&<G::Edge as GraphObject>::Metadata) -> f64>,
from_osrank: Box<dyn Fn(&G::Node, Osrank) -> Metadata<G::Node>>,
) -> Result<(), OsrankError>
where
L: LedgerView,
G: Graph + Clone,
Id<G::Node>: Clone + Eq + Hash,
RNG: Rng + SeedableRng,
<RNG as SeedableRng>::Seed: Clone,
{
//NOTE(adn) The fact we are creating a new RNG every time we call
// `random_walk` is deliberate and something to think about. We probably
// want to "restart" the randomness from the initial seed every call to
// `random_walk`, which means this function has to consume the RNG.
match seed_set {
Some(_) => {
// Phase1, rank the network and produce a NetworkView.
let phase1 = random_walk(
seed_set,
&*network,
ledger_view,
RNG::from_seed(initial_seed.clone()),
&get_weight,
)?;
// Phase2, compute the osrank only on the NetworkView
let phase2 = random_walk(
None,
&phase1.network_view,
ledger_view,
RNG::from_seed(initial_seed.clone()),
&get_weight,
)?;
rank_network(&phase2.walks, &mut *network, ledger_view, &from_osrank)
}
None => {
// Compute osrank on the full NetworkView
let create_walks = random_walk(
None,
&*network,
ledger_view,
RNG::from_seed(initial_seed.clone()),
&get_weight,
)?;
rank_network(
&create_walks.walks,
&mut *network,
ledger_view,
&from_osrank,
)
}
}
}
fn rank_node<L, G>(
random_walks: &RandomWalks<Id<G::Node>>,
node_id: Id<G::Node>,
ledger_view: &L,
) -> Osrank
where
L: LedgerView,
G: Graph,
<G::Node as GraphObject>::Id: Eq + Clone + Hash,
{
let total_walks = random_walks.len();
let node_visits = random_walks.count_visits(&node_id);
Fraction::from(1.0 - ledger_view.get_damping_factors().project)
* Osrank::new(node_visits as u32, total_walks as u32)
}
pub fn rank_network<'a, L, G: 'a>(
random_walks: &RandomWalks<Id<G::Node>>,
network_view: &'a mut G,
ledger_view: &L,
from_osrank: &dyn Fn(&G::Node, Osrank) -> Metadata<G::Node>,
) -> Result<(), OsrankError>
where
L: LedgerView,
G: Graph,
<G::Node as GraphObject>::Id: Eq + Clone + Hash,
{
for node in network_view.nodes_mut() {
let rank = rank_node::<L, G>(&random_walks, node.id().clone(), ledger_view);
node.set_metadata(from_osrank(&node, rank))
}
Ok(())
}
#[cfg(test)]
mod tests {
extern crate rand;
extern crate rand_xorshift;
use super::*;
use crate::protocol_traits::ledger::MockLedger;
use crate::types::network::{Artifact, ArtifactType, DependencyType, Network};
use crate::types::Weight;
use num_traits::Zero;
use rand_xorshift::XorShiftRng;
type MockNetwork = Network<f64>;
#[test]
fn everything_ok() {
// build the example network
let mut network = Network::default();
for node in &["p1", "p2", "p3"] {
network.add_node(
node.to_string(),
ArtifactType::Project {
osrank: Zero::zero(),
},
)
}
// Create the seed set from all projects
let seed_set = SeedSet::from(vec!["p1".to_string(), "p2".to_string(), "p3".to_string()]);
for node in &["a1", "a2", "a3", "isle"] {
network.add_node(
node.to_string(),
ArtifactType::Account {
osrank: Zero::zero(),
},
)
}
let edges = [
("p1", "a1", Weight::new(3, 7)),
("a1", "p1", Weight::new(1, 1)),
("p1", "p2", Weight::new(4, 7)),
("p2", "a2", Weight::new(1, 1)),
("a2", "p2", Weight::new(1, 3)),
("a2", "p3", Weight::new(2, 3)),
("p3", "a2", Weight::new(11, 28)),
("p3", "a3", Weight::new(1, 28)),
("p3", "p1", Weight::new(2, 7)),
("p3", "p2", Weight::new(2, 7)),
("a3", "p3", Weight::new(1, 1)),
];
for edge in &edges {
network.add_edge(
&edge.0.to_string(),
&edge.1.to_string(),
2,
DependencyType::Influence(edge.2.as_f64().unwrap()),
)
}
let mock_ledger = MockLedger::default();
let get_weight = Box::new(|m: &DependencyType<f64>| *m.get_weight());
let set_osrank = Box::new(|node: &Artifact<String>, rank| match node.get_metadata() {
ArtifactType::Project { osrank: _ } => ArtifactType::Project { osrank: rank },
ArtifactType::Account { osrank: _ } => ArtifactType::Account { osrank: rank },
});
assert_eq!(network.edge_count(), 11);
// This is the insertion point of the Graph API. If we had a GraphAPI
// "handle" in scope here, we could extract the seed from some state
// and use it in the algorithm. Faking it for now.
let initial_seed = [0; 16];
assert_eq!(
osrank_naive::<MockLedger, MockNetwork, XorShiftRng>(
Some(seed_set),
&mut network,
&mock_ledger,
initial_seed,
get_weight,
set_osrank
)
.unwrap(),
()
);
assert_eq!(
network.nodes().fold(Vec::new(), |mut ranks, node| {
// let bla = *node.get_metadata();
ranks.push(format!("{}", *node));
ranks
}),
vec![
"id: p1 osrank: 0.1425",
"id: p2 osrank: 0.2225",
"id: p3 osrank: 0.1575",
"id: a1 osrank: 0.08",
"id: a2 osrank: 0.23",
"id: a3 osrank: 0.055",
"id: isle osrank: 0"
]
);
}
}
| WalkResult | identifier_name |
channel.rs | use std::any::Any;
use std::collections::VecDeque;
use std::fmt;
use std::sync::{Arc, Mutex};
use futures::sync::oneshot;
use futures::Future;
use base::types::{ArcType, Type};
use api::generic::A;
use api::{
primitive, AsyncPushable, Function, FunctionRef, FutureResult, Generic, Getable, OpaqueValue,
OwnedFunction, Pushable, RuntimeResult, VmType, WithVM, IO,
};
use gc::{Gc, GcPtr, Traverseable};
use stack::{StackFrame, State};
use thread::{OwnedContext, ThreadInternal};
use types::VmInt;
use value::{Callable, GcStr, Userdata, ValueRepr};
use vm::{RootedThread, Status, Thread};
use {Error, ExternModule, Result as VmResult};
pub struct Sender<T> {
// No need to traverse this thread reference as any thread having a reference to this `Sender`
// would also directly own a reference to the `Thread`
thread: GcPtr<Thread>,
queue: Arc<Mutex<VecDeque<T>>>,
}
impl<T> Userdata for Sender<T>
where
T: Any + Send + Sync + fmt::Debug + Traverseable,
{
}
impl<T> fmt::Debug for Sender<T>
where
T: fmt::Debug,
{
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{:?}", *self.queue.lock().unwrap())
}
}
impl<T> Traverseable for Sender<T> {
fn traverse(&self, _gc: &mut Gc) {
// No need to traverse in Sender as values can only be accessed through Receiver
}
}
impl<T> Sender<T> {
fn send(&self, value: T) {
self.queue.lock().unwrap().push_back(value);
}
}
impl<T: Traverseable> Traverseable for Receiver<T> {
fn traverse(&self, gc: &mut Gc) {
self.queue.lock().unwrap().traverse(gc);
}
}
pub struct Receiver<T> {
queue: Arc<Mutex<VecDeque<T>>>,
}
impl<T> Userdata for Receiver<T>
where
T: Any + Send + Sync + fmt::Debug + Traverseable,
{
}
impl<T> fmt::Debug for Receiver<T>
where
T: fmt::Debug,
{
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{:?}", *self.queue.lock().unwrap())
}
}
impl<T> Receiver<T> {
fn try_recv(&self) -> Result<T, ()> {
self.queue.lock().unwrap().pop_front().ok_or(())
}
}
impl<T: VmType> VmType for Sender<T>
where
T::Type: Sized,
{
type Type = Sender<T::Type>;
fn make_type(vm: &Thread) -> ArcType {
let symbol = vm
.global_env()
.get_env()
.find_type_info("Sender")
.unwrap()
.name
.clone();
Type::app(Type::ident(symbol), collect![T::make_type(vm)])
}
}
impl<T: VmType> VmType for Receiver<T>
where
T::Type: Sized,
{
type Type = Receiver<T::Type>;
fn make_type(vm: &Thread) -> ArcType {
let symbol = vm
.global_env()
.get_env()
.find_type_info("Receiver")
.unwrap()
.name
.clone();
Type::app(Type::ident(symbol), collect![T::make_type(vm)])
}
}
field_decl!{ sender, receiver }
pub type ChannelRecord<S, R> = record_type!(sender => S, receiver => R);
/// FIXME The dummy `a` argument should not be needed to ensure that the channel can only be used
/// with a single type
fn channel(
WithVM { vm, .. }: WithVM<Generic<A>>,
) -> ChannelRecord<Sender<Generic<A>>, Receiver<Generic<A>>> {
let sender = Sender {
thread: unsafe { GcPtr::from_raw(vm) },
queue: Arc::new(Mutex::new(VecDeque::new())),
};
let receiver = Receiver {
queue: sender.queue.clone(),
};
record_no_decl!(sender => sender, receiver => receiver)
}
fn recv(receiver: &Receiver<Generic<A>>) -> Result<Generic<A>, ()> {
receiver.try_recv().map_err(|_| ())
}
fn send(sender: &Sender<Generic<A>>, value: Generic<A>) -> Result<(), ()> {
unsafe {
let value = sender
.thread
.deep_clone_value(&sender.thread, value.get_value())
.map_err(|_| ())?;
Ok(sender.send(Generic::from(value)))
}
}
extern "C" fn resume(vm: &Thread) -> Status {
let mut context = vm.context();
let value = StackFrame::current(&mut context.stack)[0].get_repr();
match value {
ValueRepr::Thread(child) => {
let lock = StackFrame::current(&mut context.stack).into_lock();
drop(context);
let result = child.resume();
context = vm.context();
context.stack.release_lock(lock);
match result {
Ok(child_context) => {
// Prevent dead lock if the following status_push call allocates
drop(child_context);
let value: Result<(), &str> = Ok(());
value.status_push(vm, &mut context)
}
Err(Error::Dead) => {
let value: Result<(), &str> = Err("Attempted to resume a dead thread");
value.status_push(vm, &mut context)
}
Err(err) => {
let fmt = format!("{}", err);
let result = unsafe {
ValueRepr::String(GcStr::from_utf8_unchecked(
context.alloc_ignore_limit(fmt.as_bytes()),
))
};
context.stack.push(result);
Status::Error
}
}
}
_ => unreachable!(),
}
}
extern "C" fn yield_(_vm: &Thread) -> Status {
Status::Yield
}
fn spawn<'vm>(
value: WithVM<'vm, Function<&'vm Thread, fn(())>>,
) -> RuntimeResult<RootedThread, Error> {
spawn_(value).into()
}
fn spawn_<'vm>(value: WithVM<'vm, Function<&'vm Thread, fn(())>>) -> VmResult<RootedThread> {
let thread = value.vm.new_thread()?;
{
let mut context = thread.context();
let callable = match value.value.get_variant().0 {
ValueRepr::Closure(c) => State::Closure(c),
ValueRepr::Function(c) => State::Extern(c),
_ => State::Unknown,
};
value.value.push(value.vm, &mut context)?;
context.stack.push(ValueRepr::Int(0));
StackFrame::current(&mut context.stack).enter_scope(1, callable);
}
Ok(thread)
}
type Action = fn(()) -> OpaqueValue<RootedThread, IO<Generic<A>>>;
#[cfg(target_arch = "wasm32")]
fn spawn_on<'vm>(
_thread: RootedThread,
_action: WithVM<'vm, FunctionRef<Action>>,
) -> IO<OpaqueValue<&'vm Thread, IO<Generic<A>>>> {
IO::Exception("spawn_on requires the `tokio_core` crate".to_string())
}
#[cfg(not(target_arch = "wasm32"))]
fn spawn_on<'vm>(
thread: RootedThread,
action: WithVM<'vm, FunctionRef<Action>>,
) -> IO<OpaqueValue<&'vm Thread, IO<Generic<A>>>> {
struct SpawnFuture<F>(Mutex<Option<F>>);
impl<F> fmt::Debug for SpawnFuture<F> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "Future")
}
}
impl<F> Userdata for SpawnFuture<F>
where
F: Send + 'static,
{
}
impl<F> Traverseable for SpawnFuture<F> {
fn traverse(&self, _: &mut Gc) {}
}
impl<F> VmType for SpawnFuture<F> {
type Type = Generic<A>;
}
fn push_future_wrapper<G>(vm: &Thread, context: &mut OwnedContext, _: &G)
where
G: Future<Item = OpaqueValue<RootedThread, IO<Generic<A>>>, Error = Error> + Send + 'static,
{
extern "C" fn future_wrapper<F>(vm: &Thread) -> Status
where
F: Future<Item = OpaqueValue<RootedThread, IO<Generic<A>>>, Error = Error>
+ Send
+ 'static,
{
let mut context = vm.context();
let value = StackFrame::current(&mut context.stack)[0].get_repr();
match value {
ValueRepr::Userdata(data) => {
let data = data.downcast_ref::<SpawnFuture<F>>().unwrap();
let future = data.0.lock().unwrap().take().unwrap();
let lock = StackFrame::current(&mut context.stack).insert_lock();
AsyncPushable::async_status_push(
FutureResult::new(future),
vm,
&mut context,
lock,
)
}
_ => unreachable!(),
}
}
type FutureArg = ();
primitive::<fn(FutureArg) -> IO<Generic<A>>>("unknown", future_wrapper::<G>)
.push(vm, context)
.unwrap();
}
use value::PartialApplicationDataDef;
let WithVM { vm, value: action } = action;
let mut action = OwnedFunction::<Action>::from_value(&thread, action.get_variant());
let future = oneshot::spawn_fn(
move || action.call_async(()),
&vm.global_env().get_event_loop().expect("event loop"),
);
let mut context = vm.context();
push_future_wrapper(vm, &mut context, &future);
let callable = match context.stack[context.stack.len() - 1].get_repr() {
ValueRepr::Function(ext) => Callable::Extern(ext),
_ => unreachable!(),
};
SpawnFuture(Mutex::new(Some(future)))
.push(vm, &mut context)
.unwrap();
let fields = [context.stack.get_values().last().unwrap().clone()];
let def = PartialApplicationDataDef(callable, &fields);
let value = ValueRepr::PartialApplication(context.alloc_with(vm, def).unwrap()).into();
context.stack.pop_many(2);
// TODO Remove rooting here
IO::Value(OpaqueValue::from_value(vm.root_value(value)))
}
fn new_thread(WithVM { vm, .. }: WithVM<()>) -> IO<RootedThread> {
match vm.new_thread() {
Ok(thread) => IO::Value(thread),
Err(err) => IO::Exception(err.to_string()),
}
}
fn sleep(ms: VmInt) -> IO<()> {
use std::time::Duration;
::std::thread::sleep(Duration::from_millis(ms as u64));
IO::Value(())
}
fn interrupt(thread: RootedThread) -> IO<()> {
thread.interrupt();
IO::Value(())
}
mod std {
pub use channel;
pub mod thread {
pub use channel as prim;
}
}
pub fn load_channel<'vm>(vm: &'vm Thread) -> VmResult<ExternModule> {
let _ = vm.register_type::<Sender<A>>("Sender", &["a"]);
let _ = vm.register_type::<Receiver<A>>("Receiver", &["a"]);
ExternModule::new(
vm,
record!{
type Sender a => Sender<A>,
type Receiver a => Sender<A>,
channel => primitive!(1 std::channel::channel),
recv => primitive!(1 std::channel::recv),
send => primitive!(2 std::channel::send),
},
)
}
pub fn load_thread<'vm>(vm: &'vm Thread) -> VmResult<ExternModule> | {
ExternModule::new(
vm,
record!{
resume => primitive::<fn(&'vm Thread) -> Result<(), String>>("std.thread.prim.resume", resume),
(yield_ "yield") => primitive::<fn(())>("std.thread.prim.yield", yield_),
spawn => primitive!(1 std::thread::prim::spawn),
spawn_on => primitive!(2 std::thread::prim::spawn_on),
new_thread => primitive!(1 std::thread::prim::new_thread),
interrupt => primitive!(1 std::thread::prim::interrupt),
sleep => primitive!(1 std::thread::prim::sleep)
},
)
} | identifier_body | |
channel.rs | use std::any::Any;
use std::collections::VecDeque;
use std::fmt;
use std::sync::{Arc, Mutex};
use futures::sync::oneshot;
use futures::Future;
use base::types::{ArcType, Type};
use api::generic::A;
use api::{
primitive, AsyncPushable, Function, FunctionRef, FutureResult, Generic, Getable, OpaqueValue,
OwnedFunction, Pushable, RuntimeResult, VmType, WithVM, IO,
};
use gc::{Gc, GcPtr, Traverseable};
use stack::{StackFrame, State};
use thread::{OwnedContext, ThreadInternal};
use types::VmInt;
use value::{Callable, GcStr, Userdata, ValueRepr};
use vm::{RootedThread, Status, Thread};
use {Error, ExternModule, Result as VmResult};
pub struct Sender<T> {
// No need to traverse this thread reference as any thread having a reference to this `Sender`
// would also directly own a reference to the `Thread`
thread: GcPtr<Thread>,
queue: Arc<Mutex<VecDeque<T>>>,
}
impl<T> Userdata for Sender<T>
where
T: Any + Send + Sync + fmt::Debug + Traverseable,
{
}
impl<T> fmt::Debug for Sender<T>
where
T: fmt::Debug,
{
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{:?}", *self.queue.lock().unwrap())
}
}
impl<T> Traverseable for Sender<T> {
fn traverse(&self, _gc: &mut Gc) {
// No need to traverse in Sender as values can only be accessed through Receiver
}
}
impl<T> Sender<T> {
fn send(&self, value: T) {
self.queue.lock().unwrap().push_back(value);
}
}
impl<T: Traverseable> Traverseable for Receiver<T> {
fn traverse(&self, gc: &mut Gc) {
self.queue.lock().unwrap().traverse(gc);
}
}
pub struct Receiver<T> {
queue: Arc<Mutex<VecDeque<T>>>,
}
impl<T> Userdata for Receiver<T>
where
T: Any + Send + Sync + fmt::Debug + Traverseable,
{
}
impl<T> fmt::Debug for Receiver<T>
where
T: fmt::Debug,
{
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{:?}", *self.queue.lock().unwrap())
}
}
impl<T> Receiver<T> {
fn try_recv(&self) -> Result<T, ()> {
self.queue.lock().unwrap().pop_front().ok_or(())
}
}
impl<T: VmType> VmType for Sender<T>
where
T::Type: Sized,
{
type Type = Sender<T::Type>;
fn make_type(vm: &Thread) -> ArcType {
let symbol = vm
.global_env()
.get_env()
.find_type_info("Sender")
.unwrap()
.name
.clone();
Type::app(Type::ident(symbol), collect![T::make_type(vm)])
}
}
impl<T: VmType> VmType for Receiver<T>
where
T::Type: Sized,
{
type Type = Receiver<T::Type>;
fn make_type(vm: &Thread) -> ArcType {
let symbol = vm
.global_env()
.get_env()
.find_type_info("Receiver")
.unwrap()
.name
.clone();
Type::app(Type::ident(symbol), collect![T::make_type(vm)])
}
}
field_decl!{ sender, receiver }
pub type ChannelRecord<S, R> = record_type!(sender => S, receiver => R);
/// FIXME The dummy `a` argument should not be needed to ensure that the channel can only be used
/// with a single type
fn channel(
WithVM { vm, .. }: WithVM<Generic<A>>,
) -> ChannelRecord<Sender<Generic<A>>, Receiver<Generic<A>>> {
let sender = Sender {
thread: unsafe { GcPtr::from_raw(vm) },
queue: Arc::new(Mutex::new(VecDeque::new())),
};
let receiver = Receiver {
queue: sender.queue.clone(),
};
record_no_decl!(sender => sender, receiver => receiver)
}
fn recv(receiver: &Receiver<Generic<A>>) -> Result<Generic<A>, ()> {
receiver.try_recv().map_err(|_| ())
}
fn send(sender: &Sender<Generic<A>>, value: Generic<A>) -> Result<(), ()> {
unsafe {
let value = sender
.thread
.deep_clone_value(&sender.thread, value.get_value())
.map_err(|_| ())?;
Ok(sender.send(Generic::from(value)))
}
}
extern "C" fn resume(vm: &Thread) -> Status {
let mut context = vm.context();
let value = StackFrame::current(&mut context.stack)[0].get_repr();
match value {
ValueRepr::Thread(child) => {
let lock = StackFrame::current(&mut context.stack).into_lock();
drop(context);
let result = child.resume();
context = vm.context();
context.stack.release_lock(lock);
match result {
Ok(child_context) => {
// Prevent dead lock if the following status_push call allocates
drop(child_context);
let value: Result<(), &str> = Ok(());
value.status_push(vm, &mut context)
}
Err(Error::Dead) => {
let value: Result<(), &str> = Err("Attempted to resume a dead thread");
value.status_push(vm, &mut context)
}
Err(err) => {
let fmt = format!("{}", err);
let result = unsafe {
ValueRepr::String(GcStr::from_utf8_unchecked(
context.alloc_ignore_limit(fmt.as_bytes()),
))
};
context.stack.push(result);
Status::Error
}
}
}
_ => unreachable!(),
}
}
extern "C" fn yield_(_vm: &Thread) -> Status {
Status::Yield
}
fn spawn<'vm>(
value: WithVM<'vm, Function<&'vm Thread, fn(())>>,
) -> RuntimeResult<RootedThread, Error> {
spawn_(value).into()
}
fn spawn_<'vm>(value: WithVM<'vm, Function<&'vm Thread, fn(())>>) -> VmResult<RootedThread> {
let thread = value.vm.new_thread()?;
{
let mut context = thread.context();
let callable = match value.value.get_variant().0 {
ValueRepr::Closure(c) => State::Closure(c),
ValueRepr::Function(c) => State::Extern(c),
_ => State::Unknown,
};
value.value.push(value.vm, &mut context)?;
context.stack.push(ValueRepr::Int(0));
StackFrame::current(&mut context.stack).enter_scope(1, callable);
}
Ok(thread)
}
type Action = fn(()) -> OpaqueValue<RootedThread, IO<Generic<A>>>;
#[cfg(target_arch = "wasm32")]
fn spawn_on<'vm>(
_thread: RootedThread,
_action: WithVM<'vm, FunctionRef<Action>>,
) -> IO<OpaqueValue<&'vm Thread, IO<Generic<A>>>> {
IO::Exception("spawn_on requires the `tokio_core` crate".to_string())
} | thread: RootedThread,
action: WithVM<'vm, FunctionRef<Action>>,
) -> IO<OpaqueValue<&'vm Thread, IO<Generic<A>>>> {
struct SpawnFuture<F>(Mutex<Option<F>>);
impl<F> fmt::Debug for SpawnFuture<F> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "Future")
}
}
impl<F> Userdata for SpawnFuture<F>
where
F: Send + 'static,
{
}
impl<F> Traverseable for SpawnFuture<F> {
fn traverse(&self, _: &mut Gc) {}
}
impl<F> VmType for SpawnFuture<F> {
type Type = Generic<A>;
}
fn push_future_wrapper<G>(vm: &Thread, context: &mut OwnedContext, _: &G)
where
G: Future<Item = OpaqueValue<RootedThread, IO<Generic<A>>>, Error = Error> + Send + 'static,
{
extern "C" fn future_wrapper<F>(vm: &Thread) -> Status
where
F: Future<Item = OpaqueValue<RootedThread, IO<Generic<A>>>, Error = Error>
+ Send
+ 'static,
{
let mut context = vm.context();
let value = StackFrame::current(&mut context.stack)[0].get_repr();
match value {
ValueRepr::Userdata(data) => {
let data = data.downcast_ref::<SpawnFuture<F>>().unwrap();
let future = data.0.lock().unwrap().take().unwrap();
let lock = StackFrame::current(&mut context.stack).insert_lock();
AsyncPushable::async_status_push(
FutureResult::new(future),
vm,
&mut context,
lock,
)
}
_ => unreachable!(),
}
}
type FutureArg = ();
primitive::<fn(FutureArg) -> IO<Generic<A>>>("unknown", future_wrapper::<G>)
.push(vm, context)
.unwrap();
}
use value::PartialApplicationDataDef;
let WithVM { vm, value: action } = action;
let mut action = OwnedFunction::<Action>::from_value(&thread, action.get_variant());
let future = oneshot::spawn_fn(
move || action.call_async(()),
&vm.global_env().get_event_loop().expect("event loop"),
);
let mut context = vm.context();
push_future_wrapper(vm, &mut context, &future);
let callable = match context.stack[context.stack.len() - 1].get_repr() {
ValueRepr::Function(ext) => Callable::Extern(ext),
_ => unreachable!(),
};
SpawnFuture(Mutex::new(Some(future)))
.push(vm, &mut context)
.unwrap();
let fields = [context.stack.get_values().last().unwrap().clone()];
let def = PartialApplicationDataDef(callable, &fields);
let value = ValueRepr::PartialApplication(context.alloc_with(vm, def).unwrap()).into();
context.stack.pop_many(2);
// TODO Remove rooting here
IO::Value(OpaqueValue::from_value(vm.root_value(value)))
}
fn new_thread(WithVM { vm, .. }: WithVM<()>) -> IO<RootedThread> {
match vm.new_thread() {
Ok(thread) => IO::Value(thread),
Err(err) => IO::Exception(err.to_string()),
}
}
fn sleep(ms: VmInt) -> IO<()> {
use std::time::Duration;
::std::thread::sleep(Duration::from_millis(ms as u64));
IO::Value(())
}
fn interrupt(thread: RootedThread) -> IO<()> {
thread.interrupt();
IO::Value(())
}
mod std {
pub use channel;
pub mod thread {
pub use channel as prim;
}
}
pub fn load_channel<'vm>(vm: &'vm Thread) -> VmResult<ExternModule> {
let _ = vm.register_type::<Sender<A>>("Sender", &["a"]);
let _ = vm.register_type::<Receiver<A>>("Receiver", &["a"]);
ExternModule::new(
vm,
record!{
type Sender a => Sender<A>,
type Receiver a => Sender<A>,
channel => primitive!(1 std::channel::channel),
recv => primitive!(1 std::channel::recv),
send => primitive!(2 std::channel::send),
},
)
}
pub fn load_thread<'vm>(vm: &'vm Thread) -> VmResult<ExternModule> {
ExternModule::new(
vm,
record!{
resume => primitive::<fn(&'vm Thread) -> Result<(), String>>("std.thread.prim.resume", resume),
(yield_ "yield") => primitive::<fn(())>("std.thread.prim.yield", yield_),
spawn => primitive!(1 std::thread::prim::spawn),
spawn_on => primitive!(2 std::thread::prim::spawn_on),
new_thread => primitive!(1 std::thread::prim::new_thread),
interrupt => primitive!(1 std::thread::prim::interrupt),
sleep => primitive!(1 std::thread::prim::sleep)
},
)
} |
#[cfg(not(target_arch = "wasm32"))]
fn spawn_on<'vm>( | random_line_split |
channel.rs | use std::any::Any;
use std::collections::VecDeque;
use std::fmt;
use std::sync::{Arc, Mutex};
use futures::sync::oneshot;
use futures::Future;
use base::types::{ArcType, Type};
use api::generic::A;
use api::{
primitive, AsyncPushable, Function, FunctionRef, FutureResult, Generic, Getable, OpaqueValue,
OwnedFunction, Pushable, RuntimeResult, VmType, WithVM, IO,
};
use gc::{Gc, GcPtr, Traverseable};
use stack::{StackFrame, State};
use thread::{OwnedContext, ThreadInternal};
use types::VmInt;
use value::{Callable, GcStr, Userdata, ValueRepr};
use vm::{RootedThread, Status, Thread};
use {Error, ExternModule, Result as VmResult};
pub struct Sender<T> {
// No need to traverse this thread reference as any thread having a reference to this `Sender`
// would also directly own a reference to the `Thread`
thread: GcPtr<Thread>,
queue: Arc<Mutex<VecDeque<T>>>,
}
impl<T> Userdata for Sender<T>
where
T: Any + Send + Sync + fmt::Debug + Traverseable,
{
}
impl<T> fmt::Debug for Sender<T>
where
T: fmt::Debug,
{
fn | (&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{:?}", *self.queue.lock().unwrap())
}
}
impl<T> Traverseable for Sender<T> {
fn traverse(&self, _gc: &mut Gc) {
// No need to traverse in Sender as values can only be accessed through Receiver
}
}
impl<T> Sender<T> {
fn send(&self, value: T) {
self.queue.lock().unwrap().push_back(value);
}
}
impl<T: Traverseable> Traverseable for Receiver<T> {
fn traverse(&self, gc: &mut Gc) {
self.queue.lock().unwrap().traverse(gc);
}
}
pub struct Receiver<T> {
queue: Arc<Mutex<VecDeque<T>>>,
}
impl<T> Userdata for Receiver<T>
where
T: Any + Send + Sync + fmt::Debug + Traverseable,
{
}
impl<T> fmt::Debug for Receiver<T>
where
T: fmt::Debug,
{
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{:?}", *self.queue.lock().unwrap())
}
}
impl<T> Receiver<T> {
fn try_recv(&self) -> Result<T, ()> {
self.queue.lock().unwrap().pop_front().ok_or(())
}
}
impl<T: VmType> VmType for Sender<T>
where
T::Type: Sized,
{
type Type = Sender<T::Type>;
fn make_type(vm: &Thread) -> ArcType {
let symbol = vm
.global_env()
.get_env()
.find_type_info("Sender")
.unwrap()
.name
.clone();
Type::app(Type::ident(symbol), collect![T::make_type(vm)])
}
}
impl<T: VmType> VmType for Receiver<T>
where
T::Type: Sized,
{
type Type = Receiver<T::Type>;
fn make_type(vm: &Thread) -> ArcType {
let symbol = vm
.global_env()
.get_env()
.find_type_info("Receiver")
.unwrap()
.name
.clone();
Type::app(Type::ident(symbol), collect![T::make_type(vm)])
}
}
field_decl!{ sender, receiver }
pub type ChannelRecord<S, R> = record_type!(sender => S, receiver => R);
/// FIXME The dummy `a` argument should not be needed to ensure that the channel can only be used
/// with a single type
fn channel(
WithVM { vm, .. }: WithVM<Generic<A>>,
) -> ChannelRecord<Sender<Generic<A>>, Receiver<Generic<A>>> {
let sender = Sender {
thread: unsafe { GcPtr::from_raw(vm) },
queue: Arc::new(Mutex::new(VecDeque::new())),
};
let receiver = Receiver {
queue: sender.queue.clone(),
};
record_no_decl!(sender => sender, receiver => receiver)
}
fn recv(receiver: &Receiver<Generic<A>>) -> Result<Generic<A>, ()> {
receiver.try_recv().map_err(|_| ())
}
fn send(sender: &Sender<Generic<A>>, value: Generic<A>) -> Result<(), ()> {
unsafe {
let value = sender
.thread
.deep_clone_value(&sender.thread, value.get_value())
.map_err(|_| ())?;
Ok(sender.send(Generic::from(value)))
}
}
extern "C" fn resume(vm: &Thread) -> Status {
let mut context = vm.context();
let value = StackFrame::current(&mut context.stack)[0].get_repr();
match value {
ValueRepr::Thread(child) => {
let lock = StackFrame::current(&mut context.stack).into_lock();
drop(context);
let result = child.resume();
context = vm.context();
context.stack.release_lock(lock);
match result {
Ok(child_context) => {
// Prevent dead lock if the following status_push call allocates
drop(child_context);
let value: Result<(), &str> = Ok(());
value.status_push(vm, &mut context)
}
Err(Error::Dead) => {
let value: Result<(), &str> = Err("Attempted to resume a dead thread");
value.status_push(vm, &mut context)
}
Err(err) => {
let fmt = format!("{}", err);
let result = unsafe {
ValueRepr::String(GcStr::from_utf8_unchecked(
context.alloc_ignore_limit(fmt.as_bytes()),
))
};
context.stack.push(result);
Status::Error
}
}
}
_ => unreachable!(),
}
}
extern "C" fn yield_(_vm: &Thread) -> Status {
Status::Yield
}
fn spawn<'vm>(
value: WithVM<'vm, Function<&'vm Thread, fn(())>>,
) -> RuntimeResult<RootedThread, Error> {
spawn_(value).into()
}
fn spawn_<'vm>(value: WithVM<'vm, Function<&'vm Thread, fn(())>>) -> VmResult<RootedThread> {
let thread = value.vm.new_thread()?;
{
let mut context = thread.context();
let callable = match value.value.get_variant().0 {
ValueRepr::Closure(c) => State::Closure(c),
ValueRepr::Function(c) => State::Extern(c),
_ => State::Unknown,
};
value.value.push(value.vm, &mut context)?;
context.stack.push(ValueRepr::Int(0));
StackFrame::current(&mut context.stack).enter_scope(1, callable);
}
Ok(thread)
}
type Action = fn(()) -> OpaqueValue<RootedThread, IO<Generic<A>>>;
#[cfg(target_arch = "wasm32")]
fn spawn_on<'vm>(
_thread: RootedThread,
_action: WithVM<'vm, FunctionRef<Action>>,
) -> IO<OpaqueValue<&'vm Thread, IO<Generic<A>>>> {
IO::Exception("spawn_on requires the `tokio_core` crate".to_string())
}
#[cfg(not(target_arch = "wasm32"))]
fn spawn_on<'vm>(
thread: RootedThread,
action: WithVM<'vm, FunctionRef<Action>>,
) -> IO<OpaqueValue<&'vm Thread, IO<Generic<A>>>> {
struct SpawnFuture<F>(Mutex<Option<F>>);
impl<F> fmt::Debug for SpawnFuture<F> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "Future")
}
}
impl<F> Userdata for SpawnFuture<F>
where
F: Send + 'static,
{
}
impl<F> Traverseable for SpawnFuture<F> {
fn traverse(&self, _: &mut Gc) {}
}
impl<F> VmType for SpawnFuture<F> {
type Type = Generic<A>;
}
fn push_future_wrapper<G>(vm: &Thread, context: &mut OwnedContext, _: &G)
where
G: Future<Item = OpaqueValue<RootedThread, IO<Generic<A>>>, Error = Error> + Send + 'static,
{
extern "C" fn future_wrapper<F>(vm: &Thread) -> Status
where
F: Future<Item = OpaqueValue<RootedThread, IO<Generic<A>>>, Error = Error>
+ Send
+ 'static,
{
let mut context = vm.context();
let value = StackFrame::current(&mut context.stack)[0].get_repr();
match value {
ValueRepr::Userdata(data) => {
let data = data.downcast_ref::<SpawnFuture<F>>().unwrap();
let future = data.0.lock().unwrap().take().unwrap();
let lock = StackFrame::current(&mut context.stack).insert_lock();
AsyncPushable::async_status_push(
FutureResult::new(future),
vm,
&mut context,
lock,
)
}
_ => unreachable!(),
}
}
type FutureArg = ();
primitive::<fn(FutureArg) -> IO<Generic<A>>>("unknown", future_wrapper::<G>)
.push(vm, context)
.unwrap();
}
use value::PartialApplicationDataDef;
let WithVM { vm, value: action } = action;
let mut action = OwnedFunction::<Action>::from_value(&thread, action.get_variant());
let future = oneshot::spawn_fn(
move || action.call_async(()),
&vm.global_env().get_event_loop().expect("event loop"),
);
let mut context = vm.context();
push_future_wrapper(vm, &mut context, &future);
let callable = match context.stack[context.stack.len() - 1].get_repr() {
ValueRepr::Function(ext) => Callable::Extern(ext),
_ => unreachable!(),
};
SpawnFuture(Mutex::new(Some(future)))
.push(vm, &mut context)
.unwrap();
let fields = [context.stack.get_values().last().unwrap().clone()];
let def = PartialApplicationDataDef(callable, &fields);
let value = ValueRepr::PartialApplication(context.alloc_with(vm, def).unwrap()).into();
context.stack.pop_many(2);
// TODO Remove rooting here
IO::Value(OpaqueValue::from_value(vm.root_value(value)))
}
fn new_thread(WithVM { vm, .. }: WithVM<()>) -> IO<RootedThread> {
match vm.new_thread() {
Ok(thread) => IO::Value(thread),
Err(err) => IO::Exception(err.to_string()),
}
}
fn sleep(ms: VmInt) -> IO<()> {
use std::time::Duration;
::std::thread::sleep(Duration::from_millis(ms as u64));
IO::Value(())
}
fn interrupt(thread: RootedThread) -> IO<()> {
thread.interrupt();
IO::Value(())
}
mod std {
pub use channel;
pub mod thread {
pub use channel as prim;
}
}
pub fn load_channel<'vm>(vm: &'vm Thread) -> VmResult<ExternModule> {
let _ = vm.register_type::<Sender<A>>("Sender", &["a"]);
let _ = vm.register_type::<Receiver<A>>("Receiver", &["a"]);
ExternModule::new(
vm,
record!{
type Sender a => Sender<A>,
type Receiver a => Sender<A>,
channel => primitive!(1 std::channel::channel),
recv => primitive!(1 std::channel::recv),
send => primitive!(2 std::channel::send),
},
)
}
pub fn load_thread<'vm>(vm: &'vm Thread) -> VmResult<ExternModule> {
ExternModule::new(
vm,
record!{
resume => primitive::<fn(&'vm Thread) -> Result<(), String>>("std.thread.prim.resume", resume),
(yield_ "yield") => primitive::<fn(())>("std.thread.prim.yield", yield_),
spawn => primitive!(1 std::thread::prim::spawn),
spawn_on => primitive!(2 std::thread::prim::spawn_on),
new_thread => primitive!(1 std::thread::prim::new_thread),
interrupt => primitive!(1 std::thread::prim::interrupt),
sleep => primitive!(1 std::thread::prim::sleep)
},
)
}
| fmt | identifier_name |
devices.js | const express = require('express')
const router = express.Router()
const axios = require('axios')
const {checkAuth} = require('../middlewares/authentication.js')
import Device from '../models/device.js'
import AlarmRule from '../models/emqx_alarm_rule.js'
import SaverRule from '../models/emqx_saver_rule.js'
import Template from '../models/template.js'
import EmqxAuthRule from "../models/emqx_auth.js";
import Data from "../models/data.js";
/*
__ __ ____ _____ ______ _ _____
| \/ |/ __ \| __ \| ____| | / ____|
| \ / | | | | | | | |__ | | | (___
| |\/| | | | | | | | __| | | \___ \
| | | | |__| | |__| | |____| |____ ____) |
|_| |_|\____/|_____/|______|______|_____/
*/
/* _____ _____
/\ | __ \_ _|
/ \ | |__) || |
/ /\ \ | ___/ | |
/ ____ \| | _| |_
/_/ \_\_| |_____|
*/
const auth ={
auth:{
username: 'admin',
password: process.env.EMQX_DEFAULT_APPLICATION_SECRET
}
}
//GET DEVICES
router.get("/device", checkAuth, async (req, res) =>{
try {
const userId = req.userData._id
//get devices
var devices = await Device.find({userId: userId})
//descoupling
devices = JSON.parse(JSON.stringify(devices))
//get saver rules
const saverRules = await getSaverRules(userId)
//get templates
const templates = await getTemplate(userId)
// get alarm rule
const alarmRules = await getAlarmRules(userId)
//saver rules to -> devices
devices.forEach((device, index) => {
devices[index].saverRule = saverRules.filter(
saverRule => saverRule.dId == device.dId)[0]
devices[index].template = templates.filter(
template => template._id == device.templateId)[0]
devices[index].alarmRules = alarmRules.filter(alarmRule => alarmRule.dId == device.dId)
})
const toSend = {
status: "success",
data: devices
}
res.json(toSend)
} catch (error) {
console.log("ERROR GETTING DEVICES")
console.log(error)
const toSend = {
status: "error",
error: error
}
return res.status(500).json(toSend)
}
})
//NEW DEVICE
router.post("/device", checkAuth, async (req, res) =>{
try {
const userId = req.userData._id
var newDevice = req.body.newDevice
newDevice.userId = userId
newDevice.createdTime = Date.now()
newDevice.password = makeid(10)
await createSaverRule(userId, newDevice.dId, true)
const device = await Device.create(newDevice)
await selectDevice(userId, newDevice.dId)
const toSend = {
status: "success"
}
return res.json(toSend)
} catch (error) {
console.log("ERROR CREATING NEW DEVICE")
console.log(error)
const toSend = {
status: "error",
error: error
}
return res.status(500).json(toSend)
}
})
//DELETE DEVICE
router.delete("/device", checkAuth, async (req, res) =>{
try {
const userId = req.userData._id
const dId = req.query.dId
await deleteSaverRule(dId)
//deleting all posible alarm rules
await deleteAllAlarmRules(userId, dId);
//deleting all posible mqtt device credentials
await deleteMqttDeviceCredentials(dId);
//deleting data mqtt
await deleteMqttDataDevices(dId)
const result = await Device.deleteOne({userId: userId, dId: dId})
const toSend = {
status: "success",
data: result
}
return res.json(toSend)
} catch (error) {
console.log("ERROR DELETING DEVICE")
console.log(error)
const toSend = {
status: "error"
}
return res.json(toSend)
}
})
//UPDATE DEVICE (SELECTOR)
router.put("/device", checkAuth, async (req, res) =>{
const dId = req.body.dId
const userId = req.userData._id
if(await selectDevice(userId,dId)){
const toSend = {
status: "success"
}
return res.json(toSend)
}else{
const toSend = {
status: "error"
}
return res.json(toSend)
}
})
//SAVER-RULE STATUS UPDATER
router.put('/saver-rule', checkAuth, async(req, res) => {
const rule = req.body.rule
await updateSaverRuleStatus(rule.emqxRuleId, rule.status)
const toSend = {
status: "success"
}
res.json(toSend)
})
/*
______ _ _ _ _ _______ _____ ____ _ _ _____
| ____| | | | \ | |__ __|_ _/ __ \| \ | |/ ____|
| |__ | | | | \| | | | | || | | | \| | (___
| __| | | | | . ` | | | | || | | | . ` |\___ \
| | | |__| | |\ | | | _| || |__| | |\ |____) |
|_| \____/|_| \_| |_| |_____\____/|_| \_|_____/
*/
async function | (userId) {
try {
const rules = await AlarmRule.find({userId})
return rules
} catch (error) {
return "error"
}
}
async function selectDevice(userId, dId){
try {
const result = await Device.updateMany({userId: userId}, {selected: false})
const result2 = await Device.updateOne({dId: dId, userId: userId},{selected:true})
return true
} catch (error) {
console.log("ERROR IN 'selectedDevice' FUNCTION")
console.log(error)
return false
}
}
/*
//SAVER RULES FUNCTION
*/
//get templates
async function getTemplate(userId) {
try {
const templates = await Template.find({ userId: userId})
return templates
} catch (error) {
return false
}
}
//get saver rules
async function getSaverRules(userId) {
try {
const rules = await SaverRule.find({ userId: userId})
return rules
} catch (error) {
console.log("Error enviando RULES")
console.log(error)
return false
}
}
//Create saver rule
async function createSaverRule(userId, dId, status) {
try {
const url = "http://"+process.env.EMQX_NODE_HOST+":8085/api/v4/rules"
const topic = userId + "/" + dId + "/+/sdata"
const rawsql = "SELECT topic, payload FROM \"" + topic + "\" WHERE payload.save = 1"
var newRule = {
rawsql: rawsql,
actions: [
{
name: "data_to_webserver",
params: {
$resource: global.saverResource.id,
payload_tmpl: '{"userId":"' + userId + '","payload":${payload},"topic":"${topic}"}'
}
}
],
description: "SAVER-RULE",
enabled: status
}
//save rule in emqx - grabamos regla en emqx
const res = await axios.post(url, newRule, auth)
if (res.status === 200 && res.data.data) {
console.log(res.data.data)
await SaverRule.create({
userId: userId,
dId: dId,
emqxRuleId: res.data.data.id,
status: status
})
return true
}else {
console.log("Aqui esta el error ERRROR")
return false
}
} catch (error) {
console.log("Error creating SAVER RULE")
console.log(error)
return false
}
}
//Update saver rule
async function updateSaverRuleStatus(emqxRuleId, status) {
const url = "http://"+process.env.EMQX_NODE_HOST+":8085/api/v4/rules/" + emqxRuleId
const newRule = {
enabled: status
}
const res = await axios.put(url, newRule, auth)
if (res.status === 200 && res.data.data) {
await SaverRule.updateOne({ emqxRuleId: emqxRuleId}, {status: status})
console.log("Saver Rule Status Update...".green)
return {
status: "success",
action: "update"
}
}
}
//delete saver rule
async function deleteSaverRule(dId) {
try {
const mongoRule = await SaverRule.findOne({dId: dId})
const url = "http://"+process.env.EMQX_NODE_HOST+":8085/api/v4/rules/" + mongoRule.emqxRuleId
const emqxRule = await axios.delete(url, auth)
const deleted = await SaverRule.deleteOne({dId: dId})
return true
} catch (error) {
console.log("Error Deleting Saver Rule")
console.log(error)
return false
}
}
//delete ALL alarm Rules...
async function deleteAllAlarmRules(userId, dId) {
try {
const rules = await AlarmRule.find({ userId: userId, dId: dId });
if (rules.length > 0) {
asyncForEach(rules, async rule => {
const url = "http://"+process.env.EMQX_NODE_HOST+":8085/api/v4/rules/" + rule.emqxRuleId;
const res = await axios.delete(url, auth);
});
await AlarmRule.deleteMany({ userId: userId, dId: dId });
}
return true;
} catch (error) {
console.log(error);
return "error";
}
}
// We can solve this by creating our own asyncForEach() method:
// thanks to Sebastien Chopin - Nuxt Creator :)
// https://codeburst.io/javascript-async-await-with-foreach-b6ba62bbf404
async function asyncForEach(array, callback) {
for (let index = 0; index < array.length; index++) {
await callback(array[index], index, array);
}
}
//delete ALL emqx device auth rules
async function deleteMqttDeviceCredentials(dId) {
try {
await EmqxAuthRule.deleteMany({ dId: dId, type: "device" });
return true;
} catch (error) {
console.log(error);
return false;
}
}
async function deleteMqttDataDevices(dId) {
try {
await Data.deleteMany({dId: dId});
return true;
} catch (error) {
console.log(error);
return false;
}
}
function makeid(length) {
var result =''
var characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
var charactersLength = characters.length
for (var i = 0; i < length; i ++) {
result += characters.charAt (
Math.floor(Math.random() * charactersLength)
)
}
return result
}
module.exports = router | getAlarmRules | identifier_name |
devices.js | const express = require('express')
const router = express.Router()
const axios = require('axios')
const {checkAuth} = require('../middlewares/authentication.js')
import Device from '../models/device.js'
import AlarmRule from '../models/emqx_alarm_rule.js'
import SaverRule from '../models/emqx_saver_rule.js'
import Template from '../models/template.js'
import EmqxAuthRule from "../models/emqx_auth.js";
import Data from "../models/data.js";
/*
__ __ ____ _____ ______ _ _____
| \/ |/ __ \| __ \| ____| | / ____|
| \ / | | | | | | | |__ | | | (___
| |\/| | | | | | | | __| | | \___ \
| | | | |__| | |__| | |____| |____ ____) |
|_| |_|\____/|_____/|______|______|_____/
*/
/* _____ _____
/\ | __ \_ _|
/ \ | |__) || |
/ /\ \ | ___/ | |
/ ____ \| | _| |_
/_/ \_\_| |_____|
*/
const auth ={
auth:{
username: 'admin',
password: process.env.EMQX_DEFAULT_APPLICATION_SECRET
}
}
//GET DEVICES
router.get("/device", checkAuth, async (req, res) =>{
try {
const userId = req.userData._id
//get devices
var devices = await Device.find({userId: userId})
//descoupling
devices = JSON.parse(JSON.stringify(devices))
//get saver rules
const saverRules = await getSaverRules(userId)
//get templates
const templates = await getTemplate(userId)
// get alarm rule
const alarmRules = await getAlarmRules(userId)
//saver rules to -> devices
devices.forEach((device, index) => {
devices[index].saverRule = saverRules.filter(
saverRule => saverRule.dId == device.dId)[0]
devices[index].template = templates.filter(
template => template._id == device.templateId)[0]
devices[index].alarmRules = alarmRules.filter(alarmRule => alarmRule.dId == device.dId)
})
const toSend = {
status: "success",
data: devices
}
res.json(toSend)
} catch (error) {
console.log("ERROR GETTING DEVICES")
console.log(error)
const toSend = {
status: "error",
error: error
}
return res.status(500).json(toSend)
}
})
//NEW DEVICE
router.post("/device", checkAuth, async (req, res) =>{
try {
const userId = req.userData._id
var newDevice = req.body.newDevice
newDevice.userId = userId
newDevice.createdTime = Date.now()
newDevice.password = makeid(10)
await createSaverRule(userId, newDevice.dId, true)
const device = await Device.create(newDevice)
await selectDevice(userId, newDevice.dId)
const toSend = {
status: "success"
}
return res.json(toSend)
} catch (error) {
console.log("ERROR CREATING NEW DEVICE")
console.log(error)
const toSend = {
status: "error",
error: error
}
return res.status(500).json(toSend)
}
})
//DELETE DEVICE
router.delete("/device", checkAuth, async (req, res) =>{
try {
const userId = req.userData._id
const dId = req.query.dId
await deleteSaverRule(dId)
//deleting all posible alarm rules
await deleteAllAlarmRules(userId, dId);
//deleting all posible mqtt device credentials
await deleteMqttDeviceCredentials(dId);
//deleting data mqtt
await deleteMqttDataDevices(dId)
const result = await Device.deleteOne({userId: userId, dId: dId})
const toSend = {
status: "success",
data: result
}
return res.json(toSend)
} catch (error) {
console.log("ERROR DELETING DEVICE")
console.log(error)
const toSend = {
status: "error"
}
return res.json(toSend)
}
})
//UPDATE DEVICE (SELECTOR)
router.put("/device", checkAuth, async (req, res) =>{
const dId = req.body.dId
const userId = req.userData._id
if(await selectDevice(userId,dId)){
const toSend = {
status: "success"
}
return res.json(toSend)
}else{
const toSend = {
status: "error"
}
return res.json(toSend)
}
})
//SAVER-RULE STATUS UPDATER
router.put('/saver-rule', checkAuth, async(req, res) => {
const rule = req.body.rule
await updateSaverRuleStatus(rule.emqxRuleId, rule.status)
const toSend = {
status: "success"
}
res.json(toSend)
})
/*
______ _ _ _ _ _______ _____ ____ _ _ _____
| ____| | | | \ | |__ __|_ _/ __ \| \ | |/ ____|
| |__ | | | | \| | | | | || | | | \| | (___
| __| | | | | . ` | | | | || | | | . ` |\___ \
| | | |__| | |\ | | | _| || |__| | |\ |____) |
|_| \____/|_| \_| |_| |_____\____/|_| \_|_____/
*/
async function getAlarmRules(userId) {
try {
const rules = await AlarmRule.find({userId})
return rules
} catch (error) {
return "error"
}
}
async function selectDevice(userId, dId){
try {
const result = await Device.updateMany({userId: userId}, {selected: false})
const result2 = await Device.updateOne({dId: dId, userId: userId},{selected:true})
return true
} catch (error) {
console.log("ERROR IN 'selectedDevice' FUNCTION")
console.log(error)
return false
}
}
/*
//SAVER RULES FUNCTION
*/
//get templates
async function getTemplate(userId) {
try {
const templates = await Template.find({ userId: userId})
return templates
} catch (error) {
return false
}
}
//get saver rules
async function getSaverRules(userId) {
try {
const rules = await SaverRule.find({ userId: userId})
return rules
} catch (error) {
console.log("Error enviando RULES")
console.log(error)
return false
}
}
//Create saver rule
async function createSaverRule(userId, dId, status) {
try {
const url = "http://"+process.env.EMQX_NODE_HOST+":8085/api/v4/rules"
const topic = userId + "/" + dId + "/+/sdata"
const rawsql = "SELECT topic, payload FROM \"" + topic + "\" WHERE payload.save = 1"
var newRule = {
rawsql: rawsql,
actions: [
{
name: "data_to_webserver",
params: {
$resource: global.saverResource.id,
payload_tmpl: '{"userId":"' + userId + '","payload":${payload},"topic":"${topic}"}'
}
}
],
description: "SAVER-RULE",
enabled: status
}
//save rule in emqx - grabamos regla en emqx
const res = await axios.post(url, newRule, auth)
if (res.status === 200 && res.data.data) {
console.log(res.data.data)
await SaverRule.create({
userId: userId,
dId: dId,
emqxRuleId: res.data.data.id,
status: status
})
return true
}else {
console.log("Aqui esta el error ERRROR")
return false
}
} catch (error) {
console.log("Error creating SAVER RULE")
console.log(error)
return false
}
}
//Update saver rule
async function updateSaverRuleStatus(emqxRuleId, status) {
const url = "http://"+process.env.EMQX_NODE_HOST+":8085/api/v4/rules/" + emqxRuleId
const newRule = {
enabled: status
}
const res = await axios.put(url, newRule, auth)
if (res.status === 200 && res.data.data) {
await SaverRule.updateOne({ emqxRuleId: emqxRuleId}, {status: status})
console.log("Saver Rule Status Update...".green)
return {
status: "success",
action: "update"
}
}
}
//delete saver rule
async function deleteSaverRule(dId) {
try {
const mongoRule = await SaverRule.findOne({dId: dId})
const url = "http://"+process.env.EMQX_NODE_HOST+":8085/api/v4/rules/" + mongoRule.emqxRuleId
const emqxRule = await axios.delete(url, auth)
const deleted = await SaverRule.deleteOne({dId: dId})
return true
} catch (error) {
console.log("Error Deleting Saver Rule")
console.log(error)
return false
}
}
//delete ALL alarm Rules...
async function deleteAllAlarmRules(userId, dId) |
// We can solve this by creating our own asyncForEach() method:
// thanks to Sebastien Chopin - Nuxt Creator :)
// https://codeburst.io/javascript-async-await-with-foreach-b6ba62bbf404
async function asyncForEach(array, callback) {
for (let index = 0; index < array.length; index++) {
await callback(array[index], index, array);
}
}
//delete ALL emqx device auth rules
async function deleteMqttDeviceCredentials(dId) {
try {
await EmqxAuthRule.deleteMany({ dId: dId, type: "device" });
return true;
} catch (error) {
console.log(error);
return false;
}
}
async function deleteMqttDataDevices(dId) {
try {
await Data.deleteMany({dId: dId});
return true;
} catch (error) {
console.log(error);
return false;
}
}
function makeid(length) {
var result =''
var characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
var charactersLength = characters.length
for (var i = 0; i < length; i ++) {
result += characters.charAt (
Math.floor(Math.random() * charactersLength)
)
}
return result
}
module.exports = router | {
try {
const rules = await AlarmRule.find({ userId: userId, dId: dId });
if (rules.length > 0) {
asyncForEach(rules, async rule => {
const url = "http://"+process.env.EMQX_NODE_HOST+":8085/api/v4/rules/" + rule.emqxRuleId;
const res = await axios.delete(url, auth);
});
await AlarmRule.deleteMany({ userId: userId, dId: dId });
}
return true;
} catch (error) {
console.log(error);
return "error";
}
} | identifier_body |
devices.js | const express = require('express')
const router = express.Router()
const axios = require('axios')
const {checkAuth} = require('../middlewares/authentication.js')
import Device from '../models/device.js'
import AlarmRule from '../models/emqx_alarm_rule.js'
import SaverRule from '../models/emqx_saver_rule.js'
import Template from '../models/template.js'
import EmqxAuthRule from "../models/emqx_auth.js";
import Data from "../models/data.js";
/*
__ __ ____ _____ ______ _ _____
| \/ |/ __ \| __ \| ____| | / ____|
| \ / | | | | | | | |__ | | | (___
| |\/| | | | | | | | __| | | \___ \
| | | | |__| | |__| | |____| |____ ____) |
|_| |_|\____/|_____/|______|______|_____/
*/
/* _____ _____
/\ | __ \_ _|
/ \ | |__) || |
/ /\ \ | ___/ | |
/ ____ \| | _| |_
/_/ \_\_| |_____|
*/
const auth ={
auth:{
username: 'admin',
password: process.env.EMQX_DEFAULT_APPLICATION_SECRET
}
}
//GET DEVICES
router.get("/device", checkAuth, async (req, res) =>{
try {
const userId = req.userData._id
//get devices
var devices = await Device.find({userId: userId})
//descoupling
devices = JSON.parse(JSON.stringify(devices))
//get saver rules
const saverRules = await getSaverRules(userId)
//get templates
const templates = await getTemplate(userId)
// get alarm rule
const alarmRules = await getAlarmRules(userId)
//saver rules to -> devices
devices.forEach((device, index) => {
devices[index].saverRule = saverRules.filter(
saverRule => saverRule.dId == device.dId)[0]
devices[index].template = templates.filter(
template => template._id == device.templateId)[0]
devices[index].alarmRules = alarmRules.filter(alarmRule => alarmRule.dId == device.dId)
})
const toSend = {
status: "success",
data: devices
}
res.json(toSend)
} catch (error) {
console.log("ERROR GETTING DEVICES")
console.log(error)
const toSend = {
status: "error",
error: error
}
return res.status(500).json(toSend)
}
})
//NEW DEVICE
router.post("/device", checkAuth, async (req, res) =>{
try {
const userId = req.userData._id
var newDevice = req.body.newDevice
newDevice.userId = userId
newDevice.createdTime = Date.now()
newDevice.password = makeid(10)
await createSaverRule(userId, newDevice.dId, true)
const device = await Device.create(newDevice)
await selectDevice(userId, newDevice.dId)
const toSend = {
status: "success"
}
return res.json(toSend)
} catch (error) {
console.log("ERROR CREATING NEW DEVICE")
console.log(error)
const toSend = {
status: "error",
error: error
}
return res.status(500).json(toSend)
}
})
//DELETE DEVICE
router.delete("/device", checkAuth, async (req, res) =>{
try {
const userId = req.userData._id
const dId = req.query.dId
await deleteSaverRule(dId)
//deleting all posible alarm rules
await deleteAllAlarmRules(userId, dId);
//deleting all posible mqtt device credentials
await deleteMqttDeviceCredentials(dId);
//deleting data mqtt
await deleteMqttDataDevices(dId)
const result = await Device.deleteOne({userId: userId, dId: dId})
const toSend = {
status: "success",
data: result
}
return res.json(toSend)
} catch (error) {
console.log("ERROR DELETING DEVICE")
console.log(error)
const toSend = {
status: "error"
}
return res.json(toSend)
}
})
//UPDATE DEVICE (SELECTOR)
router.put("/device", checkAuth, async (req, res) =>{
const dId = req.body.dId
const userId = req.userData._id
if(await selectDevice(userId,dId)){
const toSend = {
status: "success"
}
return res.json(toSend)
}else{
const toSend = {
status: "error"
}
return res.json(toSend)
}
})
//SAVER-RULE STATUS UPDATER
router.put('/saver-rule', checkAuth, async(req, res) => {
const rule = req.body.rule
await updateSaverRuleStatus(rule.emqxRuleId, rule.status)
const toSend = {
status: "success"
}
res.json(toSend)
})
/*
______ _ _ _ _ _______ _____ ____ _ _ _____
| ____| | | | \ | |__ __|_ _/ __ \| \ | |/ ____|
| |__ | | | | \| | | | | || | | | \| | (___
| __| | | | | . ` | | | | || | | | . ` |\___ \
| | | |__| | |\ | | | _| || |__| | |\ |____) |
|_| \____/|_| \_| |_| |_____\____/|_| \_|_____/
*/
async function getAlarmRules(userId) {
try {
const rules = await AlarmRule.find({userId})
return rules
} catch (error) {
return "error"
}
}
async function selectDevice(userId, dId){
try {
const result = await Device.updateMany({userId: userId}, {selected: false})
const result2 = await Device.updateOne({dId: dId, userId: userId},{selected:true})
return true
} catch (error) {
console.log("ERROR IN 'selectedDevice' FUNCTION")
console.log(error)
return false
}
}
/*
//SAVER RULES FUNCTION
*/
//get templates
async function getTemplate(userId) {
try {
const templates = await Template.find({ userId: userId})
return templates
} catch (error) {
return false
}
}
//get saver rules
async function getSaverRules(userId) {
try {
const rules = await SaverRule.find({ userId: userId})
return rules
} catch (error) {
console.log("Error enviando RULES")
console.log(error)
return false
}
}
//Create saver rule
async function createSaverRule(userId, dId, status) {
try {
const url = "http://"+process.env.EMQX_NODE_HOST+":8085/api/v4/rules"
const topic = userId + "/" + dId + "/+/sdata"
const rawsql = "SELECT topic, payload FROM \"" + topic + "\" WHERE payload.save = 1"
var newRule = {
rawsql: rawsql,
actions: [
{
name: "data_to_webserver",
params: {
$resource: global.saverResource.id,
payload_tmpl: '{"userId":"' + userId + '","payload":${payload},"topic":"${topic}"}'
}
}
],
description: "SAVER-RULE",
enabled: status
}
//save rule in emqx - grabamos regla en emqx
const res = await axios.post(url, newRule, auth)
if (res.status === 200 && res.data.data) {
console.log(res.data.data)
await SaverRule.create({
userId: userId,
dId: dId,
emqxRuleId: res.data.data.id,
status: status
})
return true
}else {
console.log("Aqui esta el error ERRROR")
return false
}
} catch (error) {
console.log("Error creating SAVER RULE")
console.log(error)
return false
}
}
//Update saver rule
async function updateSaverRuleStatus(emqxRuleId, status) { | }
const res = await axios.put(url, newRule, auth)
if (res.status === 200 && res.data.data) {
await SaverRule.updateOne({ emqxRuleId: emqxRuleId}, {status: status})
console.log("Saver Rule Status Update...".green)
return {
status: "success",
action: "update"
}
}
}
//delete saver rule
async function deleteSaverRule(dId) {
try {
const mongoRule = await SaverRule.findOne({dId: dId})
const url = "http://"+process.env.EMQX_NODE_HOST+":8085/api/v4/rules/" + mongoRule.emqxRuleId
const emqxRule = await axios.delete(url, auth)
const deleted = await SaverRule.deleteOne({dId: dId})
return true
} catch (error) {
console.log("Error Deleting Saver Rule")
console.log(error)
return false
}
}
//delete ALL alarm Rules...
async function deleteAllAlarmRules(userId, dId) {
try {
const rules = await AlarmRule.find({ userId: userId, dId: dId });
if (rules.length > 0) {
asyncForEach(rules, async rule => {
const url = "http://"+process.env.EMQX_NODE_HOST+":8085/api/v4/rules/" + rule.emqxRuleId;
const res = await axios.delete(url, auth);
});
await AlarmRule.deleteMany({ userId: userId, dId: dId });
}
return true;
} catch (error) {
console.log(error);
return "error";
}
}
// We can solve this by creating our own asyncForEach() method:
// thanks to Sebastien Chopin - Nuxt Creator :)
// https://codeburst.io/javascript-async-await-with-foreach-b6ba62bbf404
async function asyncForEach(array, callback) {
for (let index = 0; index < array.length; index++) {
await callback(array[index], index, array);
}
}
//delete ALL emqx device auth rules
async function deleteMqttDeviceCredentials(dId) {
try {
await EmqxAuthRule.deleteMany({ dId: dId, type: "device" });
return true;
} catch (error) {
console.log(error);
return false;
}
}
async function deleteMqttDataDevices(dId) {
try {
await Data.deleteMany({dId: dId});
return true;
} catch (error) {
console.log(error);
return false;
}
}
function makeid(length) {
var result =''
var characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
var charactersLength = characters.length
for (var i = 0; i < length; i ++) {
result += characters.charAt (
Math.floor(Math.random() * charactersLength)
)
}
return result
}
module.exports = router |
const url = "http://"+process.env.EMQX_NODE_HOST+":8085/api/v4/rules/" + emqxRuleId
const newRule = {
enabled: status | random_line_split |
devices.js | const express = require('express')
const router = express.Router()
const axios = require('axios')
const {checkAuth} = require('../middlewares/authentication.js')
import Device from '../models/device.js'
import AlarmRule from '../models/emqx_alarm_rule.js'
import SaverRule from '../models/emqx_saver_rule.js'
import Template from '../models/template.js'
import EmqxAuthRule from "../models/emqx_auth.js";
import Data from "../models/data.js";
/*
__ __ ____ _____ ______ _ _____
| \/ |/ __ \| __ \| ____| | / ____|
| \ / | | | | | | | |__ | | | (___
| |\/| | | | | | | | __| | | \___ \
| | | | |__| | |__| | |____| |____ ____) |
|_| |_|\____/|_____/|______|______|_____/
*/
/* _____ _____
/\ | __ \_ _|
/ \ | |__) || |
/ /\ \ | ___/ | |
/ ____ \| | _| |_
/_/ \_\_| |_____|
*/
const auth ={
auth:{
username: 'admin',
password: process.env.EMQX_DEFAULT_APPLICATION_SECRET
}
}
//GET DEVICES
router.get("/device", checkAuth, async (req, res) =>{
try {
const userId = req.userData._id
//get devices
var devices = await Device.find({userId: userId})
//descoupling
devices = JSON.parse(JSON.stringify(devices))
//get saver rules
const saverRules = await getSaverRules(userId)
//get templates
const templates = await getTemplate(userId)
// get alarm rule
const alarmRules = await getAlarmRules(userId)
//saver rules to -> devices
devices.forEach((device, index) => {
devices[index].saverRule = saverRules.filter(
saverRule => saverRule.dId == device.dId)[0]
devices[index].template = templates.filter(
template => template._id == device.templateId)[0]
devices[index].alarmRules = alarmRules.filter(alarmRule => alarmRule.dId == device.dId)
})
const toSend = {
status: "success",
data: devices
}
res.json(toSend)
} catch (error) {
console.log("ERROR GETTING DEVICES")
console.log(error)
const toSend = {
status: "error",
error: error
}
return res.status(500).json(toSend)
}
})
//NEW DEVICE
router.post("/device", checkAuth, async (req, res) =>{
try {
const userId = req.userData._id
var newDevice = req.body.newDevice
newDevice.userId = userId
newDevice.createdTime = Date.now()
newDevice.password = makeid(10)
await createSaverRule(userId, newDevice.dId, true)
const device = await Device.create(newDevice)
await selectDevice(userId, newDevice.dId)
const toSend = {
status: "success"
}
return res.json(toSend)
} catch (error) {
console.log("ERROR CREATING NEW DEVICE")
console.log(error)
const toSend = {
status: "error",
error: error
}
return res.status(500).json(toSend)
}
})
//DELETE DEVICE
router.delete("/device", checkAuth, async (req, res) =>{
try {
const userId = req.userData._id
const dId = req.query.dId
await deleteSaverRule(dId)
//deleting all posible alarm rules
await deleteAllAlarmRules(userId, dId);
//deleting all posible mqtt device credentials
await deleteMqttDeviceCredentials(dId);
//deleting data mqtt
await deleteMqttDataDevices(dId)
const result = await Device.deleteOne({userId: userId, dId: dId})
const toSend = {
status: "success",
data: result
}
return res.json(toSend)
} catch (error) {
console.log("ERROR DELETING DEVICE")
console.log(error)
const toSend = {
status: "error"
}
return res.json(toSend)
}
})
//UPDATE DEVICE (SELECTOR)
router.put("/device", checkAuth, async (req, res) =>{
const dId = req.body.dId
const userId = req.userData._id
if(await selectDevice(userId,dId)){
const toSend = {
status: "success"
}
return res.json(toSend)
}else{
const toSend = {
status: "error"
}
return res.json(toSend)
}
})
//SAVER-RULE STATUS UPDATER
router.put('/saver-rule', checkAuth, async(req, res) => {
const rule = req.body.rule
await updateSaverRuleStatus(rule.emqxRuleId, rule.status)
const toSend = {
status: "success"
}
res.json(toSend)
})
/*
______ _ _ _ _ _______ _____ ____ _ _ _____
| ____| | | | \ | |__ __|_ _/ __ \| \ | |/ ____|
| |__ | | | | \| | | | | || | | | \| | (___
| __| | | | | . ` | | | | || | | | . ` |\___ \
| | | |__| | |\ | | | _| || |__| | |\ |____) |
|_| \____/|_| \_| |_| |_____\____/|_| \_|_____/
*/
async function getAlarmRules(userId) {
try {
const rules = await AlarmRule.find({userId})
return rules
} catch (error) {
return "error"
}
}
async function selectDevice(userId, dId){
try {
const result = await Device.updateMany({userId: userId}, {selected: false})
const result2 = await Device.updateOne({dId: dId, userId: userId},{selected:true})
return true
} catch (error) {
console.log("ERROR IN 'selectedDevice' FUNCTION")
console.log(error)
return false
}
}
/*
//SAVER RULES FUNCTION
*/
//get templates
async function getTemplate(userId) {
try {
const templates = await Template.find({ userId: userId})
return templates
} catch (error) {
return false
}
}
//get saver rules
async function getSaverRules(userId) {
try {
const rules = await SaverRule.find({ userId: userId})
return rules
} catch (error) {
console.log("Error enviando RULES")
console.log(error)
return false
}
}
//Create saver rule
async function createSaverRule(userId, dId, status) {
try {
const url = "http://"+process.env.EMQX_NODE_HOST+":8085/api/v4/rules"
const topic = userId + "/" + dId + "/+/sdata"
const rawsql = "SELECT topic, payload FROM \"" + topic + "\" WHERE payload.save = 1"
var newRule = {
rawsql: rawsql,
actions: [
{
name: "data_to_webserver",
params: {
$resource: global.saverResource.id,
payload_tmpl: '{"userId":"' + userId + '","payload":${payload},"topic":"${topic}"}'
}
}
],
description: "SAVER-RULE",
enabled: status
}
//save rule in emqx - grabamos regla en emqx
const res = await axios.post(url, newRule, auth)
if (res.status === 200 && res.data.data) {
console.log(res.data.data)
await SaverRule.create({
userId: userId,
dId: dId,
emqxRuleId: res.data.data.id,
status: status
})
return true
}else {
console.log("Aqui esta el error ERRROR")
return false
}
} catch (error) {
console.log("Error creating SAVER RULE")
console.log(error)
return false
}
}
//Update saver rule
async function updateSaverRuleStatus(emqxRuleId, status) {
const url = "http://"+process.env.EMQX_NODE_HOST+":8085/api/v4/rules/" + emqxRuleId
const newRule = {
enabled: status
}
const res = await axios.put(url, newRule, auth)
if (res.status === 200 && res.data.data) {
await SaverRule.updateOne({ emqxRuleId: emqxRuleId}, {status: status})
console.log("Saver Rule Status Update...".green)
return {
status: "success",
action: "update"
}
}
}
//delete saver rule
async function deleteSaverRule(dId) {
try {
const mongoRule = await SaverRule.findOne({dId: dId})
const url = "http://"+process.env.EMQX_NODE_HOST+":8085/api/v4/rules/" + mongoRule.emqxRuleId
const emqxRule = await axios.delete(url, auth)
const deleted = await SaverRule.deleteOne({dId: dId})
return true
} catch (error) {
console.log("Error Deleting Saver Rule")
console.log(error)
return false
}
}
//delete ALL alarm Rules...
async function deleteAllAlarmRules(userId, dId) {
try {
const rules = await AlarmRule.find({ userId: userId, dId: dId });
if (rules.length > 0) {
asyncForEach(rules, async rule => {
const url = "http://"+process.env.EMQX_NODE_HOST+":8085/api/v4/rules/" + rule.emqxRuleId;
const res = await axios.delete(url, auth);
});
await AlarmRule.deleteMany({ userId: userId, dId: dId });
}
return true;
} catch (error) {
console.log(error);
return "error";
}
}
// We can solve this by creating our own asyncForEach() method:
// thanks to Sebastien Chopin - Nuxt Creator :)
// https://codeburst.io/javascript-async-await-with-foreach-b6ba62bbf404
async function asyncForEach(array, callback) {
for (let index = 0; index < array.length; index++) {
await callback(array[index], index, array);
}
}
//delete ALL emqx device auth rules
async function deleteMqttDeviceCredentials(dId) {
try {
await EmqxAuthRule.deleteMany({ dId: dId, type: "device" });
return true;
} catch (error) {
console.log(error);
return false;
}
}
async function deleteMqttDataDevices(dId) {
try {
await Data.deleteMany({dId: dId});
return true;
} catch (error) {
console.log(error);
return false;
}
}
function makeid(length) {
var result =''
var characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
var charactersLength = characters.length
for (var i = 0; i < length; i ++) |
return result
}
module.exports = router | {
result += characters.charAt (
Math.floor(Math.random() * charactersLength)
)
} | conditional_block |
compare-table.ts | /* Copyright 2016-2017 TensorHub, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { tryFormat, formatShortDate } from "../guild-util/util.js";
import { reduceFunctions } from "../guild-util/reduce.js";
import { runForId } from "../guild-run/run.js";
export function fieldsDataSource(fields) {
var sources = new Set();
fields.forEach(function(field) {
if (field.source) {
sources.add(field.source);
}
});
return Array.from(sources).join(",");
}
export function init(table, fields, options) {
// TODO: use of jQuery disabled to support compile
return undefined; /* jQuery(table).DataTable({
data: [],
rowId: "run.id",
columns: columns(fields),
order: [[2, 'desc']],
scrollY: (options && options.height) || "360px",
scrollCollapse: true,
paging: false,
language: {
info: "_TOTAL_ runs",
infoFiltered: " (filtered from _MAX_)",
infoEmpty: "_TOTAL_ runs",
search: "",
searchPlaceholder: "Filter",
zeroRecords: "Waiting for data"
},
dom: "<'row'<'col-12'f>>"
+ "<'row'<'col-12'tr>>"
+ "<'row'<'col-12'i>>"
}); */
}
function columns(fields) {
return baseCols().concat(fieldCols(fields));
}
function baseCols() {
return [
selectedCol(),
statusCol(),
timeCol(),
modelCol()
];
}
function selectedCol() {
return {
title: "<guild-compare-table-select header></guild-compare-table-select>",
data: null,
orderable: false,
width: "18px",
render: function(item, type) {
if (type == "display") {
return tableSelect();
} else {
return item.value;
}
}
}
}
function tableSelect() {
return "<guild-compare-table-select></guild-compare-table-select>";
}
function statusCol() {
return {
title: statusTitle(),
data: "status",
width: "20px",
render: function(item, type) {
if (type == "display") {
return statusIcon(item);
} else if (type == "sort") {
return "sort";
} else if (type == "filter") {
return "label";
} else {
return item.value;
}
}
}
}
function statusTitle() {
return "<span class='header-title status-title'></span>";
}
function statusIcon(status) {
return "<fa-awesome class='" + status.iconClass + "'"
+ maybeSpinAttr(status.spin)
+ " icon='" + status.icon
+ "' size='22'></fa-awesome>"
+ "<paper-tooltip position='right'"
+ " animation-delay='250' offset='0'>"
+ status.label + "</paper-tooltip>";
}
function maybeSpinAttr(spin) {
return spin ? " spin" : "";
}
function timeCol() {
return {
title: headerTitle("Time"),
data: "time",
orderSequence: ["desc", "asc"],
width: "8em",
render: function(item, type, row) {
if (type == "display") | else if (type == "sort") {
return "sort";
} else if (type == "filter") {
return "label";
} else {
return item.value;
}
}
}
}
function headerTitle(title) {
return "<span class='header-title'>" + title + "</span>";
}
function runLink(val, run) {
var link = "/train?run=" + run.id;
return "<a href='" + link + "' class='date'>" + val + "</a>";
}
function modelCol() {
return {
title: headerTitle("Model"),
data: "run",
render: {
_: "model"
}
}
}
function fieldCols(fields) {
return fields.map(function(field, index) {
return {
title: headerTitle(field.label),
data: "f" + index,
orderSequence: ["desc", "asc"],
type: fieldType(field),
render: function(field, type, _row, _meta) {
if (type == "sort") {
return field.sort;
} else {
return field.value;
}
}
}
});
}
function fieldType(field) {
// Infer numeric type by reduce function
return field.reduce ? "num" : "string";
}
export function refresh(dt, data, fields) {
var items = formatItems(data, fields);
deleteMissingRows(dt, items);
addOrUpdateRows(dt, items);
}
function formatItems(data, fields) {
return data.map(function(item, index) {
return Object.assign(
itemBase(item, index),
itemFields(item, fields));
});
}
function itemBase(item, index) {
return {
run: item.run,
time: formatTime(item.run.started),
status: runStatus(item.run),
index: index,
selected: false
}
}
function runStatus(run) {
var status = runStatus(run);
status.sort = statusSort(status);
return status;
}
function statusSort(status) {
var label = status.label;
if (label == "Running") {
return 0;
} else if (label == "Completed") {
return 1;
} else if (label == "Terminated") {
return 2;
} else if (label == "Error") {
return 3;
} else {
return 4;
}
}
function formatTime(epoch) {
return {
value: formatShortDate(new Date(epoch)),
sort: epoch
}
}
function itemFields(item, fieldDefs) {
var fields = {}
fieldDefs.forEach(function(field, index) {
var data = item[field.source];
var name = "f" + index;
fields[name] = fieldValue(data, field);
});
return fields;
}
function fieldValue(data, field) {
var raw = fieldRawValue(data, field);
var sort = raw == undefined ? null: raw;
var formatted = fieldFormattedValue(raw, field) || "";
return {sort: sort, value: formatted}
}
function fieldRawValue(data, field) {
if (field.attribute) {
return data[field.attribute];
} else if (field.reduce) {
var reduce = reduceFunctions[field.reduce];
if (reduce) {
var reduced = reduce(data);
return reduced[Object.keys(reduced)[0]];
}
}
return undefined;
}
function fieldFormattedValue(raw, field) {
return field.format
? tryFormat(raw, field.format)
: raw;
}
function deleteMissingRows(dt, items) {
var itemIds = itemIdLookup(items);
var missing = [];
dt.rows().every(function(index) {
if (!itemIds.has(dt.row(index).data().run.id)) {
missing.push(index);
}
});
if (missing.length > 0) {
dt.rows(missing).remove().draw();
}
}
function itemIdLookup(items) {
var ids = items.map(function(item) { return item.run.id; });
return new Set(ids);
}
function addOrUpdateRows(dt, items) {
var added = false;
items.forEach(function(item, index) {
var curRow = findRow(dt, item);
if (curRow != null) {
updateRow(dt, curRow, item);
} else {
addRow(dt, item);
added = true;
}
});
if (added) {
dt.columns.adjust();
}
}
function findRow(dt, target) {
var row = dt.row("#" + target.run.id);
return row.data() != undefined ? row : null;
}
function updateRow(dt, row, newItem) {
var curItem = row.data();
dt.columns().every(function(colIndex) {
var property = dt.column(colIndex).dataSrc();
var curVal = curItem[property];
var newVal = newItem[property];
if (itemValChanged(curVal, newVal)) {
dt.cell(row, colIndex).data(newVal);
}
});
}
function itemValChanged(a, b) {
return JSON.stringify(a) != JSON.stringify(b);
}
function rowCellChanged(index, curVal, newVal) {
if (index == 0) {
return curVal.status != newVal.status;
} else {
return curVal != newVal;
}
}
function addRow(dt, item) {
var row = dt.row.add(item);
row.draw();
}
export function refreshRowsForSelected(dt) {
dt.rows().every(function(index) {
var tr = dt.row(index).node();
var item = dt.row(index).data();
var select = tr.querySelector("guild-compare-table-select");
if (select.value == "true") {
item.selected = true;
// TODO: use of $ disabled to support compile
//$(tr).addClass("highlight");
} else {
item.selected = false;
// TODO: use of $ disabled to support compile
//$(tr).removeClass("highlight");
}
});
}
export function refreshSelectHeader(dt) {
var header = headerSelectForTable(dt);
var selects = selectsForTable(dt);
header.value = headerValueForSelects(selects);
}
function headerSelectForTable(dt) {
return dt.table().header().querySelector("guild-compare-table-select");
}
function selectsForTable(dt) {
return dt.table().body().querySelectorAll("guild-compare-table-select");
}
function headerValueForSelects(selects) {
var first = null;
for (var i = 0; i < selects.length; i++) {
var cur = selects[i].value;
if (first == null) {
first = cur;
} else if (first != cur) {
return "mixed";
}
}
return first || "false";
}
export function syncSelectsWithHeader(dt) {
var header = headerSelectForTable(dt);
var selects = selectsForTable(dt);
selects.forEach(function(select) {
select.value = header.value;
});
}
export function deselectRemoved(dt) {
var removed = removedItems(dt);
var deselected = false;
for (var i in removed) {
var item = removed[i];
if (item.selected) {
deselect(dt, item);
deselected = true;
}
}
return deselected;
}
export function removedItems(dt) {
return dt.rows({search: "removed"}).data().toArray();
}
export function deselect(dt, item) {
tableSelectComponent(dt, item).value = "false";
}
function tableSelectComponent(dt, item) {
var row = findRow(dt, item);
return dt.cell(row, 0).node().firstChild;
}
export function runsChanged(a, b) {
// Returns true if any of these are true:
//
// - length of a and b differ
// - run ID for a[N] and b[N] differ
// - run status for a[N] and b[N] differ
//
// This is an optimization based on our defintion of "change", which
// is restricted to run status.
//
if (!a || !b || a.length != b.length) {
return true;
} else {
for (var i = 0; i < a.length; i++) {
var aRun = a[i];
var bRun = b[i];
if (aRun.id != bRun.id || aRun.status != bRun.status) {
return true;
}
}
return false;
}
}
| {
return runLink(item.value, row.run);
} | conditional_block |
compare-table.ts | /* Copyright 2016-2017 TensorHub, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { tryFormat, formatShortDate } from "../guild-util/util.js";
import { reduceFunctions } from "../guild-util/reduce.js";
import { runForId } from "../guild-run/run.js";
export function fieldsDataSource(fields) {
var sources = new Set();
fields.forEach(function(field) {
if (field.source) {
sources.add(field.source);
}
});
return Array.from(sources).join(",");
}
export function init(table, fields, options) {
// TODO: use of jQuery disabled to support compile
return undefined; /* jQuery(table).DataTable({
data: [],
rowId: "run.id",
columns: columns(fields),
order: [[2, 'desc']],
scrollY: (options && options.height) || "360px",
scrollCollapse: true,
paging: false,
language: {
info: "_TOTAL_ runs",
infoFiltered: " (filtered from _MAX_)",
infoEmpty: "_TOTAL_ runs",
search: "",
searchPlaceholder: "Filter",
zeroRecords: "Waiting for data"
},
dom: "<'row'<'col-12'f>>"
+ "<'row'<'col-12'tr>>"
+ "<'row'<'col-12'i>>"
}); */
}
function columns(fields) {
return baseCols().concat(fieldCols(fields));
}
function baseCols() {
return [
selectedCol(),
statusCol(),
timeCol(),
modelCol()
];
}
function selectedCol() {
return {
title: "<guild-compare-table-select header></guild-compare-table-select>",
data: null,
orderable: false,
width: "18px",
render: function(item, type) {
if (type == "display") {
return tableSelect();
} else {
return item.value;
}
}
}
}
function tableSelect() {
return "<guild-compare-table-select></guild-compare-table-select>";
}
function statusCol() {
return {
title: statusTitle(),
data: "status",
width: "20px",
render: function(item, type) {
if (type == "display") {
return statusIcon(item);
} else if (type == "sort") {
return "sort";
} else if (type == "filter") {
return "label";
} else {
return item.value;
}
}
}
}
function statusTitle() {
return "<span class='header-title status-title'></span>";
}
function statusIcon(status) {
return "<fa-awesome class='" + status.iconClass + "'"
+ maybeSpinAttr(status.spin)
+ " icon='" + status.icon
+ "' size='22'></fa-awesome>"
+ "<paper-tooltip position='right'"
+ " animation-delay='250' offset='0'>"
+ status.label + "</paper-tooltip>";
}
function maybeSpinAttr(spin) {
return spin ? " spin" : "";
}
function timeCol() {
return {
title: headerTitle("Time"),
data: "time",
orderSequence: ["desc", "asc"],
width: "8em",
render: function(item, type, row) {
if (type == "display") {
return runLink(item.value, row.run);
} else if (type == "sort") {
return "sort";
} else if (type == "filter") {
return "label";
} else {
return item.value;
}
}
}
}
function headerTitle(title) {
return "<span class='header-title'>" + title + "</span>";
}
function runLink(val, run) {
var link = "/train?run=" + run.id;
return "<a href='" + link + "' class='date'>" + val + "</a>";
}
function modelCol() {
return {
title: headerTitle("Model"),
data: "run",
render: {
_: "model"
}
}
}
function fieldCols(fields) {
return fields.map(function(field, index) {
return {
title: headerTitle(field.label),
data: "f" + index,
orderSequence: ["desc", "asc"],
type: fieldType(field),
render: function(field, type, _row, _meta) {
if (type == "sort") {
return field.sort;
} else {
return field.value;
}
}
}
});
}
function fieldType(field) {
// Infer numeric type by reduce function
return field.reduce ? "num" : "string";
}
export function refresh(dt, data, fields) {
var items = formatItems(data, fields);
deleteMissingRows(dt, items);
addOrUpdateRows(dt, items);
}
function formatItems(data, fields) {
return data.map(function(item, index) {
return Object.assign(
itemBase(item, index),
itemFields(item, fields));
});
}
function itemBase(item, index) {
return {
run: item.run,
time: formatTime(item.run.started),
status: runStatus(item.run),
index: index,
selected: false
}
}
function runStatus(run) {
var status = runStatus(run);
status.sort = statusSort(status);
return status;
}
function statusSort(status) {
var label = status.label;
if (label == "Running") {
return 0;
} else if (label == "Completed") {
return 1;
} else if (label == "Terminated") {
return 2;
} else if (label == "Error") {
return 3;
} else {
return 4;
}
}
function formatTime(epoch) {
return {
value: formatShortDate(new Date(epoch)),
sort: epoch
}
}
function itemFields(item, fieldDefs) {
var fields = {}
fieldDefs.forEach(function(field, index) {
var data = item[field.source];
var name = "f" + index;
fields[name] = fieldValue(data, field);
});
return fields;
}
function fieldValue(data, field) {
var raw = fieldRawValue(data, field);
var sort = raw == undefined ? null: raw;
var formatted = fieldFormattedValue(raw, field) || "";
return {sort: sort, value: formatted}
}
function fieldRawValue(data, field) {
if (field.attribute) {
return data[field.attribute];
} else if (field.reduce) {
var reduce = reduceFunctions[field.reduce];
if (reduce) {
var reduced = reduce(data);
return reduced[Object.keys(reduced)[0]];
}
}
return undefined;
}
function fieldFormattedValue(raw, field) {
return field.format
? tryFormat(raw, field.format)
: raw;
}
function deleteMissingRows(dt, items) {
var itemIds = itemIdLookup(items);
var missing = [];
dt.rows().every(function(index) {
if (!itemIds.has(dt.row(index).data().run.id)) {
missing.push(index);
}
});
if (missing.length > 0) {
dt.rows(missing).remove().draw();
}
}
function itemIdLookup(items) |
function addOrUpdateRows(dt, items) {
var added = false;
items.forEach(function(item, index) {
var curRow = findRow(dt, item);
if (curRow != null) {
updateRow(dt, curRow, item);
} else {
addRow(dt, item);
added = true;
}
});
if (added) {
dt.columns.adjust();
}
}
function findRow(dt, target) {
var row = dt.row("#" + target.run.id);
return row.data() != undefined ? row : null;
}
function updateRow(dt, row, newItem) {
var curItem = row.data();
dt.columns().every(function(colIndex) {
var property = dt.column(colIndex).dataSrc();
var curVal = curItem[property];
var newVal = newItem[property];
if (itemValChanged(curVal, newVal)) {
dt.cell(row, colIndex).data(newVal);
}
});
}
function itemValChanged(a, b) {
return JSON.stringify(a) != JSON.stringify(b);
}
function rowCellChanged(index, curVal, newVal) {
if (index == 0) {
return curVal.status != newVal.status;
} else {
return curVal != newVal;
}
}
function addRow(dt, item) {
var row = dt.row.add(item);
row.draw();
}
export function refreshRowsForSelected(dt) {
dt.rows().every(function(index) {
var tr = dt.row(index).node();
var item = dt.row(index).data();
var select = tr.querySelector("guild-compare-table-select");
if (select.value == "true") {
item.selected = true;
// TODO: use of $ disabled to support compile
//$(tr).addClass("highlight");
} else {
item.selected = false;
// TODO: use of $ disabled to support compile
//$(tr).removeClass("highlight");
}
});
}
export function refreshSelectHeader(dt) {
var header = headerSelectForTable(dt);
var selects = selectsForTable(dt);
header.value = headerValueForSelects(selects);
}
function headerSelectForTable(dt) {
return dt.table().header().querySelector("guild-compare-table-select");
}
function selectsForTable(dt) {
return dt.table().body().querySelectorAll("guild-compare-table-select");
}
function headerValueForSelects(selects) {
var first = null;
for (var i = 0; i < selects.length; i++) {
var cur = selects[i].value;
if (first == null) {
first = cur;
} else if (first != cur) {
return "mixed";
}
}
return first || "false";
}
export function syncSelectsWithHeader(dt) {
var header = headerSelectForTable(dt);
var selects = selectsForTable(dt);
selects.forEach(function(select) {
select.value = header.value;
});
}
export function deselectRemoved(dt) {
var removed = removedItems(dt);
var deselected = false;
for (var i in removed) {
var item = removed[i];
if (item.selected) {
deselect(dt, item);
deselected = true;
}
}
return deselected;
}
export function removedItems(dt) {
return dt.rows({search: "removed"}).data().toArray();
}
export function deselect(dt, item) {
tableSelectComponent(dt, item).value = "false";
}
function tableSelectComponent(dt, item) {
var row = findRow(dt, item);
return dt.cell(row, 0).node().firstChild;
}
export function runsChanged(a, b) {
// Returns true if any of these are true:
//
// - length of a and b differ
// - run ID for a[N] and b[N] differ
// - run status for a[N] and b[N] differ
//
// This is an optimization based on our defintion of "change", which
// is restricted to run status.
//
if (!a || !b || a.length != b.length) {
return true;
} else {
for (var i = 0; i < a.length; i++) {
var aRun = a[i];
var bRun = b[i];
if (aRun.id != bRun.id || aRun.status != bRun.status) {
return true;
}
}
return false;
}
}
| {
var ids = items.map(function(item) { return item.run.id; });
return new Set(ids);
} | identifier_body |
compare-table.ts | /* Copyright 2016-2017 TensorHub, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { tryFormat, formatShortDate } from "../guild-util/util.js";
import { reduceFunctions } from "../guild-util/reduce.js";
import { runForId } from "../guild-run/run.js";
export function fieldsDataSource(fields) {
var sources = new Set();
fields.forEach(function(field) {
if (field.source) {
sources.add(field.source);
}
});
return Array.from(sources).join(",");
}
export function init(table, fields, options) {
// TODO: use of jQuery disabled to support compile
return undefined; /* jQuery(table).DataTable({
data: [],
rowId: "run.id",
columns: columns(fields),
order: [[2, 'desc']],
scrollY: (options && options.height) || "360px",
scrollCollapse: true,
paging: false,
language: {
info: "_TOTAL_ runs",
infoFiltered: " (filtered from _MAX_)",
infoEmpty: "_TOTAL_ runs",
search: "",
searchPlaceholder: "Filter",
zeroRecords: "Waiting for data"
},
dom: "<'row'<'col-12'f>>"
+ "<'row'<'col-12'tr>>"
+ "<'row'<'col-12'i>>"
}); */
}
function columns(fields) {
return baseCols().concat(fieldCols(fields));
}
function baseCols() {
return [
selectedCol(),
statusCol(),
timeCol(),
modelCol()
];
}
function selectedCol() {
return {
title: "<guild-compare-table-select header></guild-compare-table-select>",
data: null,
orderable: false,
width: "18px",
render: function(item, type) {
if (type == "display") {
return tableSelect();
} else {
return item.value;
}
}
}
}
function tableSelect() {
return "<guild-compare-table-select></guild-compare-table-select>";
}
function statusCol() {
return {
title: statusTitle(),
data: "status",
width: "20px",
render: function(item, type) {
if (type == "display") {
return statusIcon(item);
} else if (type == "sort") {
return "sort";
} else if (type == "filter") {
return "label";
} else {
return item.value;
}
}
}
}
function statusTitle() {
return "<span class='header-title status-title'></span>";
}
function statusIcon(status) {
return "<fa-awesome class='" + status.iconClass + "'"
+ maybeSpinAttr(status.spin)
+ " icon='" + status.icon
+ "' size='22'></fa-awesome>"
+ "<paper-tooltip position='right'"
+ " animation-delay='250' offset='0'>"
+ status.label + "</paper-tooltip>";
}
function maybeSpinAttr(spin) {
return spin ? " spin" : "";
}
function timeCol() {
return {
title: headerTitle("Time"),
data: "time",
orderSequence: ["desc", "asc"],
width: "8em",
render: function(item, type, row) {
if (type == "display") {
return runLink(item.value, row.run);
} else if (type == "sort") {
return "sort";
} else if (type == "filter") {
return "label";
} else {
return item.value;
}
}
}
}
function headerTitle(title) {
return "<span class='header-title'>" + title + "</span>";
}
function runLink(val, run) {
var link = "/train?run=" + run.id;
return "<a href='" + link + "' class='date'>" + val + "</a>";
}
function modelCol() {
return {
title: headerTitle("Model"),
data: "run",
render: {
_: "model"
}
}
}
function fieldCols(fields) {
return fields.map(function(field, index) {
return {
title: headerTitle(field.label),
data: "f" + index,
orderSequence: ["desc", "asc"],
type: fieldType(field),
render: function(field, type, _row, _meta) {
if (type == "sort") {
return field.sort;
} else {
return field.value;
}
}
}
});
}
function fieldType(field) {
// Infer numeric type by reduce function
return field.reduce ? "num" : "string";
}
export function refresh(dt, data, fields) {
var items = formatItems(data, fields);
deleteMissingRows(dt, items);
addOrUpdateRows(dt, items);
}
function formatItems(data, fields) {
return data.map(function(item, index) {
return Object.assign(
itemBase(item, index),
itemFields(item, fields));
});
}
function itemBase(item, index) {
return {
run: item.run,
time: formatTime(item.run.started),
status: runStatus(item.run),
index: index,
selected: false
}
}
function runStatus(run) {
var status = runStatus(run);
status.sort = statusSort(status);
return status;
}
function statusSort(status) {
var label = status.label;
if (label == "Running") {
return 0;
} else if (label == "Completed") {
return 1;
} else if (label == "Terminated") {
return 2;
} else if (label == "Error") {
return 3;
} else {
return 4;
}
}
function formatTime(epoch) {
return {
value: formatShortDate(new Date(epoch)),
sort: epoch
}
}
function itemFields(item, fieldDefs) {
var fields = {}
fieldDefs.forEach(function(field, index) {
var data = item[field.source];
var name = "f" + index;
fields[name] = fieldValue(data, field);
});
return fields;
}
function fieldValue(data, field) {
var raw = fieldRawValue(data, field);
var sort = raw == undefined ? null: raw;
var formatted = fieldFormattedValue(raw, field) || "";
return {sort: sort, value: formatted}
}
function fieldRawValue(data, field) {
if (field.attribute) {
return data[field.attribute];
} else if (field.reduce) {
var reduce = reduceFunctions[field.reduce];
if (reduce) {
var reduced = reduce(data);
return reduced[Object.keys(reduced)[0]];
}
}
return undefined;
}
function fieldFormattedValue(raw, field) {
return field.format
? tryFormat(raw, field.format)
: raw;
}
function deleteMissingRows(dt, items) {
var itemIds = itemIdLookup(items);
var missing = [];
dt.rows().every(function(index) {
if (!itemIds.has(dt.row(index).data().run.id)) {
missing.push(index);
}
});
if (missing.length > 0) {
dt.rows(missing).remove().draw();
}
}
function itemIdLookup(items) {
var ids = items.map(function(item) { return item.run.id; }); | return new Set(ids);
}
function addOrUpdateRows(dt, items) {
var added = false;
items.forEach(function(item, index) {
var curRow = findRow(dt, item);
if (curRow != null) {
updateRow(dt, curRow, item);
} else {
addRow(dt, item);
added = true;
}
});
if (added) {
dt.columns.adjust();
}
}
function findRow(dt, target) {
var row = dt.row("#" + target.run.id);
return row.data() != undefined ? row : null;
}
function updateRow(dt, row, newItem) {
var curItem = row.data();
dt.columns().every(function(colIndex) {
var property = dt.column(colIndex).dataSrc();
var curVal = curItem[property];
var newVal = newItem[property];
if (itemValChanged(curVal, newVal)) {
dt.cell(row, colIndex).data(newVal);
}
});
}
function itemValChanged(a, b) {
return JSON.stringify(a) != JSON.stringify(b);
}
function rowCellChanged(index, curVal, newVal) {
if (index == 0) {
return curVal.status != newVal.status;
} else {
return curVal != newVal;
}
}
function addRow(dt, item) {
var row = dt.row.add(item);
row.draw();
}
export function refreshRowsForSelected(dt) {
dt.rows().every(function(index) {
var tr = dt.row(index).node();
var item = dt.row(index).data();
var select = tr.querySelector("guild-compare-table-select");
if (select.value == "true") {
item.selected = true;
// TODO: use of $ disabled to support compile
//$(tr).addClass("highlight");
} else {
item.selected = false;
// TODO: use of $ disabled to support compile
//$(tr).removeClass("highlight");
}
});
}
export function refreshSelectHeader(dt) {
var header = headerSelectForTable(dt);
var selects = selectsForTable(dt);
header.value = headerValueForSelects(selects);
}
function headerSelectForTable(dt) {
return dt.table().header().querySelector("guild-compare-table-select");
}
function selectsForTable(dt) {
return dt.table().body().querySelectorAll("guild-compare-table-select");
}
function headerValueForSelects(selects) {
var first = null;
for (var i = 0; i < selects.length; i++) {
var cur = selects[i].value;
if (first == null) {
first = cur;
} else if (first != cur) {
return "mixed";
}
}
return first || "false";
}
export function syncSelectsWithHeader(dt) {
var header = headerSelectForTable(dt);
var selects = selectsForTable(dt);
selects.forEach(function(select) {
select.value = header.value;
});
}
export function deselectRemoved(dt) {
var removed = removedItems(dt);
var deselected = false;
for (var i in removed) {
var item = removed[i];
if (item.selected) {
deselect(dt, item);
deselected = true;
}
}
return deselected;
}
export function removedItems(dt) {
return dt.rows({search: "removed"}).data().toArray();
}
export function deselect(dt, item) {
tableSelectComponent(dt, item).value = "false";
}
function tableSelectComponent(dt, item) {
var row = findRow(dt, item);
return dt.cell(row, 0).node().firstChild;
}
export function runsChanged(a, b) {
// Returns true if any of these are true:
//
// - length of a and b differ
// - run ID for a[N] and b[N] differ
// - run status for a[N] and b[N] differ
//
// This is an optimization based on our defintion of "change", which
// is restricted to run status.
//
if (!a || !b || a.length != b.length) {
return true;
} else {
for (var i = 0; i < a.length; i++) {
var aRun = a[i];
var bRun = b[i];
if (aRun.id != bRun.id || aRun.status != bRun.status) {
return true;
}
}
return false;
}
} | random_line_split | |
compare-table.ts | /* Copyright 2016-2017 TensorHub, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { tryFormat, formatShortDate } from "../guild-util/util.js";
import { reduceFunctions } from "../guild-util/reduce.js";
import { runForId } from "../guild-run/run.js";
export function fieldsDataSource(fields) {
var sources = new Set();
fields.forEach(function(field) {
if (field.source) {
sources.add(field.source);
}
});
return Array.from(sources).join(",");
}
export function init(table, fields, options) {
// TODO: use of jQuery disabled to support compile
return undefined; /* jQuery(table).DataTable({
data: [],
rowId: "run.id",
columns: columns(fields),
order: [[2, 'desc']],
scrollY: (options && options.height) || "360px",
scrollCollapse: true,
paging: false,
language: {
info: "_TOTAL_ runs",
infoFiltered: " (filtered from _MAX_)",
infoEmpty: "_TOTAL_ runs",
search: "",
searchPlaceholder: "Filter",
zeroRecords: "Waiting for data"
},
dom: "<'row'<'col-12'f>>"
+ "<'row'<'col-12'tr>>"
+ "<'row'<'col-12'i>>"
}); */
}
function columns(fields) {
return baseCols().concat(fieldCols(fields));
}
function baseCols() {
return [
selectedCol(),
statusCol(),
timeCol(),
modelCol()
];
}
function selectedCol() {
return {
title: "<guild-compare-table-select header></guild-compare-table-select>",
data: null,
orderable: false,
width: "18px",
render: function(item, type) {
if (type == "display") {
return tableSelect();
} else {
return item.value;
}
}
}
}
function tableSelect() {
return "<guild-compare-table-select></guild-compare-table-select>";
}
function statusCol() {
return {
title: statusTitle(),
data: "status",
width: "20px",
render: function(item, type) {
if (type == "display") {
return statusIcon(item);
} else if (type == "sort") {
return "sort";
} else if (type == "filter") {
return "label";
} else {
return item.value;
}
}
}
}
function statusTitle() {
return "<span class='header-title status-title'></span>";
}
function statusIcon(status) {
return "<fa-awesome class='" + status.iconClass + "'"
+ maybeSpinAttr(status.spin)
+ " icon='" + status.icon
+ "' size='22'></fa-awesome>"
+ "<paper-tooltip position='right'"
+ " animation-delay='250' offset='0'>"
+ status.label + "</paper-tooltip>";
}
function maybeSpinAttr(spin) {
return spin ? " spin" : "";
}
function timeCol() {
return {
title: headerTitle("Time"),
data: "time",
orderSequence: ["desc", "asc"],
width: "8em",
render: function(item, type, row) {
if (type == "display") {
return runLink(item.value, row.run);
} else if (type == "sort") {
return "sort";
} else if (type == "filter") {
return "label";
} else {
return item.value;
}
}
}
}
function headerTitle(title) {
return "<span class='header-title'>" + title + "</span>";
}
function runLink(val, run) {
var link = "/train?run=" + run.id;
return "<a href='" + link + "' class='date'>" + val + "</a>";
}
function modelCol() {
return {
title: headerTitle("Model"),
data: "run",
render: {
_: "model"
}
}
}
function fieldCols(fields) {
return fields.map(function(field, index) {
return {
title: headerTitle(field.label),
data: "f" + index,
orderSequence: ["desc", "asc"],
type: fieldType(field),
render: function(field, type, _row, _meta) {
if (type == "sort") {
return field.sort;
} else {
return field.value;
}
}
}
});
}
function fieldType(field) {
// Infer numeric type by reduce function
return field.reduce ? "num" : "string";
}
export function refresh(dt, data, fields) {
var items = formatItems(data, fields);
deleteMissingRows(dt, items);
addOrUpdateRows(dt, items);
}
function formatItems(data, fields) {
return data.map(function(item, index) {
return Object.assign(
itemBase(item, index),
itemFields(item, fields));
});
}
function itemBase(item, index) {
return {
run: item.run,
time: formatTime(item.run.started),
status: runStatus(item.run),
index: index,
selected: false
}
}
function runStatus(run) {
var status = runStatus(run);
status.sort = statusSort(status);
return status;
}
function statusSort(status) {
var label = status.label;
if (label == "Running") {
return 0;
} else if (label == "Completed") {
return 1;
} else if (label == "Terminated") {
return 2;
} else if (label == "Error") {
return 3;
} else {
return 4;
}
}
function formatTime(epoch) {
return {
value: formatShortDate(new Date(epoch)),
sort: epoch
}
}
function itemFields(item, fieldDefs) {
var fields = {}
fieldDefs.forEach(function(field, index) {
var data = item[field.source];
var name = "f" + index;
fields[name] = fieldValue(data, field);
});
return fields;
}
function fieldValue(data, field) {
var raw = fieldRawValue(data, field);
var sort = raw == undefined ? null: raw;
var formatted = fieldFormattedValue(raw, field) || "";
return {sort: sort, value: formatted}
}
function fieldRawValue(data, field) {
if (field.attribute) {
return data[field.attribute];
} else if (field.reduce) {
var reduce = reduceFunctions[field.reduce];
if (reduce) {
var reduced = reduce(data);
return reduced[Object.keys(reduced)[0]];
}
}
return undefined;
}
function fieldFormattedValue(raw, field) {
return field.format
? tryFormat(raw, field.format)
: raw;
}
function deleteMissingRows(dt, items) {
var itemIds = itemIdLookup(items);
var missing = [];
dt.rows().every(function(index) {
if (!itemIds.has(dt.row(index).data().run.id)) {
missing.push(index);
}
});
if (missing.length > 0) {
dt.rows(missing).remove().draw();
}
}
function itemIdLookup(items) {
var ids = items.map(function(item) { return item.run.id; });
return new Set(ids);
}
function addOrUpdateRows(dt, items) {
var added = false;
items.forEach(function(item, index) {
var curRow = findRow(dt, item);
if (curRow != null) {
updateRow(dt, curRow, item);
} else {
addRow(dt, item);
added = true;
}
});
if (added) {
dt.columns.adjust();
}
}
function | (dt, target) {
var row = dt.row("#" + target.run.id);
return row.data() != undefined ? row : null;
}
function updateRow(dt, row, newItem) {
var curItem = row.data();
dt.columns().every(function(colIndex) {
var property = dt.column(colIndex).dataSrc();
var curVal = curItem[property];
var newVal = newItem[property];
if (itemValChanged(curVal, newVal)) {
dt.cell(row, colIndex).data(newVal);
}
});
}
function itemValChanged(a, b) {
return JSON.stringify(a) != JSON.stringify(b);
}
function rowCellChanged(index, curVal, newVal) {
if (index == 0) {
return curVal.status != newVal.status;
} else {
return curVal != newVal;
}
}
function addRow(dt, item) {
var row = dt.row.add(item);
row.draw();
}
export function refreshRowsForSelected(dt) {
dt.rows().every(function(index) {
var tr = dt.row(index).node();
var item = dt.row(index).data();
var select = tr.querySelector("guild-compare-table-select");
if (select.value == "true") {
item.selected = true;
// TODO: use of $ disabled to support compile
//$(tr).addClass("highlight");
} else {
item.selected = false;
// TODO: use of $ disabled to support compile
//$(tr).removeClass("highlight");
}
});
}
export function refreshSelectHeader(dt) {
var header = headerSelectForTable(dt);
var selects = selectsForTable(dt);
header.value = headerValueForSelects(selects);
}
function headerSelectForTable(dt) {
return dt.table().header().querySelector("guild-compare-table-select");
}
function selectsForTable(dt) {
return dt.table().body().querySelectorAll("guild-compare-table-select");
}
function headerValueForSelects(selects) {
var first = null;
for (var i = 0; i < selects.length; i++) {
var cur = selects[i].value;
if (first == null) {
first = cur;
} else if (first != cur) {
return "mixed";
}
}
return first || "false";
}
export function syncSelectsWithHeader(dt) {
var header = headerSelectForTable(dt);
var selects = selectsForTable(dt);
selects.forEach(function(select) {
select.value = header.value;
});
}
export function deselectRemoved(dt) {
var removed = removedItems(dt);
var deselected = false;
for (var i in removed) {
var item = removed[i];
if (item.selected) {
deselect(dt, item);
deselected = true;
}
}
return deselected;
}
export function removedItems(dt) {
return dt.rows({search: "removed"}).data().toArray();
}
export function deselect(dt, item) {
tableSelectComponent(dt, item).value = "false";
}
function tableSelectComponent(dt, item) {
var row = findRow(dt, item);
return dt.cell(row, 0).node().firstChild;
}
export function runsChanged(a, b) {
// Returns true if any of these are true:
//
// - length of a and b differ
// - run ID for a[N] and b[N] differ
// - run status for a[N] and b[N] differ
//
// This is an optimization based on our defintion of "change", which
// is restricted to run status.
//
if (!a || !b || a.length != b.length) {
return true;
} else {
for (var i = 0; i < a.length; i++) {
var aRun = a[i];
var bRun = b[i];
if (aRun.id != bRun.id || aRun.status != bRun.status) {
return true;
}
}
return false;
}
}
| findRow | identifier_name |
tree.go | package web
import (
"fmt"
"regexp"
"sort"
"strings"
"github.com/VectorsOrigin/utils"
)
/*
tree 负责路由树的解析,排序,匹配
实现前面加类型
'/web/content/<string:xmlid>',
'/web/content/<string:xmlid>/<string:filename>',
'/web/content/<int:id>',
'/web/content/<int:id>/<string:filename>',
'/web/content/<int:id>-<string:unique>',
'/web/content/<int:id>-<string:unique>/<string:filename>',
'/web/content/<string:model>/<int:id>/<string:field>',
'/web/content/<string:model>/<int:id>/<string:field>/<string:filename>'
*/
const (
StaticNode NodeType = iota // static, should equal
VariantNode // named node, match a non-/ is ok
AnyNode // catch-all node, match any
RegexpNode // regex node, should match
AllType ContentType = iota
NumberType
CharType
)
var (
HttpMethods = []string{
"GET",
"POST",
"HEAD",
"DELETE",
"PUT",
"OPTIONS",
"TRACE",
"PATCH",
}
)
type (
NodeType byte
ContentType byte
param struct {
Name string
Value string
}
Params []param
// 配置函数接口
ConfigOption func(*TTree)
// 使用Sort 接口自动排序
TSubNodes []*TNode
TNode struct {
Type NodeType
ContentType ContentType
Children TSubNodes
//StaticChild map[string]*TNode
//VariantChild map[string]*TNode
//RegexpChild map[string]*TNode //[]*TNode
Text string // Path string /web/
Path string
Route *TRoute
Level int // #动态Node排序等级 /.../ 之间的Nodes越多等级越高
regexp *regexp.Regexp
}
TTree struct {
Text string
Root map[string]*TNode
IgnoreCase bool
DelimitChar byte // Delimit Char xxx.xxx
//lock sync.RWMutex
}
)
func (p *Params) Get(key string) string {
for _, v := range *p {
if v.Name == key {
return v.Value
}
}
return ""
}
func (p *Params) Set(key, value string) {
for i, v := range *p {
if v.Name == key {
(*p)[i].Value = value
return
}
}
}
func (p *Params) SetParams(params []param) {
*p = params
}
func (self TSubNodes) Len() int {
return len(self)
}
func (self TSubNodes) Swap(i, j int) {
self[i], self[j] = self[j], self[i]
}
// static route will be put the first, so it will be match first.
// two static route, content longer is first.
func (self TSubNodes) Less(i, j int) bool {
if self[i].Type == StaticNode {
if self[j].Type == StaticNode {
return len(self[i].Text) > len(self[j].Text)
}
return true
}
if self[j].Type == StaticNode {
return false
} else {
return self[i].Level > self[j].Level
}
return i < j
}
func NewRouteTree(config_fn ...ConfigOption) *TTree {
lTree := &TTree{
Root: make(map[string]*TNode),
DelimitChar:'/',
}
/*
for _, m := range HttpMethods {
lTree.Root[m] = &TNode{
Children: TSubNodes{},
}
}*/
for _,cfg:=range config_fn{
cfg(lTree)
}
return lTree
}
// 解析Path为Node
/* /:name1/:name2 /:name1-:name2 /(:name1)sss(:name2)
/(*name) /(:name[0-9]+) /(type:name[a-z]+)
Result: @ Nodes List
@ is it dyn route
*/
func (r *TTree) parsePath(path string) (nodes []*TNode, isDyn bool) {
if path == "" {
panic("echo: path cannot be empty")
}
if r.DelimitChar=='/' && path[0] != '/' {
path = "/" + path
}
var (
i, j int // i 游标 J 上次标记
bracket int
level int // #Node的 排序等级
target *TNode // 记录等级的Node 一般为/ 开始的第一个动态
node *TNode
)
// 默认
nodes = make([]*TNode, 0)
isDyn = false
l := len(path)
//j = i - 1 // 当i==0时J必须小于它
for ; i < l; i++ {
switch path[i] {
case r.DelimitChar:
//case '/':
{ // 创建Text:'/' Node
if bracket == 0 && i > j {
//if path[j] == '/' {
// nodes = append(nodes, &TNode{Type: StaticNode, Text: string(path[j])})
//}
//j++
nodes = append(nodes, &TNode{Type: StaticNode, Text: path[j:i]})
j = i
}
//fmt.Println("/")
// # 重置计数
target = nil
level = 0 // #开始计数
}
case '(':
{
//fmt.Println("(")
bracket = 1
}
case ':':
{
//fmt.Println(":")
var typ ContentType = AllType
//fmt.Println(":", bracket, path[j:i-bracket])
if path[i-1] == '(' { //#like (:var)
nodes = append(nodes, &TNode{Type: StaticNode, Text: path[j : i-bracket]})
bracket = 1
} else {
// #为变量区分数据类型
str := path[j : i-bracket] // #like /abc1(string|upper:var)
idx := strings.Index(str, "(")
if idx == -1 {
panic(fmt.Sprintf("expect a '(' near position %d~%d", j, i))
}
nodes = append(nodes, &TNode{Type: StaticNode, Text: str[:idx]})
str = str[idx+1:]
switch str {
case "int":
typ = NumberType
case "string":
typ = CharType
default:
typ = AllType
}
//fmt.Println("type:", typ)
bracket = 1
}
j = i
var (
regex string
start = -1
)
if bracket == 1 {
// 开始记录Pos
for ; i < l && ')' != path[i]; i++ { // 移动Pos到) 遇到正则字符标记起
if start == -1 && utils.IsSpecialByte(path[i]) { // 如果是正则
start = i
}
}
if path[i] != ')' {
panic("lack of )")
}
if start > -1 {
regex = path[start:i] //正则内容
}
} else {
i = i + 1
for ; i < l && utils.IsAlnumByte(path[i]); i++ {
}
}
if len(regex) > 0 { // 正则
node = &TNode{Type: RegexpNode, regexp: regexp.MustCompile("(" + regex + ")"), Text: path[j : i-len(regex)]}
nodes = append(nodes, node)
} else { // 变量
node = &TNode{Type: VariantNode, ContentType: typ, Text: path[j:i]}
nodes = append(nodes, node)
}
isDyn = true // #标记 Route 为动态
i = i + bracket // #剔除")"字符 bracket=len(“)”)
j = i
// 当计数器遇到/或者Url末尾时将记录保存于Node中
if target != nil && ((i == l) || (i != l && path[j+1] == r.DelimitChar)) {
level++
target.Level = level
//fmt.Println("ok:", node.Text, target.Text, level)
// # 重置计数
target = nil
level = 0
}
if i == l {
return //nodes, isDyn
}
// #计数滴答
// 放置在 i == l 后 确保表达式2比1多一个层级
// @/(int:id1)-(:unique2)
// @/(:id3)-(:unique3)/(:filename)
if (i != l && path[j] != r.DelimitChar) || level != 0 {
if level == 0 {
target = node
}
level++
//fmt.Println("leve:", node.Text, target.Text, level)
}
}
case '*':
{
nodes = append(nodes, &TNode{Type: StaticNode, Text: path[j : i-bracket]})
j = i
//if bracket == 1 {
// for ; i < l && ')' == path[i]; i++ {
// }
//} else {
i = i + 1
for ; i < l && utils.IsAlnumByte(path[i]); i++ {
}
//}
nodes = append(nodes, &TNode{Type: AnyNode, Text: path[j:i]})
isDyn = true // 标记 Route 为动态
i = i + bracket // bracket=len(“)”)
j = i
if i == l {
return //nodes, isDyn
}
}
default:
{
bracket = 0
}
}
}
nodes = append(nodes, &TNode{
Type: StaticNode,
Text: path[j:i],
})
//fmt.Println("lNodes", len(lNodes))
return //nodes, isDyn
}
func (r *TTree) matchNode(aNode *TNode, aUrl string, aParams *Params) *TNode {
var retnil bool
if aNode.Type == StaticNode { // 静态节点
if strings.HasPrefix(aUrl, aNode.Text) {
//fmt.Println("J态", aUrl, " | ", aNode.Text[1:])
if len(aUrl) == len(aNode.Text) {
return aNode
}
for _, c := range aNode.Children {
e := r.matchNode(c, aUrl[len(aNode.Text):], aParams)
if e != nil {
return e
}
}
}
} else if aNode.Type == AnyNode { // 全匹配节点
//if len(aNode.Children) == 0 {
// *aParams = append(*aParams, param{aNode.Text[1:], aUrl})
// return aNode
//}
//fmt.Println("Any态", aUrl, " | ", aNode.Text[1:])
for _, c := range aNode.Children {
idx := strings.LastIndex(aUrl, c.Text)
//fmt.Println("LastIndex", aUrl, c.Text)
if idx > -1 {
h := r.matchNode(c, aUrl[idx:], aParams)
if h != nil {
*aParams = append(*aParams, param{aNode.Text[1:], aUrl[:idx]})
return h
}
}
}
*aParams = append(*aParams, param{aNode.Text[1:], aUrl})
return aNode
} else if aNode.Type == VariantNode { // 变量节点
// # 消除path like /abc 的'/'
idx := strings.IndexByte(aUrl, r.DelimitChar)
//fmt.Println("D态", aUrl, " | ", aNode.Text[1:], idx)
if idx == 0 { // #fix错误if idx > -1 {
for _, c := range aNode.Children {
h := r.matchNode(c, aUrl[idx:], aParams)
if h != nil {
/*fmt.Println("类型1", aUrl[:idx], aNode.ContentType)
if !validType(aUrl[:idx], aNode.ContentType) {
fmt.Println("错误类型", aUrl[:idx], aNode.ContentType)
return nil
}
*/
*aParams = append(*aParams, param{aNode.Text[1:], aUrl[:idx]})
return h
}
}
return nil
}
// 最底层Node
//if len(aNode.Children) == 0 {
// *aParams = append(*aParams, param{aNode.Text[1:], aUrl})
// return aNode
//}
//fmt.Println("Index", idx)
for _, c := range aNode.Children {
idx := strings.Index(aUrl, c.Text) // #匹配前面检索到的/之前的字符串
//fmt.Println("Index", idx, aUrl, c.Text, aUrl[:idx])
if idx > -1 {
if len(aUrl[:idx]) > 1 && strings.IndexByte(aUrl[:idx], r.DelimitChar) > -1 {
retnil = true
continue
}
//fmt.Println("类型2", aUrl[:idx], aNode.ContentType)
if !validType(aUrl[:idx], aNode.ContentType) {
//fmt.Println("错误类型", aUrl[:idx], aNode.ContentType)
return nil
//continue
}
h := r.matchNode(c, aUrl[idx:], aParams)
if h != nil {
*aParams = append(*aParams, param{aNode.Text[1:], aUrl[:idx]})
return h
}
retnil = true
}
}
if retnil {
return nil
}
//fmt.Printf("动态", aUrl, aNode.Text[1:])
*aParams = append(*aParams, param{aNode.Text[1:], aUrl})
return aNode
} else if aNode.Type == RegexpNode { // 正则节点
//if len(aNode.Children) == 0 && aNode.regexp.MatchString(aUrl) {
// *aParams = append(*aParams, param{aNode.Text[1:], aUrl})
// return aNode
//}
idx := strings.IndexByte(aUrl, r.DelimitChar)
if idx > -1 {
if aNode.regexp.MatchString(aUrl[:idx]) {
for _, c := range aNode.Children {
h := r.matchNode(c, aUrl[idx:], aParams)
if h != nil {
*aParams = append(*aParams, param{aNode.Text[1:], aUrl[:idx]})
return h
}
}
}
return nil
}
for _, c := range aNode.Children {
idx := strings.Index(aUrl, c.Text)
if idx > -1 && aNode.regexp.MatchString(aUrl[:idx]) {
h := r.matchNode(c, aUrl[idx:], aParams)
if h != nil {
*aParams = append(*aParams, param{aNode.Text[1:], aUrl[:idx]})
return h
}
}
}
if aNode.regexp.MatchString(aUrl) {
*aParams = append(*aParams, param{aNode.Text[1:], aUrl})
return aNode
}
}
return nil
}
func (r *TTree) Match(method string, url string) (*TRoute, Params) {
lRoot := r.Root[method]
var lParams = make(Params, 0, strings.Count(url, string(r.DelimitChar)))
for _, n := range lRoot.Children {
e := r.matchNode(n, url, &lParams)
if e != nil {
return e.Route, lParams
}
}
return nil, nil
}
func validType(content string, typ ContentType) bool {
switch typ {
case NumberType:
for i := 0; i < len(content); i++ {
if !utils.IsDigitByte(content[i]) {
return false
}
}
case CharType:
for i := 0; i < len(content); i++ {
if !utils.IsAlphaByte(content[i]) {
return false
}
}
default:
}
return true
}
// validate parsed nodes, all non-static route should have static route children.
func validNodes(nodes []*TNode) bool {
if len(nodes) == 0 {
return false
}
var lastTp = nodes[0]
for _, node := range nodes[1:] {
if lastTp.Type != StaticNode && node.Type != StaticNode {
return false
}
lastTp = node
}
return true
}
// 添加路由到Tree
func (self *TTree) AddRoute(aMethod, path string, aRoute *TRoute) {
// 解析并创建为Nodes的List形式
lNodes, lIsDyn := self.parsePath(path)
// 标记为动态路由
aRoute.isDynRoute = lIsDyn // 即将Hook的新Route是动态地址
// 绑定Route到最后一个Node
lNode := lNodes[len(lNodes)-1]
aRoute.Action = lNode.Text // 赋值Action
lNode.Route = aRoute
lNode.Path = path
// 验证合法性
if !validNodes(lNodes) {
logger.Panic("express %s is not supported", path)
}
// 插入该节点到Tree
self.addnodes(aMethod, lNodes, false)
}
// conbine 2 node together
func (self *TTree) conbine(aDes, aSrc *TNode) {
var lNode *TNode
// 是否目标Node有该Node
for _, node := range aDes.Children {
if node.Equal(aSrc) {
lNode = node
}
}
// 如果:无该Node直接添加完成所有工作
// 或者:遍历添加所有没有的新Node
if lNode == nil {
aDes.Children = append(aDes.Children, aSrc)
return
} else {
if lNode.Type == RegexpNode {
}
if aSrc.Route != nil {
if lNode.Route == nil {
lNode.Route = aSrc.Route
} else {
// 叠加合并Controller
lNode.Route.CombineController(aSrc.Route)
}
}
// 合并子节点
for _, _node := range aSrc.Children {
self.conbine(lNode, _node)
}
}
}
// conbine 2 tree together
func (self *TTree) Conbine(aTree *TTree) *TTree {
for method, snode := range aTree.Root {
// 如果主树没有该方法叉则直接移植
if _, has := self.Root[method]; !has {
self.Root[method] = snode
} else {
// 采用逐个添加
for _, node := range self.Root[method].Children {
self.conbine(node, snode)
}
}
}
return self
}
// add node nodes[i] to parent node p
func (self *TNode) addnode(aParent *TNode, aNodes []*TNode, i int, aIsHook bool) *TNode {
if len(aParent.Children) == 0 {
aParent.Children = make([]*TNode, 0)
}
// 如果:找到[已经注册]的分支节点则从该节继续[查找/添加]下一个节点
for _, n := range aParent.Children {
if n.Equal(aNodes[i]) {
// 如果:插入的节点层级已经到末尾,则为该节点注册路由
if i == len(aNodes)-1 {
// 原始路由会被替换
if aIsHook {
n.Route.CombineController(aNodes[i].Route)
} else {
n.Route = aNodes[i].Route
}
}
return n
}
}
// 如果:该节点没有对应分支则插入同级的aNodes为新的分支
aParent.Children = append(aParent.Children, aNodes[i])
sort.Sort(aParent.Children)
return aNodes[i]
}
// add nodes to trees
func (self *TTree) addnodes(aMethod string, aNodes []*TNode, aIsHook bool) {
//fmt.Println("self.R | elf.Root)
// 获得对应方法[POST,GET...]
cn := self.Root[aMethod]
if cn == nil {
// 初始化Root node
cn = &TNode{
Children: TSubNodes{},
}
self.Root[aMethod] = cn
}
var p *TNode = cn // 复制方法对应的Root
// 层级插入Nodes的Node到Root
for idx, _ := range aNodes {
p = cn.addnode(p, aNodes, idx, aIsHook)
}
}
func printNode(i int, node *TNode) {
for _, c := range node.Children {
for j := 0; j < i; j++ { // 空格距离ss
fmt.Print(" ")
}
if i > 1 {
fmt.Print("┗", " ")
}
fmt.Printf(`%s<lv:%d,%v>`, c.Text, c.Level, c.ContentType)
if c.Route != nil {
fmt.Print("<*>")
}
//if !reflect.DeepEqual(c.Route, TRoute{}) {
if c.Route != nil {
//fmt.Print(" ", c.Route.HandleType.String())
//fmt.Printf(" %p", c.handle.method.Interface())
}
fmt.Println()
printNode(i+1, c)
}
}
func (self *TTree) PrintTrees() {
for method, node := range self.Root {
if len(node.Children) > 0 {
fmt.Println(method)
printNode(1, node)
fmt.Println()
}
}
}
func (self *TNode) Equal(o *TNode) bool {
if self.Type != o.Type || self.Text != o.Text {
return false
}
return true
}
| oot", s | identifier_name |
tree.go | package web
import (
"fmt"
"regexp"
"sort"
"strings"
"github.com/VectorsOrigin/utils"
)
/*
tree 负责路由树的解析,排序,匹配
实现前面加类型
'/web/content/<string:xmlid>',
'/web/content/<string:xmlid>/<string:filename>',
'/web/content/<int:id>',
'/web/content/<int:id>/<string:filename>',
'/web/content/<int:id>-<string:unique>',
'/web/content/<int:id>-<string:unique>/<string:filename>',
'/web/content/<string:model>/<int:id>/<string:field>',
'/web/content/<string:model>/<int:id>/<string:field>/<string:filename>'
*/
const (
StaticNode NodeType = iota // static, should equal
VariantNode // named node, match a non-/ is ok
AnyNode // catch-all node, match any
RegexpNode // regex node, should match
AllType ContentType = iota
NumberType
CharType
)
var (
HttpMethods = []string{
"GET",
"POST",
"HEAD",
"DELETE",
"PUT",
"OPTIONS",
"TRACE",
"PATCH",
}
)
type (
NodeType byte
ContentType byte
param struct {
Name string
Value string
}
Params []param
// 配置函数接口
ConfigOption func(*TTree)
// 使用Sort 接口自动排序
TSubNodes []*TNode
TNode struct {
Type NodeType
ContentType ContentType
Children TSubNodes
//StaticChild map[string]*TNode
//VariantChild map[string]*TNode
//RegexpChild map[string]*TNode //[]*TNode
Text string // Path string /web/
Path string
Route *TRoute
Level int // #动态Node排序等级 /.../ 之间的Nodes越多等级越高
regexp *regexp.Regexp
}
TTree struct {
Text string
Root map[string]*TNode
IgnoreCase bool
DelimitChar byte // Delimit Char xxx.xxx
//lock sync.RWMutex
}
)
func (p *Params) Get(key string) string {
for _, v := range *p {
if v.Name == key {
return v.Value
}
}
return ""
}
func (p *Params) Set(key, value string) {
for i, v := range *p {
if v.Name == key {
(*p)[i].Value = value
return
}
}
}
func (p *Params) SetParams(params []param) {
*p = params
}
func (self TSubNodes) Len() int {
return len(self)
}
func (self TSubNodes) Swap(i, j int) {
self[i], self[j] = self[j], self[i]
}
| // two static route, content longer is first.
func (self TSubNodes) Less(i, j int) bool {
if self[i].Type == StaticNode {
if self[j].Type == StaticNode {
return len(self[i].Text) > len(self[j].Text)
}
return true
}
if self[j].Type == StaticNode {
return false
} else {
return self[i].Level > self[j].Level
}
return i < j
}
func NewRouteTree(config_fn ...ConfigOption) *TTree {
lTree := &TTree{
Root: make(map[string]*TNode),
DelimitChar:'/',
}
/*
for _, m := range HttpMethods {
lTree.Root[m] = &TNode{
Children: TSubNodes{},
}
}*/
for _,cfg:=range config_fn{
cfg(lTree)
}
return lTree
}
// 解析Path为Node
/* /:name1/:name2 /:name1-:name2 /(:name1)sss(:name2)
/(*name) /(:name[0-9]+) /(type:name[a-z]+)
Result: @ Nodes List
@ is it dyn route
*/
func (r *TTree) parsePath(path string) (nodes []*TNode, isDyn bool) {
if path == "" {
panic("echo: path cannot be empty")
}
if r.DelimitChar=='/' && path[0] != '/' {
path = "/" + path
}
var (
i, j int // i 游标 J 上次标记
bracket int
level int // #Node的 排序等级
target *TNode // 记录等级的Node 一般为/ 开始的第一个动态
node *TNode
)
// 默认
nodes = make([]*TNode, 0)
isDyn = false
l := len(path)
//j = i - 1 // 当i==0时J必须小于它
for ; i < l; i++ {
switch path[i] {
case r.DelimitChar:
//case '/':
{ // 创建Text:'/' Node
if bracket == 0 && i > j {
//if path[j] == '/' {
// nodes = append(nodes, &TNode{Type: StaticNode, Text: string(path[j])})
//}
//j++
nodes = append(nodes, &TNode{Type: StaticNode, Text: path[j:i]})
j = i
}
//fmt.Println("/")
// # 重置计数
target = nil
level = 0 // #开始计数
}
case '(':
{
//fmt.Println("(")
bracket = 1
}
case ':':
{
//fmt.Println(":")
var typ ContentType = AllType
//fmt.Println(":", bracket, path[j:i-bracket])
if path[i-1] == '(' { //#like (:var)
nodes = append(nodes, &TNode{Type: StaticNode, Text: path[j : i-bracket]})
bracket = 1
} else {
// #为变量区分数据类型
str := path[j : i-bracket] // #like /abc1(string|upper:var)
idx := strings.Index(str, "(")
if idx == -1 {
panic(fmt.Sprintf("expect a '(' near position %d~%d", j, i))
}
nodes = append(nodes, &TNode{Type: StaticNode, Text: str[:idx]})
str = str[idx+1:]
switch str {
case "int":
typ = NumberType
case "string":
typ = CharType
default:
typ = AllType
}
//fmt.Println("type:", typ)
bracket = 1
}
j = i
var (
regex string
start = -1
)
if bracket == 1 {
// 开始记录Pos
for ; i < l && ')' != path[i]; i++ { // 移动Pos到) 遇到正则字符标记起
if start == -1 && utils.IsSpecialByte(path[i]) { // 如果是正则
start = i
}
}
if path[i] != ')' {
panic("lack of )")
}
if start > -1 {
regex = path[start:i] //正则内容
}
} else {
i = i + 1
for ; i < l && utils.IsAlnumByte(path[i]); i++ {
}
}
if len(regex) > 0 { // 正则
node = &TNode{Type: RegexpNode, regexp: regexp.MustCompile("(" + regex + ")"), Text: path[j : i-len(regex)]}
nodes = append(nodes, node)
} else { // 变量
node = &TNode{Type: VariantNode, ContentType: typ, Text: path[j:i]}
nodes = append(nodes, node)
}
isDyn = true // #标记 Route 为动态
i = i + bracket // #剔除")"字符 bracket=len(“)”)
j = i
// 当计数器遇到/或者Url末尾时将记录保存于Node中
if target != nil && ((i == l) || (i != l && path[j+1] == r.DelimitChar)) {
level++
target.Level = level
//fmt.Println("ok:", node.Text, target.Text, level)
// # 重置计数
target = nil
level = 0
}
if i == l {
return //nodes, isDyn
}
// #计数滴答
// 放置在 i == l 后 确保表达式2比1多一个层级
// @/(int:id1)-(:unique2)
// @/(:id3)-(:unique3)/(:filename)
if (i != l && path[j] != r.DelimitChar) || level != 0 {
if level == 0 {
target = node
}
level++
//fmt.Println("leve:", node.Text, target.Text, level)
}
}
case '*':
{
nodes = append(nodes, &TNode{Type: StaticNode, Text: path[j : i-bracket]})
j = i
//if bracket == 1 {
// for ; i < l && ')' == path[i]; i++ {
// }
//} else {
i = i + 1
for ; i < l && utils.IsAlnumByte(path[i]); i++ {
}
//}
nodes = append(nodes, &TNode{Type: AnyNode, Text: path[j:i]})
isDyn = true // 标记 Route 为动态
i = i + bracket // bracket=len(“)”)
j = i
if i == l {
return //nodes, isDyn
}
}
default:
{
bracket = 0
}
}
}
nodes = append(nodes, &TNode{
Type: StaticNode,
Text: path[j:i],
})
//fmt.Println("lNodes", len(lNodes))
return //nodes, isDyn
}
func (r *TTree) matchNode(aNode *TNode, aUrl string, aParams *Params) *TNode {
var retnil bool
if aNode.Type == StaticNode { // 静态节点
if strings.HasPrefix(aUrl, aNode.Text) {
//fmt.Println("J态", aUrl, " | ", aNode.Text[1:])
if len(aUrl) == len(aNode.Text) {
return aNode
}
for _, c := range aNode.Children {
e := r.matchNode(c, aUrl[len(aNode.Text):], aParams)
if e != nil {
return e
}
}
}
} else if aNode.Type == AnyNode { // 全匹配节点
//if len(aNode.Children) == 0 {
// *aParams = append(*aParams, param{aNode.Text[1:], aUrl})
// return aNode
//}
//fmt.Println("Any态", aUrl, " | ", aNode.Text[1:])
for _, c := range aNode.Children {
idx := strings.LastIndex(aUrl, c.Text)
//fmt.Println("LastIndex", aUrl, c.Text)
if idx > -1 {
h := r.matchNode(c, aUrl[idx:], aParams)
if h != nil {
*aParams = append(*aParams, param{aNode.Text[1:], aUrl[:idx]})
return h
}
}
}
*aParams = append(*aParams, param{aNode.Text[1:], aUrl})
return aNode
} else if aNode.Type == VariantNode { // 变量节点
// # 消除path like /abc 的'/'
idx := strings.IndexByte(aUrl, r.DelimitChar)
//fmt.Println("D态", aUrl, " | ", aNode.Text[1:], idx)
if idx == 0 { // #fix错误if idx > -1 {
for _, c := range aNode.Children {
h := r.matchNode(c, aUrl[idx:], aParams)
if h != nil {
/*fmt.Println("类型1", aUrl[:idx], aNode.ContentType)
if !validType(aUrl[:idx], aNode.ContentType) {
fmt.Println("错误类型", aUrl[:idx], aNode.ContentType)
return nil
}
*/
*aParams = append(*aParams, param{aNode.Text[1:], aUrl[:idx]})
return h
}
}
return nil
}
// 最底层Node
//if len(aNode.Children) == 0 {
// *aParams = append(*aParams, param{aNode.Text[1:], aUrl})
// return aNode
//}
//fmt.Println("Index", idx)
for _, c := range aNode.Children {
idx := strings.Index(aUrl, c.Text) // #匹配前面检索到的/之前的字符串
//fmt.Println("Index", idx, aUrl, c.Text, aUrl[:idx])
if idx > -1 {
if len(aUrl[:idx]) > 1 && strings.IndexByte(aUrl[:idx], r.DelimitChar) > -1 {
retnil = true
continue
}
//fmt.Println("类型2", aUrl[:idx], aNode.ContentType)
if !validType(aUrl[:idx], aNode.ContentType) {
//fmt.Println("错误类型", aUrl[:idx], aNode.ContentType)
return nil
//continue
}
h := r.matchNode(c, aUrl[idx:], aParams)
if h != nil {
*aParams = append(*aParams, param{aNode.Text[1:], aUrl[:idx]})
return h
}
retnil = true
}
}
if retnil {
return nil
}
//fmt.Printf("动态", aUrl, aNode.Text[1:])
*aParams = append(*aParams, param{aNode.Text[1:], aUrl})
return aNode
} else if aNode.Type == RegexpNode { // 正则节点
//if len(aNode.Children) == 0 && aNode.regexp.MatchString(aUrl) {
// *aParams = append(*aParams, param{aNode.Text[1:], aUrl})
// return aNode
//}
idx := strings.IndexByte(aUrl, r.DelimitChar)
if idx > -1 {
if aNode.regexp.MatchString(aUrl[:idx]) {
for _, c := range aNode.Children {
h := r.matchNode(c, aUrl[idx:], aParams)
if h != nil {
*aParams = append(*aParams, param{aNode.Text[1:], aUrl[:idx]})
return h
}
}
}
return nil
}
for _, c := range aNode.Children {
idx := strings.Index(aUrl, c.Text)
if idx > -1 && aNode.regexp.MatchString(aUrl[:idx]) {
h := r.matchNode(c, aUrl[idx:], aParams)
if h != nil {
*aParams = append(*aParams, param{aNode.Text[1:], aUrl[:idx]})
return h
}
}
}
if aNode.regexp.MatchString(aUrl) {
*aParams = append(*aParams, param{aNode.Text[1:], aUrl})
return aNode
}
}
return nil
}
func (r *TTree) Match(method string, url string) (*TRoute, Params) {
lRoot := r.Root[method]
var lParams = make(Params, 0, strings.Count(url, string(r.DelimitChar)))
for _, n := range lRoot.Children {
e := r.matchNode(n, url, &lParams)
if e != nil {
return e.Route, lParams
}
}
return nil, nil
}
func validType(content string, typ ContentType) bool {
switch typ {
case NumberType:
for i := 0; i < len(content); i++ {
if !utils.IsDigitByte(content[i]) {
return false
}
}
case CharType:
for i := 0; i < len(content); i++ {
if !utils.IsAlphaByte(content[i]) {
return false
}
}
default:
}
return true
}
// validate parsed nodes, all non-static route should have static route children.
func validNodes(nodes []*TNode) bool {
if len(nodes) == 0 {
return false
}
var lastTp = nodes[0]
for _, node := range nodes[1:] {
if lastTp.Type != StaticNode && node.Type != StaticNode {
return false
}
lastTp = node
}
return true
}
// 添加路由到Tree
func (self *TTree) AddRoute(aMethod, path string, aRoute *TRoute) {
// 解析并创建为Nodes的List形式
lNodes, lIsDyn := self.parsePath(path)
// 标记为动态路由
aRoute.isDynRoute = lIsDyn // 即将Hook的新Route是动态地址
// 绑定Route到最后一个Node
lNode := lNodes[len(lNodes)-1]
aRoute.Action = lNode.Text // 赋值Action
lNode.Route = aRoute
lNode.Path = path
// 验证合法性
if !validNodes(lNodes) {
logger.Panic("express %s is not supported", path)
}
// 插入该节点到Tree
self.addnodes(aMethod, lNodes, false)
}
// conbine 2 node together
func (self *TTree) conbine(aDes, aSrc *TNode) {
var lNode *TNode
// 是否目标Node有该Node
for _, node := range aDes.Children {
if node.Equal(aSrc) {
lNode = node
}
}
// 如果:无该Node直接添加完成所有工作
// 或者:遍历添加所有没有的新Node
if lNode == nil {
aDes.Children = append(aDes.Children, aSrc)
return
} else {
if lNode.Type == RegexpNode {
}
if aSrc.Route != nil {
if lNode.Route == nil {
lNode.Route = aSrc.Route
} else {
// 叠加合并Controller
lNode.Route.CombineController(aSrc.Route)
}
}
// 合并子节点
for _, _node := range aSrc.Children {
self.conbine(lNode, _node)
}
}
}
// conbine 2 tree together
func (self *TTree) Conbine(aTree *TTree) *TTree {
for method, snode := range aTree.Root {
// 如果主树没有该方法叉则直接移植
if _, has := self.Root[method]; !has {
self.Root[method] = snode
} else {
// 采用逐个添加
for _, node := range self.Root[method].Children {
self.conbine(node, snode)
}
}
}
return self
}
// add node nodes[i] to parent node p
func (self *TNode) addnode(aParent *TNode, aNodes []*TNode, i int, aIsHook bool) *TNode {
if len(aParent.Children) == 0 {
aParent.Children = make([]*TNode, 0)
}
// 如果:找到[已经注册]的分支节点则从该节继续[查找/添加]下一个节点
for _, n := range aParent.Children {
if n.Equal(aNodes[i]) {
// 如果:插入的节点层级已经到末尾,则为该节点注册路由
if i == len(aNodes)-1 {
// 原始路由会被替换
if aIsHook {
n.Route.CombineController(aNodes[i].Route)
} else {
n.Route = aNodes[i].Route
}
}
return n
}
}
// 如果:该节点没有对应分支则插入同级的aNodes为新的分支
aParent.Children = append(aParent.Children, aNodes[i])
sort.Sort(aParent.Children)
return aNodes[i]
}
// add nodes to trees
func (self *TTree) addnodes(aMethod string, aNodes []*TNode, aIsHook bool) {
//fmt.Println("self.Root", self.Root)
// 获得对应方法[POST,GET...]
cn := self.Root[aMethod]
if cn == nil {
// 初始化Root node
cn = &TNode{
Children: TSubNodes{},
}
self.Root[aMethod] = cn
}
var p *TNode = cn // 复制方法对应的Root
// 层级插入Nodes的Node到Root
for idx, _ := range aNodes {
p = cn.addnode(p, aNodes, idx, aIsHook)
}
}
func printNode(i int, node *TNode) {
for _, c := range node.Children {
for j := 0; j < i; j++ { // 空格距离ss
fmt.Print(" ")
}
if i > 1 {
fmt.Print("┗", " ")
}
fmt.Printf(`%s<lv:%d,%v>`, c.Text, c.Level, c.ContentType)
if c.Route != nil {
fmt.Print("<*>")
}
//if !reflect.DeepEqual(c.Route, TRoute{}) {
if c.Route != nil {
//fmt.Print(" ", c.Route.HandleType.String())
//fmt.Printf(" %p", c.handle.method.Interface())
}
fmt.Println()
printNode(i+1, c)
}
}
func (self *TTree) PrintTrees() {
for method, node := range self.Root {
if len(node.Children) > 0 {
fmt.Println(method)
printNode(1, node)
fmt.Println()
}
}
}
func (self *TNode) Equal(o *TNode) bool {
if self.Type != o.Type || self.Text != o.Text {
return false
}
return true
} | // static route will be put the first, so it will be match first. | random_line_split |
tree.go | package web
import (
"fmt"
"regexp"
"sort"
"strings"
"github.com/VectorsOrigin/utils"
)
/*
tree 负责路由树的解析,排序,匹配
实现前面加类型
'/web/content/<string:xmlid>',
'/web/content/<string:xmlid>/<string:filename>',
'/web/content/<int:id>',
'/web/content/<int:id>/<string:filename>',
'/web/content/<int:id>-<string:unique>',
'/web/content/<int:id>-<string:unique>/<string:filename>',
'/web/content/<string:model>/<int:id>/<string:field>',
'/web/content/<string:model>/<int:id>/<string:field>/<string:filename>'
*/
const (
StaticNode NodeType = iota // static, should equal
VariantNode // named node, match a non-/ is ok
AnyNode // catch-all node, match any
RegexpNode // regex node, should match
AllType ContentType = iota
NumberType
CharType
)
var (
HttpMethods = []string{
"GET",
"POST",
"HEAD",
"DELETE",
"PUT",
"OPTIONS",
"TRACE",
"PATCH",
}
)
type (
NodeType byte
ContentType byte
param struct {
Name string
Value string
}
Params []param
// 配置函数接口
ConfigOption func(*TTree)
// 使用Sort 接口自动排序
TSubNodes []*TNode
TNode struct {
Type NodeType
ContentType ContentType
Children TSubNodes
//StaticChild map[string]*TNode
//VariantChild map[string]*TNode
//RegexpChild map[string]*TNode //[]*TNode
Text string // Path string /web/
Path string
Route *TRoute
Level int // #动态Node排序等级 /.../ 之间的Nodes越多等级越高
regexp *regexp.Regexp
}
TTree struct {
Text string
Root map[string]*TNode
IgnoreCase bool
DelimitChar byte // Delimit Char xxx.xxx
//lock sync.RWMutex
}
)
func (p *Params) Get(key string) string {
for _, v := range *p {
if v.Name == key {
return v.Value
}
}
return ""
}
func (p *Params) Set(key, value string) {
for i, v := range *p {
if v.Name == key {
(*p)[i].Value = value
return
}
}
}
func (p *Params) SetParams(params []param) {
*p = params
}
func (self TSubNodes) Len() int {
return len(self)
}
func (self TSubNodes) S | self[i], self[j] = self[j], self[i]
}
// static route will be put the first, so it will be match first.
// two static route, content longer is first.
func (self TSubNodes) Less(i, j int) bool {
if self[i].Type == StaticNode {
if self[j].Type == StaticNode {
return len(self[i].Text) > len(self[j].Text)
}
return true
}
if self[j].Type == StaticNode {
return false
} else {
return self[i].Level > self[j].Level
}
return i < j
}
func NewRouteTree(config_fn ...ConfigOption) *TTree {
lTree := &TTree{
Root: make(map[string]*TNode),
DelimitChar:'/',
}
/*
for _, m := range HttpMethods {
lTree.Root[m] = &TNode{
Children: TSubNodes{},
}
}*/
for _,cfg:=range config_fn{
cfg(lTree)
}
return lTree
}
// 解析Path为Node
/* /:name1/:name2 /:name1-:name2 /(:name1)sss(:name2)
/(*name) /(:name[0-9]+) /(type:name[a-z]+)
Result: @ Nodes List
@ is it dyn route
*/
func (r *TTree) parsePath(path string) (nodes []*TNode, isDyn bool) {
if path == "" {
panic("echo: path cannot be empty")
}
if r.DelimitChar=='/' && path[0] != '/' {
path = "/" + path
}
var (
i, j int // i 游标 J 上次标记
bracket int
level int // #Node的 排序等级
target *TNode // 记录等级的Node 一般为/ 开始的第一个动态
node *TNode
)
// 默认
nodes = make([]*TNode, 0)
isDyn = false
l := len(path)
//j = i - 1 // 当i==0时J必须小于它
for ; i < l; i++ {
switch path[i] {
case r.DelimitChar:
//case '/':
{ // 创建Text:'/' Node
if bracket == 0 && i > j {
//if path[j] == '/' {
// nodes = append(nodes, &TNode{Type: StaticNode, Text: string(path[j])})
//}
//j++
nodes = append(nodes, &TNode{Type: StaticNode, Text: path[j:i]})
j = i
}
//fmt.Println("/")
// # 重置计数
target = nil
level = 0 // #开始计数
}
case '(':
{
//fmt.Println("(")
bracket = 1
}
case ':':
{
//fmt.Println(":")
var typ ContentType = AllType
//fmt.Println(":", bracket, path[j:i-bracket])
if path[i-1] == '(' { //#like (:var)
nodes = append(nodes, &TNode{Type: StaticNode, Text: path[j : i-bracket]})
bracket = 1
} else {
// #为变量区分数据类型
str := path[j : i-bracket] // #like /abc1(string|upper:var)
idx := strings.Index(str, "(")
if idx == -1 {
panic(fmt.Sprintf("expect a '(' near position %d~%d", j, i))
}
nodes = append(nodes, &TNode{Type: StaticNode, Text: str[:idx]})
str = str[idx+1:]
switch str {
case "int":
typ = NumberType
case "string":
typ = CharType
default:
typ = AllType
}
//fmt.Println("type:", typ)
bracket = 1
}
j = i
var (
regex string
start = -1
)
if bracket == 1 {
// 开始记录Pos
for ; i < l && ')' != path[i]; i++ { // 移动Pos到) 遇到正则字符标记起
if start == -1 && utils.IsSpecialByte(path[i]) { // 如果是正则
start = i
}
}
if path[i] != ')' {
panic("lack of )")
}
if start > -1 {
regex = path[start:i] //正则内容
}
} else {
i = i + 1
for ; i < l && utils.IsAlnumByte(path[i]); i++ {
}
}
if len(regex) > 0 { // 正则
node = &TNode{Type: RegexpNode, regexp: regexp.MustCompile("(" + regex + ")"), Text: path[j : i-len(regex)]}
nodes = append(nodes, node)
} else { // 变量
node = &TNode{Type: VariantNode, ContentType: typ, Text: path[j:i]}
nodes = append(nodes, node)
}
isDyn = true // #标记 Route 为动态
i = i + bracket // #剔除")"字符 bracket=len(“)”)
j = i
// 当计数器遇到/或者Url末尾时将记录保存于Node中
if target != nil && ((i == l) || (i != l && path[j+1] == r.DelimitChar)) {
level++
target.Level = level
//fmt.Println("ok:", node.Text, target.Text, level)
// # 重置计数
target = nil
level = 0
}
if i == l {
return //nodes, isDyn
}
// #计数滴答
// 放置在 i == l 后 确保表达式2比1多一个层级
// @/(int:id1)-(:unique2)
// @/(:id3)-(:unique3)/(:filename)
if (i != l && path[j] != r.DelimitChar) || level != 0 {
if level == 0 {
target = node
}
level++
//fmt.Println("leve:", node.Text, target.Text, level)
}
}
case '*':
{
nodes = append(nodes, &TNode{Type: StaticNode, Text: path[j : i-bracket]})
j = i
//if bracket == 1 {
// for ; i < l && ')' == path[i]; i++ {
// }
//} else {
i = i + 1
for ; i < l && utils.IsAlnumByte(path[i]); i++ {
}
//}
nodes = append(nodes, &TNode{Type: AnyNode, Text: path[j:i]})
isDyn = true // 标记 Route 为动态
i = i + bracket // bracket=len(“)”)
j = i
if i == l {
return //nodes, isDyn
}
}
default:
{
bracket = 0
}
}
}
nodes = append(nodes, &TNode{
Type: StaticNode,
Text: path[j:i],
})
//fmt.Println("lNodes", len(lNodes))
return //nodes, isDyn
}
func (r *TTree) matchNode(aNode *TNode, aUrl string, aParams *Params) *TNode {
var retnil bool
if aNode.Type == StaticNode { // 静态节点
if strings.HasPrefix(aUrl, aNode.Text) {
//fmt.Println("J态", aUrl, " | ", aNode.Text[1:])
if len(aUrl) == len(aNode.Text) {
return aNode
}
for _, c := range aNode.Children {
e := r.matchNode(c, aUrl[len(aNode.Text):], aParams)
if e != nil {
return e
}
}
}
} else if aNode.Type == AnyNode { // 全匹配节点
//if len(aNode.Children) == 0 {
// *aParams = append(*aParams, param{aNode.Text[1:], aUrl})
// return aNode
//}
//fmt.Println("Any态", aUrl, " | ", aNode.Text[1:])
for _, c := range aNode.Children {
idx := strings.LastIndex(aUrl, c.Text)
//fmt.Println("LastIndex", aUrl, c.Text)
if idx > -1 {
h := r.matchNode(c, aUrl[idx:], aParams)
if h != nil {
*aParams = append(*aParams, param{aNode.Text[1:], aUrl[:idx]})
return h
}
}
}
*aParams = append(*aParams, param{aNode.Text[1:], aUrl})
return aNode
} else if aNode.Type == VariantNode { // 变量节点
// # 消除path like /abc 的'/'
idx := strings.IndexByte(aUrl, r.DelimitChar)
//fmt.Println("D态", aUrl, " | ", aNode.Text[1:], idx)
if idx == 0 { // #fix错误if idx > -1 {
for _, c := range aNode.Children {
h := r.matchNode(c, aUrl[idx:], aParams)
if h != nil {
/*fmt.Println("类型1", aUrl[:idx], aNode.ContentType)
if !validType(aUrl[:idx], aNode.ContentType) {
fmt.Println("错误类型", aUrl[:idx], aNode.ContentType)
return nil
}
*/
*aParams = append(*aParams, param{aNode.Text[1:], aUrl[:idx]})
return h
}
}
return nil
}
// 最底层Node
//if len(aNode.Children) == 0 {
// *aParams = append(*aParams, param{aNode.Text[1:], aUrl})
// return aNode
//}
//fmt.Println("Index", idx)
for _, c := range aNode.Children {
idx := strings.Index(aUrl, c.Text) // #匹配前面检索到的/之前的字符串
//fmt.Println("Index", idx, aUrl, c.Text, aUrl[:idx])
if idx > -1 {
if len(aUrl[:idx]) > 1 && strings.IndexByte(aUrl[:idx], r.DelimitChar) > -1 {
retnil = true
continue
}
//fmt.Println("类型2", aUrl[:idx], aNode.ContentType)
if !validType(aUrl[:idx], aNode.ContentType) {
//fmt.Println("错误类型", aUrl[:idx], aNode.ContentType)
return nil
//continue
}
h := r.matchNode(c, aUrl[idx:], aParams)
if h != nil {
*aParams = append(*aParams, param{aNode.Text[1:], aUrl[:idx]})
return h
}
retnil = true
}
}
if retnil {
return nil
}
//fmt.Printf("动态", aUrl, aNode.Text[1:])
*aParams = append(*aParams, param{aNode.Text[1:], aUrl})
return aNode
} else if aNode.Type == RegexpNode { // 正则节点
//if len(aNode.Children) == 0 && aNode.regexp.MatchString(aUrl) {
// *aParams = append(*aParams, param{aNode.Text[1:], aUrl})
// return aNode
//}
idx := strings.IndexByte(aUrl, r.DelimitChar)
if idx > -1 {
if aNode.regexp.MatchString(aUrl[:idx]) {
for _, c := range aNode.Children {
h := r.matchNode(c, aUrl[idx:], aParams)
if h != nil {
*aParams = append(*aParams, param{aNode.Text[1:], aUrl[:idx]})
return h
}
}
}
return nil
}
for _, c := range aNode.Children {
idx := strings.Index(aUrl, c.Text)
if idx > -1 && aNode.regexp.MatchString(aUrl[:idx]) {
h := r.matchNode(c, aUrl[idx:], aParams)
if h != nil {
*aParams = append(*aParams, param{aNode.Text[1:], aUrl[:idx]})
return h
}
}
}
if aNode.regexp.MatchString(aUrl) {
*aParams = append(*aParams, param{aNode.Text[1:], aUrl})
return aNode
}
}
return nil
}
func (r *TTree) Match(method string, url string) (*TRoute, Params) {
lRoot := r.Root[method]
var lParams = make(Params, 0, strings.Count(url, string(r.DelimitChar)))
for _, n := range lRoot.Children {
e := r.matchNode(n, url, &lParams)
if e != nil {
return e.Route, lParams
}
}
return nil, nil
}
func validType(content string, typ ContentType) bool {
switch typ {
case NumberType:
for i := 0; i < len(content); i++ {
if !utils.IsDigitByte(content[i]) {
return false
}
}
case CharType:
for i := 0; i < len(content); i++ {
if !utils.IsAlphaByte(content[i]) {
return false
}
}
default:
}
return true
}
// validate parsed nodes, all non-static route should have static route children.
func validNodes(nodes []*TNode) bool {
if len(nodes) == 0 {
return false
}
var lastTp = nodes[0]
for _, node := range nodes[1:] {
if lastTp.Type != StaticNode && node.Type != StaticNode {
return false
}
lastTp = node
}
return true
}
// 添加路由到Tree
func (self *TTree) AddRoute(aMethod, path string, aRoute *TRoute) {
// 解析并创建为Nodes的List形式
lNodes, lIsDyn := self.parsePath(path)
// 标记为动态路由
aRoute.isDynRoute = lIsDyn // 即将Hook的新Route是动态地址
// 绑定Route到最后一个Node
lNode := lNodes[len(lNodes)-1]
aRoute.Action = lNode.Text // 赋值Action
lNode.Route = aRoute
lNode.Path = path
// 验证合法性
if !validNodes(lNodes) {
logger.Panic("express %s is not supported", path)
}
// 插入该节点到Tree
self.addnodes(aMethod, lNodes, false)
}
// conbine 2 node together
func (self *TTree) conbine(aDes, aSrc *TNode) {
var lNode *TNode
// 是否目标Node有该Node
for _, node := range aDes.Children {
if node.Equal(aSrc) {
lNode = node
}
}
// 如果:无该Node直接添加完成所有工作
// 或者:遍历添加所有没有的新Node
if lNode == nil {
aDes.Children = append(aDes.Children, aSrc)
return
} else {
if lNode.Type == RegexpNode {
}
if aSrc.Route != nil {
if lNode.Route == nil {
lNode.Route = aSrc.Route
} else {
// 叠加合并Controller
lNode.Route.CombineController(aSrc.Route)
}
}
// 合并子节点
for _, _node := range aSrc.Children {
self.conbine(lNode, _node)
}
}
}
// conbine 2 tree together
func (self *TTree) Conbine(aTree *TTree) *TTree {
for method, snode := range aTree.Root {
// 如果主树没有该方法叉则直接移植
if _, has := self.Root[method]; !has {
self.Root[method] = snode
} else {
// 采用逐个添加
for _, node := range self.Root[method].Children {
self.conbine(node, snode)
}
}
}
return self
}
// add node nodes[i] to parent node p
func (self *TNode) addnode(aParent *TNode, aNodes []*TNode, i int, aIsHook bool) *TNode {
if len(aParent.Children) == 0 {
aParent.Children = make([]*TNode, 0)
}
// 如果:找到[已经注册]的分支节点则从该节继续[查找/添加]下一个节点
for _, n := range aParent.Children {
if n.Equal(aNodes[i]) {
// 如果:插入的节点层级已经到末尾,则为该节点注册路由
if i == len(aNodes)-1 {
// 原始路由会被替换
if aIsHook {
n.Route.CombineController(aNodes[i].Route)
} else {
n.Route = aNodes[i].Route
}
}
return n
}
}
// 如果:该节点没有对应分支则插入同级的aNodes为新的分支
aParent.Children = append(aParent.Children, aNodes[i])
sort.Sort(aParent.Children)
return aNodes[i]
}
// add nodes to trees
func (self *TTree) addnodes(aMethod string, aNodes []*TNode, aIsHook bool) {
//fmt.Println("self.Root", self.Root)
// 获得对应方法[POST,GET...]
cn := self.Root[aMethod]
if cn == nil {
// 初始化Root node
cn = &TNode{
Children: TSubNodes{},
}
self.Root[aMethod] = cn
}
var p *TNode = cn // 复制方法对应的Root
// 层级插入Nodes的Node到Root
for idx, _ := range aNodes {
p = cn.addnode(p, aNodes, idx, aIsHook)
}
}
func printNode(i int, node *TNode) {
for _, c := range node.Children {
for j := 0; j < i; j++ { // 空格距离ss
fmt.Print(" ")
}
if i > 1 {
fmt.Print("┗", " ")
}
fmt.Printf(`%s<lv:%d,%v>`, c.Text, c.Level, c.ContentType)
if c.Route != nil {
fmt.Print("<*>")
}
//if !reflect.DeepEqual(c.Route, TRoute{}) {
if c.Route != nil {
//fmt.Print(" ", c.Route.HandleType.String())
//fmt.Printf(" %p", c.handle.method.Interface())
}
fmt.Println()
printNode(i+1, c)
}
}
func (self *TTree) PrintTrees() {
for method, node := range self.Root {
if len(node.Children) > 0 {
fmt.Println(method)
printNode(1, node)
fmt.Println()
}
}
}
func (self *TNode) Equal(o *TNode) bool {
if self.Type != o.Type || self.Text != o.Text {
return false
}
return true
}
| wap(i, j int) {
| identifier_body |
tree.go | package web
import (
"fmt"
"regexp"
"sort"
"strings"
"github.com/VectorsOrigin/utils"
)
/*
tree 负责路由树的解析,排序,匹配
实现前面加类型
'/web/content/<string:xmlid>',
'/web/content/<string:xmlid>/<string:filename>',
'/web/content/<int:id>',
'/web/content/<int:id>/<string:filename>',
'/web/content/<int:id>-<string:unique>',
'/web/content/<int:id>-<string:unique>/<string:filename>',
'/web/content/<string:model>/<int:id>/<string:field>',
'/web/content/<string:model>/<int:id>/<string:field>/<string:filename>'
*/
const (
StaticNode NodeType = iota // static, should equal
VariantNode // named node, match a non-/ is ok
AnyNode // catch-all node, match any
RegexpNode // regex node, should match
AllType ContentType = iota
NumberType
CharType
)
var (
HttpMethods = []string{
"GET",
"POST",
"HEAD",
"DELETE",
"PUT",
"OPTIONS",
"TRACE",
"PATCH",
}
)
type (
NodeType byte
ContentType byte
param struct {
Name string
Value string
}
Params []param
// 配置函数接口
ConfigOption func(*TTree)
// 使用Sort 接口自动排序
TSubNodes []*TNode
TNode struct {
Type NodeType
ContentType ContentType
Children TSubNodes
//StaticChild map[string]*TNode
//VariantChild map[string]*TNode
//RegexpChild map[string]*TNode //[]*TNode
Text string // Path string /web/
Path string
Route *TRoute
Level int // #动态Node排序等级 /.../ 之间的Nodes越多等级越高
regexp *regexp.Regexp
}
TTree struct {
Text string
Root map[string]*TNode
IgnoreCase bool
DelimitChar byte // Delimit Char xxx.xxx
//lock sync.RWMutex
}
)
func (p *Params) Get(key string) string {
for _, v := range *p {
if v.Name == key {
return v.Value
}
}
return ""
}
func (p *Params) Set(key, value string) {
for i, v := range *p {
if v.Name == key {
(*p)[i].Value = value
return
}
}
}
func (p *Params) SetParams(params []param) {
*p = params
}
func (self TSubNodes) Len() int {
return len(self)
}
func (self TSubNodes) Swap(i, j int) {
self[i], self[j] = self[j], self[i]
}
// static route will be put the first, so it will be match first.
// two static route, content longer is first.
func (self TSubNodes) Less(i, j int) bool {
if self[i].Type == StaticNode {
if self[j].Type == StaticNode {
return len(self[i].Text) > len(self[j].Text)
}
return true
}
if self[j].Type == StaticNode {
return false
} else {
return self[i].Level > self[j].Level
}
return i < j
}
func NewRouteTree(config_fn ...ConfigOption) *TTree {
lTree := &TTree{
Root: make(map[string]*TNode),
DelimitChar:'/',
}
/*
for _, m := range HttpMethods {
lTree.Root[m] = &TNode{
Children: TSubNodes{},
}
}*/
for _,cfg:=range config_fn{
cfg(lTree)
}
return lTree
}
// 解析Path为Node
/* /:name1/:name2 /:name1-:name2 /(:name1)sss(:name2)
/(*name) /(:name[0-9]+) /(type:name[a-z]+)
Result: @ Nodes List
@ is it dyn route
*/
func (r *TTree) parsePath(path string) (nodes []*TNode, isDyn bool) {
if path == "" {
panic("echo: path cannot be empty")
}
if r.DelimitChar=='/' && path[0] != '/' {
path = "/" + path
}
var (
i, j int // i 游标 J 上次标记
bracket int
level int // #Node的 排序等级
target *TNode // 记录等级的Node 一般为/ 开始的第一个动态
node *TNode
)
// 默认
nodes = make([]*TNode, 0)
isDyn = false
l := len(path)
//j = i - 1 // 当i==0时J必须小于它
for ; i < l; i++ {
switch path[i] {
case r.DelimitChar:
//case '/':
{ // 创建Text:'/' Node
if bracket == 0 && i > j {
//if path[j] == '/' {
// nodes = append(nodes, &TNode{Type: StaticNode, Text: string(path[j])})
//}
//j++
nodes = append(nodes, &TNode{Type: StaticNode, Text: path[j:i]})
j = i
}
//fmt.Println("/")
// # 重置计数
target = nil
level = 0 // #开始计数
}
case '(':
{
//fmt.Println("(")
bracket = 1
}
case ':':
{
//fmt.Println(":")
var typ ContentType = AllType
//fmt.Println(":", bracket, path[j:i-bracket])
if path[i-1] == '(' { //#like (:var)
nodes = append(nodes, &TNode{Type: StaticNode, Text: path[j : i-bracket]})
bracket = 1
} else {
// #为变量区分数据类型
str := path[j : i-bracket] // #like /abc1(string|upper:var)
idx := strings.Index(str, "(")
if idx == -1 {
panic(fmt.Sprintf("expect a '(' near position %d~%d", j, i))
}
nodes = append(nodes, &TNode{Type: StaticNode, Text: str[:idx]})
str = str[idx+1:]
switch str {
case "int":
typ = NumberType
case "string":
typ = CharType
default:
typ = AllType
}
//fmt.Println("type:", typ)
bracket = 1
}
j = i
var (
regex string
start = -1
)
if bracket == 1 {
// 开始记录Pos
for ; i < l && ')' != path[i]; i++ { // 移动Pos到) 遇到正则字符标记起
if start == -1 && utils.IsSpecialByte(path[i]) { // 如果是正则
start = i
}
}
if path[i] != ')' {
panic("lack of )")
}
if start > -1 {
regex = path[start:i] //正则内容
}
} else {
i = i + 1
for ; i < l && utils.IsAlnumByte(path[i]); i++ {
}
}
if len(regex) > 0 { // 正则
node = &TNode{Type: RegexpNode, regexp: regexp.MustCompile("(" + regex + ")"), Text: path[j : i-len(regex)]}
nodes = append(nodes, node)
} else { // 变量
node = &TNode{Type: VariantNode, ContentType: typ, Text: path[j:i]}
nodes = append(nodes, node)
}
isDyn = true // #标记 Route 为动态
i = i + bracket // #剔除")"字符 bracket=len(“)”)
j = i
// 当计数器遇到/或者Url末尾时将记录保存于Node中
if target != nil && ((i == l) || (i != l && path[j+1] == r.DelimitChar)) {
level++
target.Level = level
//fmt.Println("ok:", node.Text, target.Text, level)
// # 重置计数
target = nil
level = 0
}
if i == l {
return //nodes, isDyn
}
// #计数滴答
// 放置在 i == l 后 确保表达式2比1多一个层级
// @/(int:id1)-(:unique2)
// @/(:id3)-(:unique3)/(:filename)
if (i != l && path[j] != r.DelimitChar) || level != 0 {
if level == 0 {
target = node
}
level++
//fmt.Println("leve:", node.Text, target.Text, level)
}
}
case '*':
{
nodes = append(nodes, &TNode{Type: StaticNode, Text: path[j : i-bracket]})
j = i
//if bracket == 1 {
// for ; i < l && ')' == path[i]; i++ {
// }
//} else {
i = i + 1
for ; i < l && utils.IsAlnumByte(path[i]); i++ {
}
//}
nodes = append(nodes, &TNode{Type: AnyNode, Text: path[j:i]})
isDyn = true // 标记 Route 为动态
i = i + bracket // bracket=len(“)”)
j = i
if i == l {
return //nodes, isDyn
}
}
default:
{
bracket = 0
}
}
}
nodes = append(nodes, &TNode{
Type: StaticNode,
Text: path[j:i],
})
//fmt.Println("lNodes", len(lNodes))
return //nodes, isDyn
}
func (r *TTree) matchNode(aNode *TNode, aUrl string, aParams *Params) *TNode {
var retnil bool
if aNode.Type == StaticNode { // 静态节点
if strings.HasPrefix(aUrl, aNode.Text) {
//fmt.Println("J态", aUrl, " | ", aNode.Text[1:])
if len(aUrl) == len(aNode.Text) {
return aNode
}
for _, c := range aNode.Children {
e := r.matchNode(c, aUrl[len(aNode.Text):], aParams)
if e != nil {
return e
}
}
}
} else if aNode.Type == AnyNode { // 全匹配节点
//if len(aNode.Children) == 0 {
// *aParams = append(*aParams, param{aNode.Text[1:], aUrl})
// return aNode
//}
//fmt.Println("Any态", aUrl, " | ", aNode.Text[1:])
for _, c := range aNode.Children {
idx := strings.LastIndex(aUrl, c.Text)
//fmt.Println("LastIndex", aUrl, c.Text)
if idx > -1 {
h := r.matchNode(c, aUrl[idx:], aParams)
if h != nil {
*aParams = append(*aParams, param{aNode.Text[1:], aUrl[:idx]})
return h
}
}
}
*aParams = append(*aParams, param{aNode.Text[1:], aUrl})
return aNode
} else if aNode.Type == VariantNode { // 变量节点
// # 消除path like /abc 的'/'
idx := strings.IndexByte(aUrl, r.DelimitChar)
//fmt.Println("D态", aUrl, " | ", aNode.Text[1:], idx)
if idx == 0 { // #fix错误if idx > -1 {
for _, c := range aNode.Children {
h := r.matchNode(c, aUrl[idx:], aParams)
if h != nil {
/*fmt.Println("类型1", aUrl[:idx], aNode.ContentType)
if !validType(aUrl[:idx], aNode.ContentType) {
fmt.Println("错误类型", aUrl[:idx], aNode.ContentType)
return nil
}
*/
*aParams = append(*aParams, param{aNode.Text[1:], aUrl[:idx]})
return h
}
}
return nil
}
// 最底层Node
//if len(aNode.Children) == 0 {
// *aParams = append(*aParams, param{aNode.Text[1:], aUrl})
// return aNode
//}
//fmt.Println("Index", idx)
for _, c := range aNode.Children {
idx := strings.Index(aUrl, c.Text) // #匹配前面检索到的/之前的字符串
//fmt.Println("Index", idx, aUrl, c.Text, aUrl[:idx])
if idx > -1 {
if len(aUrl[:idx]) > 1 && strings.IndexByte(aUrl[:idx], r.DelimitChar) > -1 {
retnil = true
continue
}
//fmt.Println("类型2", aUrl[:idx], aNode.ContentType)
if !validType(aUrl[:idx], aNode.ContentType) {
//fmt.Println("错误类型", aUrl[:idx], aNode.ContentType)
return nil
//continue
}
h := r.matchNode(c, aUrl[idx:], aParams)
if h != nil {
*aParams = append(*aParams, param{aNode.Text[1:], aUrl[:idx]})
return h
}
retnil = true
}
}
if retnil {
return nil
}
//fmt.Printf("动态", aUrl, aNode.Text[1:])
*aParams = append(*aParams, param{aNode.Text[1:], aUrl})
return aNode
} else if aNode.Type == RegexpNode { // 正则节点
//if len(aNode.Children) == 0 && aNode.regexp.MatchString(aUrl) {
// *aParams = append(*aParams, param{aNode.Text[1:], aUrl})
// return aNode
//}
idx := strings.IndexByte(aUrl, r.DelimitChar)
if idx > -1 {
if aNode.regexp.MatchString(aUrl[:idx]) {
for _, c := range aNode.Children {
h := r.matchNode(c, aUrl[idx:], aParams)
if h != nil {
*aParams = append(*aParams, param{aNode.Text[1:], aUrl[:idx]})
return h
}
}
}
return nil
}
for _, c := range aNode.Children {
idx := strings.Index(aUrl, c.Text)
if idx > -1 && aNode.regexp.MatchString(aUrl[:idx]) {
h := r.matchNode(c, aUrl[idx:], aParams)
if h != nil {
*aParams = append(*aParams, param{aNode.Text[1:], aUrl[:idx]})
return h
}
}
}
if aNode.regexp.MatchString(aUrl) {
*aParams = append(*aParams, param{aNode.Text[1:], aUrl})
return aNode
}
}
return nil
}
func (r *TTree) Match(method string, url string) (*TRoute, Params) {
lRoot := r.Root[method]
var lParams = make(Params, 0, strings.Count(url, string(r.DelimitChar)))
for _, n := range lRoot.Children {
e := r.matchNode(n, url, &lParams)
if e != nil {
return e.Route, lParams
}
}
return nil, nil
}
func validType(content string, typ ContentType) bool {
switch typ {
case NumberType:
for i := 0; i < len(content); i++ {
if !utils.IsDigitByte(content[i]) {
return false
}
}
case CharType:
for i := 0; i < len(content); i++ {
if !utils.IsAlphaByte(content[i]) {
return false
}
}
default:
}
return true
}
// validate parsed nodes, all non-static route should have static route children.
func validNodes(nodes []*TNode) bool {
if len(nodes) == 0 {
return false
}
var lastTp = nodes[0]
for _, node := range nodes[1:] {
if lastTp.Type != StaticNode && node.Type != StaticNode {
return false
}
lastTp = node
}
return true
}
// 添加路由到Tree
func (self *TTree) AddRoute(aMethod, path string, aRoute *TRoute) {
// 解析并创建为Nodes的List形式
lNodes, lIsDyn := self.parsePath(path)
// 标记为动态路由
aRoute.isDynRoute = lIsDyn // 即将Hook的新Route是动态地址
// 绑定Route到最后一个Node
lNode := lNodes[len(lNodes)-1]
aRoute.Action = lNode.Text // 赋值Action
lNode.Route = aRoute
lNode.Path = path
// 验证合法性
if !validNodes(lNodes) {
logger.Panic("express %s is not supported", path)
}
// 插入该节点到Tree
self.addnodes(aMethod, lNodes, false)
}
// conbine 2 node together
func (self *TTree) conbine(aDes, aSrc *TNode) {
var lNode *TNode
// 是否目标Node有该Node
for _, node := range aDes.Children {
if node.Equal(aSrc) {
lNode = node
}
}
// 如果:无该Node直接添加完成所有工作
// 或者:遍历添加所有没有的新Node
if lNode == nil {
aDes.Children = append(aDes.Children, aSrc)
return
} else {
if lNode.Type == RegexpNode {
}
if aSrc.Route != nil {
if lNode.Route == nil {
lNode.Route = aSrc.Route
} else {
// 叠加合并Controller
lNode.Route.CombineController(aSrc.Route)
}
}
// 合并子节点
for _, _node := range aSrc.Children {
self.conbine(lNode, _node)
}
}
}
// conbine 2 tree together
func (self *TTree) Conbine(aTree *TTree) *TTree {
for method, snode := range aTree.Root {
// 如果主树没有该方法叉则直接移植
if _, has := self.Root[method]; !has {
self.Root[method] = snode
} else {
// 采用逐个添加
for _, node := range self.Root[method].Children {
self.conbine(node, snode)
}
}
}
return self
}
// add node nodes[i] to parent node p
func (self *TNode) addnode(aParent *TNode, aNodes []*TNode, i int, aIsHook bool) *TNode {
if len(aParent.Children) == 0 {
aParent.Children = make([]*TNode, 0)
}
// 如果:找到[已经注册]的分支节点则从该节继续[查找/添加]下一个节点
for _, n := range aParent.Children {
if n.Equal(aNodes[i]) {
// 如果:插入的节点层级已经到末尾,则为该节点注册路由
if i == len(aNodes)-1 {
// 原始路由会被替换
if aIsHook {
n.Route.CombineController(aNodes[i].Route)
} else {
n.Route = aNodes[i].Route
}
}
return n
}
}
// 如果:该节点没有对应分支则插入同级的aNodes为新的分支
aParent.Children = append(aParent.Children, aNodes[i])
sort.Sort(aParent.Children)
return aNodes[i]
}
// add nodes to trees
func (self *TTree) addnodes(aMethod string, aNodes []*TNode, aIsHook bool) {
//fmt.Println("self.Root", self.Root)
// 获得对应方法[POST,GET...]
cn := self.Root[aMethod]
if cn == nil {
// 初始化Root node
cn = &TNode{
Children: TSubNodes{},
}
self.Root[aMethod] = cn
}
var p *TNode = cn // 复制方法对应的Root
// 层级插入Nodes的Node到Root
for idx, _ := range aNodes {
p = cn.addnode(p, aNodes, idx, aIsHook)
}
}
func printNode(i int, node *TNode) {
for _, c := range node.Children {
for j := 0; j < i; j++ { // 空格距离ss
fmt.Print(" ")
}
if i > 1 {
fmt.Print("┗", " ")
}
fmt.Printf(`%s<lv:%d,%v>`, c.Text, c.Level, c.ContentType)
if c.Route != nil {
fmt.Print("<*>")
}
//if !reflect.DeepEqual(c.Route, TRoute{}) {
if c.Route != nil {
//fmt.Print(" ", c.Route.HandleType.String())
//fmt.Printf(" %p", c.handle.method.Interface())
}
fmt.Println()
printNode(i+1, c)
}
}
func (self *TTree) PrintTrees() {
for method, node := range self.Root {
if len(node.Children) > 0 {
fmt.Println(method)
printNode(1, node)
fmt.Println()
}
}
}
func (self *TNode) Equal(o *TNode) bool {
if self.Type != o.Type || self.Text != o.Text {
return false
}
return true
}
| conditional_block | ||
builder.py | # -*- coding: utf-8 -*-
"""
Convenience IR builder.
"""
from __future__ import print_function, division, absolute_import
from contextlib import contextmanager
from pykit import error
from pykit import types, config
from pykit.ir import Value, Op, Block, Const, Undef, ops, findop, FuncArg
from pykit.ir.verification import op_verifier
from pykit.utils import flatten
def make_arg(arg):
"""Return the virtual register or the result"""
return arg.result if isinstance(arg, (Op, Block)) else arg
class OpBuilder(object):
"""
I know how to build Operations.
"""
def _op(op):
"""Helper to create Builder methods"""
def _process(self, ty, args=None, result=None, **metadata):
if args is None:
args = []
assert ty is not None
assert isinstance(args, list), args
assert not any(arg is None for arg in flatten(args)), args
result = Op(op, ty, args, result)
if metadata:
result.add_metadata(metadata)
self._insert_op(result)
return result
def _process_void(self, *args, **kwds):
result = kwds.pop('result', None)
op = _process(self, types.Void, list(args), result)
if kwds:
op.add_metadata(kwds)
return op
if ops.is_void(op):
build_op = _process_void
else:
build_op = _process
if config.op_verify:
build_op = op_verifier(build_op)
return build_op
def _insert_op(self, op):
"""Implement in subclass that emits Operations"""
_const = lambda val: Const(val, types.Void)
# __________________________________________________________________
# IR constructors
# Generated by pykit.utils._generate
Sin = _const(ops.Sin)
Asin = _const(ops.Asin)
Sinh = _const(ops.Sinh)
Asinh = _const(ops.Asinh)
Cos = _const(ops.Cos)
Acos = _const(ops.Acos)
Cosh = _const(ops.Cosh)
Acosh = _const(ops.Acosh)
Tan = _const(ops.Tan)
Atan = _const(ops.Atan)
Atan2 = _const(ops.Atan2)
Tanh = _const(ops.Tanh)
Atanh = _const(ops.Atanh)
Log = _const(ops.Log)
Log2 = _const(ops.Log2)
Log10 = _const(ops.Log10)
Log1p = _const(ops.Log1p)
Exp = _const(ops.Exp)
Exp2 = _const(ops.Exp2)
Expm1 = _const(ops.Expm1)
Floor = _const(ops.Floor)
Ceil = _const(ops.Ceil)
Abs = _const(ops.Abs)
Erfc = _const(ops.Erfc)
Rint = _const(ops.Rint)
Pow = _const(ops.Pow)
Round = _const(ops.Round)
alloca = _op(ops.alloca)
load = _op(ops.load)
store = _op(ops.store)
map = _op(ops.map)
reduce = _op(ops.reduce)
filter = _op(ops.filter)
scan = _op(ops.scan)
zip = _op(ops.zip)
allpairs = _op(ops.allpairs)
flatten = _op(ops.flatten)
print = _op(ops.print)
concat = _op(ops.concat)
length = _op(ops.length)
contains = _op(ops.contains)
list_append = _op(ops.list_append)
list_pop = _op(ops.list_pop)
set_add = _op(ops.set_add)
set_remove = _op(ops.set_remove)
dict_add = _op(ops.dict_add)
dict_remove = _op(ops.dict_remove)
dict_keys = _op(ops.dict_keys)
dict_values = _op(ops.dict_values)
dict_items = _op(ops.dict_items)
box = _op(ops.box)
unbox = _op(ops.unbox)
convert = _op(ops.convert)
new_list = _op(ops.new_list)
new_tuple = _op(ops.new_tuple)
new_dict = _op(ops.new_dict)
new_set = _op(ops.new_set)
new_struct = _op(ops.new_struct)
new_data = _op(ops.new_data)
new_exc = _op(ops.new_exc)
phi = _op(ops.phi)
exc_setup = _op(ops.exc_setup)
exc_catch = _op(ops.exc_catch)
jump = _op(ops.jump)
cbranch = _op(ops.cbranch)
exc_throw = _op(ops.exc_throw)
ret = _op(ops.ret)
function = _op(ops.function)
call = _op(ops.call)
call_math = _op(ops.call_math)
ptradd = _op(ops.ptradd)
ptrload = _op(ops.ptrload)
ptrstore = _op(ops.ptrstore)
ptrcast = _op(ops.ptrcast)
ptr_isnull = _op(ops.ptr_isnull)
getfield = _op(ops.getfield)
setfield = _op(ops.setfield)
getindex = _op(ops.getindex)
setindex = _op(ops.setindex)
getslice = _op(ops.getslice)
setslice = _op(ops.setslice)
slice = _op(ops.slice)
add = _op(ops.add)
sub = _op(ops.sub)
mul = _op(ops.mul)
div = _op(ops.div)
mod = _op(ops.mod)
lshift = _op(ops.lshift)
rshift = _op(ops.rshift)
bitand = _op(ops.bitand)
bitor = _op(ops.bitor)
bitxor = _op(ops.bitxor)
invert = _op(ops.invert)
not_ = _op(ops.not_)
uadd = _op(ops.uadd)
usub = _op(ops.usub)
eq = _op(ops.eq)
noteq = _op(ops.noteq)
lt = _op(ops.lt)
lte = _op(ops.lte)
gt = _op(ops.gt)
gte = _op(ops.gte)
is_ = _op(ops.is_)
threadpool_start = _op(ops.threadpool_start)
threadpool_submit = _op(ops.threadpool_submit)
threadpool_join = _op(ops.threadpool_join)
threadpool_close = _op(ops.threadpool_close)
thread_start = _op(ops.thread_start)
thread_join = _op(ops.thread_join)
check_overflow = _op(ops.check_overflow)
check_error = _op(ops.check_error)
addressof = _op(ops.addressof)
exc_matches = _op(ops.exc_matches)
store_tl_exc = _op(ops.store_tl_exc)
load_tl_exc = _op(ops.load_tl_exc)
gc_gotref = _op(ops.gc_gotref)
gc_giveref = _op(ops.gc_giveref)
gc_incref = _op(ops.gc_incref)
gc_decref = _op(ops.gc_decref)
gc_alloc = _op(ops.gc_alloc)
gc_dealloc = _op(ops.gc_dealloc)
def convert(self, type, args, result=None, buildop=convert):
if type == args[0].type:
return args[0]
return buildop(self, type, args, result)
class Builder(OpBuilder):
"""
I build Operations and emit them into the function.
Also provides convenience operations, such as loops, guards, etc.
"""
def __init__(self, func):
self.func = func
self.module = func.module
self._curblock = None
self._lastop = None
def emit(self, op):
"""
Emit an Operation at the current position.
Sets result register if not set already.
"""
assert self._curblock, "Builder is not positioned!"
if op.result is None:
op.result = self.func.temp()
if self._lastop == 'head' and self._curblock.ops.head:
op.insert_before(self._curblock.ops.head)
elif self._lastop in ('head', 'tail'):
self._curblock.append(op)
else:
op.insert_after(self._lastop)
self._lastop = op
def _insert_op(self, op):
if self._curblock:
self.emit(op)
# __________________________________________________________________
# Positioning
@property
def basic_block(self):
return self._curblock
def position_at_beginning(self, block):
"""Position the builder at the beginning of the given block."""
self._curblock = block
self._lastop = 'head'
def position_at_end(self, block):
"""Position the builder at the end of the given block."""
self._curblock = block
self._lastop = block.tail or 'tail'
def position_before(self, op):
"""Position the builder before the given op."""
if isinstance(op, FuncArg):
raise error.PositioningError(
"Cannot place builder before function argument")
self._curblock = op.block
self._lastop = op._prev
def position_after(self, op):
"""Position the builder after the given op."""
if isinstance(op, FuncArg):
self.position_at_beginning(op.parent.startblock)
else:
self._curblock = op.block
self._lastop = op
@contextmanager
def _position(self, block, position):
curblock, lastop = self._curblock, self._lastop
position(block)
yield
self._curblock, self._lastop = curblock, lastop
at_front = lambda self, b: self._position(b, self.position_at_beginning)
at_end = lambda self, b: self._position(b, self.position_at_end)
# __________________________________________________________________
# Convenience
def gen_call_external(self, fname, args, result=None):
"""Generate call to external function (which must be declared"""
gv = self.module.get_global(fname)
assert gv is not None, "Global %s not declared" % fname
assert gv.type.is_function, gv
assert gv.type.argtypes == [arg.type for arg in args]
op = self.call(gv.type.res, [Const(fname), args])
op.result = result or op.result
return op
def _find_handler(self, exc, exc_setup):
"""
Given an exception and an exception setup clause, generate
exc_matches() checks
"""
catch_sites = [findop(block, 'exc_catch') for block in exc_setup.args]
for exc_catch in catch_sites:
for exc_type in exc_catch.args:
with self.if_(self.exc_matches(types.Bool, [exc, exc_type])):
self.jump(exc_catch.block)
block = self._curblock
self.position_at_end(block)
def gen_error_propagation(self, exc=None):
"""
Propagate an exception. If `exc` is not given it will be loaded
to match in 'except' clauses.
"""
assert self._curblock
block = self._curblock
exc_setup = findop(block.leaders, 'exc_setup')
if exc_setup:
exc = exc or self.load_tl_exc(types.Exception)
self._find_handler(exc, exc_setup)
else:
self.gen_ret_undef()
def gen_ret_undef(self):
"""Generate a return with undefined value"""
type = self.func.type.restype
if type.is_void:
self.ret(None)
else:
self.ret(Undef(type))
def splitblock(self, name=None, terminate=False): |
# Allow splitting only after leaders and before terminator
# TODO: error check
# -------------------------------------------------
# Split
oldblock = self._curblock
newblock = self.func.new_block(name or 'block', after=self._curblock)
op = self._lastop
# Terminate if requested and not done already
if terminate and not ops.is_terminator(op):
op = self.jump(newblock)
# -------------------------------------------------
# Move ops after the split to new block
if op:
if op == 'head':
trailing = list(self._curblock.ops)
elif op == 'tail':
trailing = []
else:
trailing = list(op.block.ops.iter_from(op))[1:]
for op in trailing:
op.unlink()
newblock.extend(trailing)
# -------------------------------------------------
# Patch phis
if terminate:
self._patch_phis(oldblock.ops, oldblock, newblock)
else:
for op in oldblock:
for use in self.func.uses[op]:
if use.opcode == 'phi':
raise error.CompileError(
"Splitting this block would corrupt some phis")
self._patch_phis(newblock.ops, oldblock, newblock)
return oldblock, newblock
def _patch_phis(self, ops, oldblock, newblock):
"""
Patch uses of the instructions in `ops` when a predecessor changes
from `oldblock` to `newblock`
"""
for op in ops:
for use in self.func.uses[op]:
if use.opcode == 'phi':
# Update predecessor blocks
preds, vals = use.args
preds = [newblock if pred == oldblock else pred
for pred in preds]
use.set_args([preds, vals])
def if_(self, cond):
"""with b.if_(b.eq(a, b)): ..."""
old, exit = self.splitblock()
if_block = self.func.new_block("if_block", after=self._curblock)
self.cbranch(cond, if_block, exit)
return self.at_end(if_block)
def ifelse(self, cond):
old, exit = self.splitblock()
if_block = self.func.new_block("if_block", after=self._curblock)
el_block = self.func.new_block("else_block", after=if_block)
self.cbranch(cond, if_block, el_block)
return self.at_end(if_block), self.at_end(el_block), exit
def gen_loop(self, start=None, stop=None, step=None):
"""
Generate a loop given start, stop, step and the index variable type.
The builder's position is set to the end of the body block.
Returns (condition_block, body_block, exit_block).
"""
assert isinstance(stop, Value), "Stop should be a Constant or Operation"
ty = stop.type
start = start or Const(0, ty)
step = step or Const(1, ty)
assert start.type == ty == step.type
with self.at_front(self.func.startblock):
var = self.alloca(types.Pointer(ty), [])
prev, exit = self.splitblock('loop.exit')
cond = self.func.new_block('loop.cond', after=prev)
body = self.func.new_block('loop.body', after=cond)
with self.at_end(prev):
self.store(start, var)
self.jump(cond)
# Condition
with self.at_front(cond):
index = self.load(ty, [var])
self.store(self.add(ty, [index, step]), var)
self.cbranch(self.lt(types.Bool, [index, stop]), body, exit)
with self.at_end(body):
self.jump(cond)
self.position_at_beginning(body)
return cond, body, exit | """Split the current block, returning (old_block, new_block)"""
# -------------------------------------------------
# Sanity check | random_line_split |
builder.py | # -*- coding: utf-8 -*-
"""
Convenience IR builder.
"""
from __future__ import print_function, division, absolute_import
from contextlib import contextmanager
from pykit import error
from pykit import types, config
from pykit.ir import Value, Op, Block, Const, Undef, ops, findop, FuncArg
from pykit.ir.verification import op_verifier
from pykit.utils import flatten
def make_arg(arg):
"""Return the virtual register or the result"""
return arg.result if isinstance(arg, (Op, Block)) else arg
class OpBuilder(object):
"""
I know how to build Operations.
"""
def _op(op):
"""Helper to create Builder methods"""
def _process(self, ty, args=None, result=None, **metadata):
if args is None:
args = []
assert ty is not None
assert isinstance(args, list), args
assert not any(arg is None for arg in flatten(args)), args
result = Op(op, ty, args, result)
if metadata:
|
self._insert_op(result)
return result
def _process_void(self, *args, **kwds):
result = kwds.pop('result', None)
op = _process(self, types.Void, list(args), result)
if kwds:
op.add_metadata(kwds)
return op
if ops.is_void(op):
build_op = _process_void
else:
build_op = _process
if config.op_verify:
build_op = op_verifier(build_op)
return build_op
def _insert_op(self, op):
"""Implement in subclass that emits Operations"""
_const = lambda val: Const(val, types.Void)
# __________________________________________________________________
# IR constructors
# Generated by pykit.utils._generate
Sin = _const(ops.Sin)
Asin = _const(ops.Asin)
Sinh = _const(ops.Sinh)
Asinh = _const(ops.Asinh)
Cos = _const(ops.Cos)
Acos = _const(ops.Acos)
Cosh = _const(ops.Cosh)
Acosh = _const(ops.Acosh)
Tan = _const(ops.Tan)
Atan = _const(ops.Atan)
Atan2 = _const(ops.Atan2)
Tanh = _const(ops.Tanh)
Atanh = _const(ops.Atanh)
Log = _const(ops.Log)
Log2 = _const(ops.Log2)
Log10 = _const(ops.Log10)
Log1p = _const(ops.Log1p)
Exp = _const(ops.Exp)
Exp2 = _const(ops.Exp2)
Expm1 = _const(ops.Expm1)
Floor = _const(ops.Floor)
Ceil = _const(ops.Ceil)
Abs = _const(ops.Abs)
Erfc = _const(ops.Erfc)
Rint = _const(ops.Rint)
Pow = _const(ops.Pow)
Round = _const(ops.Round)
alloca = _op(ops.alloca)
load = _op(ops.load)
store = _op(ops.store)
map = _op(ops.map)
reduce = _op(ops.reduce)
filter = _op(ops.filter)
scan = _op(ops.scan)
zip = _op(ops.zip)
allpairs = _op(ops.allpairs)
flatten = _op(ops.flatten)
print = _op(ops.print)
concat = _op(ops.concat)
length = _op(ops.length)
contains = _op(ops.contains)
list_append = _op(ops.list_append)
list_pop = _op(ops.list_pop)
set_add = _op(ops.set_add)
set_remove = _op(ops.set_remove)
dict_add = _op(ops.dict_add)
dict_remove = _op(ops.dict_remove)
dict_keys = _op(ops.dict_keys)
dict_values = _op(ops.dict_values)
dict_items = _op(ops.dict_items)
box = _op(ops.box)
unbox = _op(ops.unbox)
convert = _op(ops.convert)
new_list = _op(ops.new_list)
new_tuple = _op(ops.new_tuple)
new_dict = _op(ops.new_dict)
new_set = _op(ops.new_set)
new_struct = _op(ops.new_struct)
new_data = _op(ops.new_data)
new_exc = _op(ops.new_exc)
phi = _op(ops.phi)
exc_setup = _op(ops.exc_setup)
exc_catch = _op(ops.exc_catch)
jump = _op(ops.jump)
cbranch = _op(ops.cbranch)
exc_throw = _op(ops.exc_throw)
ret = _op(ops.ret)
function = _op(ops.function)
call = _op(ops.call)
call_math = _op(ops.call_math)
ptradd = _op(ops.ptradd)
ptrload = _op(ops.ptrload)
ptrstore = _op(ops.ptrstore)
ptrcast = _op(ops.ptrcast)
ptr_isnull = _op(ops.ptr_isnull)
getfield = _op(ops.getfield)
setfield = _op(ops.setfield)
getindex = _op(ops.getindex)
setindex = _op(ops.setindex)
getslice = _op(ops.getslice)
setslice = _op(ops.setslice)
slice = _op(ops.slice)
add = _op(ops.add)
sub = _op(ops.sub)
mul = _op(ops.mul)
div = _op(ops.div)
mod = _op(ops.mod)
lshift = _op(ops.lshift)
rshift = _op(ops.rshift)
bitand = _op(ops.bitand)
bitor = _op(ops.bitor)
bitxor = _op(ops.bitxor)
invert = _op(ops.invert)
not_ = _op(ops.not_)
uadd = _op(ops.uadd)
usub = _op(ops.usub)
eq = _op(ops.eq)
noteq = _op(ops.noteq)
lt = _op(ops.lt)
lte = _op(ops.lte)
gt = _op(ops.gt)
gte = _op(ops.gte)
is_ = _op(ops.is_)
threadpool_start = _op(ops.threadpool_start)
threadpool_submit = _op(ops.threadpool_submit)
threadpool_join = _op(ops.threadpool_join)
threadpool_close = _op(ops.threadpool_close)
thread_start = _op(ops.thread_start)
thread_join = _op(ops.thread_join)
check_overflow = _op(ops.check_overflow)
check_error = _op(ops.check_error)
addressof = _op(ops.addressof)
exc_matches = _op(ops.exc_matches)
store_tl_exc = _op(ops.store_tl_exc)
load_tl_exc = _op(ops.load_tl_exc)
gc_gotref = _op(ops.gc_gotref)
gc_giveref = _op(ops.gc_giveref)
gc_incref = _op(ops.gc_incref)
gc_decref = _op(ops.gc_decref)
gc_alloc = _op(ops.gc_alloc)
gc_dealloc = _op(ops.gc_dealloc)
def convert(self, type, args, result=None, buildop=convert):
if type == args[0].type:
return args[0]
return buildop(self, type, args, result)
class Builder(OpBuilder):
"""
I build Operations and emit them into the function.
Also provides convenience operations, such as loops, guards, etc.
"""
def __init__(self, func):
self.func = func
self.module = func.module
self._curblock = None
self._lastop = None
def emit(self, op):
"""
Emit an Operation at the current position.
Sets result register if not set already.
"""
assert self._curblock, "Builder is not positioned!"
if op.result is None:
op.result = self.func.temp()
if self._lastop == 'head' and self._curblock.ops.head:
op.insert_before(self._curblock.ops.head)
elif self._lastop in ('head', 'tail'):
self._curblock.append(op)
else:
op.insert_after(self._lastop)
self._lastop = op
def _insert_op(self, op):
if self._curblock:
self.emit(op)
# __________________________________________________________________
# Positioning
@property
def basic_block(self):
return self._curblock
def position_at_beginning(self, block):
"""Position the builder at the beginning of the given block."""
self._curblock = block
self._lastop = 'head'
def position_at_end(self, block):
"""Position the builder at the end of the given block."""
self._curblock = block
self._lastop = block.tail or 'tail'
def position_before(self, op):
"""Position the builder before the given op."""
if isinstance(op, FuncArg):
raise error.PositioningError(
"Cannot place builder before function argument")
self._curblock = op.block
self._lastop = op._prev
def position_after(self, op):
"""Position the builder after the given op."""
if isinstance(op, FuncArg):
self.position_at_beginning(op.parent.startblock)
else:
self._curblock = op.block
self._lastop = op
@contextmanager
def _position(self, block, position):
curblock, lastop = self._curblock, self._lastop
position(block)
yield
self._curblock, self._lastop = curblock, lastop
at_front = lambda self, b: self._position(b, self.position_at_beginning)
at_end = lambda self, b: self._position(b, self.position_at_end)
# __________________________________________________________________
# Convenience
def gen_call_external(self, fname, args, result=None):
"""Generate call to external function (which must be declared"""
gv = self.module.get_global(fname)
assert gv is not None, "Global %s not declared" % fname
assert gv.type.is_function, gv
assert gv.type.argtypes == [arg.type for arg in args]
op = self.call(gv.type.res, [Const(fname), args])
op.result = result or op.result
return op
def _find_handler(self, exc, exc_setup):
"""
Given an exception and an exception setup clause, generate
exc_matches() checks
"""
catch_sites = [findop(block, 'exc_catch') for block in exc_setup.args]
for exc_catch in catch_sites:
for exc_type in exc_catch.args:
with self.if_(self.exc_matches(types.Bool, [exc, exc_type])):
self.jump(exc_catch.block)
block = self._curblock
self.position_at_end(block)
def gen_error_propagation(self, exc=None):
"""
Propagate an exception. If `exc` is not given it will be loaded
to match in 'except' clauses.
"""
assert self._curblock
block = self._curblock
exc_setup = findop(block.leaders, 'exc_setup')
if exc_setup:
exc = exc or self.load_tl_exc(types.Exception)
self._find_handler(exc, exc_setup)
else:
self.gen_ret_undef()
def gen_ret_undef(self):
"""Generate a return with undefined value"""
type = self.func.type.restype
if type.is_void:
self.ret(None)
else:
self.ret(Undef(type))
def splitblock(self, name=None, terminate=False):
"""Split the current block, returning (old_block, new_block)"""
# -------------------------------------------------
# Sanity check
# Allow splitting only after leaders and before terminator
# TODO: error check
# -------------------------------------------------
# Split
oldblock = self._curblock
newblock = self.func.new_block(name or 'block', after=self._curblock)
op = self._lastop
# Terminate if requested and not done already
if terminate and not ops.is_terminator(op):
op = self.jump(newblock)
# -------------------------------------------------
# Move ops after the split to new block
if op:
if op == 'head':
trailing = list(self._curblock.ops)
elif op == 'tail':
trailing = []
else:
trailing = list(op.block.ops.iter_from(op))[1:]
for op in trailing:
op.unlink()
newblock.extend(trailing)
# -------------------------------------------------
# Patch phis
if terminate:
self._patch_phis(oldblock.ops, oldblock, newblock)
else:
for op in oldblock:
for use in self.func.uses[op]:
if use.opcode == 'phi':
raise error.CompileError(
"Splitting this block would corrupt some phis")
self._patch_phis(newblock.ops, oldblock, newblock)
return oldblock, newblock
def _patch_phis(self, ops, oldblock, newblock):
"""
Patch uses of the instructions in `ops` when a predecessor changes
from `oldblock` to `newblock`
"""
for op in ops:
for use in self.func.uses[op]:
if use.opcode == 'phi':
# Update predecessor blocks
preds, vals = use.args
preds = [newblock if pred == oldblock else pred
for pred in preds]
use.set_args([preds, vals])
def if_(self, cond):
"""with b.if_(b.eq(a, b)): ..."""
old, exit = self.splitblock()
if_block = self.func.new_block("if_block", after=self._curblock)
self.cbranch(cond, if_block, exit)
return self.at_end(if_block)
def ifelse(self, cond):
old, exit = self.splitblock()
if_block = self.func.new_block("if_block", after=self._curblock)
el_block = self.func.new_block("else_block", after=if_block)
self.cbranch(cond, if_block, el_block)
return self.at_end(if_block), self.at_end(el_block), exit
def gen_loop(self, start=None, stop=None, step=None):
"""
Generate a loop given start, stop, step and the index variable type.
The builder's position is set to the end of the body block.
Returns (condition_block, body_block, exit_block).
"""
assert isinstance(stop, Value), "Stop should be a Constant or Operation"
ty = stop.type
start = start or Const(0, ty)
step = step or Const(1, ty)
assert start.type == ty == step.type
with self.at_front(self.func.startblock):
var = self.alloca(types.Pointer(ty), [])
prev, exit = self.splitblock('loop.exit')
cond = self.func.new_block('loop.cond', after=prev)
body = self.func.new_block('loop.body', after=cond)
with self.at_end(prev):
self.store(start, var)
self.jump(cond)
# Condition
with self.at_front(cond):
index = self.load(ty, [var])
self.store(self.add(ty, [index, step]), var)
self.cbranch(self.lt(types.Bool, [index, stop]), body, exit)
with self.at_end(body):
self.jump(cond)
self.position_at_beginning(body)
return cond, body, exit
| result.add_metadata(metadata) | conditional_block |
builder.py | # -*- coding: utf-8 -*-
"""
Convenience IR builder.
"""
from __future__ import print_function, division, absolute_import
from contextlib import contextmanager
from pykit import error
from pykit import types, config
from pykit.ir import Value, Op, Block, Const, Undef, ops, findop, FuncArg
from pykit.ir.verification import op_verifier
from pykit.utils import flatten
def make_arg(arg):
"""Return the virtual register or the result"""
return arg.result if isinstance(arg, (Op, Block)) else arg
class OpBuilder(object):
"""
I know how to build Operations.
"""
def _op(op):
"""Helper to create Builder methods"""
def _process(self, ty, args=None, result=None, **metadata):
if args is None:
args = []
assert ty is not None
assert isinstance(args, list), args
assert not any(arg is None for arg in flatten(args)), args
result = Op(op, ty, args, result)
if metadata:
result.add_metadata(metadata)
self._insert_op(result)
return result
def _process_void(self, *args, **kwds):
result = kwds.pop('result', None)
op = _process(self, types.Void, list(args), result)
if kwds:
op.add_metadata(kwds)
return op
if ops.is_void(op):
build_op = _process_void
else:
build_op = _process
if config.op_verify:
build_op = op_verifier(build_op)
return build_op
def _insert_op(self, op):
"""Implement in subclass that emits Operations"""
_const = lambda val: Const(val, types.Void)
# __________________________________________________________________
# IR constructors
# Generated by pykit.utils._generate
Sin = _const(ops.Sin)
Asin = _const(ops.Asin)
Sinh = _const(ops.Sinh)
Asinh = _const(ops.Asinh)
Cos = _const(ops.Cos)
Acos = _const(ops.Acos)
Cosh = _const(ops.Cosh)
Acosh = _const(ops.Acosh)
Tan = _const(ops.Tan)
Atan = _const(ops.Atan)
Atan2 = _const(ops.Atan2)
Tanh = _const(ops.Tanh)
Atanh = _const(ops.Atanh)
Log = _const(ops.Log)
Log2 = _const(ops.Log2)
Log10 = _const(ops.Log10)
Log1p = _const(ops.Log1p)
Exp = _const(ops.Exp)
Exp2 = _const(ops.Exp2)
Expm1 = _const(ops.Expm1)
Floor = _const(ops.Floor)
Ceil = _const(ops.Ceil)
Abs = _const(ops.Abs)
Erfc = _const(ops.Erfc)
Rint = _const(ops.Rint)
Pow = _const(ops.Pow)
Round = _const(ops.Round)
alloca = _op(ops.alloca)
load = _op(ops.load)
store = _op(ops.store)
map = _op(ops.map)
reduce = _op(ops.reduce)
filter = _op(ops.filter)
scan = _op(ops.scan)
zip = _op(ops.zip)
allpairs = _op(ops.allpairs)
flatten = _op(ops.flatten)
print = _op(ops.print)
concat = _op(ops.concat)
length = _op(ops.length)
contains = _op(ops.contains)
list_append = _op(ops.list_append)
list_pop = _op(ops.list_pop)
set_add = _op(ops.set_add)
set_remove = _op(ops.set_remove)
dict_add = _op(ops.dict_add)
dict_remove = _op(ops.dict_remove)
dict_keys = _op(ops.dict_keys)
dict_values = _op(ops.dict_values)
dict_items = _op(ops.dict_items)
box = _op(ops.box)
unbox = _op(ops.unbox)
convert = _op(ops.convert)
new_list = _op(ops.new_list)
new_tuple = _op(ops.new_tuple)
new_dict = _op(ops.new_dict)
new_set = _op(ops.new_set)
new_struct = _op(ops.new_struct)
new_data = _op(ops.new_data)
new_exc = _op(ops.new_exc)
phi = _op(ops.phi)
exc_setup = _op(ops.exc_setup)
exc_catch = _op(ops.exc_catch)
jump = _op(ops.jump)
cbranch = _op(ops.cbranch)
exc_throw = _op(ops.exc_throw)
ret = _op(ops.ret)
function = _op(ops.function)
call = _op(ops.call)
call_math = _op(ops.call_math)
ptradd = _op(ops.ptradd)
ptrload = _op(ops.ptrload)
ptrstore = _op(ops.ptrstore)
ptrcast = _op(ops.ptrcast)
ptr_isnull = _op(ops.ptr_isnull)
getfield = _op(ops.getfield)
setfield = _op(ops.setfield)
getindex = _op(ops.getindex)
setindex = _op(ops.setindex)
getslice = _op(ops.getslice)
setslice = _op(ops.setslice)
slice = _op(ops.slice)
add = _op(ops.add)
sub = _op(ops.sub)
mul = _op(ops.mul)
div = _op(ops.div)
mod = _op(ops.mod)
lshift = _op(ops.lshift)
rshift = _op(ops.rshift)
bitand = _op(ops.bitand)
bitor = _op(ops.bitor)
bitxor = _op(ops.bitxor)
invert = _op(ops.invert)
not_ = _op(ops.not_)
uadd = _op(ops.uadd)
usub = _op(ops.usub)
eq = _op(ops.eq)
noteq = _op(ops.noteq)
lt = _op(ops.lt)
lte = _op(ops.lte)
gt = _op(ops.gt)
gte = _op(ops.gte)
is_ = _op(ops.is_)
threadpool_start = _op(ops.threadpool_start)
threadpool_submit = _op(ops.threadpool_submit)
threadpool_join = _op(ops.threadpool_join)
threadpool_close = _op(ops.threadpool_close)
thread_start = _op(ops.thread_start)
thread_join = _op(ops.thread_join)
check_overflow = _op(ops.check_overflow)
check_error = _op(ops.check_error)
addressof = _op(ops.addressof)
exc_matches = _op(ops.exc_matches)
store_tl_exc = _op(ops.store_tl_exc)
load_tl_exc = _op(ops.load_tl_exc)
gc_gotref = _op(ops.gc_gotref)
gc_giveref = _op(ops.gc_giveref)
gc_incref = _op(ops.gc_incref)
gc_decref = _op(ops.gc_decref)
gc_alloc = _op(ops.gc_alloc)
gc_dealloc = _op(ops.gc_dealloc)
def convert(self, type, args, result=None, buildop=convert):
|
class Builder(OpBuilder):
"""
I build Operations and emit them into the function.
Also provides convenience operations, such as loops, guards, etc.
"""
def __init__(self, func):
self.func = func
self.module = func.module
self._curblock = None
self._lastop = None
def emit(self, op):
"""
Emit an Operation at the current position.
Sets result register if not set already.
"""
assert self._curblock, "Builder is not positioned!"
if op.result is None:
op.result = self.func.temp()
if self._lastop == 'head' and self._curblock.ops.head:
op.insert_before(self._curblock.ops.head)
elif self._lastop in ('head', 'tail'):
self._curblock.append(op)
else:
op.insert_after(self._lastop)
self._lastop = op
def _insert_op(self, op):
if self._curblock:
self.emit(op)
# __________________________________________________________________
# Positioning
@property
def basic_block(self):
return self._curblock
def position_at_beginning(self, block):
"""Position the builder at the beginning of the given block."""
self._curblock = block
self._lastop = 'head'
def position_at_end(self, block):
"""Position the builder at the end of the given block."""
self._curblock = block
self._lastop = block.tail or 'tail'
def position_before(self, op):
"""Position the builder before the given op."""
if isinstance(op, FuncArg):
raise error.PositioningError(
"Cannot place builder before function argument")
self._curblock = op.block
self._lastop = op._prev
def position_after(self, op):
"""Position the builder after the given op."""
if isinstance(op, FuncArg):
self.position_at_beginning(op.parent.startblock)
else:
self._curblock = op.block
self._lastop = op
@contextmanager
def _position(self, block, position):
curblock, lastop = self._curblock, self._lastop
position(block)
yield
self._curblock, self._lastop = curblock, lastop
at_front = lambda self, b: self._position(b, self.position_at_beginning)
at_end = lambda self, b: self._position(b, self.position_at_end)
# __________________________________________________________________
# Convenience
def gen_call_external(self, fname, args, result=None):
"""Generate call to external function (which must be declared"""
gv = self.module.get_global(fname)
assert gv is not None, "Global %s not declared" % fname
assert gv.type.is_function, gv
assert gv.type.argtypes == [arg.type for arg in args]
op = self.call(gv.type.res, [Const(fname), args])
op.result = result or op.result
return op
def _find_handler(self, exc, exc_setup):
"""
Given an exception and an exception setup clause, generate
exc_matches() checks
"""
catch_sites = [findop(block, 'exc_catch') for block in exc_setup.args]
for exc_catch in catch_sites:
for exc_type in exc_catch.args:
with self.if_(self.exc_matches(types.Bool, [exc, exc_type])):
self.jump(exc_catch.block)
block = self._curblock
self.position_at_end(block)
def gen_error_propagation(self, exc=None):
"""
Propagate an exception. If `exc` is not given it will be loaded
to match in 'except' clauses.
"""
assert self._curblock
block = self._curblock
exc_setup = findop(block.leaders, 'exc_setup')
if exc_setup:
exc = exc or self.load_tl_exc(types.Exception)
self._find_handler(exc, exc_setup)
else:
self.gen_ret_undef()
def gen_ret_undef(self):
"""Generate a return with undefined value"""
type = self.func.type.restype
if type.is_void:
self.ret(None)
else:
self.ret(Undef(type))
def splitblock(self, name=None, terminate=False):
"""Split the current block, returning (old_block, new_block)"""
# -------------------------------------------------
# Sanity check
# Allow splitting only after leaders and before terminator
# TODO: error check
# -------------------------------------------------
# Split
oldblock = self._curblock
newblock = self.func.new_block(name or 'block', after=self._curblock)
op = self._lastop
# Terminate if requested and not done already
if terminate and not ops.is_terminator(op):
op = self.jump(newblock)
# -------------------------------------------------
# Move ops after the split to new block
if op:
if op == 'head':
trailing = list(self._curblock.ops)
elif op == 'tail':
trailing = []
else:
trailing = list(op.block.ops.iter_from(op))[1:]
for op in trailing:
op.unlink()
newblock.extend(trailing)
# -------------------------------------------------
# Patch phis
if terminate:
self._patch_phis(oldblock.ops, oldblock, newblock)
else:
for op in oldblock:
for use in self.func.uses[op]:
if use.opcode == 'phi':
raise error.CompileError(
"Splitting this block would corrupt some phis")
self._patch_phis(newblock.ops, oldblock, newblock)
return oldblock, newblock
def _patch_phis(self, ops, oldblock, newblock):
"""
Patch uses of the instructions in `ops` when a predecessor changes
from `oldblock` to `newblock`
"""
for op in ops:
for use in self.func.uses[op]:
if use.opcode == 'phi':
# Update predecessor blocks
preds, vals = use.args
preds = [newblock if pred == oldblock else pred
for pred in preds]
use.set_args([preds, vals])
def if_(self, cond):
"""with b.if_(b.eq(a, b)): ..."""
old, exit = self.splitblock()
if_block = self.func.new_block("if_block", after=self._curblock)
self.cbranch(cond, if_block, exit)
return self.at_end(if_block)
def ifelse(self, cond):
old, exit = self.splitblock()
if_block = self.func.new_block("if_block", after=self._curblock)
el_block = self.func.new_block("else_block", after=if_block)
self.cbranch(cond, if_block, el_block)
return self.at_end(if_block), self.at_end(el_block), exit
def gen_loop(self, start=None, stop=None, step=None):
"""
Generate a loop given start, stop, step and the index variable type.
The builder's position is set to the end of the body block.
Returns (condition_block, body_block, exit_block).
"""
assert isinstance(stop, Value), "Stop should be a Constant or Operation"
ty = stop.type
start = start or Const(0, ty)
step = step or Const(1, ty)
assert start.type == ty == step.type
with self.at_front(self.func.startblock):
var = self.alloca(types.Pointer(ty), [])
prev, exit = self.splitblock('loop.exit')
cond = self.func.new_block('loop.cond', after=prev)
body = self.func.new_block('loop.body', after=cond)
with self.at_end(prev):
self.store(start, var)
self.jump(cond)
# Condition
with self.at_front(cond):
index = self.load(ty, [var])
self.store(self.add(ty, [index, step]), var)
self.cbranch(self.lt(types.Bool, [index, stop]), body, exit)
with self.at_end(body):
self.jump(cond)
self.position_at_beginning(body)
return cond, body, exit
| if type == args[0].type:
return args[0]
return buildop(self, type, args, result) | identifier_body |
builder.py | # -*- coding: utf-8 -*-
"""
Convenience IR builder.
"""
from __future__ import print_function, division, absolute_import
from contextlib import contextmanager
from pykit import error
from pykit import types, config
from pykit.ir import Value, Op, Block, Const, Undef, ops, findop, FuncArg
from pykit.ir.verification import op_verifier
from pykit.utils import flatten
def make_arg(arg):
"""Return the virtual register or the result"""
return arg.result if isinstance(arg, (Op, Block)) else arg
class OpBuilder(object):
"""
I know how to build Operations.
"""
def _op(op):
"""Helper to create Builder methods"""
def _process(self, ty, args=None, result=None, **metadata):
if args is None:
args = []
assert ty is not None
assert isinstance(args, list), args
assert not any(arg is None for arg in flatten(args)), args
result = Op(op, ty, args, result)
if metadata:
result.add_metadata(metadata)
self._insert_op(result)
return result
def _process_void(self, *args, **kwds):
result = kwds.pop('result', None)
op = _process(self, types.Void, list(args), result)
if kwds:
op.add_metadata(kwds)
return op
if ops.is_void(op):
build_op = _process_void
else:
build_op = _process
if config.op_verify:
build_op = op_verifier(build_op)
return build_op
def _insert_op(self, op):
"""Implement in subclass that emits Operations"""
_const = lambda val: Const(val, types.Void)
# __________________________________________________________________
# IR constructors
# Generated by pykit.utils._generate
Sin = _const(ops.Sin)
Asin = _const(ops.Asin)
Sinh = _const(ops.Sinh)
Asinh = _const(ops.Asinh)
Cos = _const(ops.Cos)
Acos = _const(ops.Acos)
Cosh = _const(ops.Cosh)
Acosh = _const(ops.Acosh)
Tan = _const(ops.Tan)
Atan = _const(ops.Atan)
Atan2 = _const(ops.Atan2)
Tanh = _const(ops.Tanh)
Atanh = _const(ops.Atanh)
Log = _const(ops.Log)
Log2 = _const(ops.Log2)
Log10 = _const(ops.Log10)
Log1p = _const(ops.Log1p)
Exp = _const(ops.Exp)
Exp2 = _const(ops.Exp2)
Expm1 = _const(ops.Expm1)
Floor = _const(ops.Floor)
Ceil = _const(ops.Ceil)
Abs = _const(ops.Abs)
Erfc = _const(ops.Erfc)
Rint = _const(ops.Rint)
Pow = _const(ops.Pow)
Round = _const(ops.Round)
alloca = _op(ops.alloca)
load = _op(ops.load)
store = _op(ops.store)
map = _op(ops.map)
reduce = _op(ops.reduce)
filter = _op(ops.filter)
scan = _op(ops.scan)
zip = _op(ops.zip)
allpairs = _op(ops.allpairs)
flatten = _op(ops.flatten)
print = _op(ops.print)
concat = _op(ops.concat)
length = _op(ops.length)
contains = _op(ops.contains)
list_append = _op(ops.list_append)
list_pop = _op(ops.list_pop)
set_add = _op(ops.set_add)
set_remove = _op(ops.set_remove)
dict_add = _op(ops.dict_add)
dict_remove = _op(ops.dict_remove)
dict_keys = _op(ops.dict_keys)
dict_values = _op(ops.dict_values)
dict_items = _op(ops.dict_items)
box = _op(ops.box)
unbox = _op(ops.unbox)
convert = _op(ops.convert)
new_list = _op(ops.new_list)
new_tuple = _op(ops.new_tuple)
new_dict = _op(ops.new_dict)
new_set = _op(ops.new_set)
new_struct = _op(ops.new_struct)
new_data = _op(ops.new_data)
new_exc = _op(ops.new_exc)
phi = _op(ops.phi)
exc_setup = _op(ops.exc_setup)
exc_catch = _op(ops.exc_catch)
jump = _op(ops.jump)
cbranch = _op(ops.cbranch)
exc_throw = _op(ops.exc_throw)
ret = _op(ops.ret)
function = _op(ops.function)
call = _op(ops.call)
call_math = _op(ops.call_math)
ptradd = _op(ops.ptradd)
ptrload = _op(ops.ptrload)
ptrstore = _op(ops.ptrstore)
ptrcast = _op(ops.ptrcast)
ptr_isnull = _op(ops.ptr_isnull)
getfield = _op(ops.getfield)
setfield = _op(ops.setfield)
getindex = _op(ops.getindex)
setindex = _op(ops.setindex)
getslice = _op(ops.getslice)
setslice = _op(ops.setslice)
slice = _op(ops.slice)
add = _op(ops.add)
sub = _op(ops.sub)
mul = _op(ops.mul)
div = _op(ops.div)
mod = _op(ops.mod)
lshift = _op(ops.lshift)
rshift = _op(ops.rshift)
bitand = _op(ops.bitand)
bitor = _op(ops.bitor)
bitxor = _op(ops.bitxor)
invert = _op(ops.invert)
not_ = _op(ops.not_)
uadd = _op(ops.uadd)
usub = _op(ops.usub)
eq = _op(ops.eq)
noteq = _op(ops.noteq)
lt = _op(ops.lt)
lte = _op(ops.lte)
gt = _op(ops.gt)
gte = _op(ops.gte)
is_ = _op(ops.is_)
threadpool_start = _op(ops.threadpool_start)
threadpool_submit = _op(ops.threadpool_submit)
threadpool_join = _op(ops.threadpool_join)
threadpool_close = _op(ops.threadpool_close)
thread_start = _op(ops.thread_start)
thread_join = _op(ops.thread_join)
check_overflow = _op(ops.check_overflow)
check_error = _op(ops.check_error)
addressof = _op(ops.addressof)
exc_matches = _op(ops.exc_matches)
store_tl_exc = _op(ops.store_tl_exc)
load_tl_exc = _op(ops.load_tl_exc)
gc_gotref = _op(ops.gc_gotref)
gc_giveref = _op(ops.gc_giveref)
gc_incref = _op(ops.gc_incref)
gc_decref = _op(ops.gc_decref)
gc_alloc = _op(ops.gc_alloc)
gc_dealloc = _op(ops.gc_dealloc)
def | (self, type, args, result=None, buildop=convert):
if type == args[0].type:
return args[0]
return buildop(self, type, args, result)
class Builder(OpBuilder):
"""
I build Operations and emit them into the function.
Also provides convenience operations, such as loops, guards, etc.
"""
def __init__(self, func):
self.func = func
self.module = func.module
self._curblock = None
self._lastop = None
def emit(self, op):
"""
Emit an Operation at the current position.
Sets result register if not set already.
"""
assert self._curblock, "Builder is not positioned!"
if op.result is None:
op.result = self.func.temp()
if self._lastop == 'head' and self._curblock.ops.head:
op.insert_before(self._curblock.ops.head)
elif self._lastop in ('head', 'tail'):
self._curblock.append(op)
else:
op.insert_after(self._lastop)
self._lastop = op
def _insert_op(self, op):
if self._curblock:
self.emit(op)
# __________________________________________________________________
# Positioning
@property
def basic_block(self):
return self._curblock
def position_at_beginning(self, block):
"""Position the builder at the beginning of the given block."""
self._curblock = block
self._lastop = 'head'
def position_at_end(self, block):
"""Position the builder at the end of the given block."""
self._curblock = block
self._lastop = block.tail or 'tail'
def position_before(self, op):
"""Position the builder before the given op."""
if isinstance(op, FuncArg):
raise error.PositioningError(
"Cannot place builder before function argument")
self._curblock = op.block
self._lastop = op._prev
def position_after(self, op):
"""Position the builder after the given op."""
if isinstance(op, FuncArg):
self.position_at_beginning(op.parent.startblock)
else:
self._curblock = op.block
self._lastop = op
@contextmanager
def _position(self, block, position):
curblock, lastop = self._curblock, self._lastop
position(block)
yield
self._curblock, self._lastop = curblock, lastop
at_front = lambda self, b: self._position(b, self.position_at_beginning)
at_end = lambda self, b: self._position(b, self.position_at_end)
# __________________________________________________________________
# Convenience
def gen_call_external(self, fname, args, result=None):
"""Generate call to external function (which must be declared"""
gv = self.module.get_global(fname)
assert gv is not None, "Global %s not declared" % fname
assert gv.type.is_function, gv
assert gv.type.argtypes == [arg.type for arg in args]
op = self.call(gv.type.res, [Const(fname), args])
op.result = result or op.result
return op
def _find_handler(self, exc, exc_setup):
"""
Given an exception and an exception setup clause, generate
exc_matches() checks
"""
catch_sites = [findop(block, 'exc_catch') for block in exc_setup.args]
for exc_catch in catch_sites:
for exc_type in exc_catch.args:
with self.if_(self.exc_matches(types.Bool, [exc, exc_type])):
self.jump(exc_catch.block)
block = self._curblock
self.position_at_end(block)
def gen_error_propagation(self, exc=None):
"""
Propagate an exception. If `exc` is not given it will be loaded
to match in 'except' clauses.
"""
assert self._curblock
block = self._curblock
exc_setup = findop(block.leaders, 'exc_setup')
if exc_setup:
exc = exc or self.load_tl_exc(types.Exception)
self._find_handler(exc, exc_setup)
else:
self.gen_ret_undef()
def gen_ret_undef(self):
"""Generate a return with undefined value"""
type = self.func.type.restype
if type.is_void:
self.ret(None)
else:
self.ret(Undef(type))
def splitblock(self, name=None, terminate=False):
"""Split the current block, returning (old_block, new_block)"""
# -------------------------------------------------
# Sanity check
# Allow splitting only after leaders and before terminator
# TODO: error check
# -------------------------------------------------
# Split
oldblock = self._curblock
newblock = self.func.new_block(name or 'block', after=self._curblock)
op = self._lastop
# Terminate if requested and not done already
if terminate and not ops.is_terminator(op):
op = self.jump(newblock)
# -------------------------------------------------
# Move ops after the split to new block
if op:
if op == 'head':
trailing = list(self._curblock.ops)
elif op == 'tail':
trailing = []
else:
trailing = list(op.block.ops.iter_from(op))[1:]
for op in trailing:
op.unlink()
newblock.extend(trailing)
# -------------------------------------------------
# Patch phis
if terminate:
self._patch_phis(oldblock.ops, oldblock, newblock)
else:
for op in oldblock:
for use in self.func.uses[op]:
if use.opcode == 'phi':
raise error.CompileError(
"Splitting this block would corrupt some phis")
self._patch_phis(newblock.ops, oldblock, newblock)
return oldblock, newblock
def _patch_phis(self, ops, oldblock, newblock):
"""
Patch uses of the instructions in `ops` when a predecessor changes
from `oldblock` to `newblock`
"""
for op in ops:
for use in self.func.uses[op]:
if use.opcode == 'phi':
# Update predecessor blocks
preds, vals = use.args
preds = [newblock if pred == oldblock else pred
for pred in preds]
use.set_args([preds, vals])
def if_(self, cond):
"""with b.if_(b.eq(a, b)): ..."""
old, exit = self.splitblock()
if_block = self.func.new_block("if_block", after=self._curblock)
self.cbranch(cond, if_block, exit)
return self.at_end(if_block)
def ifelse(self, cond):
old, exit = self.splitblock()
if_block = self.func.new_block("if_block", after=self._curblock)
el_block = self.func.new_block("else_block", after=if_block)
self.cbranch(cond, if_block, el_block)
return self.at_end(if_block), self.at_end(el_block), exit
def gen_loop(self, start=None, stop=None, step=None):
"""
Generate a loop given start, stop, step and the index variable type.
The builder's position is set to the end of the body block.
Returns (condition_block, body_block, exit_block).
"""
assert isinstance(stop, Value), "Stop should be a Constant or Operation"
ty = stop.type
start = start or Const(0, ty)
step = step or Const(1, ty)
assert start.type == ty == step.type
with self.at_front(self.func.startblock):
var = self.alloca(types.Pointer(ty), [])
prev, exit = self.splitblock('loop.exit')
cond = self.func.new_block('loop.cond', after=prev)
body = self.func.new_block('loop.body', after=cond)
with self.at_end(prev):
self.store(start, var)
self.jump(cond)
# Condition
with self.at_front(cond):
index = self.load(ty, [var])
self.store(self.add(ty, [index, step]), var)
self.cbranch(self.lt(types.Bool, [index, stop]), body, exit)
with self.at_end(body):
self.jump(cond)
self.position_at_beginning(body)
return cond, body, exit
| convert | identifier_name |
gdbstub.rs | use std::io::{self, Read, Write};
use std::ops::{Add, AddAssign};
use std::str;
use std::thread;
use std::time::Duration;
use mio;
use mio::tcp::{TcpListener, TcpStream};
use cpu::BreakReason;
use dbgcore::{self, ActiveCpu::Arm9};
use hwcore::Message;
use msgs;
use utils;
#[derive(Debug, Error)]
pub enum ErrorKind {
Hex(::std::num::ParseIntError),
Io(io::Error),
/// Client should not expect a response
NoResponse,
/// Could not find next element to parse
Parse,
}
pub type Result<T> = ::std::result::Result<T, ErrorKind>;
fn parse_next<T, I: Iterator<Item=T>>(it: &mut I) -> Result<T> {
it.next().ok_or(ErrorKind::Parse.into())
}
fn parse_next_hex<'a, I: Iterator<Item=&'a str>>(it: &mut I) -> Result<u32> {
Ok(utils::from_hex(parse_next(it)?)?)
}
fn cmd_step(ctx: &mut GdbCtx) -> Result<String> {
ctx.dbg.hw().step();
let break_data = BreakData::new(BreakReason::LimitReached, ctx.dbg);
let signal = break_data.to_signal();
*ctx.last_halt = break_data;
Ok(signal)
}
fn cmd_continue(ctx: &mut GdbCtx) -> Result<String> {
ctx.dbg.resume();
Err(ErrorKind::NoResponse)
}
struct BreakData {
reason: BreakReason,
r15: u32,
r13: u32
}
impl BreakData {
fn new(reason: BreakReason, dbg: &mut dbgcore::DbgContext) -> BreakData {
let hw = dbg.hw();
BreakData {
reason: reason,
r15: hw.pause_addr(),
r13: hw.read_reg(13),
}
}
fn to_signal(&self) -> String {
let reason_str = match self.reason {
BreakReason::Breakpoint => format!(";{}:", "swbreak"),
_ => String::new(),
};
format!("T05{:02X}:{:08X};{:02X}:{:08X}{};", 15, self.r15.swap_bytes(),
13, self.r13.swap_bytes(),
reason_str)
}
}
fn handle_gdb_cmd_q(cmd: &str, _ctx: &mut GdbCtx) -> Result<String> {
let mut s = cmd.splitn(2, ':');
let ty = parse_next(&mut s)?;
let mut out = String::new();
match ty {
"fThreadInfo" => out += "m0000000000000001",
"sThreadInfo" => out += "l",
"C" => out += "QC0000000000000001",
"Attached" => out += "1",
"Supported" => {
out += "PacketSize=400;BreakpointCommands+;swbreak+;vContSupported+";
}
_ => warn!("GDB client tried to run unsupported `q` command {}", ty)
}
Ok(out)
}
fn handle_gdb_cmd_v(cmd: &str, ctx: &mut GdbCtx) -> Result<String> {
let mut s = cmd.splitn(2, |c| c == ',' || c == ':' || c == ';');
let ty = parse_next(&mut s)?;
let mut out = String::new();
match ty {
"Cont" => {
let params = parse_next(&mut s)?;
let threads = params.split(';');
for thread in threads {
let mut thread_data = thread.split(':');
let action = parse_next(&mut thread_data)?;
let thread_name = thread_data.next();
if let Some(name) = thread_name {
match (name, utils::from_hex(name)) {
| ("-1", _)
| (_, Ok(0))
| (_, Ok(1)) => {}
| (s, _) => panic!("Attempted to issue command on invalid thread id {}", s)
}
}
match action {
"c" => return cmd_continue(ctx),
"s" => return cmd_step(ctx),
_ => warn!("GDB client tried to run unsupported `vCont` action {}", action)
}
}
}
"Cont?" => {
let supported = ["c", "s"];
out += "vCont";
for ty in supported.iter() {
out += ";";
out += ty;
}
}
_ => warn!("GDB client tried to run unsupported `v` command {}", ty)
}
Ok(out)
}
fn handle_gdb_cmd(cmd: &str, ctx: &mut GdbCtx) -> Result<String> {
let ty = parse_next(&mut cmd.chars())?;
let params = &cmd[1..];
let mut out = String::new();
ctx.dbg.pause();
match ty {
'g' => {
let hw = ctx.dbg.hw();
for reg in 0..15 {
out += &format!("{:08X}", hw.read_reg(reg).swap_bytes());
}
out += &format!("{:08X}", hw.pause_addr().swap_bytes());
for _ in 0..8 {
out += "xxxxxxxxxxxxxxxxxxxxxxxx"; // fX registers (12 bytes each)
}
out += "xxxxxxxx"; // fps register
out += &format!("{:08X}", hw.read_cpsr().swap_bytes());
}
'G' => {
let mut hw = ctx.dbg.hw();
let mut regs = params;
let next_reg = |regstr: &str| -> Result<u32> {
let val = utils::from_hex(®str[..8])?;
Ok(val.swap_bytes())
};
for reg in 0..15 {
hw.write_reg(reg, next_reg(regs)?);
regs = ®s[8..];
}
// register at 15: PC
hw.branch_to(next_reg(regs)?);
regs = ®s[8..];
// Skip 8 fX registers
regs = ®s[8 * 24..];
// Skip fps register
regs = ®s[8..];
// register at 25: CPSR
hw.write_cpsr(next_reg(regs)?);
out += "OK";
}
'H' => {
out += "OK";
}
'm' => {
let mut hw = ctx.dbg.hw();
let mut params = params.split(',');
let addr = parse_next_hex(&mut params)?;
let size = parse_next_hex(&mut params)?;
let mut buf = [0u8];
for b in 0..size {
if let Err(_) = hw.read_mem(addr+b, &mut buf) {
out += "00";
} else {
out += &format!("{:02X}", buf[0]);
}
}
}
'M' => {
let mut hw = ctx.dbg.hw();
let mut params = params.split(|c| c == ',' || c == ':');
let addr = parse_next_hex(&mut params)?;
let size = parse_next_hex(&mut params)?;
let data = parse_next(&mut params)?;
for b in 0..size {
let data_byte_range = 2*(b as usize)..2*((b as usize)+1);
let byte = utils::from_hex(&data[data_byte_range])? as u8;
hw.write_mem(addr+b, &[byte]);
}
out += "OK";
}
'p' => {
let hw = ctx.dbg.hw();
let reg = utils::from_hex(¶ms)? as usize;
let regval = match reg {
0 ..= 14 => hw.read_reg(reg),
15 => hw.pause_addr(),
25 => hw.read_cpsr(),
n => {
warn!("GDB requested bad register value {}", n);
0
}
};
out += &format!("{:08X}", regval.swap_bytes());
}
'q' => {
return handle_gdb_cmd_q(params, ctx);
}
's' => {
return cmd_step(ctx);
}
'c' => {
return cmd_continue(ctx);
}
'v' => {
return handle_gdb_cmd_v(params, ctx);
}
'z' | 'Z' => {
let mut hw = ctx.dbg.hw();
let mut params = params.split(',');
let brk_ty = parse_next(&mut params)?;
let addr = parse_next_hex(&mut params)?;
let _kind = parse_next(&mut params)?;
assert!(brk_ty == "0");
if ty == 'Z' {
hw.set_breakpoint(addr);
} else {
hw.del_breakpoint(addr);
}
out += "OK";
}
'?' => {
out += &ctx.last_halt.to_signal();
}
x => {
warn!("GDB client tried to run unsupported command {}", x);
}
}
Ok(out)
}
#[derive(Clone, Copy)]
struct Checksum(pub u32);
impl Add<u8> for Checksum {
type Output = Checksum;
fn add(self, b: u8) -> Checksum {
Checksum((self.0 + (b as u32)) % 256)
}
}
impl AddAssign<u8> for Checksum {
fn add_assign(&mut self, b: u8) {
self.0 = (*self + b).0;
}
}
enum PacketType {
Command(String),
CtrlC,
AckOk,
AckErr,
EndOfPacket,
Malformed,
}
fn load_packet<I: Iterator<Item = u8>>(it: &mut I) -> PacketType {
let mut it = it.skip_while(|b| *b != 0x03 && *b != b'$' && *b != b'-' && *b != b'+');
match it.next() {
Some(0x3) => return PacketType::CtrlC,
Some(b'$') => {}
Some(b'+') => return PacketType::AckOk,
Some(b'-') => return PacketType::AckErr,
None => return PacketType::EndOfPacket,
_ => return PacketType::Malformed
}
let mut string = String::new();
let mut checksum = Checksum(0);
for b in it.by_ref().take_while(|b| *b != b'#') {
string.push(b as char);
checksum += b;
}
if let (Some(top), Some(bot)) = (it.next(), it.next()) {
let packet_checksum = str::from_utf8(&[top, bot]).ok()
.and_then(|s| utils::from_hex(s).ok());
if Some(checksum.0) == packet_checksum {
return PacketType::Command(string)
}
}
return PacketType::Malformed
}
fn write_gdb_packet(data: &str, stream: &mut TcpStream) -> Result<()> {
let checksum = data.bytes().fold(Checksum(0), |checksum, b| checksum + b);
trace!("Replying with GDB packet: ${}#{:02X}", data, checksum.0);
write!(stream, "${}#{:02X}", data, checksum.0)?;
stream.flush()?;
Ok(())
}
fn handle_gdb_packet(data: &[u8], stream: &mut TcpStream, ctx: &mut GdbCtx) -> Result<()> {
trace!("Recieving GDB packet: {}", str::from_utf8(data).unwrap());
let mut it = data.iter().cloned();
loop {
match load_packet(&mut it) {
PacketType::Command(cmd) => {
stream.write(b"+")?;
stream.flush()?;
match handle_gdb_cmd(&cmd, ctx) {
Ok(out) => write_gdb_packet(&out, stream)?,
Err(e) => {
if let ErrorKind::NoResponse = e {}
else { return Err(e) }
}
}
}
PacketType::CtrlC => {
ctx.dbg.pause();
trace!("Recieved GDB packet with CTRL-C signal!");
}
PacketType::AckOk => {},
PacketType::AckErr => error!("GDB client replied with error packet!"),
PacketType::EndOfPacket => {
return Ok(())
}
PacketType::Malformed => {
trace!("Recieved malformed data {:?}", data);
stream.write(b"-")?;
stream.flush()?;
return Ok(())
}
}
}
}
struct GdbCtx<'a, 'b: 'a> {
dbg: &'a mut dbgcore::DbgContext<'b>,
last_halt: &'a mut BreakData,
}
const TOKEN_LISTENER: mio::Token = mio::Token(1024);
const TOKEN_CLIENT: mio::Token = mio::Token(1025);
pub struct GdbStub {
debugger: dbgcore::DbgCore,
gdb_thread: Option<thread::JoinHandle<msgs::Client<Message>>>
}
impl GdbStub {
pub fn new(msg_client: msgs::Client<Message>, debugger: dbgcore::DbgCore) -> GdbStub {
let mut stub = GdbStub {
debugger: debugger,
gdb_thread: None
};
stub.start(msg_client);
stub
}
pub fn start(&mut self, msg_client: msgs::Client<Message>) {
let mut debugger = self.debugger.clone();
self.gdb_thread = Some(thread::Builder::new().name("GDBStub".to_owned()).spawn(move || {
use mio::Events;
let poll = mio::Poll::new()
.expect("Could not create mio polling instance!");
let listener = TcpListener::bind(&"127.0.0.1:4567".parse().unwrap())
.expect("Could not bind TcpListener to port!");
poll.register(&listener, TOKEN_LISTENER, mio::Ready::readable(), mio::PollOpt::edge())
.expect("Could not register TcpListener to mio!");
| poll: poll,
socket: None,
};
let mut events = Events::with_capacity(1024);
info!("Starting GDB stub on port 4567...");
let mut last_halt = BreakData::new(BreakReason::Trapped, &mut debugger.ctx(Arm9));
't: loop {
connection.poll.poll(&mut events, Some(Duration::from_millis(100)))
.expect("Could not poll for network events!");
let mut ctx = GdbCtx {
dbg: &mut debugger.ctx(Arm9),
last_halt: &mut last_halt
};
for event in &events {
handle_event(&event, &mut connection, |buf, stream| {
handle_gdb_packet(buf, stream, &mut ctx).unwrap();
});
}
for msg in msg_client.try_iter() {
match msg {
Message::Quit => break 't,
Message::Arm9Halted(reason) => {
if let Some(ref mut stream) = connection.socket {
let break_data = BreakData::new(reason, ctx.dbg);
write_gdb_packet(&break_data.to_signal(), stream).unwrap();
}
}
_ => {}
}
}
}
msg_client
}).unwrap())
}
pub fn wait(&mut self) {
if let Some(t) = self.gdb_thread.take() {
t.join().unwrap();
}
}
}
struct Connection<'a> {
listener: &'a TcpListener,
poll: mio::Poll,
socket: Option<TcpStream>,
}
fn handle_event<F>(event: &mio::Event, connection: &mut Connection, mut client_responder: F)
where F: FnMut(&[u8], &mut TcpStream) {
let mut buf = [0u8; 1024];
match event.token() {
TOKEN_LISTENER => {
match connection.listener.accept() {
Ok((socket, _)) => {
info!("GDB stub accepting connection");
connection.poll.register(&socket, TOKEN_CLIENT, mio::Ready::readable(),
mio::PollOpt::edge())
.expect("Could not register TCP client to mio!");
connection.socket = Some(socket);
}
Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => {
return; // Socket is not ready anymore, stop accepting
}
e => panic!("GDB stub IO error! {:?}", e)
}
}
TOKEN_CLIENT => for _ in 0..128 {
match connection.socket.as_mut().unwrap().read(&mut buf) {
Ok(0) => {
connection.socket = None;
break;
}
Ok(l) => client_responder(&buf[..l], connection.socket.as_mut().unwrap()),
Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => {
continue; // Socket is not ready anymore, stop reading
}
e => panic!("GDB stub IO error! {:?}", e), // Unexpected error
}
},
_ => unimplemented!()
}
} | let mut connection = Connection {
listener: &listener, | random_line_split |
gdbstub.rs | use std::io::{self, Read, Write};
use std::ops::{Add, AddAssign};
use std::str;
use std::thread;
use std::time::Duration;
use mio;
use mio::tcp::{TcpListener, TcpStream};
use cpu::BreakReason;
use dbgcore::{self, ActiveCpu::Arm9};
use hwcore::Message;
use msgs;
use utils;
#[derive(Debug, Error)]
pub enum ErrorKind {
Hex(::std::num::ParseIntError),
Io(io::Error),
/// Client should not expect a response
NoResponse,
/// Could not find next element to parse
Parse,
}
pub type Result<T> = ::std::result::Result<T, ErrorKind>;
fn parse_next<T, I: Iterator<Item=T>>(it: &mut I) -> Result<T> {
it.next().ok_or(ErrorKind::Parse.into())
}
fn parse_next_hex<'a, I: Iterator<Item=&'a str>>(it: &mut I) -> Result<u32> {
Ok(utils::from_hex(parse_next(it)?)?)
}
fn cmd_step(ctx: &mut GdbCtx) -> Result<String> {
ctx.dbg.hw().step();
let break_data = BreakData::new(BreakReason::LimitReached, ctx.dbg);
let signal = break_data.to_signal();
*ctx.last_halt = break_data;
Ok(signal)
}
fn cmd_continue(ctx: &mut GdbCtx) -> Result<String> {
ctx.dbg.resume();
Err(ErrorKind::NoResponse)
}
struct BreakData {
reason: BreakReason,
r15: u32,
r13: u32
}
impl BreakData {
fn new(reason: BreakReason, dbg: &mut dbgcore::DbgContext) -> BreakData {
let hw = dbg.hw();
BreakData {
reason: reason,
r15: hw.pause_addr(),
r13: hw.read_reg(13),
}
}
fn to_signal(&self) -> String {
let reason_str = match self.reason {
BreakReason::Breakpoint => format!(";{}:", "swbreak"),
_ => String::new(),
};
format!("T05{:02X}:{:08X};{:02X}:{:08X}{};", 15, self.r15.swap_bytes(),
13, self.r13.swap_bytes(),
reason_str)
}
}
fn handle_gdb_cmd_q(cmd: &str, _ctx: &mut GdbCtx) -> Result<String> {
let mut s = cmd.splitn(2, ':');
let ty = parse_next(&mut s)?;
let mut out = String::new();
match ty {
"fThreadInfo" => out += "m0000000000000001",
"sThreadInfo" => out += "l",
"C" => out += "QC0000000000000001",
"Attached" => out += "1",
"Supported" => {
out += "PacketSize=400;BreakpointCommands+;swbreak+;vContSupported+";
}
_ => warn!("GDB client tried to run unsupported `q` command {}", ty)
}
Ok(out)
}
fn handle_gdb_cmd_v(cmd: &str, ctx: &mut GdbCtx) -> Result<String> {
let mut s = cmd.splitn(2, |c| c == ',' || c == ':' || c == ';');
let ty = parse_next(&mut s)?;
let mut out = String::new();
match ty {
"Cont" => {
let params = parse_next(&mut s)?;
let threads = params.split(';');
for thread in threads {
let mut thread_data = thread.split(':');
let action = parse_next(&mut thread_data)?;
let thread_name = thread_data.next();
if let Some(name) = thread_name {
match (name, utils::from_hex(name)) {
| ("-1", _)
| (_, Ok(0))
| (_, Ok(1)) => {}
| (s, _) => panic!("Attempted to issue command on invalid thread id {}", s)
}
}
match action {
"c" => return cmd_continue(ctx),
"s" => return cmd_step(ctx),
_ => warn!("GDB client tried to run unsupported `vCont` action {}", action)
}
}
}
"Cont?" => {
let supported = ["c", "s"];
out += "vCont";
for ty in supported.iter() {
out += ";";
out += ty;
}
}
_ => warn!("GDB client tried to run unsupported `v` command {}", ty)
}
Ok(out)
}
fn handle_gdb_cmd(cmd: &str, ctx: &mut GdbCtx) -> Result<String> {
let ty = parse_next(&mut cmd.chars())?;
let params = &cmd[1..];
let mut out = String::new();
ctx.dbg.pause();
match ty {
'g' => {
let hw = ctx.dbg.hw();
for reg in 0..15 {
out += &format!("{:08X}", hw.read_reg(reg).swap_bytes());
}
out += &format!("{:08X}", hw.pause_addr().swap_bytes());
for _ in 0..8 {
out += "xxxxxxxxxxxxxxxxxxxxxxxx"; // fX registers (12 bytes each)
}
out += "xxxxxxxx"; // fps register
out += &format!("{:08X}", hw.read_cpsr().swap_bytes());
}
'G' => {
let mut hw = ctx.dbg.hw();
let mut regs = params;
let next_reg = |regstr: &str| -> Result<u32> {
let val = utils::from_hex(®str[..8])?;
Ok(val.swap_bytes())
};
for reg in 0..15 {
hw.write_reg(reg, next_reg(regs)?);
regs = ®s[8..];
}
// register at 15: PC
hw.branch_to(next_reg(regs)?);
regs = ®s[8..];
// Skip 8 fX registers
regs = ®s[8 * 24..];
// Skip fps register
regs = ®s[8..];
// register at 25: CPSR
hw.write_cpsr(next_reg(regs)?);
out += "OK";
}
'H' => {
out += "OK";
}
'm' => {
let mut hw = ctx.dbg.hw();
let mut params = params.split(',');
let addr = parse_next_hex(&mut params)?;
let size = parse_next_hex(&mut params)?;
let mut buf = [0u8];
for b in 0..size {
if let Err(_) = hw.read_mem(addr+b, &mut buf) {
out += "00";
} else {
out += &format!("{:02X}", buf[0]);
}
}
}
'M' => {
let mut hw = ctx.dbg.hw();
let mut params = params.split(|c| c == ',' || c == ':');
let addr = parse_next_hex(&mut params)?;
let size = parse_next_hex(&mut params)?;
let data = parse_next(&mut params)?;
for b in 0..size {
let data_byte_range = 2*(b as usize)..2*((b as usize)+1);
let byte = utils::from_hex(&data[data_byte_range])? as u8;
hw.write_mem(addr+b, &[byte]);
}
out += "OK";
}
'p' => {
let hw = ctx.dbg.hw();
let reg = utils::from_hex(¶ms)? as usize;
let regval = match reg {
0 ..= 14 => hw.read_reg(reg),
15 => hw.pause_addr(),
25 => hw.read_cpsr(),
n => {
warn!("GDB requested bad register value {}", n);
0
}
};
out += &format!("{:08X}", regval.swap_bytes());
}
'q' => {
return handle_gdb_cmd_q(params, ctx);
}
's' => {
return cmd_step(ctx);
}
'c' => {
return cmd_continue(ctx);
}
'v' => {
return handle_gdb_cmd_v(params, ctx);
}
'z' | 'Z' => {
let mut hw = ctx.dbg.hw();
let mut params = params.split(',');
let brk_ty = parse_next(&mut params)?;
let addr = parse_next_hex(&mut params)?;
let _kind = parse_next(&mut params)?;
assert!(brk_ty == "0");
if ty == 'Z' {
hw.set_breakpoint(addr);
} else {
hw.del_breakpoint(addr);
}
out += "OK";
}
'?' => {
out += &ctx.last_halt.to_signal();
}
x => {
warn!("GDB client tried to run unsupported command {}", x);
}
}
Ok(out)
}
#[derive(Clone, Copy)]
struct Checksum(pub u32);
impl Add<u8> for Checksum {
type Output = Checksum;
fn add(self, b: u8) -> Checksum {
Checksum((self.0 + (b as u32)) % 256)
}
}
impl AddAssign<u8> for Checksum {
fn add_assign(&mut self, b: u8) {
self.0 = (*self + b).0;
}
}
enum PacketType {
Command(String),
CtrlC,
AckOk,
AckErr,
EndOfPacket,
Malformed,
}
fn load_packet<I: Iterator<Item = u8>>(it: &mut I) -> PacketType {
let mut it = it.skip_while(|b| *b != 0x03 && *b != b'$' && *b != b'-' && *b != b'+');
match it.next() {
Some(0x3) => return PacketType::CtrlC,
Some(b'$') => {}
Some(b'+') => return PacketType::AckOk,
Some(b'-') => return PacketType::AckErr,
None => return PacketType::EndOfPacket,
_ => return PacketType::Malformed
}
let mut string = String::new();
let mut checksum = Checksum(0);
for b in it.by_ref().take_while(|b| *b != b'#') {
string.push(b as char);
checksum += b;
}
if let (Some(top), Some(bot)) = (it.next(), it.next()) {
let packet_checksum = str::from_utf8(&[top, bot]).ok()
.and_then(|s| utils::from_hex(s).ok());
if Some(checksum.0) == packet_checksum {
return PacketType::Command(string)
}
}
return PacketType::Malformed
}
fn write_gdb_packet(data: &str, stream: &mut TcpStream) -> Result<()> {
let checksum = data.bytes().fold(Checksum(0), |checksum, b| checksum + b);
trace!("Replying with GDB packet: ${}#{:02X}", data, checksum.0);
write!(stream, "${}#{:02X}", data, checksum.0)?;
stream.flush()?;
Ok(())
}
fn handle_gdb_packet(data: &[u8], stream: &mut TcpStream, ctx: &mut GdbCtx) -> Result<()> {
trace!("Recieving GDB packet: {}", str::from_utf8(data).unwrap());
let mut it = data.iter().cloned();
loop {
match load_packet(&mut it) {
PacketType::Command(cmd) => {
stream.write(b"+")?;
stream.flush()?;
match handle_gdb_cmd(&cmd, ctx) {
Ok(out) => write_gdb_packet(&out, stream)?,
Err(e) => {
if let ErrorKind::NoResponse = e {}
else { return Err(e) }
}
}
}
PacketType::CtrlC => {
ctx.dbg.pause();
trace!("Recieved GDB packet with CTRL-C signal!");
}
PacketType::AckOk => {},
PacketType::AckErr => error!("GDB client replied with error packet!"),
PacketType::EndOfPacket => {
return Ok(())
}
PacketType::Malformed => {
trace!("Recieved malformed data {:?}", data);
stream.write(b"-")?;
stream.flush()?;
return Ok(())
}
}
}
}
struct | <'a, 'b: 'a> {
dbg: &'a mut dbgcore::DbgContext<'b>,
last_halt: &'a mut BreakData,
}
const TOKEN_LISTENER: mio::Token = mio::Token(1024);
const TOKEN_CLIENT: mio::Token = mio::Token(1025);
pub struct GdbStub {
debugger: dbgcore::DbgCore,
gdb_thread: Option<thread::JoinHandle<msgs::Client<Message>>>
}
impl GdbStub {
pub fn new(msg_client: msgs::Client<Message>, debugger: dbgcore::DbgCore) -> GdbStub {
let mut stub = GdbStub {
debugger: debugger,
gdb_thread: None
};
stub.start(msg_client);
stub
}
pub fn start(&mut self, msg_client: msgs::Client<Message>) {
let mut debugger = self.debugger.clone();
self.gdb_thread = Some(thread::Builder::new().name("GDBStub".to_owned()).spawn(move || {
use mio::Events;
let poll = mio::Poll::new()
.expect("Could not create mio polling instance!");
let listener = TcpListener::bind(&"127.0.0.1:4567".parse().unwrap())
.expect("Could not bind TcpListener to port!");
poll.register(&listener, TOKEN_LISTENER, mio::Ready::readable(), mio::PollOpt::edge())
.expect("Could not register TcpListener to mio!");
let mut connection = Connection {
listener: &listener,
poll: poll,
socket: None,
};
let mut events = Events::with_capacity(1024);
info!("Starting GDB stub on port 4567...");
let mut last_halt = BreakData::new(BreakReason::Trapped, &mut debugger.ctx(Arm9));
't: loop {
connection.poll.poll(&mut events, Some(Duration::from_millis(100)))
.expect("Could not poll for network events!");
let mut ctx = GdbCtx {
dbg: &mut debugger.ctx(Arm9),
last_halt: &mut last_halt
};
for event in &events {
handle_event(&event, &mut connection, |buf, stream| {
handle_gdb_packet(buf, stream, &mut ctx).unwrap();
});
}
for msg in msg_client.try_iter() {
match msg {
Message::Quit => break 't,
Message::Arm9Halted(reason) => {
if let Some(ref mut stream) = connection.socket {
let break_data = BreakData::new(reason, ctx.dbg);
write_gdb_packet(&break_data.to_signal(), stream).unwrap();
}
}
_ => {}
}
}
}
msg_client
}).unwrap())
}
pub fn wait(&mut self) {
if let Some(t) = self.gdb_thread.take() {
t.join().unwrap();
}
}
}
struct Connection<'a> {
listener: &'a TcpListener,
poll: mio::Poll,
socket: Option<TcpStream>,
}
fn handle_event<F>(event: &mio::Event, connection: &mut Connection, mut client_responder: F)
where F: FnMut(&[u8], &mut TcpStream) {
let mut buf = [0u8; 1024];
match event.token() {
TOKEN_LISTENER => {
match connection.listener.accept() {
Ok((socket, _)) => {
info!("GDB stub accepting connection");
connection.poll.register(&socket, TOKEN_CLIENT, mio::Ready::readable(),
mio::PollOpt::edge())
.expect("Could not register TCP client to mio!");
connection.socket = Some(socket);
}
Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => {
return; // Socket is not ready anymore, stop accepting
}
e => panic!("GDB stub IO error! {:?}", e)
}
}
TOKEN_CLIENT => for _ in 0..128 {
match connection.socket.as_mut().unwrap().read(&mut buf) {
Ok(0) => {
connection.socket = None;
break;
}
Ok(l) => client_responder(&buf[..l], connection.socket.as_mut().unwrap()),
Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => {
continue; // Socket is not ready anymore, stop reading
}
e => panic!("GDB stub IO error! {:?}", e), // Unexpected error
}
},
_ => unimplemented!()
}
}
| GdbCtx | identifier_name |
gdbstub.rs | use std::io::{self, Read, Write};
use std::ops::{Add, AddAssign};
use std::str;
use std::thread;
use std::time::Duration;
use mio;
use mio::tcp::{TcpListener, TcpStream};
use cpu::BreakReason;
use dbgcore::{self, ActiveCpu::Arm9};
use hwcore::Message;
use msgs;
use utils;
#[derive(Debug, Error)]
pub enum ErrorKind {
Hex(::std::num::ParseIntError),
Io(io::Error),
/// Client should not expect a response
NoResponse,
/// Could not find next element to parse
Parse,
}
pub type Result<T> = ::std::result::Result<T, ErrorKind>;
fn parse_next<T, I: Iterator<Item=T>>(it: &mut I) -> Result<T> {
it.next().ok_or(ErrorKind::Parse.into())
}
fn parse_next_hex<'a, I: Iterator<Item=&'a str>>(it: &mut I) -> Result<u32> {
Ok(utils::from_hex(parse_next(it)?)?)
}
fn cmd_step(ctx: &mut GdbCtx) -> Result<String> {
ctx.dbg.hw().step();
let break_data = BreakData::new(BreakReason::LimitReached, ctx.dbg);
let signal = break_data.to_signal();
*ctx.last_halt = break_data;
Ok(signal)
}
fn cmd_continue(ctx: &mut GdbCtx) -> Result<String> {
ctx.dbg.resume();
Err(ErrorKind::NoResponse)
}
struct BreakData {
reason: BreakReason,
r15: u32,
r13: u32
}
impl BreakData {
fn new(reason: BreakReason, dbg: &mut dbgcore::DbgContext) -> BreakData {
let hw = dbg.hw();
BreakData {
reason: reason,
r15: hw.pause_addr(),
r13: hw.read_reg(13),
}
}
fn to_signal(&self) -> String |
}
fn handle_gdb_cmd_q(cmd: &str, _ctx: &mut GdbCtx) -> Result<String> {
let mut s = cmd.splitn(2, ':');
let ty = parse_next(&mut s)?;
let mut out = String::new();
match ty {
"fThreadInfo" => out += "m0000000000000001",
"sThreadInfo" => out += "l",
"C" => out += "QC0000000000000001",
"Attached" => out += "1",
"Supported" => {
out += "PacketSize=400;BreakpointCommands+;swbreak+;vContSupported+";
}
_ => warn!("GDB client tried to run unsupported `q` command {}", ty)
}
Ok(out)
}
fn handle_gdb_cmd_v(cmd: &str, ctx: &mut GdbCtx) -> Result<String> {
let mut s = cmd.splitn(2, |c| c == ',' || c == ':' || c == ';');
let ty = parse_next(&mut s)?;
let mut out = String::new();
match ty {
"Cont" => {
let params = parse_next(&mut s)?;
let threads = params.split(';');
for thread in threads {
let mut thread_data = thread.split(':');
let action = parse_next(&mut thread_data)?;
let thread_name = thread_data.next();
if let Some(name) = thread_name {
match (name, utils::from_hex(name)) {
| ("-1", _)
| (_, Ok(0))
| (_, Ok(1)) => {}
| (s, _) => panic!("Attempted to issue command on invalid thread id {}", s)
}
}
match action {
"c" => return cmd_continue(ctx),
"s" => return cmd_step(ctx),
_ => warn!("GDB client tried to run unsupported `vCont` action {}", action)
}
}
}
"Cont?" => {
let supported = ["c", "s"];
out += "vCont";
for ty in supported.iter() {
out += ";";
out += ty;
}
}
_ => warn!("GDB client tried to run unsupported `v` command {}", ty)
}
Ok(out)
}
fn handle_gdb_cmd(cmd: &str, ctx: &mut GdbCtx) -> Result<String> {
let ty = parse_next(&mut cmd.chars())?;
let params = &cmd[1..];
let mut out = String::new();
ctx.dbg.pause();
match ty {
'g' => {
let hw = ctx.dbg.hw();
for reg in 0..15 {
out += &format!("{:08X}", hw.read_reg(reg).swap_bytes());
}
out += &format!("{:08X}", hw.pause_addr().swap_bytes());
for _ in 0..8 {
out += "xxxxxxxxxxxxxxxxxxxxxxxx"; // fX registers (12 bytes each)
}
out += "xxxxxxxx"; // fps register
out += &format!("{:08X}", hw.read_cpsr().swap_bytes());
}
'G' => {
let mut hw = ctx.dbg.hw();
let mut regs = params;
let next_reg = |regstr: &str| -> Result<u32> {
let val = utils::from_hex(®str[..8])?;
Ok(val.swap_bytes())
};
for reg in 0..15 {
hw.write_reg(reg, next_reg(regs)?);
regs = ®s[8..];
}
// register at 15: PC
hw.branch_to(next_reg(regs)?);
regs = ®s[8..];
// Skip 8 fX registers
regs = ®s[8 * 24..];
// Skip fps register
regs = ®s[8..];
// register at 25: CPSR
hw.write_cpsr(next_reg(regs)?);
out += "OK";
}
'H' => {
out += "OK";
}
'm' => {
let mut hw = ctx.dbg.hw();
let mut params = params.split(',');
let addr = parse_next_hex(&mut params)?;
let size = parse_next_hex(&mut params)?;
let mut buf = [0u8];
for b in 0..size {
if let Err(_) = hw.read_mem(addr+b, &mut buf) {
out += "00";
} else {
out += &format!("{:02X}", buf[0]);
}
}
}
'M' => {
let mut hw = ctx.dbg.hw();
let mut params = params.split(|c| c == ',' || c == ':');
let addr = parse_next_hex(&mut params)?;
let size = parse_next_hex(&mut params)?;
let data = parse_next(&mut params)?;
for b in 0..size {
let data_byte_range = 2*(b as usize)..2*((b as usize)+1);
let byte = utils::from_hex(&data[data_byte_range])? as u8;
hw.write_mem(addr+b, &[byte]);
}
out += "OK";
}
'p' => {
let hw = ctx.dbg.hw();
let reg = utils::from_hex(¶ms)? as usize;
let regval = match reg {
0 ..= 14 => hw.read_reg(reg),
15 => hw.pause_addr(),
25 => hw.read_cpsr(),
n => {
warn!("GDB requested bad register value {}", n);
0
}
};
out += &format!("{:08X}", regval.swap_bytes());
}
'q' => {
return handle_gdb_cmd_q(params, ctx);
}
's' => {
return cmd_step(ctx);
}
'c' => {
return cmd_continue(ctx);
}
'v' => {
return handle_gdb_cmd_v(params, ctx);
}
'z' | 'Z' => {
let mut hw = ctx.dbg.hw();
let mut params = params.split(',');
let brk_ty = parse_next(&mut params)?;
let addr = parse_next_hex(&mut params)?;
let _kind = parse_next(&mut params)?;
assert!(brk_ty == "0");
if ty == 'Z' {
hw.set_breakpoint(addr);
} else {
hw.del_breakpoint(addr);
}
out += "OK";
}
'?' => {
out += &ctx.last_halt.to_signal();
}
x => {
warn!("GDB client tried to run unsupported command {}", x);
}
}
Ok(out)
}
#[derive(Clone, Copy)]
struct Checksum(pub u32);
impl Add<u8> for Checksum {
type Output = Checksum;
fn add(self, b: u8) -> Checksum {
Checksum((self.0 + (b as u32)) % 256)
}
}
impl AddAssign<u8> for Checksum {
fn add_assign(&mut self, b: u8) {
self.0 = (*self + b).0;
}
}
enum PacketType {
Command(String),
CtrlC,
AckOk,
AckErr,
EndOfPacket,
Malformed,
}
fn load_packet<I: Iterator<Item = u8>>(it: &mut I) -> PacketType {
let mut it = it.skip_while(|b| *b != 0x03 && *b != b'$' && *b != b'-' && *b != b'+');
match it.next() {
Some(0x3) => return PacketType::CtrlC,
Some(b'$') => {}
Some(b'+') => return PacketType::AckOk,
Some(b'-') => return PacketType::AckErr,
None => return PacketType::EndOfPacket,
_ => return PacketType::Malformed
}
let mut string = String::new();
let mut checksum = Checksum(0);
for b in it.by_ref().take_while(|b| *b != b'#') {
string.push(b as char);
checksum += b;
}
if let (Some(top), Some(bot)) = (it.next(), it.next()) {
let packet_checksum = str::from_utf8(&[top, bot]).ok()
.and_then(|s| utils::from_hex(s).ok());
if Some(checksum.0) == packet_checksum {
return PacketType::Command(string)
}
}
return PacketType::Malformed
}
fn write_gdb_packet(data: &str, stream: &mut TcpStream) -> Result<()> {
let checksum = data.bytes().fold(Checksum(0), |checksum, b| checksum + b);
trace!("Replying with GDB packet: ${}#{:02X}", data, checksum.0);
write!(stream, "${}#{:02X}", data, checksum.0)?;
stream.flush()?;
Ok(())
}
fn handle_gdb_packet(data: &[u8], stream: &mut TcpStream, ctx: &mut GdbCtx) -> Result<()> {
trace!("Recieving GDB packet: {}", str::from_utf8(data).unwrap());
let mut it = data.iter().cloned();
loop {
match load_packet(&mut it) {
PacketType::Command(cmd) => {
stream.write(b"+")?;
stream.flush()?;
match handle_gdb_cmd(&cmd, ctx) {
Ok(out) => write_gdb_packet(&out, stream)?,
Err(e) => {
if let ErrorKind::NoResponse = e {}
else { return Err(e) }
}
}
}
PacketType::CtrlC => {
ctx.dbg.pause();
trace!("Recieved GDB packet with CTRL-C signal!");
}
PacketType::AckOk => {},
PacketType::AckErr => error!("GDB client replied with error packet!"),
PacketType::EndOfPacket => {
return Ok(())
}
PacketType::Malformed => {
trace!("Recieved malformed data {:?}", data);
stream.write(b"-")?;
stream.flush()?;
return Ok(())
}
}
}
}
struct GdbCtx<'a, 'b: 'a> {
dbg: &'a mut dbgcore::DbgContext<'b>,
last_halt: &'a mut BreakData,
}
const TOKEN_LISTENER: mio::Token = mio::Token(1024);
const TOKEN_CLIENT: mio::Token = mio::Token(1025);
pub struct GdbStub {
debugger: dbgcore::DbgCore,
gdb_thread: Option<thread::JoinHandle<msgs::Client<Message>>>
}
impl GdbStub {
pub fn new(msg_client: msgs::Client<Message>, debugger: dbgcore::DbgCore) -> GdbStub {
let mut stub = GdbStub {
debugger: debugger,
gdb_thread: None
};
stub.start(msg_client);
stub
}
pub fn start(&mut self, msg_client: msgs::Client<Message>) {
let mut debugger = self.debugger.clone();
self.gdb_thread = Some(thread::Builder::new().name("GDBStub".to_owned()).spawn(move || {
use mio::Events;
let poll = mio::Poll::new()
.expect("Could not create mio polling instance!");
let listener = TcpListener::bind(&"127.0.0.1:4567".parse().unwrap())
.expect("Could not bind TcpListener to port!");
poll.register(&listener, TOKEN_LISTENER, mio::Ready::readable(), mio::PollOpt::edge())
.expect("Could not register TcpListener to mio!");
let mut connection = Connection {
listener: &listener,
poll: poll,
socket: None,
};
let mut events = Events::with_capacity(1024);
info!("Starting GDB stub on port 4567...");
let mut last_halt = BreakData::new(BreakReason::Trapped, &mut debugger.ctx(Arm9));
't: loop {
connection.poll.poll(&mut events, Some(Duration::from_millis(100)))
.expect("Could not poll for network events!");
let mut ctx = GdbCtx {
dbg: &mut debugger.ctx(Arm9),
last_halt: &mut last_halt
};
for event in &events {
handle_event(&event, &mut connection, |buf, stream| {
handle_gdb_packet(buf, stream, &mut ctx).unwrap();
});
}
for msg in msg_client.try_iter() {
match msg {
Message::Quit => break 't,
Message::Arm9Halted(reason) => {
if let Some(ref mut stream) = connection.socket {
let break_data = BreakData::new(reason, ctx.dbg);
write_gdb_packet(&break_data.to_signal(), stream).unwrap();
}
}
_ => {}
}
}
}
msg_client
}).unwrap())
}
pub fn wait(&mut self) {
if let Some(t) = self.gdb_thread.take() {
t.join().unwrap();
}
}
}
struct Connection<'a> {
listener: &'a TcpListener,
poll: mio::Poll,
socket: Option<TcpStream>,
}
fn handle_event<F>(event: &mio::Event, connection: &mut Connection, mut client_responder: F)
where F: FnMut(&[u8], &mut TcpStream) {
let mut buf = [0u8; 1024];
match event.token() {
TOKEN_LISTENER => {
match connection.listener.accept() {
Ok((socket, _)) => {
info!("GDB stub accepting connection");
connection.poll.register(&socket, TOKEN_CLIENT, mio::Ready::readable(),
mio::PollOpt::edge())
.expect("Could not register TCP client to mio!");
connection.socket = Some(socket);
}
Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => {
return; // Socket is not ready anymore, stop accepting
}
e => panic!("GDB stub IO error! {:?}", e)
}
}
TOKEN_CLIENT => for _ in 0..128 {
match connection.socket.as_mut().unwrap().read(&mut buf) {
Ok(0) => {
connection.socket = None;
break;
}
Ok(l) => client_responder(&buf[..l], connection.socket.as_mut().unwrap()),
Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => {
continue; // Socket is not ready anymore, stop reading
}
e => panic!("GDB stub IO error! {:?}", e), // Unexpected error
}
},
_ => unimplemented!()
}
}
| {
let reason_str = match self.reason {
BreakReason::Breakpoint => format!(";{}:", "swbreak"),
_ => String::new(),
};
format!("T05{:02X}:{:08X};{:02X}:{:08X}{};", 15, self.r15.swap_bytes(),
13, self.r13.swap_bytes(),
reason_str)
} | identifier_body |
spinning_square.rs | // Copyright 2018 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
use anyhow::{Context as _, Error};
use carnelian::{
app::{Config, ViewCreationParameters},
color::Color,
derive_handle_message_with_default,
drawing::{load_font, path_for_rectangle, path_for_rounded_rectangle, FontFace},
input::{self},
render::{BlendMode, Context as RenderContext, Fill, FillRule, Layer, Path, Style},
scene::{
facets::{Facet, FacetId, TextFacetOptions},
scene::{Scene, SceneBuilder, SceneOrder},
LayerGroup,
},
App, AppAssistant, AppAssistantPtr, AppSender, AssistantCreatorFunc, Coord, LocalBoxFuture,
MessageTarget, Point, Rect, Size, ViewAssistant, ViewAssistantContext, ViewAssistantPtr,
ViewKey,
};
use euclid::{point2, size2, vec2, Angle, Transform2D};
use fidl::prelude::*;
use fidl_test_placeholders::{EchoMarker, EchoRequest, EchoRequestStream};
use fuchsia_async as fasync;
use fuchsia_zircon::Time;
use futures::prelude::*;
use std::{f32::consts::PI, path::PathBuf};
struct SpinningSquareAppAssistant {
app_sender: AppSender,
}
impl SpinningSquareAppAssistant {
fn new(app_sender: AppSender) -> Self {
Self { app_sender }
}
}
impl AppAssistant for SpinningSquareAppAssistant {
fn setup(&mut self) -> Result<(), Error> {
Ok(())
}
fn create_view_assistant_with_parameters(
&mut self,
params: ViewCreationParameters,
) -> Result<ViewAssistantPtr, Error> {
let additional = params.options.is_some();
let direction = params
.options
.and_then(|options| options.downcast_ref::<Direction>().map(|direction| *direction))
.unwrap_or(Direction::CounterClockwise);
SpinningSquareViewAssistant::new(
params.view_key,
direction,
self.app_sender.clone(),
additional,
)
}
/// Return the list of names of services this app wants to provide
fn outgoing_services_names(&self) -> Vec<&'static str> {
[EchoMarker::PROTOCOL_NAME].to_vec()
}
/// Handle a request to connect to a service provided by this app
fn handle_service_connection_request(
&mut self,
_service_name: &str,
channel: fasync::Channel,
) -> Result<(), Error> {
Self::create_echo_server(channel, false);
Ok(())
}
fn filter_config(&mut self, config: &mut Config) {
config.display_resource_release_delay = std::time::Duration::new(0, 0);
}
}
impl SpinningSquareAppAssistant {
fn create_echo_server(channel: fasync::Channel, quiet: bool) {
fasync::Task::local(
async move {
let mut stream = EchoRequestStream::from_channel(channel);
while let Some(EchoRequest::EchoString { value, responder }) =
stream.try_next().await.context("error running echo server")?
{
if !quiet {
println!("Spinning Square received echo request for string {:?}", value);
}
responder
.send(value.as_ref().map(|s| &**s))
.context("error sending response")?;
if !quiet {
println!("echo response sent successfully");
}
}
Ok(())
}
.unwrap_or_else(|e: anyhow::Error| eprintln!("{:?}", e)),
)
.detach();
}
}
struct SceneDetails {
scene: Scene,
square: FacetId,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Direction {
Clockwise,
CounterClockwise,
}
impl Direction {
pub fn toggle(self) -> Self {
match self {
Self::Clockwise => Self::CounterClockwise,
Self::CounterClockwise => Self::Clockwise,
}
}
}
#[derive(Debug)]
pub struct ToggleRoundedMessage {}
#[derive(Debug)]
pub struct ToggleDirectionMessage {}
struct SpinningSquareFacet {
direction: Direction,
square_color: Color,
rounded: bool,
start: Time,
square_path: Option<Path>,
size: Size,
}
impl SpinningSquareFacet {
fn new(square_color: Color, start: Time, size: Size, direction: Direction) -> Self {
Self { direction, square_color, rounded: false, start, square_path: None, size }
}
fn clone_square_path(&self) -> Path {
self.square_path.as_ref().expect("square_path").clone()
}
fn handle_toggle_rounded_message(&mut self, _msg: &ToggleRoundedMessage) {
self.rounded = !self.rounded;
self.square_path = None;
}
fn handle_toggle_direction_message(&mut self, _msg: &ToggleDirectionMessage) {
self.direction = self.direction.toggle();
}
fn handle_other_message(&mut self, _msg: &carnelian::Message) {
println!("handle_other_message");
}
}
impl Facet for SpinningSquareFacet {
fn update_layers(
&mut self,
size: Size,
layer_group: &mut dyn LayerGroup,
render_context: &mut RenderContext,
view_context: &ViewAssistantContext,
) -> Result<(), Error> {
const SPEED: f32 = 0.25;
const SECONDS_PER_NANOSECOND: f32 = 1e-9;
const SQUARE_PATH_SIZE: Coord = 1.0;
const SQUARE_PATH_SIZE_2: Coord = SQUARE_PATH_SIZE / 2.0;
const CORNER_RADIUS: Coord = SQUARE_PATH_SIZE / 4.0;
let center_x = size.width * 0.5;
let center_y = size.height * 0.5;
self.size = size;
let square_size = size.width.min(size.height) * 0.6;
let presentation_time = view_context.presentation_time;
let t = ((presentation_time.into_nanos() - self.start.into_nanos()) as f32
* SECONDS_PER_NANOSECOND
* SPEED)
% 1.0;
let angle =
t * PI * 2.0 * if self.direction == Direction::CounterClockwise { -1.0 } else { 1.0 };
if self.square_path.is_none() {
let top_left = point2(-SQUARE_PATH_SIZE_2, -SQUARE_PATH_SIZE_2);
let square = Rect::new(top_left, size2(SQUARE_PATH_SIZE, SQUARE_PATH_SIZE));
let square_path = if self.rounded {
path_for_rounded_rectangle(&square, CORNER_RADIUS, render_context)
} else {
path_for_rectangle(&square, render_context)
};
self.square_path.replace(square_path);
}
let transformation = Transform2D::rotation(Angle::radians(angle))
.then_scale(square_size, square_size)
.then_translate(vec2(center_x, center_y));
let mut raster_builder = render_context.raster_builder().expect("raster_builder");
raster_builder.add(&self.clone_square_path(), Some(&transformation));
let square_raster = raster_builder.build();
layer_group.insert(
SceneOrder::default(),
Layer {
raster: square_raster,
clip: None,
style: Style {
fill_rule: FillRule::NonZero,
fill: Fill::Solid(self.square_color),
blend_mode: BlendMode::Over,
},
},
);
Ok(())
}
derive_handle_message_with_default!(handle_other_message,
ToggleRoundedMessage => handle_toggle_rounded_message,
ToggleDirectionMessage => handle_toggle_direction_message
);
fn calculate_size(&self, _available: Size) -> Size {
self.size
}
}
struct SpinningSquareViewAssistant {
direction: Direction,
view_key: ViewKey,
background_color: Color,
square_color: Color,
start: Time,
app_sender: AppSender,
scene_details: Option<SceneDetails>,
face: FontFace,
additional: bool,
}
impl SpinningSquareViewAssistant {
fn new(
view_key: ViewKey,
direction: Direction,
app_sender: AppSender,
additional: bool,
) -> Result<ViewAssistantPtr, Error> {
let square_color = Color { r: 0xbb, g: 0x00, b: 0xff, a: 0xbb };
let background_color = Color { r: 0x3f, g: 0x8a, b: 0x99, a: 0xff };
let start = Time::get_monotonic();
let face = load_font(PathBuf::from("/pkg/data/fonts/RobotoSlab-Regular.ttf"))?;
Ok(Box::new(SpinningSquareViewAssistant {
direction,
view_key,
background_color,
square_color,
start,
scene_details: None,
app_sender,
face,
additional,
}))
}
fn ensure_scene_built(&mut self, size: Size) {
if self.scene_details.is_none() {
let min_dimension = size.width.min(size.height);
let font_size = (min_dimension / 5.0).ceil().min(64.0);
let mut builder =
SceneBuilder::new().background_color(self.background_color).animated(true);
let mut square = None;
builder.group().stack().center().contents(|builder| {
if self.additional {
let key_text = format!("{}", self.view_key);
let _ = builder.text(
self.face.clone(),
&key_text,
font_size,
Point::zero(),
TextFacetOptions::default(),
);
}
let square_facet =
SpinningSquareFacet::new(self.square_color, self.start, size, self.direction);
square = Some(builder.facet(Box::new(square_facet)));
const STRIPE_COUNT: usize = 5;
let stripe_height = size.height / (STRIPE_COUNT * 2 + 1) as f32;
const STRIPE_WIDTH_RATIO: f32 = 0.8;
let stripe_size = size2(size.width * STRIPE_WIDTH_RATIO, stripe_height);
builder.group().column().max_size().space_evenly().contents(|builder| {
for _ in 0..STRIPE_COUNT {
builder.rectangle(stripe_size, Color::white());
}
});
});
let square = square.expect("square");
let scene = builder.build();
self.scene_details = Some(SceneDetails { scene, square });
}
}
fn toggle_rounded(&mut self) {
if let Some(scene_details) = self.scene_details.as_mut() {
// since we have the scene, we could call send_message directly,
// but this lets us demonstrate facet-targeted messages.
self.app_sender.queue_message(
MessageTarget::Facet(self.view_key, scene_details.square),
Box::new(ToggleRoundedMessage {}),
);
self.app_sender.request_render(self.view_key);
}
}
fn move_backward(&mut self) {
if let Some(scene_details) = self.scene_details.as_mut() {
scene_details
.scene
.move_facet_backward(scene_details.square)
.unwrap_or_else(|e| println!("error in move_facet_backward: {}", e));
self.app_sender.request_render(self.view_key);
}
}
fn move_forward(&mut self) {
if let Some(scene_details) = self.scene_details.as_mut() {
scene_details
.scene
.move_facet_forward(scene_details.square)
.unwrap_or_else(|e| println!("error in move_facet_forward: {}", e));
self.app_sender.request_render(self.view_key);
}
}
fn toggle_direction(&mut self) {
if let Some(scene_details) = self.scene_details.as_mut() {
self.app_sender.queue_message(
MessageTarget::Facet(self.view_key, scene_details.square),
Box::new(ToggleDirectionMessage {}),
);
self.app_sender.request_render(self.view_key);
}
}
fn make_new_view(&mut self) {
let direction = self.direction.toggle();
self.app_sender.create_additional_view(Some(Box::new(direction)));
}
fn close_additional_view(&mut self) {
if self.additional {
self.app_sender.close_additional_view(self.view_key);
} else {
println!("Cannot close initial window");
}
}
}
impl ViewAssistant for SpinningSquareViewAssistant {
fn resize(&mut self, new_size: &Size) -> Result<(), Error> {
self.scene_details = None;
self.ensure_scene_built(*new_size);
Ok(())
}
fn get_scene(&mut self, size: Size) -> Option<&mut Scene> {
self.ensure_scene_built(size);
Some(&mut self.scene_details.as_mut().unwrap().scene)
}
fn handle_keyboard_event(
&mut self,
_context: &mut ViewAssistantContext,
_event: &input::Event,
keyboard_event: &input::keyboard::Event,
) -> Result<(), Error> {
const SPACE: u32 = ' ' as u32;
const B: u32 = 'b' as u32;
const F: u32 = 'f' as u32;
const D: u32 = 'd' as u32;
const V: u32 = 'v' as u32;
const C: u32 = 'c' as u32;
if let Some(code_point) = keyboard_event.code_point |
Ok(())
}
}
fn make_app_assistant_fut(
app_sender: &AppSender,
) -> LocalBoxFuture<'_, Result<AppAssistantPtr, Error>> {
let f = async move {
let assistant = Box::new(SpinningSquareAppAssistant::new(app_sender.clone()));
Ok::<AppAssistantPtr, Error>(assistant)
};
Box::pin(f)
}
fn make_app_assistant() -> AssistantCreatorFunc {
Box::new(make_app_assistant_fut)
}
fn main() -> Result<(), Error> {
fuchsia_trace_provider::trace_provider_create_with_fdio();
App::run(make_app_assistant())
}
| {
if keyboard_event.phase == input::keyboard::Phase::Pressed
|| keyboard_event.phase == input::keyboard::Phase::Repeat
{
match code_point {
SPACE => self.toggle_rounded(),
B => self.move_backward(),
F => self.move_forward(),
D => self.toggle_direction(),
V => self.make_new_view(),
C => self.close_additional_view(),
_ => println!("code_point = {}", code_point),
}
}
} | conditional_block |
spinning_square.rs | // Copyright 2018 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
use anyhow::{Context as _, Error};
use carnelian::{
app::{Config, ViewCreationParameters},
color::Color,
derive_handle_message_with_default,
drawing::{load_font, path_for_rectangle, path_for_rounded_rectangle, FontFace},
input::{self},
render::{BlendMode, Context as RenderContext, Fill, FillRule, Layer, Path, Style},
scene::{
facets::{Facet, FacetId, TextFacetOptions},
scene::{Scene, SceneBuilder, SceneOrder},
LayerGroup,
},
App, AppAssistant, AppAssistantPtr, AppSender, AssistantCreatorFunc, Coord, LocalBoxFuture,
MessageTarget, Point, Rect, Size, ViewAssistant, ViewAssistantContext, ViewAssistantPtr,
ViewKey,
};
use euclid::{point2, size2, vec2, Angle, Transform2D};
use fidl::prelude::*;
use fidl_test_placeholders::{EchoMarker, EchoRequest, EchoRequestStream};
use fuchsia_async as fasync;
use fuchsia_zircon::Time;
use futures::prelude::*;
use std::{f32::consts::PI, path::PathBuf};
struct SpinningSquareAppAssistant {
app_sender: AppSender,
}
impl SpinningSquareAppAssistant {
fn new(app_sender: AppSender) -> Self {
Self { app_sender }
}
}
impl AppAssistant for SpinningSquareAppAssistant {
fn setup(&mut self) -> Result<(), Error> {
Ok(())
}
fn create_view_assistant_with_parameters(
&mut self,
params: ViewCreationParameters,
) -> Result<ViewAssistantPtr, Error> {
let additional = params.options.is_some();
let direction = params
.options
.and_then(|options| options.downcast_ref::<Direction>().map(|direction| *direction))
.unwrap_or(Direction::CounterClockwise);
SpinningSquareViewAssistant::new(
params.view_key,
direction,
self.app_sender.clone(),
additional,
)
}
/// Return the list of names of services this app wants to provide
fn outgoing_services_names(&self) -> Vec<&'static str> {
[EchoMarker::PROTOCOL_NAME].to_vec()
}
/// Handle a request to connect to a service provided by this app
fn handle_service_connection_request(
&mut self,
_service_name: &str,
channel: fasync::Channel,
) -> Result<(), Error> {
Self::create_echo_server(channel, false);
Ok(())
}
fn filter_config(&mut self, config: &mut Config) {
config.display_resource_release_delay = std::time::Duration::new(0, 0);
}
}
impl SpinningSquareAppAssistant {
fn create_echo_server(channel: fasync::Channel, quiet: bool) {
fasync::Task::local(
async move {
let mut stream = EchoRequestStream::from_channel(channel);
while let Some(EchoRequest::EchoString { value, responder }) =
stream.try_next().await.context("error running echo server")?
{
if !quiet {
println!("Spinning Square received echo request for string {:?}", value);
}
responder
.send(value.as_ref().map(|s| &**s))
.context("error sending response")?;
if !quiet {
println!("echo response sent successfully");
}
}
Ok(())
}
.unwrap_or_else(|e: anyhow::Error| eprintln!("{:?}", e)),
)
.detach();
}
}
struct SceneDetails {
scene: Scene,
square: FacetId,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Direction {
Clockwise,
CounterClockwise,
}
impl Direction {
pub fn toggle(self) -> Self { | }
#[derive(Debug)]
pub struct ToggleRoundedMessage {}
#[derive(Debug)]
pub struct ToggleDirectionMessage {}
struct SpinningSquareFacet {
direction: Direction,
square_color: Color,
rounded: bool,
start: Time,
square_path: Option<Path>,
size: Size,
}
impl SpinningSquareFacet {
fn new(square_color: Color, start: Time, size: Size, direction: Direction) -> Self {
Self { direction, square_color, rounded: false, start, square_path: None, size }
}
fn clone_square_path(&self) -> Path {
self.square_path.as_ref().expect("square_path").clone()
}
fn handle_toggle_rounded_message(&mut self, _msg: &ToggleRoundedMessage) {
self.rounded = !self.rounded;
self.square_path = None;
}
fn handle_toggle_direction_message(&mut self, _msg: &ToggleDirectionMessage) {
self.direction = self.direction.toggle();
}
fn handle_other_message(&mut self, _msg: &carnelian::Message) {
println!("handle_other_message");
}
}
impl Facet for SpinningSquareFacet {
fn update_layers(
&mut self,
size: Size,
layer_group: &mut dyn LayerGroup,
render_context: &mut RenderContext,
view_context: &ViewAssistantContext,
) -> Result<(), Error> {
const SPEED: f32 = 0.25;
const SECONDS_PER_NANOSECOND: f32 = 1e-9;
const SQUARE_PATH_SIZE: Coord = 1.0;
const SQUARE_PATH_SIZE_2: Coord = SQUARE_PATH_SIZE / 2.0;
const CORNER_RADIUS: Coord = SQUARE_PATH_SIZE / 4.0;
let center_x = size.width * 0.5;
let center_y = size.height * 0.5;
self.size = size;
let square_size = size.width.min(size.height) * 0.6;
let presentation_time = view_context.presentation_time;
let t = ((presentation_time.into_nanos() - self.start.into_nanos()) as f32
* SECONDS_PER_NANOSECOND
* SPEED)
% 1.0;
let angle =
t * PI * 2.0 * if self.direction == Direction::CounterClockwise { -1.0 } else { 1.0 };
if self.square_path.is_none() {
let top_left = point2(-SQUARE_PATH_SIZE_2, -SQUARE_PATH_SIZE_2);
let square = Rect::new(top_left, size2(SQUARE_PATH_SIZE, SQUARE_PATH_SIZE));
let square_path = if self.rounded {
path_for_rounded_rectangle(&square, CORNER_RADIUS, render_context)
} else {
path_for_rectangle(&square, render_context)
};
self.square_path.replace(square_path);
}
let transformation = Transform2D::rotation(Angle::radians(angle))
.then_scale(square_size, square_size)
.then_translate(vec2(center_x, center_y));
let mut raster_builder = render_context.raster_builder().expect("raster_builder");
raster_builder.add(&self.clone_square_path(), Some(&transformation));
let square_raster = raster_builder.build();
layer_group.insert(
SceneOrder::default(),
Layer {
raster: square_raster,
clip: None,
style: Style {
fill_rule: FillRule::NonZero,
fill: Fill::Solid(self.square_color),
blend_mode: BlendMode::Over,
},
},
);
Ok(())
}
derive_handle_message_with_default!(handle_other_message,
ToggleRoundedMessage => handle_toggle_rounded_message,
ToggleDirectionMessage => handle_toggle_direction_message
);
fn calculate_size(&self, _available: Size) -> Size {
self.size
}
}
struct SpinningSquareViewAssistant {
direction: Direction,
view_key: ViewKey,
background_color: Color,
square_color: Color,
start: Time,
app_sender: AppSender,
scene_details: Option<SceneDetails>,
face: FontFace,
additional: bool,
}
impl SpinningSquareViewAssistant {
fn new(
view_key: ViewKey,
direction: Direction,
app_sender: AppSender,
additional: bool,
) -> Result<ViewAssistantPtr, Error> {
let square_color = Color { r: 0xbb, g: 0x00, b: 0xff, a: 0xbb };
let background_color = Color { r: 0x3f, g: 0x8a, b: 0x99, a: 0xff };
let start = Time::get_monotonic();
let face = load_font(PathBuf::from("/pkg/data/fonts/RobotoSlab-Regular.ttf"))?;
Ok(Box::new(SpinningSquareViewAssistant {
direction,
view_key,
background_color,
square_color,
start,
scene_details: None,
app_sender,
face,
additional,
}))
}
fn ensure_scene_built(&mut self, size: Size) {
if self.scene_details.is_none() {
let min_dimension = size.width.min(size.height);
let font_size = (min_dimension / 5.0).ceil().min(64.0);
let mut builder =
SceneBuilder::new().background_color(self.background_color).animated(true);
let mut square = None;
builder.group().stack().center().contents(|builder| {
if self.additional {
let key_text = format!("{}", self.view_key);
let _ = builder.text(
self.face.clone(),
&key_text,
font_size,
Point::zero(),
TextFacetOptions::default(),
);
}
let square_facet =
SpinningSquareFacet::new(self.square_color, self.start, size, self.direction);
square = Some(builder.facet(Box::new(square_facet)));
const STRIPE_COUNT: usize = 5;
let stripe_height = size.height / (STRIPE_COUNT * 2 + 1) as f32;
const STRIPE_WIDTH_RATIO: f32 = 0.8;
let stripe_size = size2(size.width * STRIPE_WIDTH_RATIO, stripe_height);
builder.group().column().max_size().space_evenly().contents(|builder| {
for _ in 0..STRIPE_COUNT {
builder.rectangle(stripe_size, Color::white());
}
});
});
let square = square.expect("square");
let scene = builder.build();
self.scene_details = Some(SceneDetails { scene, square });
}
}
fn toggle_rounded(&mut self) {
if let Some(scene_details) = self.scene_details.as_mut() {
// since we have the scene, we could call send_message directly,
// but this lets us demonstrate facet-targeted messages.
self.app_sender.queue_message(
MessageTarget::Facet(self.view_key, scene_details.square),
Box::new(ToggleRoundedMessage {}),
);
self.app_sender.request_render(self.view_key);
}
}
fn move_backward(&mut self) {
if let Some(scene_details) = self.scene_details.as_mut() {
scene_details
.scene
.move_facet_backward(scene_details.square)
.unwrap_or_else(|e| println!("error in move_facet_backward: {}", e));
self.app_sender.request_render(self.view_key);
}
}
fn move_forward(&mut self) {
if let Some(scene_details) = self.scene_details.as_mut() {
scene_details
.scene
.move_facet_forward(scene_details.square)
.unwrap_or_else(|e| println!("error in move_facet_forward: {}", e));
self.app_sender.request_render(self.view_key);
}
}
fn toggle_direction(&mut self) {
if let Some(scene_details) = self.scene_details.as_mut() {
self.app_sender.queue_message(
MessageTarget::Facet(self.view_key, scene_details.square),
Box::new(ToggleDirectionMessage {}),
);
self.app_sender.request_render(self.view_key);
}
}
fn make_new_view(&mut self) {
let direction = self.direction.toggle();
self.app_sender.create_additional_view(Some(Box::new(direction)));
}
fn close_additional_view(&mut self) {
if self.additional {
self.app_sender.close_additional_view(self.view_key);
} else {
println!("Cannot close initial window");
}
}
}
impl ViewAssistant for SpinningSquareViewAssistant {
fn resize(&mut self, new_size: &Size) -> Result<(), Error> {
self.scene_details = None;
self.ensure_scene_built(*new_size);
Ok(())
}
fn get_scene(&mut self, size: Size) -> Option<&mut Scene> {
self.ensure_scene_built(size);
Some(&mut self.scene_details.as_mut().unwrap().scene)
}
fn handle_keyboard_event(
&mut self,
_context: &mut ViewAssistantContext,
_event: &input::Event,
keyboard_event: &input::keyboard::Event,
) -> Result<(), Error> {
const SPACE: u32 = ' ' as u32;
const B: u32 = 'b' as u32;
const F: u32 = 'f' as u32;
const D: u32 = 'd' as u32;
const V: u32 = 'v' as u32;
const C: u32 = 'c' as u32;
if let Some(code_point) = keyboard_event.code_point {
if keyboard_event.phase == input::keyboard::Phase::Pressed
|| keyboard_event.phase == input::keyboard::Phase::Repeat
{
match code_point {
SPACE => self.toggle_rounded(),
B => self.move_backward(),
F => self.move_forward(),
D => self.toggle_direction(),
V => self.make_new_view(),
C => self.close_additional_view(),
_ => println!("code_point = {}", code_point),
}
}
}
Ok(())
}
}
fn make_app_assistant_fut(
app_sender: &AppSender,
) -> LocalBoxFuture<'_, Result<AppAssistantPtr, Error>> {
let f = async move {
let assistant = Box::new(SpinningSquareAppAssistant::new(app_sender.clone()));
Ok::<AppAssistantPtr, Error>(assistant)
};
Box::pin(f)
}
fn make_app_assistant() -> AssistantCreatorFunc {
Box::new(make_app_assistant_fut)
}
fn main() -> Result<(), Error> {
fuchsia_trace_provider::trace_provider_create_with_fdio();
App::run(make_app_assistant())
} | match self {
Self::Clockwise => Self::CounterClockwise,
Self::CounterClockwise => Self::Clockwise,
}
} | random_line_split |
spinning_square.rs | // Copyright 2018 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
use anyhow::{Context as _, Error};
use carnelian::{
app::{Config, ViewCreationParameters},
color::Color,
derive_handle_message_with_default,
drawing::{load_font, path_for_rectangle, path_for_rounded_rectangle, FontFace},
input::{self},
render::{BlendMode, Context as RenderContext, Fill, FillRule, Layer, Path, Style},
scene::{
facets::{Facet, FacetId, TextFacetOptions},
scene::{Scene, SceneBuilder, SceneOrder},
LayerGroup,
},
App, AppAssistant, AppAssistantPtr, AppSender, AssistantCreatorFunc, Coord, LocalBoxFuture,
MessageTarget, Point, Rect, Size, ViewAssistant, ViewAssistantContext, ViewAssistantPtr,
ViewKey,
};
use euclid::{point2, size2, vec2, Angle, Transform2D};
use fidl::prelude::*;
use fidl_test_placeholders::{EchoMarker, EchoRequest, EchoRequestStream};
use fuchsia_async as fasync;
use fuchsia_zircon::Time;
use futures::prelude::*;
use std::{f32::consts::PI, path::PathBuf};
struct SpinningSquareAppAssistant {
app_sender: AppSender,
}
impl SpinningSquareAppAssistant {
fn new(app_sender: AppSender) -> Self {
Self { app_sender }
}
}
impl AppAssistant for SpinningSquareAppAssistant {
fn setup(&mut self) -> Result<(), Error> {
Ok(())
}
fn create_view_assistant_with_parameters(
&mut self,
params: ViewCreationParameters,
) -> Result<ViewAssistantPtr, Error> {
let additional = params.options.is_some();
let direction = params
.options
.and_then(|options| options.downcast_ref::<Direction>().map(|direction| *direction))
.unwrap_or(Direction::CounterClockwise);
SpinningSquareViewAssistant::new(
params.view_key,
direction,
self.app_sender.clone(),
additional,
)
}
/// Return the list of names of services this app wants to provide
fn outgoing_services_names(&self) -> Vec<&'static str> {
[EchoMarker::PROTOCOL_NAME].to_vec()
}
/// Handle a request to connect to a service provided by this app
fn handle_service_connection_request(
&mut self,
_service_name: &str,
channel: fasync::Channel,
) -> Result<(), Error> {
Self::create_echo_server(channel, false);
Ok(())
}
fn filter_config(&mut self, config: &mut Config) {
config.display_resource_release_delay = std::time::Duration::new(0, 0);
}
}
impl SpinningSquareAppAssistant {
fn create_echo_server(channel: fasync::Channel, quiet: bool) {
fasync::Task::local(
async move {
let mut stream = EchoRequestStream::from_channel(channel);
while let Some(EchoRequest::EchoString { value, responder }) =
stream.try_next().await.context("error running echo server")?
{
if !quiet {
println!("Spinning Square received echo request for string {:?}", value);
}
responder
.send(value.as_ref().map(|s| &**s))
.context("error sending response")?;
if !quiet {
println!("echo response sent successfully");
}
}
Ok(())
}
.unwrap_or_else(|e: anyhow::Error| eprintln!("{:?}", e)),
)
.detach();
}
}
struct SceneDetails {
scene: Scene,
square: FacetId,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Direction {
Clockwise,
CounterClockwise,
}
impl Direction {
pub fn toggle(self) -> Self {
match self {
Self::Clockwise => Self::CounterClockwise,
Self::CounterClockwise => Self::Clockwise,
}
}
}
#[derive(Debug)]
pub struct ToggleRoundedMessage {}
#[derive(Debug)]
pub struct ToggleDirectionMessage {}
struct SpinningSquareFacet {
direction: Direction,
square_color: Color,
rounded: bool,
start: Time,
square_path: Option<Path>,
size: Size,
}
impl SpinningSquareFacet {
fn new(square_color: Color, start: Time, size: Size, direction: Direction) -> Self {
Self { direction, square_color, rounded: false, start, square_path: None, size }
}
fn clone_square_path(&self) -> Path {
self.square_path.as_ref().expect("square_path").clone()
}
fn handle_toggle_rounded_message(&mut self, _msg: &ToggleRoundedMessage) {
self.rounded = !self.rounded;
self.square_path = None;
}
fn handle_toggle_direction_message(&mut self, _msg: &ToggleDirectionMessage) {
self.direction = self.direction.toggle();
}
fn handle_other_message(&mut self, _msg: &carnelian::Message) {
println!("handle_other_message");
}
}
impl Facet for SpinningSquareFacet {
fn update_layers(
&mut self,
size: Size,
layer_group: &mut dyn LayerGroup,
render_context: &mut RenderContext,
view_context: &ViewAssistantContext,
) -> Result<(), Error> {
const SPEED: f32 = 0.25;
const SECONDS_PER_NANOSECOND: f32 = 1e-9;
const SQUARE_PATH_SIZE: Coord = 1.0;
const SQUARE_PATH_SIZE_2: Coord = SQUARE_PATH_SIZE / 2.0;
const CORNER_RADIUS: Coord = SQUARE_PATH_SIZE / 4.0;
let center_x = size.width * 0.5;
let center_y = size.height * 0.5;
self.size = size;
let square_size = size.width.min(size.height) * 0.6;
let presentation_time = view_context.presentation_time;
let t = ((presentation_time.into_nanos() - self.start.into_nanos()) as f32
* SECONDS_PER_NANOSECOND
* SPEED)
% 1.0;
let angle =
t * PI * 2.0 * if self.direction == Direction::CounterClockwise { -1.0 } else { 1.0 };
if self.square_path.is_none() {
let top_left = point2(-SQUARE_PATH_SIZE_2, -SQUARE_PATH_SIZE_2);
let square = Rect::new(top_left, size2(SQUARE_PATH_SIZE, SQUARE_PATH_SIZE));
let square_path = if self.rounded {
path_for_rounded_rectangle(&square, CORNER_RADIUS, render_context)
} else {
path_for_rectangle(&square, render_context)
};
self.square_path.replace(square_path);
}
let transformation = Transform2D::rotation(Angle::radians(angle))
.then_scale(square_size, square_size)
.then_translate(vec2(center_x, center_y));
let mut raster_builder = render_context.raster_builder().expect("raster_builder");
raster_builder.add(&self.clone_square_path(), Some(&transformation));
let square_raster = raster_builder.build();
layer_group.insert(
SceneOrder::default(),
Layer {
raster: square_raster,
clip: None,
style: Style {
fill_rule: FillRule::NonZero,
fill: Fill::Solid(self.square_color),
blend_mode: BlendMode::Over,
},
},
);
Ok(())
}
derive_handle_message_with_default!(handle_other_message,
ToggleRoundedMessage => handle_toggle_rounded_message,
ToggleDirectionMessage => handle_toggle_direction_message
);
fn calculate_size(&self, _available: Size) -> Size {
self.size
}
}
struct SpinningSquareViewAssistant {
direction: Direction,
view_key: ViewKey,
background_color: Color,
square_color: Color,
start: Time,
app_sender: AppSender,
scene_details: Option<SceneDetails>,
face: FontFace,
additional: bool,
}
impl SpinningSquareViewAssistant {
fn new(
view_key: ViewKey,
direction: Direction,
app_sender: AppSender,
additional: bool,
) -> Result<ViewAssistantPtr, Error> {
let square_color = Color { r: 0xbb, g: 0x00, b: 0xff, a: 0xbb };
let background_color = Color { r: 0x3f, g: 0x8a, b: 0x99, a: 0xff };
let start = Time::get_monotonic();
let face = load_font(PathBuf::from("/pkg/data/fonts/RobotoSlab-Regular.ttf"))?;
Ok(Box::new(SpinningSquareViewAssistant {
direction,
view_key,
background_color,
square_color,
start,
scene_details: None,
app_sender,
face,
additional,
}))
}
fn ensure_scene_built(&mut self, size: Size) {
if self.scene_details.is_none() {
let min_dimension = size.width.min(size.height);
let font_size = (min_dimension / 5.0).ceil().min(64.0);
let mut builder =
SceneBuilder::new().background_color(self.background_color).animated(true);
let mut square = None;
builder.group().stack().center().contents(|builder| {
if self.additional {
let key_text = format!("{}", self.view_key);
let _ = builder.text(
self.face.clone(),
&key_text,
font_size,
Point::zero(),
TextFacetOptions::default(),
);
}
let square_facet =
SpinningSquareFacet::new(self.square_color, self.start, size, self.direction);
square = Some(builder.facet(Box::new(square_facet)));
const STRIPE_COUNT: usize = 5;
let stripe_height = size.height / (STRIPE_COUNT * 2 + 1) as f32;
const STRIPE_WIDTH_RATIO: f32 = 0.8;
let stripe_size = size2(size.width * STRIPE_WIDTH_RATIO, stripe_height);
builder.group().column().max_size().space_evenly().contents(|builder| {
for _ in 0..STRIPE_COUNT {
builder.rectangle(stripe_size, Color::white());
}
});
});
let square = square.expect("square");
let scene = builder.build();
self.scene_details = Some(SceneDetails { scene, square });
}
}
fn toggle_rounded(&mut self) {
if let Some(scene_details) = self.scene_details.as_mut() {
// since we have the scene, we could call send_message directly,
// but this lets us demonstrate facet-targeted messages.
self.app_sender.queue_message(
MessageTarget::Facet(self.view_key, scene_details.square),
Box::new(ToggleRoundedMessage {}),
);
self.app_sender.request_render(self.view_key);
}
}
fn move_backward(&mut self) {
if let Some(scene_details) = self.scene_details.as_mut() {
scene_details
.scene
.move_facet_backward(scene_details.square)
.unwrap_or_else(|e| println!("error in move_facet_backward: {}", e));
self.app_sender.request_render(self.view_key);
}
}
fn move_forward(&mut self) {
if let Some(scene_details) = self.scene_details.as_mut() {
scene_details
.scene
.move_facet_forward(scene_details.square)
.unwrap_or_else(|e| println!("error in move_facet_forward: {}", e));
self.app_sender.request_render(self.view_key);
}
}
fn toggle_direction(&mut self) {
if let Some(scene_details) = self.scene_details.as_mut() {
self.app_sender.queue_message(
MessageTarget::Facet(self.view_key, scene_details.square),
Box::new(ToggleDirectionMessage {}),
);
self.app_sender.request_render(self.view_key);
}
}
fn make_new_view(&mut self) {
let direction = self.direction.toggle();
self.app_sender.create_additional_view(Some(Box::new(direction)));
}
fn close_additional_view(&mut self) {
if self.additional {
self.app_sender.close_additional_view(self.view_key);
} else {
println!("Cannot close initial window");
}
}
}
impl ViewAssistant for SpinningSquareViewAssistant {
fn | (&mut self, new_size: &Size) -> Result<(), Error> {
self.scene_details = None;
self.ensure_scene_built(*new_size);
Ok(())
}
fn get_scene(&mut self, size: Size) -> Option<&mut Scene> {
self.ensure_scene_built(size);
Some(&mut self.scene_details.as_mut().unwrap().scene)
}
fn handle_keyboard_event(
&mut self,
_context: &mut ViewAssistantContext,
_event: &input::Event,
keyboard_event: &input::keyboard::Event,
) -> Result<(), Error> {
const SPACE: u32 = ' ' as u32;
const B: u32 = 'b' as u32;
const F: u32 = 'f' as u32;
const D: u32 = 'd' as u32;
const V: u32 = 'v' as u32;
const C: u32 = 'c' as u32;
if let Some(code_point) = keyboard_event.code_point {
if keyboard_event.phase == input::keyboard::Phase::Pressed
|| keyboard_event.phase == input::keyboard::Phase::Repeat
{
match code_point {
SPACE => self.toggle_rounded(),
B => self.move_backward(),
F => self.move_forward(),
D => self.toggle_direction(),
V => self.make_new_view(),
C => self.close_additional_view(),
_ => println!("code_point = {}", code_point),
}
}
}
Ok(())
}
}
fn make_app_assistant_fut(
app_sender: &AppSender,
) -> LocalBoxFuture<'_, Result<AppAssistantPtr, Error>> {
let f = async move {
let assistant = Box::new(SpinningSquareAppAssistant::new(app_sender.clone()));
Ok::<AppAssistantPtr, Error>(assistant)
};
Box::pin(f)
}
fn make_app_assistant() -> AssistantCreatorFunc {
Box::new(make_app_assistant_fut)
}
fn main() -> Result<(), Error> {
fuchsia_trace_provider::trace_provider_create_with_fdio();
App::run(make_app_assistant())
}
| resize | identifier_name |
aup2rpp.py | import struct
import xml.etree.ElementTree as ET
import uuid
import math
import pprint
import os
import html
import argparse
AU_SAMPLE_FORMAT_16 = 3
AU_SAMPLE_FORMAT_24 = 4
AU_SAMPLE_FORMAT_FLOAT = 6
def load_au_file(au_fpath):
with open(au_fpath, 'rb') as f:
# See https://github.com/audacity/audacity/blob/master/src/blockfile/SimpleBlockFile.cpp
# wxUint32 magic; // magic number
# wxUint32 dataOffset; // byte offset to start of audio data
# wxUint32 dataSize; // data length, in bytes (optional)
# wxUint32 encoding; // data encoding enumeration
# wxUint32 sampleRate; // samples per second
# wxUint32 channels; // number of interleaved channels
hcount = 6
hdata = struct.unpack('I' * hcount, f.read(hcount * 4))
result = {
'magic': hdata[0],
'data_offset': hdata[1],
'data_size': hdata[2],
'encoding': hdata[3],
'sample_rate': hdata[4],
'channels': hdata[5]
}
#print(result)
if result['magic'] == 0x2e736e64:
encoding = result['encoding']
else:
print("ERROR: Endianess needs to be swapped but I dunno what to do")
return
f.seek(result['data_offset'])
ds = result['data_size']
#if ds == 0xffffffff:
# Size was specified as optional... read to end of file I guess?
#ds = -1
if encoding == AU_SAMPLE_FORMAT_16:
sfc = 'h'
ss = 2
elif encoding == AU_SAMPLE_FORMAT_24:
print("ERROR: 24-bit samples? Dunno how to read them")
return
elif encoding == AU_SAMPLE_FORMAT_FLOAT:
sfc = 'f'
ss = 4
else:
print("ERROR: I dunno this format ", encoding)
return
sample_data = []
# Note: the file may be very big
i = 0
while i < ds:
d = f.read(ss)
if len(d) == 0:
break
sample_data.append(struct.unpack(sfc, d)[0])
i += 1
result['encoding'] = encoding
print(' ', result)
result['sample_data'] = sample_data
return result
class WavWriter:
def __init__(self, f, sample_rate, channels, bits_per_sample):
self.f = f
self.sample_rate = sample_rate
self.channels = channels
self.bits_per_sample = bits_per_sample
self.finalized = False
self.samples_count = 0
self.fmt_chunk_size = 2 + 2 + 4 + 4 + 2 + 2
self.initial_fpos = f.tell()
# Leave blank header size, we'll write it once all audio has been written.
# Go straight to the offset where we will write samples
riff_header_size = 8
riff_chunk_size_without_data = 4 + (8 + self.fmt_chunk_size) + 8 + 0
f.write(bytearray(riff_header_size + riff_chunk_size_without_data))
self.data_fpos = f.tell()
def append_multichannel_samples(self, sample_data_per_channel):
assert not self.finalized
assert self.channels == len(sample_data_per_channel)
nchannels = self.channels
if nchannels == 1:
# We can take a shortcut
interleaved_sample_data = sample_data_per_channel[0]
max_sample_count = len(interleaved_sample_data)
else:
# Get max channel length
max_sample_count = 0
for sample_data in sample_data_per_channel:
if len(sample_data) > max_sample_count:
if max_sample_count != 0:
# Ew, we had to adjust maximum twice
print("WARNING: appending multichannel sample data with different amount of samples!")
max_sample_count = len(sample_data)
# Make sure all channels have the same size
for sample_data in sample_data_per_channel:
if len(sample_data) > max_sample_count:
# Damn, where is resize(n)?
del sample_data[-(len(sample_data) - max_sample_count):]
else:
while len(sample_data) < max_sample_count:
sample_data.append(0)
# Interleave
interleaved_sample_data = [0] * (max_sample_count * nchannels)
for channel, sample_data in enumerate(sample_data_per_channel):
i = channel
for v in sample_data:
interleaved_sample_data[i] = v
i += nchannels
self.append_interleaved_samples(interleaved_sample_data)
def append_interleaved_samples(self, sample_data):
assert not self.finalized
nsamples = len(sample_data) // self.channels
assert nsamples * self.channels == len(sample_data)
sfc = 'h'
if self.bits_per_sample == 32:
sfc = 'i'
f = self.f
for v in sample_data:
f.write(struct.pack(sfc, v))
self.samples_count += nsamples
def finalize(self):
assert not self.finalized
f = self.f
end = f.tell()
data_chunk_size = f.tell() - self.data_fpos
f.seek(self.initial_fpos)
assert data_chunk_size == (self.samples_count * self.channels * self.bits_per_sample // 8)
# "WAVE" letters + two FourCC+size headers and their chunk size.
# Does not include the size of the top-level header "RIFF"+size.
riff_chunk_size = 4 + (8 + self.fmt_chunk_size) + (8 + data_chunk_size)
f.write(b'RIFF')
f.write(struct.pack('I', riff_chunk_size))
f.write(b'WAVE')
#wave_chunk_size = ???
#f.write(struct.pack('I', wave_chunk_size))
# ----------
f.write(b'fmt ')
f.write(struct.pack('I', self.fmt_chunk_size))
# Format
# PCM = 1 (i.e. Linear quantization) Values other than 1 indicate some form of compression.
f.write(struct.pack('H', 1))
f.write(struct.pack('H', self.channels))
f.write(struct.pack('I', self.sample_rate))
# SampleRate * NumChannels * BitsPerSample/8
byte_rate = self.sample_rate * self.channels * self.bits_per_sample // 8
f.write(struct.pack('I', byte_rate))
# NumChannels * BitsPerSample/8
block_align = self.channels * self.bits_per_sample // 8
f.write(struct.pack('H', block_align))
# 8 bits = 8, 16 bits = 16, etc.
f.write(struct.pack('H', self.bits_per_sample))
f.write(b'data')
f.write(struct.pack('I', data_chunk_size))
# And what follows is what we wrote before
self.finalized = True
# Legacy shortcut
# def write_wav_file(fpath, sample_rate, channels, bits_per_sample, sample_data):
# with open(fpath, 'wb') as f:
# w = WavWriter(f, sample_rate, channels, bits_per_sample)
# w.append_samples(sample_data)
# w.finalize()
def convert_au_files_to_wav(src_paths_by_channel, dst_path):
if len(src_paths_by_channel) == 0:
return
# Eliminate channels with no blocks
temp = []
for c in src_paths_by_channel:
if len(c) != 0:
temp.append(c)
src_paths_by_channel = temp
print("Converting blocks ", src_paths_by_channel)
# Concatenate a bunch of .au block files into a single WAV file
with open(dst_path, 'wb') as f:
w = None
nchannels = len(src_paths_by_channel)
# For each block
for block_index in range(len(src_paths_by_channel[0])):
samples_by_channel = []
# Process each corrsponding channel for that block
for channel in range(nchannels):
src_paths = src_paths_by_channel[channel]
if block_index >= len(src_paths):
# That block doesn't have data on each channel...
samples_by_channel.append([])
continue
au = load_au_file(src_paths[block_index])
samples = au['sample_data']
if au['channels'] != 1:
# TODO Deal with this eventually...
# As far as I've seen, Audacity actually saves stereo blocks as separate mono .au files. WHY??
print("ERROR: I didn't expect .au files to have 2 channels "
"(at least my experience so far has shown they were always mono)")
return 0
# Make sure it ends up in the encoding we want
if au['encoding'] == AU_SAMPLE_FORMAT_FLOAT:
for i, v in enumerate(samples):
# We want 16-bit PCM
samples[i] = int(v * 32767.0)
elif au['encoding'] == AU_SAMPLE_FORMAT_24:
print("ERROR: 24 bits not supported")
return
elif au['encoding'] == AU_SAMPLE_FORMAT_16:
pass # Already OK
else:
print("ERROR: Unknown .au encoding: ", au['encoding'])
return 0
if w is None:
w = WavWriter(f, au['sample_rate'], nchannels, 16)
elif w.sample_rate != au['sample_rate']:
print("ERROR: sample rate differs in one of the .au files I wanted to concatenate into one .wav")
# TODO Resample, or return multiple files and split the clip...
break
samples_by_channel.append(samples)
w.append_multichannel_samples(samples_by_channel)
w.finalize()
return 0 if w is None else w.samples_count
def load_audacity_project(fpath):
root = ET.parse(fpath).getroot()
rate = int(float(root.attrib["rate"]))
name = root.attrib['projname']
ns = { 'ns': 'http://audacity.sourceforge.net/xml/' }
data_dir = os.path.splitext(fpath)[0] + '_data'
if not os.path.isdir(data_dir):
data_dir = ""
def unescape(s):
return html.unescape(s)
output = {
'rate': rate,
'name': unescape(name),
'data_dir': data_dir,
'tracks': []
}
for project_item in root:
tag = project_item.tag.split('}')[1]
if tag == 'wavetrack':
o_track = {
'name': unescape(project_item.attrib['name']),
'channel': int(project_item.attrib['channel']),
'linked': True if project_item.attrib['linked'] == '1' else False,
'mute': True if project_item.attrib['mute'] == '1' else False,
'solo': True if project_item.attrib['solo'] == '1' else False,
'rate': int(project_item.attrib['rate']),
'gain': float(project_item.attrib['gain']),
'pan': float(project_item.attrib['pan']),
'color_index': int(project_item.attrib['colorindex']),
'clips': []
}
output['tracks'].append(o_track)
waveclips = project_item.findall('ns:waveclip', ns)
for waveclip in waveclips:
o_clip = {
'offset': float(waveclip.attrib['offset']),
'color_index': int(waveclip.attrib['colorindex']),
}
o_track['clips'].append(o_clip)
sequence = waveclip.findall('ns:sequence', ns)[0]
o_sequence = {
'max_samples': int(sequence.attrib['maxsamples']),
'sample_format': int(sequence.attrib['sampleformat']),
'numsamples': int(sequence.attrib['numsamples']),
'blocks': []
}
o_clip['sequence'] = o_sequence
for waveblock in sequence.findall('ns:waveblock', ns):
waveblock_start = int(waveblock.attrib['start'])
for block in waveblock:
btag = block.tag.split('}')[1]
if btag == 'simpleblockfile':
o_sequence['blocks'].append({
'type': btag,
'start': waveblock_start,
'len': int(block.attrib['len']),
'filename': unescape(block.attrib['filename']),
'min': float(block.attrib['min']),
'max': float(block.attrib['max']),
'rms': float(block.attrib['rms']),
})
elif btag == 'pcmaliasblockfile':
o_sequence['blocks'].append({
'type': btag,
'start': waveblock_start,
'len': int(block.attrib['aliaslen']),
'file_start': int(block.attrib['aliasstart']),
'filename': unescape(block.attrib['aliasfile']),
'summary_file': block.attrib['summaryfile'],
'channel': int(block.attrib['aliaschannel']),
'min': float(block.attrib['min']),
'max': float(block.attrib['max']),
'rms': float(block.attrib['rms'])
})
elif btag == 'silentblockfile':
o_sequence['blocks'].append({
'type': btag,
'len': int(block.attrib['len'])
})
else:
print("WARNING: Unknown block type: '{0}'".format(btag))
envelope = waveclip.findall('ns:envelope', ns)[0]
points = []
for point in envelope.findall('ns:controlpoint', ns):
points.append({
't': float(point.attrib['t']),
'val': float(point.attrib['val'])
})
o_clip['envelope'] = {
'points': points
}
return output
def convert_au_files_from_audacity_project(project, target_dir):
# This is where most of the conversion happens.
indexed_files = {}
if project['data_dir'] != "":
# Audacity saves its media files under a nested hierarchy,
# I don't quite understand why since files seem to have unique names
for root, dirs, files in os.walk(project['data_dir']):
for name in files:
indexed_files[name] = os.path.join(root, name)
if not os.path.isdir(target_dir):
os.makedirs(target_dir)
tracks = project['tracks']
# TODO Eventually just make an entirely new project dictionary rather than modifying the input one
converted_tracks = []
project['converted_tracks'] = converted_tracks
for track_index, track in enumerate(tracks):
previous_track = None if track_index == 0 else tracks[track_index - 1]
next_track = None if track_index + 1 == len(tracks) else tracks[track_index + 1]
is_stereo_track = False
if track['channel'] == 1:
if previous_track is not None and previous_track['linked']:
# Ignore second channel of a linked stereo track,
# should be handled both in the previous iteration.
# This means a converted project may have less tracks.
continue
elif track['channel'] == 0 and track['linked']:
is_stereo_track = True
converted_track = {
'name': track['name'],
'mute': track['mute'],
'solo': track['solo'],
'rate': track['rate'],
'gain': track['gain'],
'pan': track['pan'],
'color_index': track['color_index'],
}
converted_tracks.append(converted_track)
converted_clips = []
converted_track['converted_clips'] = converted_clips
for clip_index, clip in enumerate(track['clips']):
sequence = clip['sequence']
au_fpaths = [[], []]
converted_numsamples = 0
converted_clip_start = clip['offset'] # In seconds
blocks = sequence['blocks']
clip2 = None
if is_stereo_track:
clip2 = next_track['clips'][clip_index]
if clip2['offset'] != clip['offset']:
print("WARNING: Stereo track has non-aligned clips??")
# Okayyy
clip2 = None
# Convert clip-wise envelopes into a track-wise one
if len(clip['envelope']['points']) > 0:
if 'envelope' not in converted_track:
converted_envelope = { 'points': [] }
converted_track['envelope'] = converted_envelope
else:
converted_envelope = converted_track['envelope']
# Note: points will be sorted once we have gone through all clips
points = clip['envelope']['points']
for p in points:
converted_envelope['points'].append({
't': p['t'],
'val': p['val']
})
# A clip can be made of many different blocks.
# The goal is to process them in order to get one file per clip,
# and then possibly splitting the clip or ignoring blocks.
# Another fun part is joining stereo tracks,
# because they are saved separately
for block_index, block in enumerate(blocks):
btype = block['type']
is_last = block_index + 1 == len(blocks)
is_next_different = not is_last and btype != blocks[block_index + 1]['type']
if btype == 'simpleblockfile' or btype == 'pcmaliasblockfile':
if converted_numsamples == 0:
converted_clip_start = clip['offset'] + block['start'] / project['rate']
converted_numsamples += block['len']
if btype == 'simpleblockfile':
# This is mostly because I assume this rather than knowing it
|
elif btype == 'pcmaliasblockfile':
# We don't do anything special regarding stereo, the source file should be fine already
if not is_last:
next_block = blocks[block_index + 1]
if next_block['type'] == 'pcmaliasblockfile':
if next_block['filename'] != block['filename']:
is_next_different = True
if is_last or is_next_different:
converted_clips.append({
'offset': converted_clip_start,
'numsamples': converted_numsamples,
'filename': block['filename'],
'file_start': block['file_start']
})
converted_numsamples = 0
elif btype == 'silentblockfile':
pass # Ignore
else:
print("WARNING: Unsupported block type: '{0}'".format(btype))
# Reorder envelope points by time
if 'envelope' in converted_track:
envelope = converted_track['envelope']
envelope['points'] = sorted(envelope['points'], key=lambda x: x['t'])
def write_rpp_file_from_audacity_project(fpath, project):
audacity_color_to_peakcol = [
0, # 0: Default color in Audacity (blue)
0x013333ff, # 1: Red
0x0133ff33, # 2: Green
0x01222222 # 3: Black
]
def get_file_tag(fname):
ext = os.path.splitext(fname)[1]
if ext == '.wav':
return 'WAVE'
elif ext == 'ogg':
return 'VORBIS'
return ext[1:].upper()
# Audacity saves gain as a linear value, and it turns out Reaper also does
# def linear2db(p_linear)
# return math.log(p_linear) * 8.6858896380650365530225783783321
class RppWriter:
def __init__(self, f):
self.indent_unit = " "
self.indent = ""
self.f = f
def open_block(self, tag, *args):
self.f.write('{0}<{1}'.format(self.indent, tag))
self._args(args)
self.indent += self.indent_unit
def close_block(self):
self.indent = self.indent[:-len(self.indent_unit)]
self.f.write('{0}>\n'.format(self.indent))
def line(self, tag, *args):
self.f.write('{0}{1}'.format(self.indent, tag))
self._args(args)
def _args(self, args):
for v in args:
if type(v) == str:
s = ' "{0}"'# if v.contains(' ') else ' {0}'
self.f.write(s.format(v))
elif type(v) == bool:
self.f.write(' {0}'.format(1 if v else 0))
elif type(v) == uuid.UUID:
self.f.write(' {' + str(v).upper() + '}')
else:
self.f.write(' ' + str(v))
self.f.write('\n')
# One nice thing about Reaper projects is that you can omit things in it,
# it will not complain and just load what it finds, apparently
with open(fpath, 'w', encoding="utf-8") as f:
w = RppWriter(f)
# Arbitrary version, which happens to be mine at time of writing.
# TODO I don't know what the number at the end is
w.open_block('REAPER_PROJECT', 0.1, '5.92/x64', 1534982487)
project_samplerate = int(project['rate'])
w.line('SAMPLERATE', project_samplerate, 0, 0)
for track in project['converted_tracks']:
track_uid = uuid.uuid4()
w.open_block('TRACK', track_uid)
w.line('NAME', track['name'])
w.line('TRACKID', track_uid)
w.line('VOLPAN', track['gain'], track['pan'], -1, -1, 1)
w.line('NCHAN', 2)
w.line('MUTESOLO', track['mute'], track['solo'])
w.line('PEAKCOL', audacity_color_to_peakcol[track['color_index']])
if 'envelope' in track:
w.open_block('VOLENV2')
for point in track['envelope']['points']:
w.line('PT', point['t'], point['val'])
w.close_block()
for clip in track['converted_clips']:
w.open_block('ITEM')
w.line('POSITION', clip['offset'])
# TODO I don't know what these UIDs are
w.line('IGUID', uuid.uuid4())
w.line('GUID', uuid.uuid4())
w.line('NAME', os.path.basename(clip['filename']))
nsamples = clip['numsamples']
item_len_seconds = nsamples / project_samplerate
w.line('LENGTH', item_len_seconds)
if 'file_start' in clip:
w.line('SOFFS', clip['file_start'] / project_samplerate)
w.open_block('SOURCE ' + get_file_tag(clip['filename']))
w.line('FILE', clip['filename'])
w.close_block()
# Note: sources like this can exist:
# <SOURCE SECTION
# LENGTH 3.55565072008221
# STARTPOS 7.40378238649376
# OVERLAP 0.01
# <SOURCE FLAC
# FILE "D:\PROJETS\AUDIO\coproductions\1287\Episodes\Episode 7\foule_armee.flac"
# >
# >
w.close_block()
w.close_block()
w.close_block()
def convert(aup_path):
project = load_audacity_project(aup_path)
# pp = pprint.PrettyPrinter(indent=4)
# pp.pprint(project)
# return
data_dir = os.path.splitext(aup_path)[0] + '_wav_data'
convert_au_files_from_audacity_project(project, data_dir)
rpp_path = os.path.splitext(aup_path)[0] + '.rpp'
write_rpp_file_from_audacity_project(rpp_path, project)
print("Done")
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='Converts Audacity projects into Reaper projects.')
parser.add_argument('audacity_project', metavar='audacity_project', type=str,
help='Path to the Audacity project to convert (.aup file)')
args = parser.parse_args()
convert(args.audacity_project)
| assert block['filename'].endswith('.au')
block2 = None
if is_stereo_track and clip2 is not None:
for b in clip2['sequence']['blocks']:
if b['start'] == block['start'] and b['len'] == block['len']:
block2 = b
break
if block2 is not None:
src_fpath = indexed_files[block['filename']]
au_fpaths[0].append(src_fpath)
src_fpath2 = indexed_files[block2['filename']]
au_fpaths[1].append(src_fpath2)
else:
src_fpath = indexed_files[block['filename']]
au_fpaths[0].append(src_fpath)
if is_last or is_next_different:
dst_fname = "track{0}_clip{1}.wav".format(track_index, len(converted_clips))
dst_fpath = os.path.join(target_dir, dst_fname)
if os.path.isfile(dst_fpath):
print("Overwriting ", dst_fpath)
# TODO Try to not duplicate files when the .au was re-used.
# We could do this by hashing au_fpaths, and if it's the same then use existing result
samples_in_file = convert_au_files_to_wav(au_fpaths, dst_fpath)
# Check this because there is redundancy, I'm curious if that can fail
if samples_in_file != converted_numsamples:
print("WARNING: Sample count mismatch between what I found in the .aup and the actual files")
print(" .aup: {0}, file: {1}".format(total_samples, converted_numsamples))
converted_clips.append({
'offset': converted_clip_start,
'numsamples': converted_numsamples,
'filename': dst_fpath
})
au_fpaths[0].clear()
au_fpaths[1].clear()
converted_numsamples = 0 | conditional_block |
aup2rpp.py | import struct
import xml.etree.ElementTree as ET
import uuid
import math
import pprint
import os
import html
import argparse
AU_SAMPLE_FORMAT_16 = 3
AU_SAMPLE_FORMAT_24 = 4
AU_SAMPLE_FORMAT_FLOAT = 6
def load_au_file(au_fpath):
with open(au_fpath, 'rb') as f:
# See https://github.com/audacity/audacity/blob/master/src/blockfile/SimpleBlockFile.cpp
# wxUint32 magic; // magic number
# wxUint32 dataOffset; // byte offset to start of audio data
# wxUint32 dataSize; // data length, in bytes (optional)
# wxUint32 encoding; // data encoding enumeration
# wxUint32 sampleRate; // samples per second
# wxUint32 channels; // number of interleaved channels
hcount = 6
hdata = struct.unpack('I' * hcount, f.read(hcount * 4))
result = {
'magic': hdata[0],
'data_offset': hdata[1],
'data_size': hdata[2],
'encoding': hdata[3],
'sample_rate': hdata[4],
'channels': hdata[5]
}
#print(result)
if result['magic'] == 0x2e736e64:
encoding = result['encoding']
else:
print("ERROR: Endianess needs to be swapped but I dunno what to do")
return
f.seek(result['data_offset'])
ds = result['data_size']
#if ds == 0xffffffff:
# Size was specified as optional... read to end of file I guess?
#ds = -1
if encoding == AU_SAMPLE_FORMAT_16:
sfc = 'h'
ss = 2
elif encoding == AU_SAMPLE_FORMAT_24:
print("ERROR: 24-bit samples? Dunno how to read them")
return
elif encoding == AU_SAMPLE_FORMAT_FLOAT:
sfc = 'f'
ss = 4
else:
print("ERROR: I dunno this format ", encoding)
return
sample_data = []
# Note: the file may be very big
i = 0
while i < ds:
d = f.read(ss)
if len(d) == 0:
break
sample_data.append(struct.unpack(sfc, d)[0])
i += 1
result['encoding'] = encoding
print(' ', result)
result['sample_data'] = sample_data
return result
class WavWriter:
def __init__(self, f, sample_rate, channels, bits_per_sample):
self.f = f
self.sample_rate = sample_rate
self.channels = channels
self.bits_per_sample = bits_per_sample
self.finalized = False
self.samples_count = 0
self.fmt_chunk_size = 2 + 2 + 4 + 4 + 2 + 2
self.initial_fpos = f.tell()
# Leave blank header size, we'll write it once all audio has been written.
# Go straight to the offset where we will write samples
riff_header_size = 8
riff_chunk_size_without_data = 4 + (8 + self.fmt_chunk_size) + 8 + 0
f.write(bytearray(riff_header_size + riff_chunk_size_without_data))
self.data_fpos = f.tell()
def append_multichannel_samples(self, sample_data_per_channel):
assert not self.finalized
assert self.channels == len(sample_data_per_channel)
nchannels = self.channels
if nchannels == 1:
# We can take a shortcut
interleaved_sample_data = sample_data_per_channel[0]
max_sample_count = len(interleaved_sample_data)
else:
# Get max channel length
max_sample_count = 0
for sample_data in sample_data_per_channel:
if len(sample_data) > max_sample_count:
if max_sample_count != 0:
# Ew, we had to adjust maximum twice
print("WARNING: appending multichannel sample data with different amount of samples!")
max_sample_count = len(sample_data)
# Make sure all channels have the same size
for sample_data in sample_data_per_channel:
if len(sample_data) > max_sample_count:
# Damn, where is resize(n)?
del sample_data[-(len(sample_data) - max_sample_count):]
else:
while len(sample_data) < max_sample_count:
sample_data.append(0)
# Interleave
interleaved_sample_data = [0] * (max_sample_count * nchannels)
for channel, sample_data in enumerate(sample_data_per_channel):
i = channel
for v in sample_data:
interleaved_sample_data[i] = v
i += nchannels
self.append_interleaved_samples(interleaved_sample_data)
def append_interleaved_samples(self, sample_data):
assert not self.finalized
nsamples = len(sample_data) // self.channels
assert nsamples * self.channels == len(sample_data)
sfc = 'h'
if self.bits_per_sample == 32:
sfc = 'i'
f = self.f
for v in sample_data:
f.write(struct.pack(sfc, v))
self.samples_count += nsamples
def finalize(self):
assert not self.finalized
f = self.f
end = f.tell()
data_chunk_size = f.tell() - self.data_fpos
f.seek(self.initial_fpos)
assert data_chunk_size == (self.samples_count * self.channels * self.bits_per_sample // 8)
# "WAVE" letters + two FourCC+size headers and their chunk size.
# Does not include the size of the top-level header "RIFF"+size.
riff_chunk_size = 4 + (8 + self.fmt_chunk_size) + (8 + data_chunk_size)
f.write(b'RIFF')
f.write(struct.pack('I', riff_chunk_size))
f.write(b'WAVE')
#wave_chunk_size = ???
#f.write(struct.pack('I', wave_chunk_size))
# ----------
f.write(b'fmt ')
f.write(struct.pack('I', self.fmt_chunk_size))
# Format
# PCM = 1 (i.e. Linear quantization) Values other than 1 indicate some form of compression.
f.write(struct.pack('H', 1))
f.write(struct.pack('H', self.channels))
f.write(struct.pack('I', self.sample_rate))
# SampleRate * NumChannels * BitsPerSample/8
byte_rate = self.sample_rate * self.channels * self.bits_per_sample // 8
f.write(struct.pack('I', byte_rate))
# NumChannels * BitsPerSample/8
block_align = self.channels * self.bits_per_sample // 8
f.write(struct.pack('H', block_align))
# 8 bits = 8, 16 bits = 16, etc.
f.write(struct.pack('H', self.bits_per_sample))
f.write(b'data')
f.write(struct.pack('I', data_chunk_size))
# And what follows is what we wrote before
self.finalized = True
# Legacy shortcut
# def write_wav_file(fpath, sample_rate, channels, bits_per_sample, sample_data):
# with open(fpath, 'wb') as f:
# w = WavWriter(f, sample_rate, channels, bits_per_sample)
# w.append_samples(sample_data)
# w.finalize()
def convert_au_files_to_wav(src_paths_by_channel, dst_path):
if len(src_paths_by_channel) == 0:
return
# Eliminate channels with no blocks
temp = []
for c in src_paths_by_channel:
if len(c) != 0:
temp.append(c)
src_paths_by_channel = temp
print("Converting blocks ", src_paths_by_channel)
# Concatenate a bunch of .au block files into a single WAV file
with open(dst_path, 'wb') as f:
w = None
nchannels = len(src_paths_by_channel)
# For each block
for block_index in range(len(src_paths_by_channel[0])):
samples_by_channel = []
# Process each corrsponding channel for that block
for channel in range(nchannels):
src_paths = src_paths_by_channel[channel]
if block_index >= len(src_paths):
# That block doesn't have data on each channel...
samples_by_channel.append([])
continue
au = load_au_file(src_paths[block_index])
samples = au['sample_data']
if au['channels'] != 1:
# TODO Deal with this eventually...
# As far as I've seen, Audacity actually saves stereo blocks as separate mono .au files. WHY??
print("ERROR: I didn't expect .au files to have 2 channels "
"(at least my experience so far has shown they were always mono)")
return 0
# Make sure it ends up in the encoding we want
if au['encoding'] == AU_SAMPLE_FORMAT_FLOAT:
for i, v in enumerate(samples):
# We want 16-bit PCM
samples[i] = int(v * 32767.0)
elif au['encoding'] == AU_SAMPLE_FORMAT_24:
print("ERROR: 24 bits not supported")
return
elif au['encoding'] == AU_SAMPLE_FORMAT_16:
pass # Already OK
else:
print("ERROR: Unknown .au encoding: ", au['encoding'])
return 0
if w is None:
w = WavWriter(f, au['sample_rate'], nchannels, 16)
elif w.sample_rate != au['sample_rate']:
print("ERROR: sample rate differs in one of the .au files I wanted to concatenate into one .wav")
# TODO Resample, or return multiple files and split the clip...
break
samples_by_channel.append(samples)
w.append_multichannel_samples(samples_by_channel)
w.finalize()
return 0 if w is None else w.samples_count
def load_audacity_project(fpath):
root = ET.parse(fpath).getroot()
rate = int(float(root.attrib["rate"]))
name = root.attrib['projname']
ns = { 'ns': 'http://audacity.sourceforge.net/xml/' }
data_dir = os.path.splitext(fpath)[0] + '_data'
if not os.path.isdir(data_dir):
data_dir = ""
def unescape(s):
|
output = {
'rate': rate,
'name': unescape(name),
'data_dir': data_dir,
'tracks': []
}
for project_item in root:
tag = project_item.tag.split('}')[1]
if tag == 'wavetrack':
o_track = {
'name': unescape(project_item.attrib['name']),
'channel': int(project_item.attrib['channel']),
'linked': True if project_item.attrib['linked'] == '1' else False,
'mute': True if project_item.attrib['mute'] == '1' else False,
'solo': True if project_item.attrib['solo'] == '1' else False,
'rate': int(project_item.attrib['rate']),
'gain': float(project_item.attrib['gain']),
'pan': float(project_item.attrib['pan']),
'color_index': int(project_item.attrib['colorindex']),
'clips': []
}
output['tracks'].append(o_track)
waveclips = project_item.findall('ns:waveclip', ns)
for waveclip in waveclips:
o_clip = {
'offset': float(waveclip.attrib['offset']),
'color_index': int(waveclip.attrib['colorindex']),
}
o_track['clips'].append(o_clip)
sequence = waveclip.findall('ns:sequence', ns)[0]
o_sequence = {
'max_samples': int(sequence.attrib['maxsamples']),
'sample_format': int(sequence.attrib['sampleformat']),
'numsamples': int(sequence.attrib['numsamples']),
'blocks': []
}
o_clip['sequence'] = o_sequence
for waveblock in sequence.findall('ns:waveblock', ns):
waveblock_start = int(waveblock.attrib['start'])
for block in waveblock:
btag = block.tag.split('}')[1]
if btag == 'simpleblockfile':
o_sequence['blocks'].append({
'type': btag,
'start': waveblock_start,
'len': int(block.attrib['len']),
'filename': unescape(block.attrib['filename']),
'min': float(block.attrib['min']),
'max': float(block.attrib['max']),
'rms': float(block.attrib['rms']),
})
elif btag == 'pcmaliasblockfile':
o_sequence['blocks'].append({
'type': btag,
'start': waveblock_start,
'len': int(block.attrib['aliaslen']),
'file_start': int(block.attrib['aliasstart']),
'filename': unescape(block.attrib['aliasfile']),
'summary_file': block.attrib['summaryfile'],
'channel': int(block.attrib['aliaschannel']),
'min': float(block.attrib['min']),
'max': float(block.attrib['max']),
'rms': float(block.attrib['rms'])
})
elif btag == 'silentblockfile':
o_sequence['blocks'].append({
'type': btag,
'len': int(block.attrib['len'])
})
else:
print("WARNING: Unknown block type: '{0}'".format(btag))
envelope = waveclip.findall('ns:envelope', ns)[0]
points = []
for point in envelope.findall('ns:controlpoint', ns):
points.append({
't': float(point.attrib['t']),
'val': float(point.attrib['val'])
})
o_clip['envelope'] = {
'points': points
}
return output
def convert_au_files_from_audacity_project(project, target_dir):
# This is where most of the conversion happens.
indexed_files = {}
if project['data_dir'] != "":
# Audacity saves its media files under a nested hierarchy,
# I don't quite understand why since files seem to have unique names
for root, dirs, files in os.walk(project['data_dir']):
for name in files:
indexed_files[name] = os.path.join(root, name)
if not os.path.isdir(target_dir):
os.makedirs(target_dir)
tracks = project['tracks']
# TODO Eventually just make an entirely new project dictionary rather than modifying the input one
converted_tracks = []
project['converted_tracks'] = converted_tracks
for track_index, track in enumerate(tracks):
previous_track = None if track_index == 0 else tracks[track_index - 1]
next_track = None if track_index + 1 == len(tracks) else tracks[track_index + 1]
is_stereo_track = False
if track['channel'] == 1:
if previous_track is not None and previous_track['linked']:
# Ignore second channel of a linked stereo track,
# should be handled both in the previous iteration.
# This means a converted project may have less tracks.
continue
elif track['channel'] == 0 and track['linked']:
is_stereo_track = True
converted_track = {
'name': track['name'],
'mute': track['mute'],
'solo': track['solo'],
'rate': track['rate'],
'gain': track['gain'],
'pan': track['pan'],
'color_index': track['color_index'],
}
converted_tracks.append(converted_track)
converted_clips = []
converted_track['converted_clips'] = converted_clips
for clip_index, clip in enumerate(track['clips']):
sequence = clip['sequence']
au_fpaths = [[], []]
converted_numsamples = 0
converted_clip_start = clip['offset'] # In seconds
blocks = sequence['blocks']
clip2 = None
if is_stereo_track:
clip2 = next_track['clips'][clip_index]
if clip2['offset'] != clip['offset']:
print("WARNING: Stereo track has non-aligned clips??")
# Okayyy
clip2 = None
# Convert clip-wise envelopes into a track-wise one
if len(clip['envelope']['points']) > 0:
if 'envelope' not in converted_track:
converted_envelope = { 'points': [] }
converted_track['envelope'] = converted_envelope
else:
converted_envelope = converted_track['envelope']
# Note: points will be sorted once we have gone through all clips
points = clip['envelope']['points']
for p in points:
converted_envelope['points'].append({
't': p['t'],
'val': p['val']
})
# A clip can be made of many different blocks.
# The goal is to process them in order to get one file per clip,
# and then possibly splitting the clip or ignoring blocks.
# Another fun part is joining stereo tracks,
# because they are saved separately
for block_index, block in enumerate(blocks):
btype = block['type']
is_last = block_index + 1 == len(blocks)
is_next_different = not is_last and btype != blocks[block_index + 1]['type']
if btype == 'simpleblockfile' or btype == 'pcmaliasblockfile':
if converted_numsamples == 0:
converted_clip_start = clip['offset'] + block['start'] / project['rate']
converted_numsamples += block['len']
if btype == 'simpleblockfile':
# This is mostly because I assume this rather than knowing it
assert block['filename'].endswith('.au')
block2 = None
if is_stereo_track and clip2 is not None:
for b in clip2['sequence']['blocks']:
if b['start'] == block['start'] and b['len'] == block['len']:
block2 = b
break
if block2 is not None:
src_fpath = indexed_files[block['filename']]
au_fpaths[0].append(src_fpath)
src_fpath2 = indexed_files[block2['filename']]
au_fpaths[1].append(src_fpath2)
else:
src_fpath = indexed_files[block['filename']]
au_fpaths[0].append(src_fpath)
if is_last or is_next_different:
dst_fname = "track{0}_clip{1}.wav".format(track_index, len(converted_clips))
dst_fpath = os.path.join(target_dir, dst_fname)
if os.path.isfile(dst_fpath):
print("Overwriting ", dst_fpath)
# TODO Try to not duplicate files when the .au was re-used.
# We could do this by hashing au_fpaths, and if it's the same then use existing result
samples_in_file = convert_au_files_to_wav(au_fpaths, dst_fpath)
# Check this because there is redundancy, I'm curious if that can fail
if samples_in_file != converted_numsamples:
print("WARNING: Sample count mismatch between what I found in the .aup and the actual files")
print(" .aup: {0}, file: {1}".format(total_samples, converted_numsamples))
converted_clips.append({
'offset': converted_clip_start,
'numsamples': converted_numsamples,
'filename': dst_fpath
})
au_fpaths[0].clear()
au_fpaths[1].clear()
converted_numsamples = 0
elif btype == 'pcmaliasblockfile':
# We don't do anything special regarding stereo, the source file should be fine already
if not is_last:
next_block = blocks[block_index + 1]
if next_block['type'] == 'pcmaliasblockfile':
if next_block['filename'] != block['filename']:
is_next_different = True
if is_last or is_next_different:
converted_clips.append({
'offset': converted_clip_start,
'numsamples': converted_numsamples,
'filename': block['filename'],
'file_start': block['file_start']
})
converted_numsamples = 0
elif btype == 'silentblockfile':
pass # Ignore
else:
print("WARNING: Unsupported block type: '{0}'".format(btype))
# Reorder envelope points by time
if 'envelope' in converted_track:
envelope = converted_track['envelope']
envelope['points'] = sorted(envelope['points'], key=lambda x: x['t'])
def write_rpp_file_from_audacity_project(fpath, project):
audacity_color_to_peakcol = [
0, # 0: Default color in Audacity (blue)
0x013333ff, # 1: Red
0x0133ff33, # 2: Green
0x01222222 # 3: Black
]
def get_file_tag(fname):
ext = os.path.splitext(fname)[1]
if ext == '.wav':
return 'WAVE'
elif ext == 'ogg':
return 'VORBIS'
return ext[1:].upper()
# Audacity saves gain as a linear value, and it turns out Reaper also does
# def linear2db(p_linear)
# return math.log(p_linear) * 8.6858896380650365530225783783321
class RppWriter:
def __init__(self, f):
self.indent_unit = " "
self.indent = ""
self.f = f
def open_block(self, tag, *args):
self.f.write('{0}<{1}'.format(self.indent, tag))
self._args(args)
self.indent += self.indent_unit
def close_block(self):
self.indent = self.indent[:-len(self.indent_unit)]
self.f.write('{0}>\n'.format(self.indent))
def line(self, tag, *args):
self.f.write('{0}{1}'.format(self.indent, tag))
self._args(args)
def _args(self, args):
for v in args:
if type(v) == str:
s = ' "{0}"'# if v.contains(' ') else ' {0}'
self.f.write(s.format(v))
elif type(v) == bool:
self.f.write(' {0}'.format(1 if v else 0))
elif type(v) == uuid.UUID:
self.f.write(' {' + str(v).upper() + '}')
else:
self.f.write(' ' + str(v))
self.f.write('\n')
# One nice thing about Reaper projects is that you can omit things in it,
# it will not complain and just load what it finds, apparently
with open(fpath, 'w', encoding="utf-8") as f:
w = RppWriter(f)
# Arbitrary version, which happens to be mine at time of writing.
# TODO I don't know what the number at the end is
w.open_block('REAPER_PROJECT', 0.1, '5.92/x64', 1534982487)
project_samplerate = int(project['rate'])
w.line('SAMPLERATE', project_samplerate, 0, 0)
for track in project['converted_tracks']:
track_uid = uuid.uuid4()
w.open_block('TRACK', track_uid)
w.line('NAME', track['name'])
w.line('TRACKID', track_uid)
w.line('VOLPAN', track['gain'], track['pan'], -1, -1, 1)
w.line('NCHAN', 2)
w.line('MUTESOLO', track['mute'], track['solo'])
w.line('PEAKCOL', audacity_color_to_peakcol[track['color_index']])
if 'envelope' in track:
w.open_block('VOLENV2')
for point in track['envelope']['points']:
w.line('PT', point['t'], point['val'])
w.close_block()
for clip in track['converted_clips']:
w.open_block('ITEM')
w.line('POSITION', clip['offset'])
# TODO I don't know what these UIDs are
w.line('IGUID', uuid.uuid4())
w.line('GUID', uuid.uuid4())
w.line('NAME', os.path.basename(clip['filename']))
nsamples = clip['numsamples']
item_len_seconds = nsamples / project_samplerate
w.line('LENGTH', item_len_seconds)
if 'file_start' in clip:
w.line('SOFFS', clip['file_start'] / project_samplerate)
w.open_block('SOURCE ' + get_file_tag(clip['filename']))
w.line('FILE', clip['filename'])
w.close_block()
# Note: sources like this can exist:
# <SOURCE SECTION
# LENGTH 3.55565072008221
# STARTPOS 7.40378238649376
# OVERLAP 0.01
# <SOURCE FLAC
# FILE "D:\PROJETS\AUDIO\coproductions\1287\Episodes\Episode 7\foule_armee.flac"
# >
# >
w.close_block()
w.close_block()
w.close_block()
def convert(aup_path):
project = load_audacity_project(aup_path)
# pp = pprint.PrettyPrinter(indent=4)
# pp.pprint(project)
# return
data_dir = os.path.splitext(aup_path)[0] + '_wav_data'
convert_au_files_from_audacity_project(project, data_dir)
rpp_path = os.path.splitext(aup_path)[0] + '.rpp'
write_rpp_file_from_audacity_project(rpp_path, project)
print("Done")
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='Converts Audacity projects into Reaper projects.')
parser.add_argument('audacity_project', metavar='audacity_project', type=str,
help='Path to the Audacity project to convert (.aup file)')
args = parser.parse_args()
convert(args.audacity_project)
| return html.unescape(s) | identifier_body |
aup2rpp.py | import struct
import xml.etree.ElementTree as ET
import uuid
import math
import pprint
import os
import html
import argparse
AU_SAMPLE_FORMAT_16 = 3
AU_SAMPLE_FORMAT_24 = 4
AU_SAMPLE_FORMAT_FLOAT = 6
def load_au_file(au_fpath):
with open(au_fpath, 'rb') as f:
# See https://github.com/audacity/audacity/blob/master/src/blockfile/SimpleBlockFile.cpp
# wxUint32 magic; // magic number
# wxUint32 dataOffset; // byte offset to start of audio data
# wxUint32 dataSize; // data length, in bytes (optional)
# wxUint32 encoding; // data encoding enumeration
# wxUint32 sampleRate; // samples per second
# wxUint32 channels; // number of interleaved channels
hcount = 6
hdata = struct.unpack('I' * hcount, f.read(hcount * 4))
result = {
'magic': hdata[0],
'data_offset': hdata[1],
'data_size': hdata[2],
'encoding': hdata[3],
'sample_rate': hdata[4],
'channels': hdata[5]
}
#print(result)
if result['magic'] == 0x2e736e64:
encoding = result['encoding']
else:
print("ERROR: Endianess needs to be swapped but I dunno what to do")
return
f.seek(result['data_offset'])
ds = result['data_size']
#if ds == 0xffffffff:
# Size was specified as optional... read to end of file I guess?
#ds = -1
if encoding == AU_SAMPLE_FORMAT_16:
sfc = 'h'
ss = 2
elif encoding == AU_SAMPLE_FORMAT_24:
print("ERROR: 24-bit samples? Dunno how to read them")
return
elif encoding == AU_SAMPLE_FORMAT_FLOAT:
sfc = 'f'
ss = 4
else:
print("ERROR: I dunno this format ", encoding)
return
sample_data = []
# Note: the file may be very big
i = 0
while i < ds:
d = f.read(ss)
if len(d) == 0:
break
sample_data.append(struct.unpack(sfc, d)[0])
i += 1
result['encoding'] = encoding
print(' ', result)
result['sample_data'] = sample_data
return result
class WavWriter:
def __init__(self, f, sample_rate, channels, bits_per_sample):
self.f = f
self.sample_rate = sample_rate
self.channels = channels
self.bits_per_sample = bits_per_sample
self.finalized = False
self.samples_count = 0
self.fmt_chunk_size = 2 + 2 + 4 + 4 + 2 + 2
self.initial_fpos = f.tell()
# Leave blank header size, we'll write it once all audio has been written.
# Go straight to the offset where we will write samples
riff_header_size = 8
riff_chunk_size_without_data = 4 + (8 + self.fmt_chunk_size) + 8 + 0
f.write(bytearray(riff_header_size + riff_chunk_size_without_data))
self.data_fpos = f.tell()
def append_multichannel_samples(self, sample_data_per_channel):
assert not self.finalized
assert self.channels == len(sample_data_per_channel)
nchannels = self.channels
if nchannels == 1:
# We can take a shortcut
interleaved_sample_data = sample_data_per_channel[0]
max_sample_count = len(interleaved_sample_data)
else:
# Get max channel length
max_sample_count = 0
for sample_data in sample_data_per_channel:
if len(sample_data) > max_sample_count:
if max_sample_count != 0:
# Ew, we had to adjust maximum twice
print("WARNING: appending multichannel sample data with different amount of samples!")
max_sample_count = len(sample_data)
# Make sure all channels have the same size
for sample_data in sample_data_per_channel:
if len(sample_data) > max_sample_count:
# Damn, where is resize(n)?
del sample_data[-(len(sample_data) - max_sample_count):]
else:
while len(sample_data) < max_sample_count:
sample_data.append(0)
# Interleave
interleaved_sample_data = [0] * (max_sample_count * nchannels)
for channel, sample_data in enumerate(sample_data_per_channel):
i = channel
for v in sample_data:
interleaved_sample_data[i] = v
i += nchannels
self.append_interleaved_samples(interleaved_sample_data)
def append_interleaved_samples(self, sample_data):
assert not self.finalized
nsamples = len(sample_data) // self.channels
assert nsamples * self.channels == len(sample_data)
sfc = 'h'
if self.bits_per_sample == 32:
sfc = 'i'
f = self.f
for v in sample_data:
f.write(struct.pack(sfc, v))
self.samples_count += nsamples
def finalize(self):
assert not self.finalized
f = self.f
end = f.tell()
data_chunk_size = f.tell() - self.data_fpos
f.seek(self.initial_fpos)
assert data_chunk_size == (self.samples_count * self.channels * self.bits_per_sample // 8)
# "WAVE" letters + two FourCC+size headers and their chunk size.
# Does not include the size of the top-level header "RIFF"+size.
riff_chunk_size = 4 + (8 + self.fmt_chunk_size) + (8 + data_chunk_size)
f.write(b'RIFF')
f.write(struct.pack('I', riff_chunk_size))
f.write(b'WAVE')
#wave_chunk_size = ???
#f.write(struct.pack('I', wave_chunk_size))
# ----------
f.write(b'fmt ')
f.write(struct.pack('I', self.fmt_chunk_size))
# Format
# PCM = 1 (i.e. Linear quantization) Values other than 1 indicate some form of compression.
f.write(struct.pack('H', 1))
f.write(struct.pack('H', self.channels))
f.write(struct.pack('I', self.sample_rate))
# SampleRate * NumChannels * BitsPerSample/8
byte_rate = self.sample_rate * self.channels * self.bits_per_sample // 8
f.write(struct.pack('I', byte_rate))
# NumChannels * BitsPerSample/8
block_align = self.channels * self.bits_per_sample // 8
f.write(struct.pack('H', block_align))
# 8 bits = 8, 16 bits = 16, etc.
f.write(struct.pack('H', self.bits_per_sample))
f.write(b'data')
f.write(struct.pack('I', data_chunk_size))
# And what follows is what we wrote before
self.finalized = True
# Legacy shortcut
# def write_wav_file(fpath, sample_rate, channels, bits_per_sample, sample_data):
# with open(fpath, 'wb') as f:
# w = WavWriter(f, sample_rate, channels, bits_per_sample)
# w.append_samples(sample_data)
# w.finalize()
def convert_au_files_to_wav(src_paths_by_channel, dst_path):
if len(src_paths_by_channel) == 0:
return
# Eliminate channels with no blocks
temp = []
for c in src_paths_by_channel:
if len(c) != 0:
temp.append(c)
src_paths_by_channel = temp
print("Converting blocks ", src_paths_by_channel)
# Concatenate a bunch of .au block files into a single WAV file
with open(dst_path, 'wb') as f:
w = None
nchannels = len(src_paths_by_channel)
# For each block
for block_index in range(len(src_paths_by_channel[0])):
samples_by_channel = []
# Process each corrsponding channel for that block
for channel in range(nchannels):
src_paths = src_paths_by_channel[channel]
if block_index >= len(src_paths):
# That block doesn't have data on each channel...
samples_by_channel.append([])
continue
au = load_au_file(src_paths[block_index])
samples = au['sample_data']
if au['channels'] != 1:
# TODO Deal with this eventually...
# As far as I've seen, Audacity actually saves stereo blocks as separate mono .au files. WHY??
print("ERROR: I didn't expect .au files to have 2 channels "
"(at least my experience so far has shown they were always mono)")
return 0
# Make sure it ends up in the encoding we want
if au['encoding'] == AU_SAMPLE_FORMAT_FLOAT:
for i, v in enumerate(samples):
# We want 16-bit PCM
samples[i] = int(v * 32767.0)
elif au['encoding'] == AU_SAMPLE_FORMAT_24:
print("ERROR: 24 bits not supported")
return
elif au['encoding'] == AU_SAMPLE_FORMAT_16:
pass # Already OK
else:
print("ERROR: Unknown .au encoding: ", au['encoding'])
return 0
if w is None:
w = WavWriter(f, au['sample_rate'], nchannels, 16)
elif w.sample_rate != au['sample_rate']:
print("ERROR: sample rate differs in one of the .au files I wanted to concatenate into one .wav")
# TODO Resample, or return multiple files and split the clip...
break
| samples_by_channel.append(samples)
w.append_multichannel_samples(samples_by_channel)
w.finalize()
return 0 if w is None else w.samples_count
def load_audacity_project(fpath):
root = ET.parse(fpath).getroot()
rate = int(float(root.attrib["rate"]))
name = root.attrib['projname']
ns = { 'ns': 'http://audacity.sourceforge.net/xml/' }
data_dir = os.path.splitext(fpath)[0] + '_data'
if not os.path.isdir(data_dir):
data_dir = ""
def unescape(s):
return html.unescape(s)
output = {
'rate': rate,
'name': unescape(name),
'data_dir': data_dir,
'tracks': []
}
for project_item in root:
tag = project_item.tag.split('}')[1]
if tag == 'wavetrack':
o_track = {
'name': unescape(project_item.attrib['name']),
'channel': int(project_item.attrib['channel']),
'linked': True if project_item.attrib['linked'] == '1' else False,
'mute': True if project_item.attrib['mute'] == '1' else False,
'solo': True if project_item.attrib['solo'] == '1' else False,
'rate': int(project_item.attrib['rate']),
'gain': float(project_item.attrib['gain']),
'pan': float(project_item.attrib['pan']),
'color_index': int(project_item.attrib['colorindex']),
'clips': []
}
output['tracks'].append(o_track)
waveclips = project_item.findall('ns:waveclip', ns)
for waveclip in waveclips:
o_clip = {
'offset': float(waveclip.attrib['offset']),
'color_index': int(waveclip.attrib['colorindex']),
}
o_track['clips'].append(o_clip)
sequence = waveclip.findall('ns:sequence', ns)[0]
o_sequence = {
'max_samples': int(sequence.attrib['maxsamples']),
'sample_format': int(sequence.attrib['sampleformat']),
'numsamples': int(sequence.attrib['numsamples']),
'blocks': []
}
o_clip['sequence'] = o_sequence
for waveblock in sequence.findall('ns:waveblock', ns):
waveblock_start = int(waveblock.attrib['start'])
for block in waveblock:
btag = block.tag.split('}')[1]
if btag == 'simpleblockfile':
o_sequence['blocks'].append({
'type': btag,
'start': waveblock_start,
'len': int(block.attrib['len']),
'filename': unescape(block.attrib['filename']),
'min': float(block.attrib['min']),
'max': float(block.attrib['max']),
'rms': float(block.attrib['rms']),
})
elif btag == 'pcmaliasblockfile':
o_sequence['blocks'].append({
'type': btag,
'start': waveblock_start,
'len': int(block.attrib['aliaslen']),
'file_start': int(block.attrib['aliasstart']),
'filename': unescape(block.attrib['aliasfile']),
'summary_file': block.attrib['summaryfile'],
'channel': int(block.attrib['aliaschannel']),
'min': float(block.attrib['min']),
'max': float(block.attrib['max']),
'rms': float(block.attrib['rms'])
})
elif btag == 'silentblockfile':
o_sequence['blocks'].append({
'type': btag,
'len': int(block.attrib['len'])
})
else:
print("WARNING: Unknown block type: '{0}'".format(btag))
envelope = waveclip.findall('ns:envelope', ns)[0]
points = []
for point in envelope.findall('ns:controlpoint', ns):
points.append({
't': float(point.attrib['t']),
'val': float(point.attrib['val'])
})
o_clip['envelope'] = {
'points': points
}
return output
def convert_au_files_from_audacity_project(project, target_dir):
# This is where most of the conversion happens.
indexed_files = {}
if project['data_dir'] != "":
# Audacity saves its media files under a nested hierarchy,
# I don't quite understand why since files seem to have unique names
for root, dirs, files in os.walk(project['data_dir']):
for name in files:
indexed_files[name] = os.path.join(root, name)
if not os.path.isdir(target_dir):
os.makedirs(target_dir)
tracks = project['tracks']
# TODO Eventually just make an entirely new project dictionary rather than modifying the input one
converted_tracks = []
project['converted_tracks'] = converted_tracks
for track_index, track in enumerate(tracks):
previous_track = None if track_index == 0 else tracks[track_index - 1]
next_track = None if track_index + 1 == len(tracks) else tracks[track_index + 1]
is_stereo_track = False
if track['channel'] == 1:
if previous_track is not None and previous_track['linked']:
# Ignore second channel of a linked stereo track,
# should be handled both in the previous iteration.
# This means a converted project may have less tracks.
continue
elif track['channel'] == 0 and track['linked']:
is_stereo_track = True
converted_track = {
'name': track['name'],
'mute': track['mute'],
'solo': track['solo'],
'rate': track['rate'],
'gain': track['gain'],
'pan': track['pan'],
'color_index': track['color_index'],
}
converted_tracks.append(converted_track)
converted_clips = []
converted_track['converted_clips'] = converted_clips
for clip_index, clip in enumerate(track['clips']):
sequence = clip['sequence']
au_fpaths = [[], []]
converted_numsamples = 0
converted_clip_start = clip['offset'] # In seconds
blocks = sequence['blocks']
clip2 = None
if is_stereo_track:
clip2 = next_track['clips'][clip_index]
if clip2['offset'] != clip['offset']:
print("WARNING: Stereo track has non-aligned clips??")
# Okayyy
clip2 = None
# Convert clip-wise envelopes into a track-wise one
if len(clip['envelope']['points']) > 0:
if 'envelope' not in converted_track:
converted_envelope = { 'points': [] }
converted_track['envelope'] = converted_envelope
else:
converted_envelope = converted_track['envelope']
# Note: points will be sorted once we have gone through all clips
points = clip['envelope']['points']
for p in points:
converted_envelope['points'].append({
't': p['t'],
'val': p['val']
})
# A clip can be made of many different blocks.
# The goal is to process them in order to get one file per clip,
# and then possibly splitting the clip or ignoring blocks.
# Another fun part is joining stereo tracks,
# because they are saved separately
for block_index, block in enumerate(blocks):
btype = block['type']
is_last = block_index + 1 == len(blocks)
is_next_different = not is_last and btype != blocks[block_index + 1]['type']
if btype == 'simpleblockfile' or btype == 'pcmaliasblockfile':
if converted_numsamples == 0:
converted_clip_start = clip['offset'] + block['start'] / project['rate']
converted_numsamples += block['len']
if btype == 'simpleblockfile':
# This is mostly because I assume this rather than knowing it
assert block['filename'].endswith('.au')
block2 = None
if is_stereo_track and clip2 is not None:
for b in clip2['sequence']['blocks']:
if b['start'] == block['start'] and b['len'] == block['len']:
block2 = b
break
if block2 is not None:
src_fpath = indexed_files[block['filename']]
au_fpaths[0].append(src_fpath)
src_fpath2 = indexed_files[block2['filename']]
au_fpaths[1].append(src_fpath2)
else:
src_fpath = indexed_files[block['filename']]
au_fpaths[0].append(src_fpath)
if is_last or is_next_different:
dst_fname = "track{0}_clip{1}.wav".format(track_index, len(converted_clips))
dst_fpath = os.path.join(target_dir, dst_fname)
if os.path.isfile(dst_fpath):
print("Overwriting ", dst_fpath)
# TODO Try to not duplicate files when the .au was re-used.
# We could do this by hashing au_fpaths, and if it's the same then use existing result
samples_in_file = convert_au_files_to_wav(au_fpaths, dst_fpath)
# Check this because there is redundancy, I'm curious if that can fail
if samples_in_file != converted_numsamples:
print("WARNING: Sample count mismatch between what I found in the .aup and the actual files")
print(" .aup: {0}, file: {1}".format(total_samples, converted_numsamples))
converted_clips.append({
'offset': converted_clip_start,
'numsamples': converted_numsamples,
'filename': dst_fpath
})
au_fpaths[0].clear()
au_fpaths[1].clear()
converted_numsamples = 0
elif btype == 'pcmaliasblockfile':
# We don't do anything special regarding stereo, the source file should be fine already
if not is_last:
next_block = blocks[block_index + 1]
if next_block['type'] == 'pcmaliasblockfile':
if next_block['filename'] != block['filename']:
is_next_different = True
if is_last or is_next_different:
converted_clips.append({
'offset': converted_clip_start,
'numsamples': converted_numsamples,
'filename': block['filename'],
'file_start': block['file_start']
})
converted_numsamples = 0
elif btype == 'silentblockfile':
pass # Ignore
else:
print("WARNING: Unsupported block type: '{0}'".format(btype))
# Reorder envelope points by time
if 'envelope' in converted_track:
envelope = converted_track['envelope']
envelope['points'] = sorted(envelope['points'], key=lambda x: x['t'])
def write_rpp_file_from_audacity_project(fpath, project):
audacity_color_to_peakcol = [
0, # 0: Default color in Audacity (blue)
0x013333ff, # 1: Red
0x0133ff33, # 2: Green
0x01222222 # 3: Black
]
def get_file_tag(fname):
ext = os.path.splitext(fname)[1]
if ext == '.wav':
return 'WAVE'
elif ext == 'ogg':
return 'VORBIS'
return ext[1:].upper()
# Audacity saves gain as a linear value, and it turns out Reaper also does
# def linear2db(p_linear)
# return math.log(p_linear) * 8.6858896380650365530225783783321
class RppWriter:
def __init__(self, f):
self.indent_unit = " "
self.indent = ""
self.f = f
def open_block(self, tag, *args):
self.f.write('{0}<{1}'.format(self.indent, tag))
self._args(args)
self.indent += self.indent_unit
def close_block(self):
self.indent = self.indent[:-len(self.indent_unit)]
self.f.write('{0}>\n'.format(self.indent))
def line(self, tag, *args):
self.f.write('{0}{1}'.format(self.indent, tag))
self._args(args)
def _args(self, args):
for v in args:
if type(v) == str:
s = ' "{0}"'# if v.contains(' ') else ' {0}'
self.f.write(s.format(v))
elif type(v) == bool:
self.f.write(' {0}'.format(1 if v else 0))
elif type(v) == uuid.UUID:
self.f.write(' {' + str(v).upper() + '}')
else:
self.f.write(' ' + str(v))
self.f.write('\n')
# One nice thing about Reaper projects is that you can omit things in it,
# it will not complain and just load what it finds, apparently
with open(fpath, 'w', encoding="utf-8") as f:
w = RppWriter(f)
# Arbitrary version, which happens to be mine at time of writing.
# TODO I don't know what the number at the end is
w.open_block('REAPER_PROJECT', 0.1, '5.92/x64', 1534982487)
project_samplerate = int(project['rate'])
w.line('SAMPLERATE', project_samplerate, 0, 0)
for track in project['converted_tracks']:
track_uid = uuid.uuid4()
w.open_block('TRACK', track_uid)
w.line('NAME', track['name'])
w.line('TRACKID', track_uid)
w.line('VOLPAN', track['gain'], track['pan'], -1, -1, 1)
w.line('NCHAN', 2)
w.line('MUTESOLO', track['mute'], track['solo'])
w.line('PEAKCOL', audacity_color_to_peakcol[track['color_index']])
if 'envelope' in track:
w.open_block('VOLENV2')
for point in track['envelope']['points']:
w.line('PT', point['t'], point['val'])
w.close_block()
for clip in track['converted_clips']:
w.open_block('ITEM')
w.line('POSITION', clip['offset'])
# TODO I don't know what these UIDs are
w.line('IGUID', uuid.uuid4())
w.line('GUID', uuid.uuid4())
w.line('NAME', os.path.basename(clip['filename']))
nsamples = clip['numsamples']
item_len_seconds = nsamples / project_samplerate
w.line('LENGTH', item_len_seconds)
if 'file_start' in clip:
w.line('SOFFS', clip['file_start'] / project_samplerate)
w.open_block('SOURCE ' + get_file_tag(clip['filename']))
w.line('FILE', clip['filename'])
w.close_block()
# Note: sources like this can exist:
# <SOURCE SECTION
# LENGTH 3.55565072008221
# STARTPOS 7.40378238649376
# OVERLAP 0.01
# <SOURCE FLAC
# FILE "D:\PROJETS\AUDIO\coproductions\1287\Episodes\Episode 7\foule_armee.flac"
# >
# >
w.close_block()
w.close_block()
w.close_block()
def convert(aup_path):
project = load_audacity_project(aup_path)
# pp = pprint.PrettyPrinter(indent=4)
# pp.pprint(project)
# return
data_dir = os.path.splitext(aup_path)[0] + '_wav_data'
convert_au_files_from_audacity_project(project, data_dir)
rpp_path = os.path.splitext(aup_path)[0] + '.rpp'
write_rpp_file_from_audacity_project(rpp_path, project)
print("Done")
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='Converts Audacity projects into Reaper projects.')
parser.add_argument('audacity_project', metavar='audacity_project', type=str,
help='Path to the Audacity project to convert (.aup file)')
args = parser.parse_args()
convert(args.audacity_project) | random_line_split | |
aup2rpp.py | import struct
import xml.etree.ElementTree as ET
import uuid
import math
import pprint
import os
import html
import argparse
AU_SAMPLE_FORMAT_16 = 3
AU_SAMPLE_FORMAT_24 = 4
AU_SAMPLE_FORMAT_FLOAT = 6
def load_au_file(au_fpath):
with open(au_fpath, 'rb') as f:
# See https://github.com/audacity/audacity/blob/master/src/blockfile/SimpleBlockFile.cpp
# wxUint32 magic; // magic number
# wxUint32 dataOffset; // byte offset to start of audio data
# wxUint32 dataSize; // data length, in bytes (optional)
# wxUint32 encoding; // data encoding enumeration
# wxUint32 sampleRate; // samples per second
# wxUint32 channels; // number of interleaved channels
hcount = 6
hdata = struct.unpack('I' * hcount, f.read(hcount * 4))
result = {
'magic': hdata[0],
'data_offset': hdata[1],
'data_size': hdata[2],
'encoding': hdata[3],
'sample_rate': hdata[4],
'channels': hdata[5]
}
#print(result)
if result['magic'] == 0x2e736e64:
encoding = result['encoding']
else:
print("ERROR: Endianess needs to be swapped but I dunno what to do")
return
f.seek(result['data_offset'])
ds = result['data_size']
#if ds == 0xffffffff:
# Size was specified as optional... read to end of file I guess?
#ds = -1
if encoding == AU_SAMPLE_FORMAT_16:
sfc = 'h'
ss = 2
elif encoding == AU_SAMPLE_FORMAT_24:
print("ERROR: 24-bit samples? Dunno how to read them")
return
elif encoding == AU_SAMPLE_FORMAT_FLOAT:
sfc = 'f'
ss = 4
else:
print("ERROR: I dunno this format ", encoding)
return
sample_data = []
# Note: the file may be very big
i = 0
while i < ds:
d = f.read(ss)
if len(d) == 0:
break
sample_data.append(struct.unpack(sfc, d)[0])
i += 1
result['encoding'] = encoding
print(' ', result)
result['sample_data'] = sample_data
return result
class | :
def __init__(self, f, sample_rate, channels, bits_per_sample):
self.f = f
self.sample_rate = sample_rate
self.channels = channels
self.bits_per_sample = bits_per_sample
self.finalized = False
self.samples_count = 0
self.fmt_chunk_size = 2 + 2 + 4 + 4 + 2 + 2
self.initial_fpos = f.tell()
# Leave blank header size, we'll write it once all audio has been written.
# Go straight to the offset where we will write samples
riff_header_size = 8
riff_chunk_size_without_data = 4 + (8 + self.fmt_chunk_size) + 8 + 0
f.write(bytearray(riff_header_size + riff_chunk_size_without_data))
self.data_fpos = f.tell()
def append_multichannel_samples(self, sample_data_per_channel):
assert not self.finalized
assert self.channels == len(sample_data_per_channel)
nchannels = self.channels
if nchannels == 1:
# We can take a shortcut
interleaved_sample_data = sample_data_per_channel[0]
max_sample_count = len(interleaved_sample_data)
else:
# Get max channel length
max_sample_count = 0
for sample_data in sample_data_per_channel:
if len(sample_data) > max_sample_count:
if max_sample_count != 0:
# Ew, we had to adjust maximum twice
print("WARNING: appending multichannel sample data with different amount of samples!")
max_sample_count = len(sample_data)
# Make sure all channels have the same size
for sample_data in sample_data_per_channel:
if len(sample_data) > max_sample_count:
# Damn, where is resize(n)?
del sample_data[-(len(sample_data) - max_sample_count):]
else:
while len(sample_data) < max_sample_count:
sample_data.append(0)
# Interleave
interleaved_sample_data = [0] * (max_sample_count * nchannels)
for channel, sample_data in enumerate(sample_data_per_channel):
i = channel
for v in sample_data:
interleaved_sample_data[i] = v
i += nchannels
self.append_interleaved_samples(interleaved_sample_data)
def append_interleaved_samples(self, sample_data):
assert not self.finalized
nsamples = len(sample_data) // self.channels
assert nsamples * self.channels == len(sample_data)
sfc = 'h'
if self.bits_per_sample == 32:
sfc = 'i'
f = self.f
for v in sample_data:
f.write(struct.pack(sfc, v))
self.samples_count += nsamples
def finalize(self):
assert not self.finalized
f = self.f
end = f.tell()
data_chunk_size = f.tell() - self.data_fpos
f.seek(self.initial_fpos)
assert data_chunk_size == (self.samples_count * self.channels * self.bits_per_sample // 8)
# "WAVE" letters + two FourCC+size headers and their chunk size.
# Does not include the size of the top-level header "RIFF"+size.
riff_chunk_size = 4 + (8 + self.fmt_chunk_size) + (8 + data_chunk_size)
f.write(b'RIFF')
f.write(struct.pack('I', riff_chunk_size))
f.write(b'WAVE')
#wave_chunk_size = ???
#f.write(struct.pack('I', wave_chunk_size))
# ----------
f.write(b'fmt ')
f.write(struct.pack('I', self.fmt_chunk_size))
# Format
# PCM = 1 (i.e. Linear quantization) Values other than 1 indicate some form of compression.
f.write(struct.pack('H', 1))
f.write(struct.pack('H', self.channels))
f.write(struct.pack('I', self.sample_rate))
# SampleRate * NumChannels * BitsPerSample/8
byte_rate = self.sample_rate * self.channels * self.bits_per_sample // 8
f.write(struct.pack('I', byte_rate))
# NumChannels * BitsPerSample/8
block_align = self.channels * self.bits_per_sample // 8
f.write(struct.pack('H', block_align))
# 8 bits = 8, 16 bits = 16, etc.
f.write(struct.pack('H', self.bits_per_sample))
f.write(b'data')
f.write(struct.pack('I', data_chunk_size))
# And what follows is what we wrote before
self.finalized = True
# Legacy shortcut
# def write_wav_file(fpath, sample_rate, channels, bits_per_sample, sample_data):
# with open(fpath, 'wb') as f:
# w = WavWriter(f, sample_rate, channels, bits_per_sample)
# w.append_samples(sample_data)
# w.finalize()
def convert_au_files_to_wav(src_paths_by_channel, dst_path):
if len(src_paths_by_channel) == 0:
return
# Eliminate channels with no blocks
temp = []
for c in src_paths_by_channel:
if len(c) != 0:
temp.append(c)
src_paths_by_channel = temp
print("Converting blocks ", src_paths_by_channel)
# Concatenate a bunch of .au block files into a single WAV file
with open(dst_path, 'wb') as f:
w = None
nchannels = len(src_paths_by_channel)
# For each block
for block_index in range(len(src_paths_by_channel[0])):
samples_by_channel = []
# Process each corrsponding channel for that block
for channel in range(nchannels):
src_paths = src_paths_by_channel[channel]
if block_index >= len(src_paths):
# That block doesn't have data on each channel...
samples_by_channel.append([])
continue
au = load_au_file(src_paths[block_index])
samples = au['sample_data']
if au['channels'] != 1:
# TODO Deal with this eventually...
# As far as I've seen, Audacity actually saves stereo blocks as separate mono .au files. WHY??
print("ERROR: I didn't expect .au files to have 2 channels "
"(at least my experience so far has shown they were always mono)")
return 0
# Make sure it ends up in the encoding we want
if au['encoding'] == AU_SAMPLE_FORMAT_FLOAT:
for i, v in enumerate(samples):
# We want 16-bit PCM
samples[i] = int(v * 32767.0)
elif au['encoding'] == AU_SAMPLE_FORMAT_24:
print("ERROR: 24 bits not supported")
return
elif au['encoding'] == AU_SAMPLE_FORMAT_16:
pass # Already OK
else:
print("ERROR: Unknown .au encoding: ", au['encoding'])
return 0
if w is None:
w = WavWriter(f, au['sample_rate'], nchannels, 16)
elif w.sample_rate != au['sample_rate']:
print("ERROR: sample rate differs in one of the .au files I wanted to concatenate into one .wav")
# TODO Resample, or return multiple files and split the clip...
break
samples_by_channel.append(samples)
w.append_multichannel_samples(samples_by_channel)
w.finalize()
return 0 if w is None else w.samples_count
def load_audacity_project(fpath):
root = ET.parse(fpath).getroot()
rate = int(float(root.attrib["rate"]))
name = root.attrib['projname']
ns = { 'ns': 'http://audacity.sourceforge.net/xml/' }
data_dir = os.path.splitext(fpath)[0] + '_data'
if not os.path.isdir(data_dir):
data_dir = ""
def unescape(s):
return html.unescape(s)
output = {
'rate': rate,
'name': unescape(name),
'data_dir': data_dir,
'tracks': []
}
for project_item in root:
tag = project_item.tag.split('}')[1]
if tag == 'wavetrack':
o_track = {
'name': unescape(project_item.attrib['name']),
'channel': int(project_item.attrib['channel']),
'linked': True if project_item.attrib['linked'] == '1' else False,
'mute': True if project_item.attrib['mute'] == '1' else False,
'solo': True if project_item.attrib['solo'] == '1' else False,
'rate': int(project_item.attrib['rate']),
'gain': float(project_item.attrib['gain']),
'pan': float(project_item.attrib['pan']),
'color_index': int(project_item.attrib['colorindex']),
'clips': []
}
output['tracks'].append(o_track)
waveclips = project_item.findall('ns:waveclip', ns)
for waveclip in waveclips:
o_clip = {
'offset': float(waveclip.attrib['offset']),
'color_index': int(waveclip.attrib['colorindex']),
}
o_track['clips'].append(o_clip)
sequence = waveclip.findall('ns:sequence', ns)[0]
o_sequence = {
'max_samples': int(sequence.attrib['maxsamples']),
'sample_format': int(sequence.attrib['sampleformat']),
'numsamples': int(sequence.attrib['numsamples']),
'blocks': []
}
o_clip['sequence'] = o_sequence
for waveblock in sequence.findall('ns:waveblock', ns):
waveblock_start = int(waveblock.attrib['start'])
for block in waveblock:
btag = block.tag.split('}')[1]
if btag == 'simpleblockfile':
o_sequence['blocks'].append({
'type': btag,
'start': waveblock_start,
'len': int(block.attrib['len']),
'filename': unescape(block.attrib['filename']),
'min': float(block.attrib['min']),
'max': float(block.attrib['max']),
'rms': float(block.attrib['rms']),
})
elif btag == 'pcmaliasblockfile':
o_sequence['blocks'].append({
'type': btag,
'start': waveblock_start,
'len': int(block.attrib['aliaslen']),
'file_start': int(block.attrib['aliasstart']),
'filename': unescape(block.attrib['aliasfile']),
'summary_file': block.attrib['summaryfile'],
'channel': int(block.attrib['aliaschannel']),
'min': float(block.attrib['min']),
'max': float(block.attrib['max']),
'rms': float(block.attrib['rms'])
})
elif btag == 'silentblockfile':
o_sequence['blocks'].append({
'type': btag,
'len': int(block.attrib['len'])
})
else:
print("WARNING: Unknown block type: '{0}'".format(btag))
envelope = waveclip.findall('ns:envelope', ns)[0]
points = []
for point in envelope.findall('ns:controlpoint', ns):
points.append({
't': float(point.attrib['t']),
'val': float(point.attrib['val'])
})
o_clip['envelope'] = {
'points': points
}
return output
def convert_au_files_from_audacity_project(project, target_dir):
# This is where most of the conversion happens.
indexed_files = {}
if project['data_dir'] != "":
# Audacity saves its media files under a nested hierarchy,
# I don't quite understand why since files seem to have unique names
for root, dirs, files in os.walk(project['data_dir']):
for name in files:
indexed_files[name] = os.path.join(root, name)
if not os.path.isdir(target_dir):
os.makedirs(target_dir)
tracks = project['tracks']
# TODO Eventually just make an entirely new project dictionary rather than modifying the input one
converted_tracks = []
project['converted_tracks'] = converted_tracks
for track_index, track in enumerate(tracks):
previous_track = None if track_index == 0 else tracks[track_index - 1]
next_track = None if track_index + 1 == len(tracks) else tracks[track_index + 1]
is_stereo_track = False
if track['channel'] == 1:
if previous_track is not None and previous_track['linked']:
# Ignore second channel of a linked stereo track,
# should be handled both in the previous iteration.
# This means a converted project may have less tracks.
continue
elif track['channel'] == 0 and track['linked']:
is_stereo_track = True
converted_track = {
'name': track['name'],
'mute': track['mute'],
'solo': track['solo'],
'rate': track['rate'],
'gain': track['gain'],
'pan': track['pan'],
'color_index': track['color_index'],
}
converted_tracks.append(converted_track)
converted_clips = []
converted_track['converted_clips'] = converted_clips
for clip_index, clip in enumerate(track['clips']):
sequence = clip['sequence']
au_fpaths = [[], []]
converted_numsamples = 0
converted_clip_start = clip['offset'] # In seconds
blocks = sequence['blocks']
clip2 = None
if is_stereo_track:
clip2 = next_track['clips'][clip_index]
if clip2['offset'] != clip['offset']:
print("WARNING: Stereo track has non-aligned clips??")
# Okayyy
clip2 = None
# Convert clip-wise envelopes into a track-wise one
if len(clip['envelope']['points']) > 0:
if 'envelope' not in converted_track:
converted_envelope = { 'points': [] }
converted_track['envelope'] = converted_envelope
else:
converted_envelope = converted_track['envelope']
# Note: points will be sorted once we have gone through all clips
points = clip['envelope']['points']
for p in points:
converted_envelope['points'].append({
't': p['t'],
'val': p['val']
})
# A clip can be made of many different blocks.
# The goal is to process them in order to get one file per clip,
# and then possibly splitting the clip or ignoring blocks.
# Another fun part is joining stereo tracks,
# because they are saved separately
for block_index, block in enumerate(blocks):
btype = block['type']
is_last = block_index + 1 == len(blocks)
is_next_different = not is_last and btype != blocks[block_index + 1]['type']
if btype == 'simpleblockfile' or btype == 'pcmaliasblockfile':
if converted_numsamples == 0:
converted_clip_start = clip['offset'] + block['start'] / project['rate']
converted_numsamples += block['len']
if btype == 'simpleblockfile':
# This is mostly because I assume this rather than knowing it
assert block['filename'].endswith('.au')
block2 = None
if is_stereo_track and clip2 is not None:
for b in clip2['sequence']['blocks']:
if b['start'] == block['start'] and b['len'] == block['len']:
block2 = b
break
if block2 is not None:
src_fpath = indexed_files[block['filename']]
au_fpaths[0].append(src_fpath)
src_fpath2 = indexed_files[block2['filename']]
au_fpaths[1].append(src_fpath2)
else:
src_fpath = indexed_files[block['filename']]
au_fpaths[0].append(src_fpath)
if is_last or is_next_different:
dst_fname = "track{0}_clip{1}.wav".format(track_index, len(converted_clips))
dst_fpath = os.path.join(target_dir, dst_fname)
if os.path.isfile(dst_fpath):
print("Overwriting ", dst_fpath)
# TODO Try to not duplicate files when the .au was re-used.
# We could do this by hashing au_fpaths, and if it's the same then use existing result
samples_in_file = convert_au_files_to_wav(au_fpaths, dst_fpath)
# Check this because there is redundancy, I'm curious if that can fail
if samples_in_file != converted_numsamples:
print("WARNING: Sample count mismatch between what I found in the .aup and the actual files")
print(" .aup: {0}, file: {1}".format(total_samples, converted_numsamples))
converted_clips.append({
'offset': converted_clip_start,
'numsamples': converted_numsamples,
'filename': dst_fpath
})
au_fpaths[0].clear()
au_fpaths[1].clear()
converted_numsamples = 0
elif btype == 'pcmaliasblockfile':
# We don't do anything special regarding stereo, the source file should be fine already
if not is_last:
next_block = blocks[block_index + 1]
if next_block['type'] == 'pcmaliasblockfile':
if next_block['filename'] != block['filename']:
is_next_different = True
if is_last or is_next_different:
converted_clips.append({
'offset': converted_clip_start,
'numsamples': converted_numsamples,
'filename': block['filename'],
'file_start': block['file_start']
})
converted_numsamples = 0
elif btype == 'silentblockfile':
pass # Ignore
else:
print("WARNING: Unsupported block type: '{0}'".format(btype))
# Reorder envelope points by time
if 'envelope' in converted_track:
envelope = converted_track['envelope']
envelope['points'] = sorted(envelope['points'], key=lambda x: x['t'])
def write_rpp_file_from_audacity_project(fpath, project):
audacity_color_to_peakcol = [
0, # 0: Default color in Audacity (blue)
0x013333ff, # 1: Red
0x0133ff33, # 2: Green
0x01222222 # 3: Black
]
def get_file_tag(fname):
ext = os.path.splitext(fname)[1]
if ext == '.wav':
return 'WAVE'
elif ext == 'ogg':
return 'VORBIS'
return ext[1:].upper()
# Audacity saves gain as a linear value, and it turns out Reaper also does
# def linear2db(p_linear)
# return math.log(p_linear) * 8.6858896380650365530225783783321
class RppWriter:
def __init__(self, f):
self.indent_unit = " "
self.indent = ""
self.f = f
def open_block(self, tag, *args):
self.f.write('{0}<{1}'.format(self.indent, tag))
self._args(args)
self.indent += self.indent_unit
def close_block(self):
self.indent = self.indent[:-len(self.indent_unit)]
self.f.write('{0}>\n'.format(self.indent))
def line(self, tag, *args):
self.f.write('{0}{1}'.format(self.indent, tag))
self._args(args)
def _args(self, args):
for v in args:
if type(v) == str:
s = ' "{0}"'# if v.contains(' ') else ' {0}'
self.f.write(s.format(v))
elif type(v) == bool:
self.f.write(' {0}'.format(1 if v else 0))
elif type(v) == uuid.UUID:
self.f.write(' {' + str(v).upper() + '}')
else:
self.f.write(' ' + str(v))
self.f.write('\n')
# One nice thing about Reaper projects is that you can omit things in it,
# it will not complain and just load what it finds, apparently
with open(fpath, 'w', encoding="utf-8") as f:
w = RppWriter(f)
# Arbitrary version, which happens to be mine at time of writing.
# TODO I don't know what the number at the end is
w.open_block('REAPER_PROJECT', 0.1, '5.92/x64', 1534982487)
project_samplerate = int(project['rate'])
w.line('SAMPLERATE', project_samplerate, 0, 0)
for track in project['converted_tracks']:
track_uid = uuid.uuid4()
w.open_block('TRACK', track_uid)
w.line('NAME', track['name'])
w.line('TRACKID', track_uid)
w.line('VOLPAN', track['gain'], track['pan'], -1, -1, 1)
w.line('NCHAN', 2)
w.line('MUTESOLO', track['mute'], track['solo'])
w.line('PEAKCOL', audacity_color_to_peakcol[track['color_index']])
if 'envelope' in track:
w.open_block('VOLENV2')
for point in track['envelope']['points']:
w.line('PT', point['t'], point['val'])
w.close_block()
for clip in track['converted_clips']:
w.open_block('ITEM')
w.line('POSITION', clip['offset'])
# TODO I don't know what these UIDs are
w.line('IGUID', uuid.uuid4())
w.line('GUID', uuid.uuid4())
w.line('NAME', os.path.basename(clip['filename']))
nsamples = clip['numsamples']
item_len_seconds = nsamples / project_samplerate
w.line('LENGTH', item_len_seconds)
if 'file_start' in clip:
w.line('SOFFS', clip['file_start'] / project_samplerate)
w.open_block('SOURCE ' + get_file_tag(clip['filename']))
w.line('FILE', clip['filename'])
w.close_block()
# Note: sources like this can exist:
# <SOURCE SECTION
# LENGTH 3.55565072008221
# STARTPOS 7.40378238649376
# OVERLAP 0.01
# <SOURCE FLAC
# FILE "D:\PROJETS\AUDIO\coproductions\1287\Episodes\Episode 7\foule_armee.flac"
# >
# >
w.close_block()
w.close_block()
w.close_block()
def convert(aup_path):
project = load_audacity_project(aup_path)
# pp = pprint.PrettyPrinter(indent=4)
# pp.pprint(project)
# return
data_dir = os.path.splitext(aup_path)[0] + '_wav_data'
convert_au_files_from_audacity_project(project, data_dir)
rpp_path = os.path.splitext(aup_path)[0] + '.rpp'
write_rpp_file_from_audacity_project(rpp_path, project)
print("Done")
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='Converts Audacity projects into Reaper projects.')
parser.add_argument('audacity_project', metavar='audacity_project', type=str,
help='Path to the Audacity project to convert (.aup file)')
args = parser.parse_args()
convert(args.audacity_project)
| WavWriter | identifier_name |
ipfs.go | package ipfs
import (
"context"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"log"
"os"
"path/filepath"
"strings"
"sync"
"time"
config "github.com/ipfs/go-ipfs-config"
files "github.com/ipfs/go-ipfs-files"
"github.com/ipfs/go-ipfs/core"
"github.com/ipfs/go-ipfs/core/coreapi"
"github.com/ipfs/go-ipfs/core/node/libp2p"
"github.com/ipfs/go-ipfs/plugin/loader"
"github.com/ipfs/go-ipfs/repo/fsrepo"
icore "github.com/ipfs/interface-go-ipfs-core"
ipath "github.com/ipfs/interface-go-ipfs-core/path"
peer "github.com/libp2p/go-libp2p-core/peer"
ma "github.com/multiformats/go-multiaddr"
"github.com/qor/oss"
)
// Config provides configuration for the Ipfs node.
type Config struct {
RootPath string `json:"root_path,omitempty"`
Networking bool `json:"networking,omitempty"`
EncryptedConnnections bool `json:"encrypted_connections,omitempty"`
// Default peers to connect to in multiaddr string format
Peers []string `json:"peers,omitempty"`
// Type of node (full, client, server)
NodeType string `json:"node_type,omitempty"`
// Temp dir for receiving files with Get() operation
TempDir string `json:"temp_dir,omitempty"`
// Datastore config
DataStore json.RawMessage `json:"datastore,omitempty"`
// Address config - same format as ipfs addresses config
Addresses json.RawMessage `json:"addresses,omitempty"`
// Private network flag, indicates will have to generate swarm.key and
// put it into the repo path
// TODO should this be the actual swarm key, or could be a file to load
// or the key used to access vault or some other kind of secret store.
// The key should be writen to file swarm.key in the ipfs repo path
PrivateNetwork bool `json:"private_network,omitempty"`
// The storage strategy 'fs' (filesystem) or 'os' (object store)
// defaults to 'os' object store.
//StorageType string `json:"store,omitempty"`
// TODO other raw message types for ipfs specific configuration, eg. Addresses
}
// Ipfs provides storage interface using IPFS
type Ipfs struct {
// ipfs core api
coreAPI icore.CoreAPI
// Configuration
config *Config
// ipfs node
ipfsNode *core.IpfsNode
}
// New creates a new Ipfs instance
func New(cfg *Config) (*Ipfs, error) {
ipfs := &Ipfs{config: cfg}
// Check root path
if err := ensureDir(cfg.RootPath); err != nil {
return nil, err
}
// Check temp dir path
if err := ensureDir(cfg.TempDir); err != nil {
return nil, err
}
// Create ipfs node base on configuration
if err := ipfs.setupPlugins(cfg.RootPath); err != nil {
return nil, err
}
// Initialize the default ipfs config
// Create a config with default options and a 2048 bit key
defaultCfg, err := config.Init(ioutil.Discard, 2048)
if err != nil {
return nil, err
}
ctx := context.Background()
defaultCfg.Bootstrap = cfg.Peers
// Addressess
if ipfs.config.Addresses != nil {
// Parse any overrides for datastore
var addr config.Addresses
err = json.Unmarshal(ipfs.config.Addresses, &addr)
if err != nil {
return nil, err
}
defaultCfg.Addresses = addr
}
// Write swarm key to repo path
// Create a Temporary Repo
err = ipfs.createRepo(ctx, cfg.RootPath, defaultCfg)
if err != nil {
return nil, fmt.Errorf("failed to create ipfs repo: %s", err)
}
// Create the IPFS node
api, err := ipfs.createNode(ctx, cfg.RootPath)
if err != nil {
return nil, fmt.Errorf("failed to create ipfs node: %s", err)
}
ipfs.coreAPI = api
// connect to configured peers
/**
err = ipfs.connectToPeers(ctx, defaultCfg)
// TODO should only log err
if err != nil {
return nil, fmt.Errorf("failed to connect to bootstrap peers: %v", err)
}
*/
// Create the storage strategy
return ipfs, nil
}
// NodeAddr formats and returns the node identifier for the ipfs node
func (fs *Ipfs) NodeAddr() string {
p := peer.AddrInfo{
ID: fs.ipfsNode.Identity,
Addrs: fs.ipfsNode.PeerHost.Addrs(),
}
addr, err := peer.AddrInfoToP2pAddrs(&p)
if err != nil {
return ""
}
if len(addr) <= 0 {
return ""
}
return addr[0].String()
}
// ensureDir ensures directory at path exist if not creates it.
func ensureDir(path string) (err error) {
if _, err = os.Stat(path); os.IsNotExist(err) |
return err
}
// StorageInterface impl
// Get retrieves object at path and returns as a os.File instance
// path should be ipfs cid. Caller should close file when done
func (fs *Ipfs) Get(path string) (f *os.File, err error) {
// Create output filename from the CID path string
var fname string
fname, err = fs.makeFilename(path)
if err != nil {
return
}
// Return file if exist since content is same
if _, err = os.Stat(fname); os.IsExist(err) {
return os.Open(fname)
}
p := ipath.New(path)
unixfs := fs.coreAPI.Unixfs()
node, err := unixfs.Get(context.Background(), p)
if err != nil {
return nil, err
}
// Write content to filesystem
if err = files.WriteTo(node, fname); err != nil {
return nil, err
}
return os.Open(fname)
}
// GetStream provides a stream for the file at path which should be CID string
func (fs *Ipfs) GetStream(path string) (io.ReadCloser, error) {
p := ipath.New(path)
unixfs := fs.coreAPI.Unixfs()
node, err := unixfs.Get(context.Background(), p)
if err != nil {
return nil, err
}
// node should be files.File
file, ok := node.(files.File)
if !ok {
return nil, fmt.Errorf("path is not a file: '%s'", path)
}
return file, nil
}
// Put implies adding file to ipfs. If reader is nil then assume path references
// the file or directory to add. The file is pinned to prevent GC, when deleted the
// pin is removed.
func (fs *Ipfs) Put(path string, reader io.Reader) (*oss.Object, error) {
// The ipfs file
var node files.Node
if reader == nil {
st, err := os.Stat(path)
if err != nil {
return nil, err
}
node, err = files.NewSerialFile(path, false, st)
if err != nil {
return nil, err
}
} else {
node = files.NewReaderFile(reader)
}
res, err := fs.coreAPI.Unixfs().Add(context.Background(), node)
if err != nil {
return nil, err
}
// Pin the file
p := res.String()
now := time.Now()
ipath := ipath.New(p)
err = fs.coreAPI.Pin().Add(context.Background(), ipath)
return &oss.Object{
Path: p,
Name: strings.Split(p, "/")[2],
LastModified: &now,
StorageInterface: fs,
}, err
}
// Delete removes pinned path so it maybe GC. path should be the
// CID to remove
func (fs *Ipfs) Delete(path string) error {
// Remoe file if on disk and unpinn
if fname, err := fs.makeFilename(path); err == nil {
os.Remove(fname)
}
ipath := ipath.New(path)
return fs.coreAPI.Pin().Rm(context.Background(), ipath)
}
// List the files at directory path (path should be ipfs cid for directory)
func (fs *Ipfs) List(path string) ([]*oss.Object, error) {
dir := ipath.New(path)
entries, err := fs.coreAPI.Unixfs().Ls(context.Background(), dir)
if err != nil {
return nil, err
}
dl := make([]*oss.Object, 0)
now := time.Now()
loop:
for {
select {
case entry, ok := <-entries:
if !ok {
break loop
}
var n string
p := entry.Cid.String()
if strings.HasPrefix(p, "/ipfs/") {
n = strings.Split(p, "/")[2]
} else {
n = p
p = "/ipfs/" + p
}
dl = append(dl, &oss.Object{
Path: p,
Name: n,
LastModified: &now,
StorageInterface: fs,
})
}
}
return dl, nil
}
// GetURL no-op
func (fs *Ipfs) GetURL(path string) (string, error) {
return path, nil
}
// GetEndpoint no-op
func (fs *Ipfs) GetEndpoint() string {
return "/ipfs"
}
// Creates an IPFS node and returns its coreAPI
func (fs *Ipfs) createNode(ctx context.Context, repoPath string) (icore.CoreAPI, error) {
// Open the repo
repo, err := fsrepo.Open(repoPath)
if err != nil {
return nil, err
}
// Construct the node
nodeOptions := &core.BuildCfg{
Online: true,
// This option sets the node to be a full DHT node
// (both fetching and storing DHT Records)
Routing: libp2p.DHTOption,
// Routing: libp2p.DHTClientOption,
// This option sets the node to be a client DHT node (only fetching records)
Repo: repo,
}
node, err := core.NewNode(ctx, nodeOptions)
if err != nil {
return nil, err
}
fs.ipfsNode = node
// Attach the Core API to the constructed node
return coreapi.NewCoreAPI(node)
}
func (fs *Ipfs) setupPlugins(path string) error {
// Load any external plugins if available
plugins, err := loader.NewPluginLoader(path)
if err != nil {
return fmt.Errorf("error loading plugins: %s", err)
}
// Load preloaded and external plugins
if err := plugins.Initialize(); err != nil {
return fmt.Errorf("error initializing plugins: %s", err)
}
if err := plugins.Inject(); err != nil {
// Dont fail on Inject()
// return fmt.Errorf("error initializing plugins: %s", err)
}
return nil
}
// TODO fix this, change default configuration values.
// Will need to add config options.
func (fs *Ipfs) createRepo(ctx context.Context, repoPath string, defaultCfg *config.Config) (err error) {
// Provide specific config modifications from default init.
if fs.config.DataStore != nil {
// Parse any overrides for datastore
var ds config.Datastore
err = json.Unmarshal(fs.config.DataStore, &ds)
if err != nil {
return
}
defaultCfg.Datastore = ds
}
// Create the repo with the config
err = fsrepo.Init(repoPath, defaultCfg)
if err != nil {
return fmt.Errorf("failed to init ipfs node: %s", err)
}
return nil
}
// makeFilename creates filename from ipfs path
func (fs *Ipfs) makeFilename(path string) (string, error) {
paths := strings.Split(path, "/")
if len(paths) == 0 {
return "", fmt.Errorf("path specified does not specify a valid ipfs CID")
}
return filepath.Join(fs.config.TempDir, paths[len(paths)-1]), nil
}
// connectToPeers connects the ipfs node to its peers
func (fs *Ipfs) connectToPeers(ctx context.Context, defaultCfg *config.Config) error {
addrInfos := make(map[peer.ID]*peer.AddrInfo, len(fs.config.Peers))
for _, addrStr := range fs.config.Peers {
addr, err := ma.NewMultiaddr(addrStr)
if err != nil {
return err
}
pii, err := peer.AddrInfoFromP2pAddr(addr)
if err != nil {
return err
}
pi, ok := addrInfos[pii.ID]
if !ok {
pi = &peer.AddrInfo{ID: pii.ID}
addrInfos[pi.ID] = pi
}
pi.Addrs = append(pi.Addrs, pii.Addrs...)
}
var wg sync.WaitGroup
wg.Add(len(addrInfos))
for _, addrInfo := range addrInfos {
go func(addrInfo *peer.AddrInfo) {
defer wg.Done()
err := fs.coreAPI.Swarm().Connect(ctx, *addrInfo)
if err != nil {
// TODO get logger
log.Printf("failed to connect to %s: %s", addrInfo.ID, err)
}
}(addrInfo)
}
wg.Wait()
return nil
}
| {
// Try to make 0700
if err = os.MkdirAll(path, os.ModePerm); err != nil {
return fmt.Errorf("failed to create root dir: %s", path)
}
} | conditional_block |
ipfs.go | package ipfs
import (
"context"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"log"
"os"
"path/filepath"
"strings"
"sync"
"time"
config "github.com/ipfs/go-ipfs-config"
files "github.com/ipfs/go-ipfs-files"
"github.com/ipfs/go-ipfs/core"
"github.com/ipfs/go-ipfs/core/coreapi"
"github.com/ipfs/go-ipfs/core/node/libp2p"
"github.com/ipfs/go-ipfs/plugin/loader"
"github.com/ipfs/go-ipfs/repo/fsrepo"
icore "github.com/ipfs/interface-go-ipfs-core"
ipath "github.com/ipfs/interface-go-ipfs-core/path"
peer "github.com/libp2p/go-libp2p-core/peer"
ma "github.com/multiformats/go-multiaddr"
"github.com/qor/oss"
)
// Config provides configuration for the Ipfs node.
type Config struct {
RootPath string `json:"root_path,omitempty"`
Networking bool `json:"networking,omitempty"`
EncryptedConnnections bool `json:"encrypted_connections,omitempty"`
// Default peers to connect to in multiaddr string format
Peers []string `json:"peers,omitempty"`
// Type of node (full, client, server)
NodeType string `json:"node_type,omitempty"`
// Temp dir for receiving files with Get() operation
TempDir string `json:"temp_dir,omitempty"`
// Datastore config
DataStore json.RawMessage `json:"datastore,omitempty"`
// Address config - same format as ipfs addresses config
Addresses json.RawMessage `json:"addresses,omitempty"`
// Private network flag, indicates will have to generate swarm.key and
// put it into the repo path
// TODO should this be the actual swarm key, or could be a file to load
// or the key used to access vault or some other kind of secret store.
// The key should be writen to file swarm.key in the ipfs repo path
PrivateNetwork bool `json:"private_network,omitempty"`
// The storage strategy 'fs' (filesystem) or 'os' (object store)
// defaults to 'os' object store.
//StorageType string `json:"store,omitempty"`
// TODO other raw message types for ipfs specific configuration, eg. Addresses
}
// Ipfs provides storage interface using IPFS
type Ipfs struct {
// ipfs core api
coreAPI icore.CoreAPI
// Configuration
config *Config
// ipfs node
ipfsNode *core.IpfsNode
}
// New creates a new Ipfs instance
func New(cfg *Config) (*Ipfs, error) {
ipfs := &Ipfs{config: cfg}
| }
// Check temp dir path
if err := ensureDir(cfg.TempDir); err != nil {
return nil, err
}
// Create ipfs node base on configuration
if err := ipfs.setupPlugins(cfg.RootPath); err != nil {
return nil, err
}
// Initialize the default ipfs config
// Create a config with default options and a 2048 bit key
defaultCfg, err := config.Init(ioutil.Discard, 2048)
if err != nil {
return nil, err
}
ctx := context.Background()
defaultCfg.Bootstrap = cfg.Peers
// Addressess
if ipfs.config.Addresses != nil {
// Parse any overrides for datastore
var addr config.Addresses
err = json.Unmarshal(ipfs.config.Addresses, &addr)
if err != nil {
return nil, err
}
defaultCfg.Addresses = addr
}
// Write swarm key to repo path
// Create a Temporary Repo
err = ipfs.createRepo(ctx, cfg.RootPath, defaultCfg)
if err != nil {
return nil, fmt.Errorf("failed to create ipfs repo: %s", err)
}
// Create the IPFS node
api, err := ipfs.createNode(ctx, cfg.RootPath)
if err != nil {
return nil, fmt.Errorf("failed to create ipfs node: %s", err)
}
ipfs.coreAPI = api
// connect to configured peers
/**
err = ipfs.connectToPeers(ctx, defaultCfg)
// TODO should only log err
if err != nil {
return nil, fmt.Errorf("failed to connect to bootstrap peers: %v", err)
}
*/
// Create the storage strategy
return ipfs, nil
}
// NodeAddr formats and returns the node identifier for the ipfs node
func (fs *Ipfs) NodeAddr() string {
p := peer.AddrInfo{
ID: fs.ipfsNode.Identity,
Addrs: fs.ipfsNode.PeerHost.Addrs(),
}
addr, err := peer.AddrInfoToP2pAddrs(&p)
if err != nil {
return ""
}
if len(addr) <= 0 {
return ""
}
return addr[0].String()
}
// ensureDir ensures directory at path exist if not creates it.
func ensureDir(path string) (err error) {
if _, err = os.Stat(path); os.IsNotExist(err) {
// Try to make 0700
if err = os.MkdirAll(path, os.ModePerm); err != nil {
return fmt.Errorf("failed to create root dir: %s", path)
}
}
return err
}
// StorageInterface impl
// Get retrieves object at path and returns as a os.File instance
// path should be ipfs cid. Caller should close file when done
func (fs *Ipfs) Get(path string) (f *os.File, err error) {
// Create output filename from the CID path string
var fname string
fname, err = fs.makeFilename(path)
if err != nil {
return
}
// Return file if exist since content is same
if _, err = os.Stat(fname); os.IsExist(err) {
return os.Open(fname)
}
p := ipath.New(path)
unixfs := fs.coreAPI.Unixfs()
node, err := unixfs.Get(context.Background(), p)
if err != nil {
return nil, err
}
// Write content to filesystem
if err = files.WriteTo(node, fname); err != nil {
return nil, err
}
return os.Open(fname)
}
// GetStream provides a stream for the file at path which should be CID string
func (fs *Ipfs) GetStream(path string) (io.ReadCloser, error) {
p := ipath.New(path)
unixfs := fs.coreAPI.Unixfs()
node, err := unixfs.Get(context.Background(), p)
if err != nil {
return nil, err
}
// node should be files.File
file, ok := node.(files.File)
if !ok {
return nil, fmt.Errorf("path is not a file: '%s'", path)
}
return file, nil
}
// Put implies adding file to ipfs. If reader is nil then assume path references
// the file or directory to add. The file is pinned to prevent GC, when deleted the
// pin is removed.
func (fs *Ipfs) Put(path string, reader io.Reader) (*oss.Object, error) {
// The ipfs file
var node files.Node
if reader == nil {
st, err := os.Stat(path)
if err != nil {
return nil, err
}
node, err = files.NewSerialFile(path, false, st)
if err != nil {
return nil, err
}
} else {
node = files.NewReaderFile(reader)
}
res, err := fs.coreAPI.Unixfs().Add(context.Background(), node)
if err != nil {
return nil, err
}
// Pin the file
p := res.String()
now := time.Now()
ipath := ipath.New(p)
err = fs.coreAPI.Pin().Add(context.Background(), ipath)
return &oss.Object{
Path: p,
Name: strings.Split(p, "/")[2],
LastModified: &now,
StorageInterface: fs,
}, err
}
// Delete removes pinned path so it maybe GC. path should be the
// CID to remove
func (fs *Ipfs) Delete(path string) error {
// Remoe file if on disk and unpinn
if fname, err := fs.makeFilename(path); err == nil {
os.Remove(fname)
}
ipath := ipath.New(path)
return fs.coreAPI.Pin().Rm(context.Background(), ipath)
}
// List the files at directory path (path should be ipfs cid for directory)
func (fs *Ipfs) List(path string) ([]*oss.Object, error) {
dir := ipath.New(path)
entries, err := fs.coreAPI.Unixfs().Ls(context.Background(), dir)
if err != nil {
return nil, err
}
dl := make([]*oss.Object, 0)
now := time.Now()
loop:
for {
select {
case entry, ok := <-entries:
if !ok {
break loop
}
var n string
p := entry.Cid.String()
if strings.HasPrefix(p, "/ipfs/") {
n = strings.Split(p, "/")[2]
} else {
n = p
p = "/ipfs/" + p
}
dl = append(dl, &oss.Object{
Path: p,
Name: n,
LastModified: &now,
StorageInterface: fs,
})
}
}
return dl, nil
}
// GetURL no-op
func (fs *Ipfs) GetURL(path string) (string, error) {
return path, nil
}
// GetEndpoint no-op
func (fs *Ipfs) GetEndpoint() string {
return "/ipfs"
}
// Creates an IPFS node and returns its coreAPI
func (fs *Ipfs) createNode(ctx context.Context, repoPath string) (icore.CoreAPI, error) {
// Open the repo
repo, err := fsrepo.Open(repoPath)
if err != nil {
return nil, err
}
// Construct the node
nodeOptions := &core.BuildCfg{
Online: true,
// This option sets the node to be a full DHT node
// (both fetching and storing DHT Records)
Routing: libp2p.DHTOption,
// Routing: libp2p.DHTClientOption,
// This option sets the node to be a client DHT node (only fetching records)
Repo: repo,
}
node, err := core.NewNode(ctx, nodeOptions)
if err != nil {
return nil, err
}
fs.ipfsNode = node
// Attach the Core API to the constructed node
return coreapi.NewCoreAPI(node)
}
func (fs *Ipfs) setupPlugins(path string) error {
// Load any external plugins if available
plugins, err := loader.NewPluginLoader(path)
if err != nil {
return fmt.Errorf("error loading plugins: %s", err)
}
// Load preloaded and external plugins
if err := plugins.Initialize(); err != nil {
return fmt.Errorf("error initializing plugins: %s", err)
}
if err := plugins.Inject(); err != nil {
// Dont fail on Inject()
// return fmt.Errorf("error initializing plugins: %s", err)
}
return nil
}
// TODO fix this, change default configuration values.
// Will need to add config options.
func (fs *Ipfs) createRepo(ctx context.Context, repoPath string, defaultCfg *config.Config) (err error) {
// Provide specific config modifications from default init.
if fs.config.DataStore != nil {
// Parse any overrides for datastore
var ds config.Datastore
err = json.Unmarshal(fs.config.DataStore, &ds)
if err != nil {
return
}
defaultCfg.Datastore = ds
}
// Create the repo with the config
err = fsrepo.Init(repoPath, defaultCfg)
if err != nil {
return fmt.Errorf("failed to init ipfs node: %s", err)
}
return nil
}
// makeFilename creates filename from ipfs path
func (fs *Ipfs) makeFilename(path string) (string, error) {
paths := strings.Split(path, "/")
if len(paths) == 0 {
return "", fmt.Errorf("path specified does not specify a valid ipfs CID")
}
return filepath.Join(fs.config.TempDir, paths[len(paths)-1]), nil
}
// connectToPeers connects the ipfs node to its peers
func (fs *Ipfs) connectToPeers(ctx context.Context, defaultCfg *config.Config) error {
addrInfos := make(map[peer.ID]*peer.AddrInfo, len(fs.config.Peers))
for _, addrStr := range fs.config.Peers {
addr, err := ma.NewMultiaddr(addrStr)
if err != nil {
return err
}
pii, err := peer.AddrInfoFromP2pAddr(addr)
if err != nil {
return err
}
pi, ok := addrInfos[pii.ID]
if !ok {
pi = &peer.AddrInfo{ID: pii.ID}
addrInfos[pi.ID] = pi
}
pi.Addrs = append(pi.Addrs, pii.Addrs...)
}
var wg sync.WaitGroup
wg.Add(len(addrInfos))
for _, addrInfo := range addrInfos {
go func(addrInfo *peer.AddrInfo) {
defer wg.Done()
err := fs.coreAPI.Swarm().Connect(ctx, *addrInfo)
if err != nil {
// TODO get logger
log.Printf("failed to connect to %s: %s", addrInfo.ID, err)
}
}(addrInfo)
}
wg.Wait()
return nil
} | // Check root path
if err := ensureDir(cfg.RootPath); err != nil {
return nil, err | random_line_split |
ipfs.go | package ipfs
import (
"context"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"log"
"os"
"path/filepath"
"strings"
"sync"
"time"
config "github.com/ipfs/go-ipfs-config"
files "github.com/ipfs/go-ipfs-files"
"github.com/ipfs/go-ipfs/core"
"github.com/ipfs/go-ipfs/core/coreapi"
"github.com/ipfs/go-ipfs/core/node/libp2p"
"github.com/ipfs/go-ipfs/plugin/loader"
"github.com/ipfs/go-ipfs/repo/fsrepo"
icore "github.com/ipfs/interface-go-ipfs-core"
ipath "github.com/ipfs/interface-go-ipfs-core/path"
peer "github.com/libp2p/go-libp2p-core/peer"
ma "github.com/multiformats/go-multiaddr"
"github.com/qor/oss"
)
// Config provides configuration for the Ipfs node.
type Config struct {
RootPath string `json:"root_path,omitempty"`
Networking bool `json:"networking,omitempty"`
EncryptedConnnections bool `json:"encrypted_connections,omitempty"`
// Default peers to connect to in multiaddr string format
Peers []string `json:"peers,omitempty"`
// Type of node (full, client, server)
NodeType string `json:"node_type,omitempty"`
// Temp dir for receiving files with Get() operation
TempDir string `json:"temp_dir,omitempty"`
// Datastore config
DataStore json.RawMessage `json:"datastore,omitempty"`
// Address config - same format as ipfs addresses config
Addresses json.RawMessage `json:"addresses,omitempty"`
// Private network flag, indicates will have to generate swarm.key and
// put it into the repo path
// TODO should this be the actual swarm key, or could be a file to load
// or the key used to access vault or some other kind of secret store.
// The key should be writen to file swarm.key in the ipfs repo path
PrivateNetwork bool `json:"private_network,omitempty"`
// The storage strategy 'fs' (filesystem) or 'os' (object store)
// defaults to 'os' object store.
//StorageType string `json:"store,omitempty"`
// TODO other raw message types for ipfs specific configuration, eg. Addresses
}
// Ipfs provides storage interface using IPFS
type Ipfs struct {
// ipfs core api
coreAPI icore.CoreAPI
// Configuration
config *Config
// ipfs node
ipfsNode *core.IpfsNode
}
// New creates a new Ipfs instance
func New(cfg *Config) (*Ipfs, error) {
ipfs := &Ipfs{config: cfg}
// Check root path
if err := ensureDir(cfg.RootPath); err != nil {
return nil, err
}
// Check temp dir path
if err := ensureDir(cfg.TempDir); err != nil {
return nil, err
}
// Create ipfs node base on configuration
if err := ipfs.setupPlugins(cfg.RootPath); err != nil {
return nil, err
}
// Initialize the default ipfs config
// Create a config with default options and a 2048 bit key
defaultCfg, err := config.Init(ioutil.Discard, 2048)
if err != nil {
return nil, err
}
ctx := context.Background()
defaultCfg.Bootstrap = cfg.Peers
// Addressess
if ipfs.config.Addresses != nil {
// Parse any overrides for datastore
var addr config.Addresses
err = json.Unmarshal(ipfs.config.Addresses, &addr)
if err != nil {
return nil, err
}
defaultCfg.Addresses = addr
}
// Write swarm key to repo path
// Create a Temporary Repo
err = ipfs.createRepo(ctx, cfg.RootPath, defaultCfg)
if err != nil {
return nil, fmt.Errorf("failed to create ipfs repo: %s", err)
}
// Create the IPFS node
api, err := ipfs.createNode(ctx, cfg.RootPath)
if err != nil {
return nil, fmt.Errorf("failed to create ipfs node: %s", err)
}
ipfs.coreAPI = api
// connect to configured peers
/**
err = ipfs.connectToPeers(ctx, defaultCfg)
// TODO should only log err
if err != nil {
return nil, fmt.Errorf("failed to connect to bootstrap peers: %v", err)
}
*/
// Create the storage strategy
return ipfs, nil
}
// NodeAddr formats and returns the node identifier for the ipfs node
func (fs *Ipfs) NodeAddr() string {
p := peer.AddrInfo{
ID: fs.ipfsNode.Identity,
Addrs: fs.ipfsNode.PeerHost.Addrs(),
}
addr, err := peer.AddrInfoToP2pAddrs(&p)
if err != nil {
return ""
}
if len(addr) <= 0 {
return ""
}
return addr[0].String()
}
// ensureDir ensures directory at path exist if not creates it.
func ensureDir(path string) (err error) {
if _, err = os.Stat(path); os.IsNotExist(err) {
// Try to make 0700
if err = os.MkdirAll(path, os.ModePerm); err != nil {
return fmt.Errorf("failed to create root dir: %s", path)
}
}
return err
}
// StorageInterface impl
// Get retrieves object at path and returns as a os.File instance
// path should be ipfs cid. Caller should close file when done
func (fs *Ipfs) Get(path string) (f *os.File, err error) {
// Create output filename from the CID path string
var fname string
fname, err = fs.makeFilename(path)
if err != nil {
return
}
// Return file if exist since content is same
if _, err = os.Stat(fname); os.IsExist(err) {
return os.Open(fname)
}
p := ipath.New(path)
unixfs := fs.coreAPI.Unixfs()
node, err := unixfs.Get(context.Background(), p)
if err != nil {
return nil, err
}
// Write content to filesystem
if err = files.WriteTo(node, fname); err != nil {
return nil, err
}
return os.Open(fname)
}
// GetStream provides a stream for the file at path which should be CID string
func (fs *Ipfs) GetStream(path string) (io.ReadCloser, error) {
p := ipath.New(path)
unixfs := fs.coreAPI.Unixfs()
node, err := unixfs.Get(context.Background(), p)
if err != nil {
return nil, err
}
// node should be files.File
file, ok := node.(files.File)
if !ok {
return nil, fmt.Errorf("path is not a file: '%s'", path)
}
return file, nil
}
// Put implies adding file to ipfs. If reader is nil then assume path references
// the file or directory to add. The file is pinned to prevent GC, when deleted the
// pin is removed.
func (fs *Ipfs) Put(path string, reader io.Reader) (*oss.Object, error) {
// The ipfs file
var node files.Node
if reader == nil {
st, err := os.Stat(path)
if err != nil {
return nil, err
}
node, err = files.NewSerialFile(path, false, st)
if err != nil {
return nil, err
}
} else {
node = files.NewReaderFile(reader)
}
res, err := fs.coreAPI.Unixfs().Add(context.Background(), node)
if err != nil {
return nil, err
}
// Pin the file
p := res.String()
now := time.Now()
ipath := ipath.New(p)
err = fs.coreAPI.Pin().Add(context.Background(), ipath)
return &oss.Object{
Path: p,
Name: strings.Split(p, "/")[2],
LastModified: &now,
StorageInterface: fs,
}, err
}
// Delete removes pinned path so it maybe GC. path should be the
// CID to remove
func (fs *Ipfs) Delete(path string) error {
// Remoe file if on disk and unpinn
if fname, err := fs.makeFilename(path); err == nil {
os.Remove(fname)
}
ipath := ipath.New(path)
return fs.coreAPI.Pin().Rm(context.Background(), ipath)
}
// List the files at directory path (path should be ipfs cid for directory)
func (fs *Ipfs) List(path string) ([]*oss.Object, error) {
dir := ipath.New(path)
entries, err := fs.coreAPI.Unixfs().Ls(context.Background(), dir)
if err != nil {
return nil, err
}
dl := make([]*oss.Object, 0)
now := time.Now()
loop:
for {
select {
case entry, ok := <-entries:
if !ok {
break loop
}
var n string
p := entry.Cid.String()
if strings.HasPrefix(p, "/ipfs/") {
n = strings.Split(p, "/")[2]
} else {
n = p
p = "/ipfs/" + p
}
dl = append(dl, &oss.Object{
Path: p,
Name: n,
LastModified: &now,
StorageInterface: fs,
})
}
}
return dl, nil
}
// GetURL no-op
func (fs *Ipfs) GetURL(path string) (string, error) {
return path, nil
}
// GetEndpoint no-op
func (fs *Ipfs) GetEndpoint() string {
return "/ipfs"
}
// Creates an IPFS node and returns its coreAPI
func (fs *Ipfs) createNode(ctx context.Context, repoPath string) (icore.CoreAPI, error) {
// Open the repo
repo, err := fsrepo.Open(repoPath)
if err != nil {
return nil, err
}
// Construct the node
nodeOptions := &core.BuildCfg{
Online: true,
// This option sets the node to be a full DHT node
// (both fetching and storing DHT Records)
Routing: libp2p.DHTOption,
// Routing: libp2p.DHTClientOption,
// This option sets the node to be a client DHT node (only fetching records)
Repo: repo,
}
node, err := core.NewNode(ctx, nodeOptions)
if err != nil {
return nil, err
}
fs.ipfsNode = node
// Attach the Core API to the constructed node
return coreapi.NewCoreAPI(node)
}
func (fs *Ipfs) setupPlugins(path string) error |
// TODO fix this, change default configuration values.
// Will need to add config options.
func (fs *Ipfs) createRepo(ctx context.Context, repoPath string, defaultCfg *config.Config) (err error) {
// Provide specific config modifications from default init.
if fs.config.DataStore != nil {
// Parse any overrides for datastore
var ds config.Datastore
err = json.Unmarshal(fs.config.DataStore, &ds)
if err != nil {
return
}
defaultCfg.Datastore = ds
}
// Create the repo with the config
err = fsrepo.Init(repoPath, defaultCfg)
if err != nil {
return fmt.Errorf("failed to init ipfs node: %s", err)
}
return nil
}
// makeFilename creates filename from ipfs path
func (fs *Ipfs) makeFilename(path string) (string, error) {
paths := strings.Split(path, "/")
if len(paths) == 0 {
return "", fmt.Errorf("path specified does not specify a valid ipfs CID")
}
return filepath.Join(fs.config.TempDir, paths[len(paths)-1]), nil
}
// connectToPeers connects the ipfs node to its peers
func (fs *Ipfs) connectToPeers(ctx context.Context, defaultCfg *config.Config) error {
addrInfos := make(map[peer.ID]*peer.AddrInfo, len(fs.config.Peers))
for _, addrStr := range fs.config.Peers {
addr, err := ma.NewMultiaddr(addrStr)
if err != nil {
return err
}
pii, err := peer.AddrInfoFromP2pAddr(addr)
if err != nil {
return err
}
pi, ok := addrInfos[pii.ID]
if !ok {
pi = &peer.AddrInfo{ID: pii.ID}
addrInfos[pi.ID] = pi
}
pi.Addrs = append(pi.Addrs, pii.Addrs...)
}
var wg sync.WaitGroup
wg.Add(len(addrInfos))
for _, addrInfo := range addrInfos {
go func(addrInfo *peer.AddrInfo) {
defer wg.Done()
err := fs.coreAPI.Swarm().Connect(ctx, *addrInfo)
if err != nil {
// TODO get logger
log.Printf("failed to connect to %s: %s", addrInfo.ID, err)
}
}(addrInfo)
}
wg.Wait()
return nil
}
| {
// Load any external plugins if available
plugins, err := loader.NewPluginLoader(path)
if err != nil {
return fmt.Errorf("error loading plugins: %s", err)
}
// Load preloaded and external plugins
if err := plugins.Initialize(); err != nil {
return fmt.Errorf("error initializing plugins: %s", err)
}
if err := plugins.Inject(); err != nil {
// Dont fail on Inject()
// return fmt.Errorf("error initializing plugins: %s", err)
}
return nil
} | identifier_body |
ipfs.go | package ipfs
import (
"context"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"log"
"os"
"path/filepath"
"strings"
"sync"
"time"
config "github.com/ipfs/go-ipfs-config"
files "github.com/ipfs/go-ipfs-files"
"github.com/ipfs/go-ipfs/core"
"github.com/ipfs/go-ipfs/core/coreapi"
"github.com/ipfs/go-ipfs/core/node/libp2p"
"github.com/ipfs/go-ipfs/plugin/loader"
"github.com/ipfs/go-ipfs/repo/fsrepo"
icore "github.com/ipfs/interface-go-ipfs-core"
ipath "github.com/ipfs/interface-go-ipfs-core/path"
peer "github.com/libp2p/go-libp2p-core/peer"
ma "github.com/multiformats/go-multiaddr"
"github.com/qor/oss"
)
// Config provides configuration for the Ipfs node.
type Config struct {
RootPath string `json:"root_path,omitempty"`
Networking bool `json:"networking,omitempty"`
EncryptedConnnections bool `json:"encrypted_connections,omitempty"`
// Default peers to connect to in multiaddr string format
Peers []string `json:"peers,omitempty"`
// Type of node (full, client, server)
NodeType string `json:"node_type,omitempty"`
// Temp dir for receiving files with Get() operation
TempDir string `json:"temp_dir,omitempty"`
// Datastore config
DataStore json.RawMessage `json:"datastore,omitempty"`
// Address config - same format as ipfs addresses config
Addresses json.RawMessage `json:"addresses,omitempty"`
// Private network flag, indicates will have to generate swarm.key and
// put it into the repo path
// TODO should this be the actual swarm key, or could be a file to load
// or the key used to access vault or some other kind of secret store.
// The key should be writen to file swarm.key in the ipfs repo path
PrivateNetwork bool `json:"private_network,omitempty"`
// The storage strategy 'fs' (filesystem) or 'os' (object store)
// defaults to 'os' object store.
//StorageType string `json:"store,omitempty"`
// TODO other raw message types for ipfs specific configuration, eg. Addresses
}
// Ipfs provides storage interface using IPFS
type Ipfs struct {
// ipfs core api
coreAPI icore.CoreAPI
// Configuration
config *Config
// ipfs node
ipfsNode *core.IpfsNode
}
// New creates a new Ipfs instance
func New(cfg *Config) (*Ipfs, error) {
ipfs := &Ipfs{config: cfg}
// Check root path
if err := ensureDir(cfg.RootPath); err != nil {
return nil, err
}
// Check temp dir path
if err := ensureDir(cfg.TempDir); err != nil {
return nil, err
}
// Create ipfs node base on configuration
if err := ipfs.setupPlugins(cfg.RootPath); err != nil {
return nil, err
}
// Initialize the default ipfs config
// Create a config with default options and a 2048 bit key
defaultCfg, err := config.Init(ioutil.Discard, 2048)
if err != nil {
return nil, err
}
ctx := context.Background()
defaultCfg.Bootstrap = cfg.Peers
// Addressess
if ipfs.config.Addresses != nil {
// Parse any overrides for datastore
var addr config.Addresses
err = json.Unmarshal(ipfs.config.Addresses, &addr)
if err != nil {
return nil, err
}
defaultCfg.Addresses = addr
}
// Write swarm key to repo path
// Create a Temporary Repo
err = ipfs.createRepo(ctx, cfg.RootPath, defaultCfg)
if err != nil {
return nil, fmt.Errorf("failed to create ipfs repo: %s", err)
}
// Create the IPFS node
api, err := ipfs.createNode(ctx, cfg.RootPath)
if err != nil {
return nil, fmt.Errorf("failed to create ipfs node: %s", err)
}
ipfs.coreAPI = api
// connect to configured peers
/**
err = ipfs.connectToPeers(ctx, defaultCfg)
// TODO should only log err
if err != nil {
return nil, fmt.Errorf("failed to connect to bootstrap peers: %v", err)
}
*/
// Create the storage strategy
return ipfs, nil
}
// NodeAddr formats and returns the node identifier for the ipfs node
func (fs *Ipfs) NodeAddr() string {
p := peer.AddrInfo{
ID: fs.ipfsNode.Identity,
Addrs: fs.ipfsNode.PeerHost.Addrs(),
}
addr, err := peer.AddrInfoToP2pAddrs(&p)
if err != nil {
return ""
}
if len(addr) <= 0 {
return ""
}
return addr[0].String()
}
// ensureDir ensures directory at path exist if not creates it.
func ensureDir(path string) (err error) {
if _, err = os.Stat(path); os.IsNotExist(err) {
// Try to make 0700
if err = os.MkdirAll(path, os.ModePerm); err != nil {
return fmt.Errorf("failed to create root dir: %s", path)
}
}
return err
}
// StorageInterface impl
// Get retrieves object at path and returns as a os.File instance
// path should be ipfs cid. Caller should close file when done
func (fs *Ipfs) Get(path string) (f *os.File, err error) {
// Create output filename from the CID path string
var fname string
fname, err = fs.makeFilename(path)
if err != nil {
return
}
// Return file if exist since content is same
if _, err = os.Stat(fname); os.IsExist(err) {
return os.Open(fname)
}
p := ipath.New(path)
unixfs := fs.coreAPI.Unixfs()
node, err := unixfs.Get(context.Background(), p)
if err != nil {
return nil, err
}
// Write content to filesystem
if err = files.WriteTo(node, fname); err != nil {
return nil, err
}
return os.Open(fname)
}
// GetStream provides a stream for the file at path which should be CID string
func (fs *Ipfs) GetStream(path string) (io.ReadCloser, error) {
p := ipath.New(path)
unixfs := fs.coreAPI.Unixfs()
node, err := unixfs.Get(context.Background(), p)
if err != nil {
return nil, err
}
// node should be files.File
file, ok := node.(files.File)
if !ok {
return nil, fmt.Errorf("path is not a file: '%s'", path)
}
return file, nil
}
// Put implies adding file to ipfs. If reader is nil then assume path references
// the file or directory to add. The file is pinned to prevent GC, when deleted the
// pin is removed.
func (fs *Ipfs) Put(path string, reader io.Reader) (*oss.Object, error) {
// The ipfs file
var node files.Node
if reader == nil {
st, err := os.Stat(path)
if err != nil {
return nil, err
}
node, err = files.NewSerialFile(path, false, st)
if err != nil {
return nil, err
}
} else {
node = files.NewReaderFile(reader)
}
res, err := fs.coreAPI.Unixfs().Add(context.Background(), node)
if err != nil {
return nil, err
}
// Pin the file
p := res.String()
now := time.Now()
ipath := ipath.New(p)
err = fs.coreAPI.Pin().Add(context.Background(), ipath)
return &oss.Object{
Path: p,
Name: strings.Split(p, "/")[2],
LastModified: &now,
StorageInterface: fs,
}, err
}
// Delete removes pinned path so it maybe GC. path should be the
// CID to remove
func (fs *Ipfs) Delete(path string) error {
// Remoe file if on disk and unpinn
if fname, err := fs.makeFilename(path); err == nil {
os.Remove(fname)
}
ipath := ipath.New(path)
return fs.coreAPI.Pin().Rm(context.Background(), ipath)
}
// List the files at directory path (path should be ipfs cid for directory)
func (fs *Ipfs) List(path string) ([]*oss.Object, error) {
dir := ipath.New(path)
entries, err := fs.coreAPI.Unixfs().Ls(context.Background(), dir)
if err != nil {
return nil, err
}
dl := make([]*oss.Object, 0)
now := time.Now()
loop:
for {
select {
case entry, ok := <-entries:
if !ok {
break loop
}
var n string
p := entry.Cid.String()
if strings.HasPrefix(p, "/ipfs/") {
n = strings.Split(p, "/")[2]
} else {
n = p
p = "/ipfs/" + p
}
dl = append(dl, &oss.Object{
Path: p,
Name: n,
LastModified: &now,
StorageInterface: fs,
})
}
}
return dl, nil
}
// GetURL no-op
func (fs *Ipfs) | (path string) (string, error) {
return path, nil
}
// GetEndpoint no-op
func (fs *Ipfs) GetEndpoint() string {
return "/ipfs"
}
// Creates an IPFS node and returns its coreAPI
func (fs *Ipfs) createNode(ctx context.Context, repoPath string) (icore.CoreAPI, error) {
// Open the repo
repo, err := fsrepo.Open(repoPath)
if err != nil {
return nil, err
}
// Construct the node
nodeOptions := &core.BuildCfg{
Online: true,
// This option sets the node to be a full DHT node
// (both fetching and storing DHT Records)
Routing: libp2p.DHTOption,
// Routing: libp2p.DHTClientOption,
// This option sets the node to be a client DHT node (only fetching records)
Repo: repo,
}
node, err := core.NewNode(ctx, nodeOptions)
if err != nil {
return nil, err
}
fs.ipfsNode = node
// Attach the Core API to the constructed node
return coreapi.NewCoreAPI(node)
}
func (fs *Ipfs) setupPlugins(path string) error {
// Load any external plugins if available
plugins, err := loader.NewPluginLoader(path)
if err != nil {
return fmt.Errorf("error loading plugins: %s", err)
}
// Load preloaded and external plugins
if err := plugins.Initialize(); err != nil {
return fmt.Errorf("error initializing plugins: %s", err)
}
if err := plugins.Inject(); err != nil {
// Dont fail on Inject()
// return fmt.Errorf("error initializing plugins: %s", err)
}
return nil
}
// TODO fix this, change default configuration values.
// Will need to add config options.
func (fs *Ipfs) createRepo(ctx context.Context, repoPath string, defaultCfg *config.Config) (err error) {
// Provide specific config modifications from default init.
if fs.config.DataStore != nil {
// Parse any overrides for datastore
var ds config.Datastore
err = json.Unmarshal(fs.config.DataStore, &ds)
if err != nil {
return
}
defaultCfg.Datastore = ds
}
// Create the repo with the config
err = fsrepo.Init(repoPath, defaultCfg)
if err != nil {
return fmt.Errorf("failed to init ipfs node: %s", err)
}
return nil
}
// makeFilename creates filename from ipfs path
func (fs *Ipfs) makeFilename(path string) (string, error) {
paths := strings.Split(path, "/")
if len(paths) == 0 {
return "", fmt.Errorf("path specified does not specify a valid ipfs CID")
}
return filepath.Join(fs.config.TempDir, paths[len(paths)-1]), nil
}
// connectToPeers connects the ipfs node to its peers
func (fs *Ipfs) connectToPeers(ctx context.Context, defaultCfg *config.Config) error {
addrInfos := make(map[peer.ID]*peer.AddrInfo, len(fs.config.Peers))
for _, addrStr := range fs.config.Peers {
addr, err := ma.NewMultiaddr(addrStr)
if err != nil {
return err
}
pii, err := peer.AddrInfoFromP2pAddr(addr)
if err != nil {
return err
}
pi, ok := addrInfos[pii.ID]
if !ok {
pi = &peer.AddrInfo{ID: pii.ID}
addrInfos[pi.ID] = pi
}
pi.Addrs = append(pi.Addrs, pii.Addrs...)
}
var wg sync.WaitGroup
wg.Add(len(addrInfos))
for _, addrInfo := range addrInfos {
go func(addrInfo *peer.AddrInfo) {
defer wg.Done()
err := fs.coreAPI.Swarm().Connect(ctx, *addrInfo)
if err != nil {
// TODO get logger
log.Printf("failed to connect to %s: %s", addrInfo.ID, err)
}
}(addrInfo)
}
wg.Wait()
return nil
}
| GetURL | identifier_name |
tree.py | from typing import List, Tuple, Union, Dict, Any
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from manual_ml.base import BaseModel
from manual_ml.helpers.metrics import accuracy
class Tree(BaseModel):
"""
Binary classification tree
"""
def __init__(self,
min_data: int=2,
max_depth: int =3,
dynamic_bias: bool=True,
bias: float=0.5):
self.params = {'max_depth': max_depth,
'min_data': min_data,
'dynamic_bias': dynamic_bias,
'bias': bias}
self.feature_names = []
self.tree: Dict[str, Any] = None
def | (self,
nodes: List[str]=None,
root: bool=True):
if nodes is None:
nodes = []
if root:
nodes = self.tree
Tree.print_node(nodes)
if nodes['class'] == -1:
self._print(nodes=nodes['l_node'],
root=False)
self._print(nodes=nodes['r_node'],
root=False)
@staticmethod
def print_node(node):
bs =' ' * node['depth'] * 2
bs2 = '-' * 2
print(bs+'|'+bs2+'*' * 50)
print(bs+'|'+bs+node['node_str'])
print(bs+'|'+bs+'Depth:', node['depth'])
print(bs+'|'+bs+'n samples:', node['n'])
if not node['terminal']:
print(bs+'|'+bs+'Name: '+node['name'])
print(bs+'|'+bs+'Split Value:', node['split_val'])
print(bs+'|'+bs+'Gini coeff:', node['gini'])
print(bs+'|'+bs+'Class prop requirement:', node['bias'],
'('+node['biasMode']+')')
print(bs+'|'+bs+'Prop L:', node['prop_l'])
print(bs+'|'+bs+'Prop R:', node['prop_r'])
else:
print(bs+'|'+bs+'Leaf')
print(bs+'|'+bs+node['note'])
def fit(self, x, y, debug=False):
"""
Convert data to matrix if dataframe
Recursively create nodes using tree.buildNodes()
"""
# Set feature names
self.set_names(x)
# Convert to mats if not
x = self.strip_df(x)
y = self.strip_df(y)
self.tree = Tree.build_nodes(x, y,
max_depth=self.params['max_depth'],
min_data=self.params['min_data'],
dynamic_bias=self.params['dynamic_bias'],
debug=debug, names=self.feature_names)
return self
@staticmethod
def build_nodes(x, y, names: List[str],
max_depth: int=2,
min_data: int=2,
dynamic_bias: bool=False,
depth: int=0,
nom_class: int=-777,
bias: float=0.5,
d_str: str= 'Root',
debug: bool=False):
"""
Recursively all branches of nodes. Each branch continues adding nodes until a terminal condition is met.
:param x: Features.
:param y: Labels.
:param names: Feature column names.
:param max_depth: Max branch depth. Default=2.
:param min_data: Min number of observations left to build another node. Default=2.
:param dynamic_bias:
:param depth: Current depth.
:param nom_class:
:param bias:
:param d_str: String name for node.
:param debug:
:return:
"""
if dynamic_bias:
bias = Tree.prop(y)
ds = 'dynamic'
else:
if bias == '':
ds = 'highest'
else:
ds = 'static'
# Add terminal checks here
# If a terminal node, return a node (dict) containing just the class label
# This label is set by highest represented label in subset
if depth > max_depth:
# Too deep: Terminal
cla = Tree.high_class(y, bias)
node = {'class': cla,
'depth': depth,
'note': 'Max depth reached, class is: '+ str(cla),
'terminal': True,
'n': len(x),
'node_str': d_str}
elif x.shape[0] < min_data:
if x.shape[0] == 0:
# Too few data points: Terminal
cla = nom_class
else:
cla = Tree.high_class(y, bias)
node = {'class': cla,
'depth': depth,
'note': f'Too few data points, class is: {cla}',
'terminal': True,
'n': len(x),
'node_str': d_str}
# In this case, y will be empty
# So use nominal class that will be the opposite of the other side node
elif x.shape[1] < 1:
# Too few features: Terminal
cla = Tree.high_class(y, bias)
node = {'class': cla,
'depth': depth,
'note': f'No features remaining, class is: {cla}',
'terminal': True,
'n': len(x),
'node_str': d_str}
elif len(np.unique(y)) == 1:
# Only one class: Terminal
cla = Tree.high_class(y, bias)
node = {'class': cla,
'depth': depth,
'note': f'One class at depth, class is: {cla}',
'terminal': True,
'n': len(x),
'node_str': d_str}
else:
# Not terminal. Build next node.
# First find best split to run
col_idx, best_x, gini = Tree.get_best_split_all(x, y)
# Split into left and right subsets
l_idx = (x[:, col_idx] < best_x).squeeze()
r_idx = (x[:, col_idx] >= best_x).squeeze()
nom_class_l = -999
nom_class_r = -999
if np.sum(l_idx) == 0:
nom_class_l = np.int8(not Tree.high_class(y[r_idx], bias))
if np.sum(r_idx) == 0:
nom_class_r = np.int8(not Tree.high_class(y[l_idx], bias))
# Build next node, leaving out used feature and data not in this split
l_node = Tree.build_nodes(x[l_idx][:, ~col_idx], y[l_idx],
max_depth=max_depth,
min_data=min_data,
depth=depth + 1,
nom_class=nom_class_l,
dynamic_bias=dynamic_bias,
bias=bias,
d_str=d_str + '->L',
names=[n for ni, n in enumerate(names) if ni != np.argmax(col_idx)])
r_node = Tree.build_nodes(x[r_idx][:, ~col_idx], y[r_idx],
max_depth=max_depth,
min_data=min_data,
depth=depth + 1,
nom_class=nom_class_r,
dynamic_bias=dynamic_bias,
bias=bias,
d_str=d_str + '->R',
names=[n for ni, n in enumerate(names) if ni != np.argmax(col_idx)])
# Return a full node containing meta/debug data
# As this isn't a leaf/terminal node, set class to -1
node = {'name': names[np.argmax(col_idx)],
'n': len(x),
'n_l': np.sum(l_idx),
'n_r': np.sum(r_idx),
'l_idx': l_idx,
'r_idx': r_idx,
'split_val': best_x.squeeze(),
'gini': gini.squeeze(),
'depth': depth,
'l_node': l_node,
'r_node': r_node,
'class': -1,
'prop_l': Tree.prop(y[l_idx]),
'prop_r': Tree.prop(y[r_idx]),
'biasMode': ds,
'bias': bias,
'node_str' : d_str,
'terminal': False}
if debug:
Tree.print_node(node)
return node
def predict(self, x) -> np.ndarray:
"""Predict from tree."""
y_pred = x.apply(Tree._predict,
args=(self.tree,),
axis=1)
return y_pred
@staticmethod
def _predict(x, mod) -> np.ndarray:
# If this is a leaf node, return class
if mod['class'] > -1:
return mod['class']
# If this isn't a leaf node, check X against split value
# and follow tree
if x.loc[mod['name']] < mod['split_val']:
# If less than split val, go left
y_pred = Tree._predict(x, mod['l_node'])
else:
# If greater than split val, go right
y_pred = Tree._predict(x, mod['r_node'])
return y_pred
@staticmethod
def gi(groups: Union[List[int], np.array],
classes: Union[List[int], np.array]) -> float:
"""Calculate Gini."""
groups = np.array(groups)
classes = np.array(classes)
# For each group
sum_p = 0.0
for g in np.unique(groups):
# print('G:',g)
g_idx = groups == g
# Calculate and sum class proportions
p = 0.0
# For each class
for c in np.unique(classes):
# print('C:',c)
c_idx = classes[g_idx] == c
# Get proportions and square
# And sum across classes
p += (np.sum(c_idx) / np.sum(g_idx)) ** 2
# print('P:',P)
# Weight by size of group
# And sum across groups
sum_p += (1 - p) * sum(g_idx) / len(g_idx)
return sum_p
@staticmethod
def split(x, y, split_val) -> float:
groups = np.int8(x < split_val)
return Tree.gi(groups, y)
@staticmethod
def get_best_split_all(x, y) -> Tuple[int, float, float]:
"""
This function calculates all splits on all columns
Returns the column index with best split and the values to use
"""
m = x.shape[1]
col_best_gin = np.ones(shape=m)
col_best_val = np.ones(shape=m)
for c in range(m):
best = 1
best_x = 0
for i in np.unique(x[:, c]):
gini = Tree.split(x[:, c], y, i)
if gini < best:
best = gini
best_x = i
col_best_gin[c] = best
col_best_val[c] = best_x
# Select best feature to split on
col_idx = np.argmin(col_best_gin)
# Convert to bool index
col_idx = np.array(range(x.shape[1])) == col_idx
return col_idx, col_best_val[col_idx], col_best_gin[col_idx]
@staticmethod
def prop(y: np.array) -> Union[int, float]:
if np.sum(y) > 0:
return y.sum() / y.shape[0]
else:
return 0
@staticmethod
def high_class(y,
bias: str='') -> int:
if bias == '':
# Just return highest class
return np.argmax(y.value_counts())
else:
# Return logical of class prop>bias
if len(y) > 0:
return np.int8(Tree.prop(y) > bias)
else:
return 0
if __name__ == '__main__':
data = pd.DataFrame({'x1': [2.77, 1.73, 3.68, 3.96, 2.99, 7.50, 9.00, 7.44,
10.12, 6.64],
'x2': [1.78, 1.17, 2.81, 2.62, 2.21, 3.16, 3.34, 0.48,
3.23, 3.32],
'y': [1, 0, 0, 0, 0, 1, 1, 1, 0, 0]})
y = data.y
x = data[['x1', 'x2']]
mod = Tree(max_depth=2,
min_data=2,
dynamic_bias=False)
mod.fit(x, y)
mod._print()
y_pred = mod.predict(x)
accuracy(y, y_pred)
plt.scatter(data.x1[data.y == 0], data.x2[data.y == 0])
plt.scatter(data.x1[data.y == 1], data.x2[data.y == 1])
plt.show()
plt.scatter(data.x1[y_pred == 0], data.x2[y_pred == 0])
plt.scatter(data.x1[y_pred == 1], data.x2[y_pred == 1])
plt.show()
| _print | identifier_name |
tree.py | from typing import List, Tuple, Union, Dict, Any
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from manual_ml.base import BaseModel
from manual_ml.helpers.metrics import accuracy
class Tree(BaseModel):
"""
Binary classification tree
"""
def __init__(self,
min_data: int=2,
max_depth: int =3,
dynamic_bias: bool=True,
bias: float=0.5):
self.params = {'max_depth': max_depth,
'min_data': min_data,
'dynamic_bias': dynamic_bias,
'bias': bias}
self.feature_names = []
self.tree: Dict[str, Any] = None
def _print(self,
nodes: List[str]=None,
root: bool=True):
if nodes is None:
nodes = []
if root:
nodes = self.tree
Tree.print_node(nodes)
if nodes['class'] == -1:
self._print(nodes=nodes['l_node'],
root=False)
self._print(nodes=nodes['r_node'],
root=False)
@staticmethod
def print_node(node):
|
def fit(self, x, y, debug=False):
"""
Convert data to matrix if dataframe
Recursively create nodes using tree.buildNodes()
"""
# Set feature names
self.set_names(x)
# Convert to mats if not
x = self.strip_df(x)
y = self.strip_df(y)
self.tree = Tree.build_nodes(x, y,
max_depth=self.params['max_depth'],
min_data=self.params['min_data'],
dynamic_bias=self.params['dynamic_bias'],
debug=debug, names=self.feature_names)
return self
@staticmethod
def build_nodes(x, y, names: List[str],
max_depth: int=2,
min_data: int=2,
dynamic_bias: bool=False,
depth: int=0,
nom_class: int=-777,
bias: float=0.5,
d_str: str= 'Root',
debug: bool=False):
"""
Recursively all branches of nodes. Each branch continues adding nodes until a terminal condition is met.
:param x: Features.
:param y: Labels.
:param names: Feature column names.
:param max_depth: Max branch depth. Default=2.
:param min_data: Min number of observations left to build another node. Default=2.
:param dynamic_bias:
:param depth: Current depth.
:param nom_class:
:param bias:
:param d_str: String name for node.
:param debug:
:return:
"""
if dynamic_bias:
bias = Tree.prop(y)
ds = 'dynamic'
else:
if bias == '':
ds = 'highest'
else:
ds = 'static'
# Add terminal checks here
# If a terminal node, return a node (dict) containing just the class label
# This label is set by highest represented label in subset
if depth > max_depth:
# Too deep: Terminal
cla = Tree.high_class(y, bias)
node = {'class': cla,
'depth': depth,
'note': 'Max depth reached, class is: '+ str(cla),
'terminal': True,
'n': len(x),
'node_str': d_str}
elif x.shape[0] < min_data:
if x.shape[0] == 0:
# Too few data points: Terminal
cla = nom_class
else:
cla = Tree.high_class(y, bias)
node = {'class': cla,
'depth': depth,
'note': f'Too few data points, class is: {cla}',
'terminal': True,
'n': len(x),
'node_str': d_str}
# In this case, y will be empty
# So use nominal class that will be the opposite of the other side node
elif x.shape[1] < 1:
# Too few features: Terminal
cla = Tree.high_class(y, bias)
node = {'class': cla,
'depth': depth,
'note': f'No features remaining, class is: {cla}',
'terminal': True,
'n': len(x),
'node_str': d_str}
elif len(np.unique(y)) == 1:
# Only one class: Terminal
cla = Tree.high_class(y, bias)
node = {'class': cla,
'depth': depth,
'note': f'One class at depth, class is: {cla}',
'terminal': True,
'n': len(x),
'node_str': d_str}
else:
# Not terminal. Build next node.
# First find best split to run
col_idx, best_x, gini = Tree.get_best_split_all(x, y)
# Split into left and right subsets
l_idx = (x[:, col_idx] < best_x).squeeze()
r_idx = (x[:, col_idx] >= best_x).squeeze()
nom_class_l = -999
nom_class_r = -999
if np.sum(l_idx) == 0:
nom_class_l = np.int8(not Tree.high_class(y[r_idx], bias))
if np.sum(r_idx) == 0:
nom_class_r = np.int8(not Tree.high_class(y[l_idx], bias))
# Build next node, leaving out used feature and data not in this split
l_node = Tree.build_nodes(x[l_idx][:, ~col_idx], y[l_idx],
max_depth=max_depth,
min_data=min_data,
depth=depth + 1,
nom_class=nom_class_l,
dynamic_bias=dynamic_bias,
bias=bias,
d_str=d_str + '->L',
names=[n for ni, n in enumerate(names) if ni != np.argmax(col_idx)])
r_node = Tree.build_nodes(x[r_idx][:, ~col_idx], y[r_idx],
max_depth=max_depth,
min_data=min_data,
depth=depth + 1,
nom_class=nom_class_r,
dynamic_bias=dynamic_bias,
bias=bias,
d_str=d_str + '->R',
names=[n for ni, n in enumerate(names) if ni != np.argmax(col_idx)])
# Return a full node containing meta/debug data
# As this isn't a leaf/terminal node, set class to -1
node = {'name': names[np.argmax(col_idx)],
'n': len(x),
'n_l': np.sum(l_idx),
'n_r': np.sum(r_idx),
'l_idx': l_idx,
'r_idx': r_idx,
'split_val': best_x.squeeze(),
'gini': gini.squeeze(),
'depth': depth,
'l_node': l_node,
'r_node': r_node,
'class': -1,
'prop_l': Tree.prop(y[l_idx]),
'prop_r': Tree.prop(y[r_idx]),
'biasMode': ds,
'bias': bias,
'node_str' : d_str,
'terminal': False}
if debug:
Tree.print_node(node)
return node
def predict(self, x) -> np.ndarray:
"""Predict from tree."""
y_pred = x.apply(Tree._predict,
args=(self.tree,),
axis=1)
return y_pred
@staticmethod
def _predict(x, mod) -> np.ndarray:
# If this is a leaf node, return class
if mod['class'] > -1:
return mod['class']
# If this isn't a leaf node, check X against split value
# and follow tree
if x.loc[mod['name']] < mod['split_val']:
# If less than split val, go left
y_pred = Tree._predict(x, mod['l_node'])
else:
# If greater than split val, go right
y_pred = Tree._predict(x, mod['r_node'])
return y_pred
@staticmethod
def gi(groups: Union[List[int], np.array],
classes: Union[List[int], np.array]) -> float:
"""Calculate Gini."""
groups = np.array(groups)
classes = np.array(classes)
# For each group
sum_p = 0.0
for g in np.unique(groups):
# print('G:',g)
g_idx = groups == g
# Calculate and sum class proportions
p = 0.0
# For each class
for c in np.unique(classes):
# print('C:',c)
c_idx = classes[g_idx] == c
# Get proportions and square
# And sum across classes
p += (np.sum(c_idx) / np.sum(g_idx)) ** 2
# print('P:',P)
# Weight by size of group
# And sum across groups
sum_p += (1 - p) * sum(g_idx) / len(g_idx)
return sum_p
@staticmethod
def split(x, y, split_val) -> float:
groups = np.int8(x < split_val)
return Tree.gi(groups, y)
@staticmethod
def get_best_split_all(x, y) -> Tuple[int, float, float]:
"""
This function calculates all splits on all columns
Returns the column index with best split and the values to use
"""
m = x.shape[1]
col_best_gin = np.ones(shape=m)
col_best_val = np.ones(shape=m)
for c in range(m):
best = 1
best_x = 0
for i in np.unique(x[:, c]):
gini = Tree.split(x[:, c], y, i)
if gini < best:
best = gini
best_x = i
col_best_gin[c] = best
col_best_val[c] = best_x
# Select best feature to split on
col_idx = np.argmin(col_best_gin)
# Convert to bool index
col_idx = np.array(range(x.shape[1])) == col_idx
return col_idx, col_best_val[col_idx], col_best_gin[col_idx]
@staticmethod
def prop(y: np.array) -> Union[int, float]:
if np.sum(y) > 0:
return y.sum() / y.shape[0]
else:
return 0
@staticmethod
def high_class(y,
bias: str='') -> int:
if bias == '':
# Just return highest class
return np.argmax(y.value_counts())
else:
# Return logical of class prop>bias
if len(y) > 0:
return np.int8(Tree.prop(y) > bias)
else:
return 0
if __name__ == '__main__':
data = pd.DataFrame({'x1': [2.77, 1.73, 3.68, 3.96, 2.99, 7.50, 9.00, 7.44,
10.12, 6.64],
'x2': [1.78, 1.17, 2.81, 2.62, 2.21, 3.16, 3.34, 0.48,
3.23, 3.32],
'y': [1, 0, 0, 0, 0, 1, 1, 1, 0, 0]})
y = data.y
x = data[['x1', 'x2']]
mod = Tree(max_depth=2,
min_data=2,
dynamic_bias=False)
mod.fit(x, y)
mod._print()
y_pred = mod.predict(x)
accuracy(y, y_pred)
plt.scatter(data.x1[data.y == 0], data.x2[data.y == 0])
plt.scatter(data.x1[data.y == 1], data.x2[data.y == 1])
plt.show()
plt.scatter(data.x1[y_pred == 0], data.x2[y_pred == 0])
plt.scatter(data.x1[y_pred == 1], data.x2[y_pred == 1])
plt.show()
| bs =' ' * node['depth'] * 2
bs2 = '-' * 2
print(bs+'|'+bs2+'*' * 50)
print(bs+'|'+bs+node['node_str'])
print(bs+'|'+bs+'Depth:', node['depth'])
print(bs+'|'+bs+'n samples:', node['n'])
if not node['terminal']:
print(bs+'|'+bs+'Name: '+node['name'])
print(bs+'|'+bs+'Split Value:', node['split_val'])
print(bs+'|'+bs+'Gini coeff:', node['gini'])
print(bs+'|'+bs+'Class prop requirement:', node['bias'],
'('+node['biasMode']+')')
print(bs+'|'+bs+'Prop L:', node['prop_l'])
print(bs+'|'+bs+'Prop R:', node['prop_r'])
else:
print(bs+'|'+bs+'Leaf')
print(bs+'|'+bs+node['note']) | identifier_body |
tree.py | from typing import List, Tuple, Union, Dict, Any
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from manual_ml.base import BaseModel
from manual_ml.helpers.metrics import accuracy
class Tree(BaseModel):
"""
Binary classification tree
"""
def __init__(self,
min_data: int=2,
max_depth: int =3,
dynamic_bias: bool=True,
bias: float=0.5):
self.params = {'max_depth': max_depth,
'min_data': min_data,
'dynamic_bias': dynamic_bias,
'bias': bias}
self.feature_names = []
self.tree: Dict[str, Any] = None
def _print(self,
nodes: List[str]=None,
root: bool=True):
if nodes is None:
nodes = []
if root:
nodes = self.tree
Tree.print_node(nodes)
if nodes['class'] == -1:
self._print(nodes=nodes['l_node'],
root=False)
self._print(nodes=nodes['r_node'],
root=False)
@staticmethod
def print_node(node):
bs =' ' * node['depth'] * 2
bs2 = '-' * 2
print(bs+'|'+bs2+'*' * 50)
print(bs+'|'+bs+node['node_str'])
print(bs+'|'+bs+'Depth:', node['depth'])
print(bs+'|'+bs+'n samples:', node['n'])
if not node['terminal']:
print(bs+'|'+bs+'Name: '+node['name'])
print(bs+'|'+bs+'Split Value:', node['split_val'])
print(bs+'|'+bs+'Gini coeff:', node['gini'])
print(bs+'|'+bs+'Class prop requirement:', node['bias'],
'('+node['biasMode']+')')
print(bs+'|'+bs+'Prop L:', node['prop_l'])
print(bs+'|'+bs+'Prop R:', node['prop_r'])
else:
print(bs+'|'+bs+'Leaf')
print(bs+'|'+bs+node['note'])
def fit(self, x, y, debug=False):
"""
Convert data to matrix if dataframe
Recursively create nodes using tree.buildNodes()
"""
# Set feature names
self.set_names(x)
# Convert to mats if not
x = self.strip_df(x)
y = self.strip_df(y)
self.tree = Tree.build_nodes(x, y,
max_depth=self.params['max_depth'],
min_data=self.params['min_data'],
dynamic_bias=self.params['dynamic_bias'],
debug=debug, names=self.feature_names)
return self
@staticmethod
def build_nodes(x, y, names: List[str],
max_depth: int=2,
min_data: int=2,
dynamic_bias: bool=False,
depth: int=0,
nom_class: int=-777,
bias: float=0.5,
d_str: str= 'Root',
debug: bool=False):
"""
Recursively all branches of nodes. Each branch continues adding nodes until a terminal condition is met.
:param x: Features.
:param y: Labels.
:param names: Feature column names.
:param max_depth: Max branch depth. Default=2.
:param min_data: Min number of observations left to build another node. Default=2.
:param dynamic_bias:
:param depth: Current depth.
:param nom_class:
:param bias:
:param d_str: String name for node.
:param debug:
:return:
"""
if dynamic_bias:
bias = Tree.prop(y)
ds = 'dynamic'
else:
if bias == '':
ds = 'highest'
else:
ds = 'static'
# Add terminal checks here
# If a terminal node, return a node (dict) containing just the class label
# This label is set by highest represented label in subset
if depth > max_depth:
# Too deep: Terminal
cla = Tree.high_class(y, bias)
node = {'class': cla,
'depth': depth,
'note': 'Max depth reached, class is: '+ str(cla),
'terminal': True,
'n': len(x),
'node_str': d_str}
elif x.shape[0] < min_data:
if x.shape[0] == 0:
# Too few data points: Terminal
cla = nom_class
else:
cla = Tree.high_class(y, bias)
node = {'class': cla,
'depth': depth,
'note': f'Too few data points, class is: {cla}',
'terminal': True,
'n': len(x),
'node_str': d_str}
# In this case, y will be empty
# So use nominal class that will be the opposite of the other side node
elif x.shape[1] < 1:
# Too few features: Terminal
cla = Tree.high_class(y, bias)
node = {'class': cla,
'depth': depth,
'note': f'No features remaining, class is: {cla}',
'terminal': True,
'n': len(x),
'node_str': d_str}
elif len(np.unique(y)) == 1:
# Only one class: Terminal | 'note': f'One class at depth, class is: {cla}',
'terminal': True,
'n': len(x),
'node_str': d_str}
else:
# Not terminal. Build next node.
# First find best split to run
col_idx, best_x, gini = Tree.get_best_split_all(x, y)
# Split into left and right subsets
l_idx = (x[:, col_idx] < best_x).squeeze()
r_idx = (x[:, col_idx] >= best_x).squeeze()
nom_class_l = -999
nom_class_r = -999
if np.sum(l_idx) == 0:
nom_class_l = np.int8(not Tree.high_class(y[r_idx], bias))
if np.sum(r_idx) == 0:
nom_class_r = np.int8(not Tree.high_class(y[l_idx], bias))
# Build next node, leaving out used feature and data not in this split
l_node = Tree.build_nodes(x[l_idx][:, ~col_idx], y[l_idx],
max_depth=max_depth,
min_data=min_data,
depth=depth + 1,
nom_class=nom_class_l,
dynamic_bias=dynamic_bias,
bias=bias,
d_str=d_str + '->L',
names=[n for ni, n in enumerate(names) if ni != np.argmax(col_idx)])
r_node = Tree.build_nodes(x[r_idx][:, ~col_idx], y[r_idx],
max_depth=max_depth,
min_data=min_data,
depth=depth + 1,
nom_class=nom_class_r,
dynamic_bias=dynamic_bias,
bias=bias,
d_str=d_str + '->R',
names=[n for ni, n in enumerate(names) if ni != np.argmax(col_idx)])
# Return a full node containing meta/debug data
# As this isn't a leaf/terminal node, set class to -1
node = {'name': names[np.argmax(col_idx)],
'n': len(x),
'n_l': np.sum(l_idx),
'n_r': np.sum(r_idx),
'l_idx': l_idx,
'r_idx': r_idx,
'split_val': best_x.squeeze(),
'gini': gini.squeeze(),
'depth': depth,
'l_node': l_node,
'r_node': r_node,
'class': -1,
'prop_l': Tree.prop(y[l_idx]),
'prop_r': Tree.prop(y[r_idx]),
'biasMode': ds,
'bias': bias,
'node_str' : d_str,
'terminal': False}
if debug:
Tree.print_node(node)
return node
def predict(self, x) -> np.ndarray:
"""Predict from tree."""
y_pred = x.apply(Tree._predict,
args=(self.tree,),
axis=1)
return y_pred
@staticmethod
def _predict(x, mod) -> np.ndarray:
# If this is a leaf node, return class
if mod['class'] > -1:
return mod['class']
# If this isn't a leaf node, check X against split value
# and follow tree
if x.loc[mod['name']] < mod['split_val']:
# If less than split val, go left
y_pred = Tree._predict(x, mod['l_node'])
else:
# If greater than split val, go right
y_pred = Tree._predict(x, mod['r_node'])
return y_pred
@staticmethod
def gi(groups: Union[List[int], np.array],
classes: Union[List[int], np.array]) -> float:
"""Calculate Gini."""
groups = np.array(groups)
classes = np.array(classes)
# For each group
sum_p = 0.0
for g in np.unique(groups):
# print('G:',g)
g_idx = groups == g
# Calculate and sum class proportions
p = 0.0
# For each class
for c in np.unique(classes):
# print('C:',c)
c_idx = classes[g_idx] == c
# Get proportions and square
# And sum across classes
p += (np.sum(c_idx) / np.sum(g_idx)) ** 2
# print('P:',P)
# Weight by size of group
# And sum across groups
sum_p += (1 - p) * sum(g_idx) / len(g_idx)
return sum_p
@staticmethod
def split(x, y, split_val) -> float:
groups = np.int8(x < split_val)
return Tree.gi(groups, y)
@staticmethod
def get_best_split_all(x, y) -> Tuple[int, float, float]:
"""
This function calculates all splits on all columns
Returns the column index with best split and the values to use
"""
m = x.shape[1]
col_best_gin = np.ones(shape=m)
col_best_val = np.ones(shape=m)
for c in range(m):
best = 1
best_x = 0
for i in np.unique(x[:, c]):
gini = Tree.split(x[:, c], y, i)
if gini < best:
best = gini
best_x = i
col_best_gin[c] = best
col_best_val[c] = best_x
# Select best feature to split on
col_idx = np.argmin(col_best_gin)
# Convert to bool index
col_idx = np.array(range(x.shape[1])) == col_idx
return col_idx, col_best_val[col_idx], col_best_gin[col_idx]
@staticmethod
def prop(y: np.array) -> Union[int, float]:
if np.sum(y) > 0:
return y.sum() / y.shape[0]
else:
return 0
@staticmethod
def high_class(y,
bias: str='') -> int:
if bias == '':
# Just return highest class
return np.argmax(y.value_counts())
else:
# Return logical of class prop>bias
if len(y) > 0:
return np.int8(Tree.prop(y) > bias)
else:
return 0
if __name__ == '__main__':
data = pd.DataFrame({'x1': [2.77, 1.73, 3.68, 3.96, 2.99, 7.50, 9.00, 7.44,
10.12, 6.64],
'x2': [1.78, 1.17, 2.81, 2.62, 2.21, 3.16, 3.34, 0.48,
3.23, 3.32],
'y': [1, 0, 0, 0, 0, 1, 1, 1, 0, 0]})
y = data.y
x = data[['x1', 'x2']]
mod = Tree(max_depth=2,
min_data=2,
dynamic_bias=False)
mod.fit(x, y)
mod._print()
y_pred = mod.predict(x)
accuracy(y, y_pred)
plt.scatter(data.x1[data.y == 0], data.x2[data.y == 0])
plt.scatter(data.x1[data.y == 1], data.x2[data.y == 1])
plt.show()
plt.scatter(data.x1[y_pred == 0], data.x2[y_pred == 0])
plt.scatter(data.x1[y_pred == 1], data.x2[y_pred == 1])
plt.show() | cla = Tree.high_class(y, bias)
node = {'class': cla,
'depth': depth, | random_line_split |
tree.py | from typing import List, Tuple, Union, Dict, Any
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from manual_ml.base import BaseModel
from manual_ml.helpers.metrics import accuracy
class Tree(BaseModel):
"""
Binary classification tree
"""
def __init__(self,
min_data: int=2,
max_depth: int =3,
dynamic_bias: bool=True,
bias: float=0.5):
self.params = {'max_depth': max_depth,
'min_data': min_data,
'dynamic_bias': dynamic_bias,
'bias': bias}
self.feature_names = []
self.tree: Dict[str, Any] = None
def _print(self,
nodes: List[str]=None,
root: bool=True):
if nodes is None:
nodes = []
if root:
nodes = self.tree
Tree.print_node(nodes)
if nodes['class'] == -1:
self._print(nodes=nodes['l_node'],
root=False)
self._print(nodes=nodes['r_node'],
root=False)
@staticmethod
def print_node(node):
bs =' ' * node['depth'] * 2
bs2 = '-' * 2
print(bs+'|'+bs2+'*' * 50)
print(bs+'|'+bs+node['node_str'])
print(bs+'|'+bs+'Depth:', node['depth'])
print(bs+'|'+bs+'n samples:', node['n'])
if not node['terminal']:
print(bs+'|'+bs+'Name: '+node['name'])
print(bs+'|'+bs+'Split Value:', node['split_val'])
print(bs+'|'+bs+'Gini coeff:', node['gini'])
print(bs+'|'+bs+'Class prop requirement:', node['bias'],
'('+node['biasMode']+')')
print(bs+'|'+bs+'Prop L:', node['prop_l'])
print(bs+'|'+bs+'Prop R:', node['prop_r'])
else:
print(bs+'|'+bs+'Leaf')
print(bs+'|'+bs+node['note'])
def fit(self, x, y, debug=False):
"""
Convert data to matrix if dataframe
Recursively create nodes using tree.buildNodes()
"""
# Set feature names
self.set_names(x)
# Convert to mats if not
x = self.strip_df(x)
y = self.strip_df(y)
self.tree = Tree.build_nodes(x, y,
max_depth=self.params['max_depth'],
min_data=self.params['min_data'],
dynamic_bias=self.params['dynamic_bias'],
debug=debug, names=self.feature_names)
return self
@staticmethod
def build_nodes(x, y, names: List[str],
max_depth: int=2,
min_data: int=2,
dynamic_bias: bool=False,
depth: int=0,
nom_class: int=-777,
bias: float=0.5,
d_str: str= 'Root',
debug: bool=False):
"""
Recursively all branches of nodes. Each branch continues adding nodes until a terminal condition is met.
:param x: Features.
:param y: Labels.
:param names: Feature column names.
:param max_depth: Max branch depth. Default=2.
:param min_data: Min number of observations left to build another node. Default=2.
:param dynamic_bias:
:param depth: Current depth.
:param nom_class:
:param bias:
:param d_str: String name for node.
:param debug:
:return:
"""
if dynamic_bias:
bias = Tree.prop(y)
ds = 'dynamic'
else:
if bias == '':
ds = 'highest'
else:
ds = 'static'
# Add terminal checks here
# If a terminal node, return a node (dict) containing just the class label
# This label is set by highest represented label in subset
if depth > max_depth:
# Too deep: Terminal
cla = Tree.high_class(y, bias)
node = {'class': cla,
'depth': depth,
'note': 'Max depth reached, class is: '+ str(cla),
'terminal': True,
'n': len(x),
'node_str': d_str}
elif x.shape[0] < min_data:
if x.shape[0] == 0:
# Too few data points: Terminal
|
else:
cla = Tree.high_class(y, bias)
node = {'class': cla,
'depth': depth,
'note': f'Too few data points, class is: {cla}',
'terminal': True,
'n': len(x),
'node_str': d_str}
# In this case, y will be empty
# So use nominal class that will be the opposite of the other side node
elif x.shape[1] < 1:
# Too few features: Terminal
cla = Tree.high_class(y, bias)
node = {'class': cla,
'depth': depth,
'note': f'No features remaining, class is: {cla}',
'terminal': True,
'n': len(x),
'node_str': d_str}
elif len(np.unique(y)) == 1:
# Only one class: Terminal
cla = Tree.high_class(y, bias)
node = {'class': cla,
'depth': depth,
'note': f'One class at depth, class is: {cla}',
'terminal': True,
'n': len(x),
'node_str': d_str}
else:
# Not terminal. Build next node.
# First find best split to run
col_idx, best_x, gini = Tree.get_best_split_all(x, y)
# Split into left and right subsets
l_idx = (x[:, col_idx] < best_x).squeeze()
r_idx = (x[:, col_idx] >= best_x).squeeze()
nom_class_l = -999
nom_class_r = -999
if np.sum(l_idx) == 0:
nom_class_l = np.int8(not Tree.high_class(y[r_idx], bias))
if np.sum(r_idx) == 0:
nom_class_r = np.int8(not Tree.high_class(y[l_idx], bias))
# Build next node, leaving out used feature and data not in this split
l_node = Tree.build_nodes(x[l_idx][:, ~col_idx], y[l_idx],
max_depth=max_depth,
min_data=min_data,
depth=depth + 1,
nom_class=nom_class_l,
dynamic_bias=dynamic_bias,
bias=bias,
d_str=d_str + '->L',
names=[n for ni, n in enumerate(names) if ni != np.argmax(col_idx)])
r_node = Tree.build_nodes(x[r_idx][:, ~col_idx], y[r_idx],
max_depth=max_depth,
min_data=min_data,
depth=depth + 1,
nom_class=nom_class_r,
dynamic_bias=dynamic_bias,
bias=bias,
d_str=d_str + '->R',
names=[n for ni, n in enumerate(names) if ni != np.argmax(col_idx)])
# Return a full node containing meta/debug data
# As this isn't a leaf/terminal node, set class to -1
node = {'name': names[np.argmax(col_idx)],
'n': len(x),
'n_l': np.sum(l_idx),
'n_r': np.sum(r_idx),
'l_idx': l_idx,
'r_idx': r_idx,
'split_val': best_x.squeeze(),
'gini': gini.squeeze(),
'depth': depth,
'l_node': l_node,
'r_node': r_node,
'class': -1,
'prop_l': Tree.prop(y[l_idx]),
'prop_r': Tree.prop(y[r_idx]),
'biasMode': ds,
'bias': bias,
'node_str' : d_str,
'terminal': False}
if debug:
Tree.print_node(node)
return node
def predict(self, x) -> np.ndarray:
"""Predict from tree."""
y_pred = x.apply(Tree._predict,
args=(self.tree,),
axis=1)
return y_pred
@staticmethod
def _predict(x, mod) -> np.ndarray:
# If this is a leaf node, return class
if mod['class'] > -1:
return mod['class']
# If this isn't a leaf node, check X against split value
# and follow tree
if x.loc[mod['name']] < mod['split_val']:
# If less than split val, go left
y_pred = Tree._predict(x, mod['l_node'])
else:
# If greater than split val, go right
y_pred = Tree._predict(x, mod['r_node'])
return y_pred
@staticmethod
def gi(groups: Union[List[int], np.array],
classes: Union[List[int], np.array]) -> float:
"""Calculate Gini."""
groups = np.array(groups)
classes = np.array(classes)
# For each group
sum_p = 0.0
for g in np.unique(groups):
# print('G:',g)
g_idx = groups == g
# Calculate and sum class proportions
p = 0.0
# For each class
for c in np.unique(classes):
# print('C:',c)
c_idx = classes[g_idx] == c
# Get proportions and square
# And sum across classes
p += (np.sum(c_idx) / np.sum(g_idx)) ** 2
# print('P:',P)
# Weight by size of group
# And sum across groups
sum_p += (1 - p) * sum(g_idx) / len(g_idx)
return sum_p
@staticmethod
def split(x, y, split_val) -> float:
groups = np.int8(x < split_val)
return Tree.gi(groups, y)
@staticmethod
def get_best_split_all(x, y) -> Tuple[int, float, float]:
"""
This function calculates all splits on all columns
Returns the column index with best split and the values to use
"""
m = x.shape[1]
col_best_gin = np.ones(shape=m)
col_best_val = np.ones(shape=m)
for c in range(m):
best = 1
best_x = 0
for i in np.unique(x[:, c]):
gini = Tree.split(x[:, c], y, i)
if gini < best:
best = gini
best_x = i
col_best_gin[c] = best
col_best_val[c] = best_x
# Select best feature to split on
col_idx = np.argmin(col_best_gin)
# Convert to bool index
col_idx = np.array(range(x.shape[1])) == col_idx
return col_idx, col_best_val[col_idx], col_best_gin[col_idx]
@staticmethod
def prop(y: np.array) -> Union[int, float]:
if np.sum(y) > 0:
return y.sum() / y.shape[0]
else:
return 0
@staticmethod
def high_class(y,
bias: str='') -> int:
if bias == '':
# Just return highest class
return np.argmax(y.value_counts())
else:
# Return logical of class prop>bias
if len(y) > 0:
return np.int8(Tree.prop(y) > bias)
else:
return 0
if __name__ == '__main__':
data = pd.DataFrame({'x1': [2.77, 1.73, 3.68, 3.96, 2.99, 7.50, 9.00, 7.44,
10.12, 6.64],
'x2': [1.78, 1.17, 2.81, 2.62, 2.21, 3.16, 3.34, 0.48,
3.23, 3.32],
'y': [1, 0, 0, 0, 0, 1, 1, 1, 0, 0]})
y = data.y
x = data[['x1', 'x2']]
mod = Tree(max_depth=2,
min_data=2,
dynamic_bias=False)
mod.fit(x, y)
mod._print()
y_pred = mod.predict(x)
accuracy(y, y_pred)
plt.scatter(data.x1[data.y == 0], data.x2[data.y == 0])
plt.scatter(data.x1[data.y == 1], data.x2[data.y == 1])
plt.show()
plt.scatter(data.x1[y_pred == 0], data.x2[y_pred == 0])
plt.scatter(data.x1[y_pred == 1], data.x2[y_pred == 1])
plt.show()
| cla = nom_class | conditional_block |
opt.rs | //! CLI argument handling
use anyhow::Result;
use cargo::core::resolver::CliFeatures;
use cargo::ops::Packages;
use std::fmt;
use std::path::PathBuf;
use structopt::StructOpt;
#[derive(StructOpt)]
#[structopt(bin_name = "cargo")]
pub(crate) enum Cli {
/// Profile a binary with Xcode Instruments.
///
/// By default, cargo-instruments will build your main binary.
#[structopt(
name = "instruments",
after_help = "EXAMPLE:\n cargo instruments -t time Profile main binary with the (recommended) Time Profiler."
)]
Instruments(AppConfig),
}
#[derive(Debug, StructOpt)]
#[structopt(setting = structopt::clap::AppSettings::TrailingVarArg)]
pub(crate) struct AppConfig {
/// List available templates
#[structopt(short = "l", long)]
pub(crate) list_templates: bool,
/// Specify the instruments template to run
///
/// To see available templates, pass `--list-templates`.
#[structopt(
short = "t",
long = "template",
value_name = "TEMPLATE",
required_unless = "list-templates"
)]
pub(crate) template_name: Option<String>,
/// Specify package for example/bin/bench
///
/// For package that has only one bin, it's the same as `--bin PACKAGE_NAME`
#[structopt(short = "p", long, value_name = "NAME")]
package: Option<String>,
/// Example binary to run
#[structopt(long, group = "target", value_name = "NAME")]
example: Option<String>,
/// Binary to run
#[structopt(long, group = "target", value_name = "NAME")]
bin: Option<String>,
/// Benchmark target to run
#[structopt(long, group = "target", value_name = "NAME")]
bench: Option<String>,
/// Pass --release to cargo
#[structopt(long, conflicts_with = "profile")]
release: bool,
/// Pass --profile NAME to cargo
#[structopt(long, value_name = "NAME")]
profile: Option<String>,
/// Output .trace file to the given path
///
/// Defaults to `target/instruments/{name}_{template-name}_{date}.trace`.
///
/// If the file already exists, a new Run will be added.
#[structopt(short = "o", long = "output", value_name = "PATH", parse(from_os_str))]
pub(crate) trace_filepath: Option<PathBuf>,
/// Limit recording time to the specified value (in milliseconds)
///
/// The program will be terminated after this limit is exceeded.
#[structopt(long, value_name = "MILLIS")]
pub(crate) time_limit: Option<usize>,
/// Open the generated .trace file after profiling
///
/// The trace file will open in Xcode Instruments.
#[structopt(long, hidden = true)]
pub(crate) open: bool,
/// Do not open the generated trace file in Instruments.app.
#[structopt(long)]
pub(crate) no_open: bool,
/// Features to pass to cargo.
#[structopt(long, value_name = "CARGO-FEATURES")]
pub(crate) features: Option<String>,
/// Path to Cargo.toml
#[structopt(long, value_name = "PATH")]
pub(crate) manifest_path: Option<PathBuf>,
/// Activate all features for the selected target.
#[structopt(long, display_order = 1001)]
pub(crate) all_features: bool,
/// Do not activate the default features for the selected target
#[structopt(long, display_order = 1001)]
pub(crate) no_default_features: bool,
/// Arguments passed to the target binary.
///
/// To pass flags, precede child args with `--`,
/// e.g. `cargo instruments -- -t test1.txt --slow-mode`.
#[structopt(value_name = "ARGS")]
pub(crate) target_args: Vec<String>,
}
/// Represents the kind of target to profile.
#[derive(Debug, PartialEq)]
pub(crate) enum Target {
Main,
Example(String),
Bin(String),
Bench(String),
}
/// The package in which to look for the specified target (example/bin/bench)
#[derive(Clone, Debug, PartialEq)]
pub(crate) enum Package {
Default,
Package(String),
}
impl From<Package> for Packages {
fn from(p: Package) -> Self {
match p {
Package::Default => Packages::Default,
Package::Package(s) => Packages::Packages(vec![s]),
}
}
}
impl fmt::Display for Package {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
Package::Default => {
write!(f, "Default: search all packages for example/bin/bench")
}
Package::Package(s) => write!(f, "{}", s),
}
}
}
impl fmt::Display for Target {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
Target::Main => write!(f, "src/main.rs"),
Target::Example(bin) => write!(f, "examples/{}.rs", bin),
Target::Bin(bin) => write!(f, "bin/{}.rs", bin),
Target::Bench(bench) => write!(f, "bench {}", bench),
}
}
}
/// Cargo-specific options
pub(crate) struct CargoOpts {
pub(crate) package: Package,
pub(crate) target: Target,
pub(crate) profile: String,
pub(crate) features: CliFeatures,
}
impl AppConfig {
pub(crate) fn to_cargo_opts(&self) -> Result<CargoOpts> {
let package = self.get_package();
let target = self.get_target();
let features = self.features.clone().map(|s| vec![s]).unwrap_or_default();
let features = CliFeatures::from_command_line(
&features,
self.all_features,
!self.no_default_features,
)?;
let profile = self
.profile
.clone()
.unwrap_or_else(|| (if self.release { "release" } else { "dev" }).to_owned());
Ok(CargoOpts { package, target, profile, features })
}
fn | (&self) -> Package {
if let Some(ref package) = self.package {
Package::Package(package.clone())
} else {
Package::Default
}
}
// valid target: --example, --bin, --bench
fn get_target(&self) -> Target {
if let Some(ref example) = self.example {
Target::Example(example.clone())
} else if let Some(ref bin) = self.bin {
Target::Bin(bin.clone())
} else if let Some(ref bench) = self.bench {
Target::Bench(bench.clone())
} else {
Target::Main
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn defaults() {
let opts = AppConfig::from_iter(&["instruments", "-t", "template"]);
assert!(opts.example.is_none());
assert!(opts.bin.is_none());
assert!(!opts.release);
assert!(opts.trace_filepath.is_none());
assert!(opts.package.is_none());
assert!(opts.manifest_path.is_none());
}
#[test]
fn package_is_given() {
let opts =
AppConfig::from_iter(&["instruments", "--package", "foo", "--template", "alloc"]);
assert!(opts.example.is_none());
assert!(opts.bin.is_none());
assert!(opts.bench.is_none());
assert_eq!(opts.package.unwrap().as_str(), "foo");
let opts = AppConfig::from_iter(&[
"instruments",
"--package",
"foo",
"--template",
"alloc",
"--bin",
"bin_arg",
]);
assert!(opts.example.is_none());
assert!(opts.bench.is_none());
assert_eq!(opts.bin.unwrap().as_str(), "bin_arg");
assert_eq!(opts.package.unwrap().as_str(), "foo");
}
#[test]
#[should_panic(expected = "cannot be used with one or more of the other")]
fn group_is_exclusive() {
let opts = AppConfig::from_iter(&["instruments", "-t", "time", "--bin", "bin_arg"]);
assert!(opts.example.is_none());
assert_eq!(opts.bin.unwrap().as_str(), "bin_arg");
let opts =
AppConfig::from_iter(&["instruments", "-t", "time", "--example", "example_binary"]);
assert!(opts.bin.is_none());
assert_eq!(opts.example.unwrap().as_str(), "example_binary");
let _opts = AppConfig::from_iter_safe(&[
"instruments",
"-t",
"time",
"--bin",
"thing",
"--example",
"other",
])
.unwrap();
}
#[test]
fn limit_millis() {
let opts = AppConfig::from_iter(&["instruments", "-t", "time", "--time-limit", "42000"]);
assert_eq!(opts.time_limit, Some(42000));
let opts = AppConfig::from_iter(&["instruments", "-t", "time", "--time-limit", "808"]);
assert_eq!(opts.time_limit, Some(808));
let opts = AppConfig::from_iter(&["instruments", "-t", "time"]);
assert_eq!(opts.time_limit, None);
}
#[test]
fn features() {
let opts = &[
"instruments",
"--template",
"time",
"--example",
"hello",
"--features",
"svg im",
"--",
"hi",
];
let opts = AppConfig::from_iter(opts);
assert_eq!(opts.template_name, Some("time".into()));
assert_eq!(opts.example, Some("hello".to_string()));
assert_eq!(opts.features, Some("svg im".to_string()));
let features: Vec<_> = opts
.to_cargo_opts()
.unwrap()
.features
.features
.iter()
.map(|feat| feat.to_string())
.collect();
assert_eq!(features, vec!["im", "svg"]);
}
#[test]
fn var_args() {
let opts = AppConfig::from_iter(&[
"instruments",
"-t",
"alloc",
"--time-limit",
"808",
"--",
"hi",
"-h",
"--bin",
]);
assert_eq!(opts.template_name, Some("alloc".into()));
assert_eq!(opts.time_limit, Some(808));
assert_eq!(opts.target_args, vec!["hi", "-h", "--bin"]);
}
#[test]
fn manifest_path() {
let opts = AppConfig::from_iter(&[
"instruments",
"--manifest-path",
"/path/to/Cargo.toml",
"--template",
"alloc",
]);
assert!(opts.example.is_none());
assert!(opts.bin.is_none());
assert!(opts.bench.is_none());
assert!(opts.package.is_none());
assert_eq!(opts.manifest_path.unwrap(), PathBuf::from("/path/to/Cargo.toml"));
}
}
| get_package | identifier_name |
opt.rs | //! CLI argument handling
use anyhow::Result;
use cargo::core::resolver::CliFeatures;
use cargo::ops::Packages;
use std::fmt;
use std::path::PathBuf;
use structopt::StructOpt;
#[derive(StructOpt)]
#[structopt(bin_name = "cargo")]
pub(crate) enum Cli {
/// Profile a binary with Xcode Instruments.
///
/// By default, cargo-instruments will build your main binary.
#[structopt(
name = "instruments",
after_help = "EXAMPLE:\n cargo instruments -t time Profile main binary with the (recommended) Time Profiler."
)]
Instruments(AppConfig),
}
#[derive(Debug, StructOpt)]
#[structopt(setting = structopt::clap::AppSettings::TrailingVarArg)]
pub(crate) struct AppConfig {
/// List available templates
#[structopt(short = "l", long)]
pub(crate) list_templates: bool,
/// Specify the instruments template to run
///
/// To see available templates, pass `--list-templates`.
#[structopt(
short = "t",
long = "template",
value_name = "TEMPLATE",
required_unless = "list-templates"
)]
pub(crate) template_name: Option<String>,
/// Specify package for example/bin/bench
///
/// For package that has only one bin, it's the same as `--bin PACKAGE_NAME`
#[structopt(short = "p", long, value_name = "NAME")]
package: Option<String>,
/// Example binary to run
#[structopt(long, group = "target", value_name = "NAME")]
example: Option<String>,
/// Binary to run
#[structopt(long, group = "target", value_name = "NAME")]
bin: Option<String>,
/// Benchmark target to run
#[structopt(long, group = "target", value_name = "NAME")]
bench: Option<String>,
/// Pass --release to cargo
#[structopt(long, conflicts_with = "profile")]
release: bool,
/// Pass --profile NAME to cargo
#[structopt(long, value_name = "NAME")]
profile: Option<String>,
/// Output .trace file to the given path
///
/// Defaults to `target/instruments/{name}_{template-name}_{date}.trace`.
///
/// If the file already exists, a new Run will be added.
#[structopt(short = "o", long = "output", value_name = "PATH", parse(from_os_str))]
pub(crate) trace_filepath: Option<PathBuf>,
/// Limit recording time to the specified value (in milliseconds)
///
/// The program will be terminated after this limit is exceeded.
#[structopt(long, value_name = "MILLIS")]
pub(crate) time_limit: Option<usize>,
/// Open the generated .trace file after profiling
///
/// The trace file will open in Xcode Instruments.
#[structopt(long, hidden = true)]
pub(crate) open: bool,
/// Do not open the generated trace file in Instruments.app.
#[structopt(long)]
pub(crate) no_open: bool,
/// Features to pass to cargo.
#[structopt(long, value_name = "CARGO-FEATURES")]
pub(crate) features: Option<String>,
/// Path to Cargo.toml
#[structopt(long, value_name = "PATH")]
pub(crate) manifest_path: Option<PathBuf>,
/// Activate all features for the selected target.
#[structopt(long, display_order = 1001)]
pub(crate) all_features: bool,
/// Do not activate the default features for the selected target
#[structopt(long, display_order = 1001)]
pub(crate) no_default_features: bool,
/// Arguments passed to the target binary.
///
/// To pass flags, precede child args with `--`,
/// e.g. `cargo instruments -- -t test1.txt --slow-mode`.
#[structopt(value_name = "ARGS")]
pub(crate) target_args: Vec<String>,
}
/// Represents the kind of target to profile.
#[derive(Debug, PartialEq)]
pub(crate) enum Target {
Main,
Example(String),
Bin(String),
Bench(String),
}
/// The package in which to look for the specified target (example/bin/bench)
#[derive(Clone, Debug, PartialEq)]
pub(crate) enum Package {
Default,
Package(String),
}
impl From<Package> for Packages {
fn from(p: Package) -> Self |
}
impl fmt::Display for Package {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
Package::Default => {
write!(f, "Default: search all packages for example/bin/bench")
}
Package::Package(s) => write!(f, "{}", s),
}
}
}
impl fmt::Display for Target {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
Target::Main => write!(f, "src/main.rs"),
Target::Example(bin) => write!(f, "examples/{}.rs", bin),
Target::Bin(bin) => write!(f, "bin/{}.rs", bin),
Target::Bench(bench) => write!(f, "bench {}", bench),
}
}
}
/// Cargo-specific options
pub(crate) struct CargoOpts {
pub(crate) package: Package,
pub(crate) target: Target,
pub(crate) profile: String,
pub(crate) features: CliFeatures,
}
impl AppConfig {
pub(crate) fn to_cargo_opts(&self) -> Result<CargoOpts> {
let package = self.get_package();
let target = self.get_target();
let features = self.features.clone().map(|s| vec![s]).unwrap_or_default();
let features = CliFeatures::from_command_line(
&features,
self.all_features,
!self.no_default_features,
)?;
let profile = self
.profile
.clone()
.unwrap_or_else(|| (if self.release { "release" } else { "dev" }).to_owned());
Ok(CargoOpts { package, target, profile, features })
}
fn get_package(&self) -> Package {
if let Some(ref package) = self.package {
Package::Package(package.clone())
} else {
Package::Default
}
}
// valid target: --example, --bin, --bench
fn get_target(&self) -> Target {
if let Some(ref example) = self.example {
Target::Example(example.clone())
} else if let Some(ref bin) = self.bin {
Target::Bin(bin.clone())
} else if let Some(ref bench) = self.bench {
Target::Bench(bench.clone())
} else {
Target::Main
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn defaults() {
let opts = AppConfig::from_iter(&["instruments", "-t", "template"]);
assert!(opts.example.is_none());
assert!(opts.bin.is_none());
assert!(!opts.release);
assert!(opts.trace_filepath.is_none());
assert!(opts.package.is_none());
assert!(opts.manifest_path.is_none());
}
#[test]
fn package_is_given() {
let opts =
AppConfig::from_iter(&["instruments", "--package", "foo", "--template", "alloc"]);
assert!(opts.example.is_none());
assert!(opts.bin.is_none());
assert!(opts.bench.is_none());
assert_eq!(opts.package.unwrap().as_str(), "foo");
let opts = AppConfig::from_iter(&[
"instruments",
"--package",
"foo",
"--template",
"alloc",
"--bin",
"bin_arg",
]);
assert!(opts.example.is_none());
assert!(opts.bench.is_none());
assert_eq!(opts.bin.unwrap().as_str(), "bin_arg");
assert_eq!(opts.package.unwrap().as_str(), "foo");
}
#[test]
#[should_panic(expected = "cannot be used with one or more of the other")]
fn group_is_exclusive() {
let opts = AppConfig::from_iter(&["instruments", "-t", "time", "--bin", "bin_arg"]);
assert!(opts.example.is_none());
assert_eq!(opts.bin.unwrap().as_str(), "bin_arg");
let opts =
AppConfig::from_iter(&["instruments", "-t", "time", "--example", "example_binary"]);
assert!(opts.bin.is_none());
assert_eq!(opts.example.unwrap().as_str(), "example_binary");
let _opts = AppConfig::from_iter_safe(&[
"instruments",
"-t",
"time",
"--bin",
"thing",
"--example",
"other",
])
.unwrap();
}
#[test]
fn limit_millis() {
let opts = AppConfig::from_iter(&["instruments", "-t", "time", "--time-limit", "42000"]);
assert_eq!(opts.time_limit, Some(42000));
let opts = AppConfig::from_iter(&["instruments", "-t", "time", "--time-limit", "808"]);
assert_eq!(opts.time_limit, Some(808));
let opts = AppConfig::from_iter(&["instruments", "-t", "time"]);
assert_eq!(opts.time_limit, None);
}
#[test]
fn features() {
let opts = &[
"instruments",
"--template",
"time",
"--example",
"hello",
"--features",
"svg im",
"--",
"hi",
];
let opts = AppConfig::from_iter(opts);
assert_eq!(opts.template_name, Some("time".into()));
assert_eq!(opts.example, Some("hello".to_string()));
assert_eq!(opts.features, Some("svg im".to_string()));
let features: Vec<_> = opts
.to_cargo_opts()
.unwrap()
.features
.features
.iter()
.map(|feat| feat.to_string())
.collect();
assert_eq!(features, vec!["im", "svg"]);
}
#[test]
fn var_args() {
let opts = AppConfig::from_iter(&[
"instruments",
"-t",
"alloc",
"--time-limit",
"808",
"--",
"hi",
"-h",
"--bin",
]);
assert_eq!(opts.template_name, Some("alloc".into()));
assert_eq!(opts.time_limit, Some(808));
assert_eq!(opts.target_args, vec!["hi", "-h", "--bin"]);
}
#[test]
fn manifest_path() {
let opts = AppConfig::from_iter(&[
"instruments",
"--manifest-path",
"/path/to/Cargo.toml",
"--template",
"alloc",
]);
assert!(opts.example.is_none());
assert!(opts.bin.is_none());
assert!(opts.bench.is_none());
assert!(opts.package.is_none());
assert_eq!(opts.manifest_path.unwrap(), PathBuf::from("/path/to/Cargo.toml"));
}
}
| {
match p {
Package::Default => Packages::Default,
Package::Package(s) => Packages::Packages(vec![s]),
}
} | identifier_body |
opt.rs | //! CLI argument handling
use anyhow::Result;
use cargo::core::resolver::CliFeatures;
use cargo::ops::Packages;
use std::fmt;
use std::path::PathBuf;
use structopt::StructOpt;
#[derive(StructOpt)]
#[structopt(bin_name = "cargo")]
pub(crate) enum Cli {
/// Profile a binary with Xcode Instruments.
///
/// By default, cargo-instruments will build your main binary.
#[structopt(
name = "instruments",
after_help = "EXAMPLE:\n cargo instruments -t time Profile main binary with the (recommended) Time Profiler." |
#[derive(Debug, StructOpt)]
#[structopt(setting = structopt::clap::AppSettings::TrailingVarArg)]
pub(crate) struct AppConfig {
/// List available templates
#[structopt(short = "l", long)]
pub(crate) list_templates: bool,
/// Specify the instruments template to run
///
/// To see available templates, pass `--list-templates`.
#[structopt(
short = "t",
long = "template",
value_name = "TEMPLATE",
required_unless = "list-templates"
)]
pub(crate) template_name: Option<String>,
/// Specify package for example/bin/bench
///
/// For package that has only one bin, it's the same as `--bin PACKAGE_NAME`
#[structopt(short = "p", long, value_name = "NAME")]
package: Option<String>,
/// Example binary to run
#[structopt(long, group = "target", value_name = "NAME")]
example: Option<String>,
/// Binary to run
#[structopt(long, group = "target", value_name = "NAME")]
bin: Option<String>,
/// Benchmark target to run
#[structopt(long, group = "target", value_name = "NAME")]
bench: Option<String>,
/// Pass --release to cargo
#[structopt(long, conflicts_with = "profile")]
release: bool,
/// Pass --profile NAME to cargo
#[structopt(long, value_name = "NAME")]
profile: Option<String>,
/// Output .trace file to the given path
///
/// Defaults to `target/instruments/{name}_{template-name}_{date}.trace`.
///
/// If the file already exists, a new Run will be added.
#[structopt(short = "o", long = "output", value_name = "PATH", parse(from_os_str))]
pub(crate) trace_filepath: Option<PathBuf>,
/// Limit recording time to the specified value (in milliseconds)
///
/// The program will be terminated after this limit is exceeded.
#[structopt(long, value_name = "MILLIS")]
pub(crate) time_limit: Option<usize>,
/// Open the generated .trace file after profiling
///
/// The trace file will open in Xcode Instruments.
#[structopt(long, hidden = true)]
pub(crate) open: bool,
/// Do not open the generated trace file in Instruments.app.
#[structopt(long)]
pub(crate) no_open: bool,
/// Features to pass to cargo.
#[structopt(long, value_name = "CARGO-FEATURES")]
pub(crate) features: Option<String>,
/// Path to Cargo.toml
#[structopt(long, value_name = "PATH")]
pub(crate) manifest_path: Option<PathBuf>,
/// Activate all features for the selected target.
#[structopt(long, display_order = 1001)]
pub(crate) all_features: bool,
/// Do not activate the default features for the selected target
#[structopt(long, display_order = 1001)]
pub(crate) no_default_features: bool,
/// Arguments passed to the target binary.
///
/// To pass flags, precede child args with `--`,
/// e.g. `cargo instruments -- -t test1.txt --slow-mode`.
#[structopt(value_name = "ARGS")]
pub(crate) target_args: Vec<String>,
}
/// Represents the kind of target to profile.
#[derive(Debug, PartialEq)]
pub(crate) enum Target {
Main,
Example(String),
Bin(String),
Bench(String),
}
/// The package in which to look for the specified target (example/bin/bench)
#[derive(Clone, Debug, PartialEq)]
pub(crate) enum Package {
Default,
Package(String),
}
impl From<Package> for Packages {
fn from(p: Package) -> Self {
match p {
Package::Default => Packages::Default,
Package::Package(s) => Packages::Packages(vec![s]),
}
}
}
impl fmt::Display for Package {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
Package::Default => {
write!(f, "Default: search all packages for example/bin/bench")
}
Package::Package(s) => write!(f, "{}", s),
}
}
}
impl fmt::Display for Target {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
Target::Main => write!(f, "src/main.rs"),
Target::Example(bin) => write!(f, "examples/{}.rs", bin),
Target::Bin(bin) => write!(f, "bin/{}.rs", bin),
Target::Bench(bench) => write!(f, "bench {}", bench),
}
}
}
/// Cargo-specific options
pub(crate) struct CargoOpts {
pub(crate) package: Package,
pub(crate) target: Target,
pub(crate) profile: String,
pub(crate) features: CliFeatures,
}
impl AppConfig {
pub(crate) fn to_cargo_opts(&self) -> Result<CargoOpts> {
let package = self.get_package();
let target = self.get_target();
let features = self.features.clone().map(|s| vec![s]).unwrap_or_default();
let features = CliFeatures::from_command_line(
&features,
self.all_features,
!self.no_default_features,
)?;
let profile = self
.profile
.clone()
.unwrap_or_else(|| (if self.release { "release" } else { "dev" }).to_owned());
Ok(CargoOpts { package, target, profile, features })
}
fn get_package(&self) -> Package {
if let Some(ref package) = self.package {
Package::Package(package.clone())
} else {
Package::Default
}
}
// valid target: --example, --bin, --bench
fn get_target(&self) -> Target {
if let Some(ref example) = self.example {
Target::Example(example.clone())
} else if let Some(ref bin) = self.bin {
Target::Bin(bin.clone())
} else if let Some(ref bench) = self.bench {
Target::Bench(bench.clone())
} else {
Target::Main
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn defaults() {
let opts = AppConfig::from_iter(&["instruments", "-t", "template"]);
assert!(opts.example.is_none());
assert!(opts.bin.is_none());
assert!(!opts.release);
assert!(opts.trace_filepath.is_none());
assert!(opts.package.is_none());
assert!(opts.manifest_path.is_none());
}
#[test]
fn package_is_given() {
let opts =
AppConfig::from_iter(&["instruments", "--package", "foo", "--template", "alloc"]);
assert!(opts.example.is_none());
assert!(opts.bin.is_none());
assert!(opts.bench.is_none());
assert_eq!(opts.package.unwrap().as_str(), "foo");
let opts = AppConfig::from_iter(&[
"instruments",
"--package",
"foo",
"--template",
"alloc",
"--bin",
"bin_arg",
]);
assert!(opts.example.is_none());
assert!(opts.bench.is_none());
assert_eq!(opts.bin.unwrap().as_str(), "bin_arg");
assert_eq!(opts.package.unwrap().as_str(), "foo");
}
#[test]
#[should_panic(expected = "cannot be used with one or more of the other")]
fn group_is_exclusive() {
let opts = AppConfig::from_iter(&["instruments", "-t", "time", "--bin", "bin_arg"]);
assert!(opts.example.is_none());
assert_eq!(opts.bin.unwrap().as_str(), "bin_arg");
let opts =
AppConfig::from_iter(&["instruments", "-t", "time", "--example", "example_binary"]);
assert!(opts.bin.is_none());
assert_eq!(opts.example.unwrap().as_str(), "example_binary");
let _opts = AppConfig::from_iter_safe(&[
"instruments",
"-t",
"time",
"--bin",
"thing",
"--example",
"other",
])
.unwrap();
}
#[test]
fn limit_millis() {
let opts = AppConfig::from_iter(&["instruments", "-t", "time", "--time-limit", "42000"]);
assert_eq!(opts.time_limit, Some(42000));
let opts = AppConfig::from_iter(&["instruments", "-t", "time", "--time-limit", "808"]);
assert_eq!(opts.time_limit, Some(808));
let opts = AppConfig::from_iter(&["instruments", "-t", "time"]);
assert_eq!(opts.time_limit, None);
}
#[test]
fn features() {
let opts = &[
"instruments",
"--template",
"time",
"--example",
"hello",
"--features",
"svg im",
"--",
"hi",
];
let opts = AppConfig::from_iter(opts);
assert_eq!(opts.template_name, Some("time".into()));
assert_eq!(opts.example, Some("hello".to_string()));
assert_eq!(opts.features, Some("svg im".to_string()));
let features: Vec<_> = opts
.to_cargo_opts()
.unwrap()
.features
.features
.iter()
.map(|feat| feat.to_string())
.collect();
assert_eq!(features, vec!["im", "svg"]);
}
#[test]
fn var_args() {
let opts = AppConfig::from_iter(&[
"instruments",
"-t",
"alloc",
"--time-limit",
"808",
"--",
"hi",
"-h",
"--bin",
]);
assert_eq!(opts.template_name, Some("alloc".into()));
assert_eq!(opts.time_limit, Some(808));
assert_eq!(opts.target_args, vec!["hi", "-h", "--bin"]);
}
#[test]
fn manifest_path() {
let opts = AppConfig::from_iter(&[
"instruments",
"--manifest-path",
"/path/to/Cargo.toml",
"--template",
"alloc",
]);
assert!(opts.example.is_none());
assert!(opts.bin.is_none());
assert!(opts.bench.is_none());
assert!(opts.package.is_none());
assert_eq!(opts.manifest_path.unwrap(), PathBuf::from("/path/to/Cargo.toml"));
}
} | )]
Instruments(AppConfig),
} | random_line_split |
quotes.py | # quotes.py
# http://sites.google.com/site/pocketsense/
#
# Original Version: TFB (http://thefinancebuff.com)
#
# This script retrieves price quotes for a list of stock and mutual fund ticker symbols from Yahoo! Finance.
# It creates a dummy OFX file and then imports the file to the default application associated with the .ofx extension.
# I wrote this script in order to use Microsoft Money after the quote downloading feature is disabled by Microsoft.
#
# For more information, see
# http://thefinancebuff.com/2009/09/security-quote-script-for-microsoft-money.html
# Revisions (pocketsense)
# -----------------------------------------------------
# 04-Mar-2010*rlc
# - Initial changes/edits for incorporation w/ the "pocketsense" pkg (formatting, method of call, etc.)
# - Examples:
# - Debug control
# - use .\xfr for data
# - moved stock/fund ticker symbols to sites.dat, separating user info from the code
# 18-mar-2010*rlc
# - Skip stock/fund symbols that aren't recognized by Yahoo! Finance (rather than throw an error)
# 07-May-2010*rlc
# - Try not to bomb if the server connection fails or times out and set return STATUS accordingly
# - Changed output file format to QUOTES+time$.ofx
# 09-Sep-2010*rlc
# - Add support for alternate Yahoo! quote site URL (defined in sites.dat as YahooURL: url)
# - Use CSV utility to parse csv data
# - Write out quote history file to quotes.csv
# 12-Oct-2010*rlc
# - Fixed bug in QuoteHistory date field
# 24-Nov-2010*rlc
# - Skip quotes with missing parameters. Otherwise, Money mail throw an error during import.
# - Add an "account balance" data field of zero (balance=0) for the overall statement.
# 10-Jan-2010*rlc
# - Write quote summary to xfrdir\quotes.htm
# - Moved _header, OfxField, OfxTag, _genuid, and OfxDate functios to Removed "\r" from linebreaks.
# Will reuse when combining statements
# 18-Feb-2011*rlc:
# - Use ticker symbol when stock name from Yahoo is null
# - Added Cal's yahoo screen scraper for symbols not available via the csv interface
# - Added YahooTimeZone option
# - Added support for quote multiplier option
# 22-Mar-2011*rlc:
# - Added support for alternate ticker symbol to send to Money (instead of Yahoo symbol)
# Default symbol = Yahoo ticker
# 03Sep2013*rlc
# - Modify to support European versions of MS Money 2005 (and probably 2003/2004)
# * Added INVTRANLIST tag set
# * Added support for forceQuotes option. Force additional quote reponse to adjust
# shares held to non-zero and back.
# - Updated YahooScrape code for updated Yahoo html screen-formatting
# 19Jul2013*rlc
# - Bug fix. Strip commas from YahooScrape price results
# - Added YahooScrape support for quote symbols with a '^' char (e.g., ^DJI)
# 21Oct2013*rlc
# - Added support for quoteAccount
# 09Jan2014*rlc
# - Fixed bug related to ForceQuotes and change of calendar year.
# 19Jan2014*rlc:
# -Added support for EnableGoogleFinance option
# -Reworked the way that quotes are retrieved, to improve reliability
# 14Feb2014*rlc:
# -Extended url timeout. Some ex-US users were having issues.
# -Fixed bug that popped up when EnableYahooFinace=No
# 25Feb2014*rlc:
# -Changed try/catch for URLopen to catch *any* exception
# 14Sep2015*rlc
# -Changed yahoo time parse to read hours in 24hr format
# 09Nov2017*rlc
# -Replace Yahoo quotes csv w/ json
# -Removed yahooScrape option
# 24Mar2018*rlc
# -Use longName when available for Yahoo quotes. Mutual fund *family* name is sometimes given as shortName (see vhcox as example)
import os, sys, time, urllib2, socket, shlex, re, csv, uuid, json
import site_cfg
from control2 import *
from rlib1 import *
from datetime import datetime
join = str.join
class Security:
"""
Encapsulate a stock or mutual fund. A Security has a ticker, a name, a price quote, and
the as-of date and time for the price quote. Name, price and as-of date and time are retrieved
from Yahoo! Finance.
fields:
status, source, ticker, name, price, quoteTime, pclose, pchange
"""
def __init__(self, item):
#item = {"ticker":TickerSym, 'm':multiplier, 's':symbol}
# TickerSym = symbol to grab from Yahoo
# m = multiplier for quote
# s = symbol to pass to Money
self.ticker = item['ticker']
self.multiplier = item['m']
self.symbol = item['s']
self.status = True
socket.setdefaulttimeout(10) #default socket timeout for server read, secs
def _removeIllegalChars(self, inputString):
pattern = re.compile("[^a-zA-Z0-9 ,.-]+")
return pattern.sub("", inputString)
def getQuote(self):
#Yahoo! Finance:
# name (n), lastprice (l1), date (d1), time(t1), previous close (p), %change (p2)
if Debug: print "Getting quote for:", self.ticker
self.status=False
self.source='Y'
#note: each try for a quote sets self.status=true if successful
if eYahoo:
csvtxt = self.getYahooQuote()
quote = self.csvparse(csvtxt)
if self.status: self.source='Y'
if not self.status and eGoogle:
# try screen scrape
csvtxt = self.getGoogleQuote()
quote = self.csvparse(csvtxt)
if self.status: self.source='G'
if not self.status:
print "** ", self.ticker, ': invalid quote response. Skipping...'
self.name = '*InvalidSymbol*'
else:
#show/save what we got rlc*2010
# example: "Amazon.com, Inc.",78.46,"9/3/2009","4:00pm", 80.00, "-1.96%"
# Security names may have embedded commas, so use CSV utility to parse (rlc*2010)
if Debug: print "Quote result string:", csvtxt
self.name = quote[0]
self.price = quote[1]
self.date = quote[2]
self.time = quote[3]
self.pclose = quote[4]
self.pchange = quote[5]
#clean things up, format datetime str, and apply multiplier
# if security name is null, replace name with symbol
if self.name.strip()=='': self.name = self.ticker
self.price = str(float2(self.price)*self.multiplier) #adjust price by multiplier
self.date = self.date.lstrip('0 ')
self.datetime = datetime.strptime(self.date + " " + self.time, "%m/%d/%Y %H:%M%p")
self.quoteTime = self.datetime.strftime("%Y%m%d%H%M%S") + '[' + YahooTimeZone + ']'
if '?' not in self.pclose and 'N/A' not in self.pclose:
#adjust last close price by multiplier
self.pclose = str(float2(self.pclose)*self.multiplier) #previous close
name = self.ticker
if self.symbol <> self.ticker:
name = self.ticker + '(' + self.symbol + ')'
print self.source+':' , name, self.price, self.date, self.time, self.pchange
def csvparse(self, csvtxt):
quote=[]
self.status=True
csvlst = [csvtxt] # csv.reader reads lists the same as files
reader = csv.reader(csvlst)
for row in reader: # we only have one row... so read it into a quote list
quote = row # quote[]= [name, price, quoteTime, pclose, pchange], all as strings
if len(quote) < 6:
self.status=False
elif quote[1] == '0.00' or quote[2] == 'N/A':
self.status=False
return quote
def getYahooQuote(self):
#read Yahoo json data api, and return csv
url = YahooURL + "?symbols=%s" % self.ticker
csvtxt=""
self.status=True
try:
ht=urllib2.urlopen(url).read()
self.quoteURL = 'https://finance.yahoo.com/quote/%s' % self.ticker #html link
except:
if Debug: print "** Error reading " + url + "\n"
self.status = False
if self.status:
try:
j = json.loads(ht) #parse json to dict
jd = j['quoteResponse']['result'][0] #inside response pkg
#use longName if available, otherwise use shortName field
try:
name = jd['longName']
except:
name = jd['shortName']
price = jd['regularMarketPrice']
mtime = jd['regularMarketTime']
lastPrice = jd['regularMarketPreviousClose']
changePer = jd['regularMarketChangePercent']
qtime = time.localtime(mtime)
qdateS = time.strftime("%m/%d/%Y", qtime)
qtimeS = time.strftime("%I:%M%p", qtime)
changeS = '{0:.2}%'.format(changePer)
name = '"' + self._removeIllegalChars(name) + '"' #cleanup foreign chars and quote
csvtxt = ','.join([name, str(price), qdateS, qtimeS, str(lastPrice), changeS])
if Debug: print "Yahoo csvtxt=",csvtxt
except:
#not formatted as expected?
if Debug: print "An error occured by parsing the Yahoo Finance reponse for: ", self.ticker
self.status=False
return csvtxt
def getGoogleQuote(self):
#New screen scrape function: 19-Jan-2014*rlc
# This function creates a csvtxt string with the same format as the Yahoo csv interface
# Example return: "Amazon.com, Inc.","78.46","9/3/2009","4:00pm", 80.00, "-1.96%"
# Gets data from Google Finance
self.status = True # fresh start
csvtxt = ""
if Debug: print "Trying Google Finance for: ", self.ticker
#Example url: https://www.google.com/finance?q=msft
url = GoogleURL + "?q=" + self.ticker
try:
ht=urllib2.urlopen(url).read()
self.quoteURL = url
except:
print "** error reading " + url + "\n"
self.status = False
ticker = self.ticker.replace("^","\^") #use literal regex character
if self.status:
try:
#Name
t1 = '(<meta itemprop="name".*?content=")(.*?)(")'
p = re.compile(t1, re.IGNORECASE | re.DOTALL)
rslt = p.findall(ht)
name= rslt[0][1]
#price
t1 = '(<meta itemprop="price".*?content=")(.*?)(")'
p = re.compile(t1, re.IGNORECASE | re.DOTALL)
rslt = p.findall(ht)
price= rslt[0][1]
#Price change%
t1 = '(<meta itemprop="priceChangePercent".*?content=")(.*?)(")'
p = re.compile(t1, re.IGNORECASE | re.DOTALL)
rslt = p.findall(ht)
pchange= rslt[0][1] + '%'
#Google date/time format= "yyyy-mm-ddThh:mm:ssZ"
# Example = "2014-01-10T21:30:00Z"
t1 = '(<meta itemprop="quoteTime".*?content=")(.*?)(")'
p = re.compile(t1, re.IGNORECASE | re.DOTALL | re.MULTILINE)
rslt = p.findall(ht)
date1= rslt[0][1]
qdate = datetime.strptime(date1, "%Y-%m-%dT%H:%M:%SZ")
date2 = qdate.strftime("%m/%d/%Y").lstrip('0 ') #mm/dd/yyyy, but no leading zero or spaces
#name may contain commas and illegal chars, so clenaup & enclose in quotes
name = '"' + self._removeIllegalChars(name) + '"'
#price may contain commas, but we don't want them
price = ''.join([c for c in price if c in '1234567890.'])
csvtxt = ','.join([name, price, date2, '04:00PM', '?', pchange])
if Debug: print "Google csvtxt=",csvtxt
except:
self.status=False
if Debug: print "An error occured by parsing the Google Finance reponse for: ", self.ticker
return csvtxt
class | :
"""
Create an OFX file based on a list of stocks and mutual funds.
"""
def __init__(self, currency, account, shares, stockList, mfList):
self.currency = currency
self.account = account
self.shares = shares
self.stockList = stockList
self.mfList = mfList
self.dtasof = self.get_dtasof()
def get_dtasof(self):
#15-Feb-2011: Use the latest quote date/time for the statement
today = datetime.today()
dtasof = today.strftime("%Y%m%d")+'120000' #default to today @ noon
lastdate = datetime(1,1,1) #but compare actual dates to long, long ago...
for ticker in self.stockList + self.mfList:
if ticker.datetime > lastdate and not ticker.datetime > today:
lastdate = ticker.datetime
dtasof = ticker.quoteTime
return dtasof
def _signOn(self):
"""Generate server signon response message"""
return OfxTag("SIGNONMSGSRSV1",
OfxTag("SONRS",
OfxTag("STATUS",
OfxField("CODE", "0"),
OfxField("SEVERITY", "INFO"),
OfxField("MESSAGE","Successful Sign On")
),
OfxField("DTSERVER", OfxDate()),
OfxField("LANGUAGE", "ENG"),
OfxField("DTPROFUP", "20010918083000"),
OfxTag("FI", OfxField("ORG", "PocketSense"))
)
)
def invPosList(self):
# create INVPOSLIST section, including all stock and MF symbols
posstock = []
for stock in self.stockList:
posstock.append(self._pos("stock", stock.symbol, stock.price, stock.quoteTime))
posmf = []
for mf in self.mfList:
posmf.append(self._pos("mf", mf.symbol, mf.price, mf.quoteTime))
return OfxTag("INVPOSLIST",
join("", posstock), #str.join("",StrList) = "str(0)+str(1)+str(2)..."
join("", posmf))
def _pos(self, type, symbol, price, quoteTime):
return OfxTag("POS" + type.upper(),
OfxTag("INVPOS",
OfxTag("SECID",
OfxField("UNIQUEID", symbol),
OfxField("UNIQUEIDTYPE", "TICKER")
),
OfxField("HELDINACCT", "CASH"),
OfxField("POSTYPE", "LONG"),
OfxField("UNITS", str(self.shares)),
OfxField("UNITPRICE", price),
OfxField("MKTVAL", str(float2(price)*self.shares)),
#OfxField("MKTVAL", "0"), #rlc:08-2013
OfxField("DTPRICEASOF", quoteTime)
)
)
def invStmt(self, acctid):
#write the INVSTMTRS section
stmt = OfxTag("INVSTMTRS",
OfxField("DTASOF", self.dtasof),
OfxField("CURDEF", self.currency),
OfxTag("INVACCTFROM",
OfxField("BROKERID", "PocketSense"),
OfxField("ACCTID",acctid)
),
OfxTag("INVTRANLIST",
OfxField("DTSTART", self.dtasof),
OfxField("DTEND", self.dtasof),
),
self.invPosList()
)
return stmt
def invServerMsg(self,stmt):
#wrap stmt in INVSTMTMSGSRSV1 tag set
s = OfxTag("INVSTMTTRNRS",
OfxField("TRNUID",ofxUUID()),
OfxTag("STATUS",
OfxField("CODE", "0"),
OfxField("SEVERITY", "INFO")),
OfxField("CLTCOOKIE","4"),
stmt)
return OfxTag("INVSTMTMSGSRSV1", s)
def _secList(self):
stockinfo = []
for stock in self.stockList:
stockinfo.append(self._info("stock", stock.symbol, stock.name, stock.price))
mfinfo = []
for mf in self.mfList:
mfinfo.append(self._info("mf", mf.symbol, mf.name, mf.price))
return OfxTag("SECLISTMSGSRSV1",
OfxTag("SECLIST",
join("", stockinfo),
join("", mfinfo)
)
)
def _info(self, type, symbol, name, price):
secInfo = OfxTag("SECINFO",
OfxTag("SECID",
OfxField("UNIQUEID", symbol),
OfxField("UNIQUEIDTYPE", "TICKER")
),
OfxField("SECNAME", name),
OfxField("TICKER", symbol),
OfxField("UNITPRICE", price),
OfxField("DTASOF", self.dtasof)
)
if type.upper() == "MF":
info = OfxTag(type.upper() + "INFO",
secInfo,
OfxField("MFTYPE", "OPENEND")
)
else:
info = OfxTag(type.upper() + "INFO", secInfo)
return info
def getOfxMsg(self):
#create main OFX message block
return join('', [OfxTag('OFX',
'<!--Created by PocketSense scripts for Money-->',
'<!--https://sites.google.com/site/pocketsense/home-->',
self._signOn(),
self.invServerMsg(self.invStmt(self.account)),
self._secList()
)])
def writeFile(self, name):
f = open(name,"w")
f.write(OfxSGMLHeader())
f.write(self.getOfxMsg())
f.close()
#----------------------------------------------------------------------------
def getQuotes():
global YahooURL, eYahoo, GoogleURL, eGoogle, YahooTimeZone
status = True #overall status flag across all operations (true == no errors getting data)
#get site and other user-defined data
userdat = site_cfg.site_cfg()
stocks = userdat.stocks
funds = userdat.funds
eYahoo = userdat.enableYahooFinance
YahooURL = userdat.YahooURL
GoogleURL = userdat.GoogleURL
eGoogle = userdat.enableGoogleFinance
YahooTimeZone = userdat.YahooTimeZone
currency = userdat.quotecurrency
account = userdat.quoteAccount
ofxFile1, ofxFile2, htmFileName = '','',''
stockList = []
print "Getting security and fund quotes..."
for item in stocks:
sec = Security(item)
sec.getQuote()
status = status and sec.status
if sec.status: stockList.append(sec)
mfList = []
for item in funds:
sec = Security(item)
sec.getQuote()
status = status and sec.status
if sec.status: mfList.append(sec)
qList = stockList + mfList
if len(qList) > 0: #write results only if we have some data
#create quotes ofx file
if not os.path.exists(xfrdir):
os.mkdir(xfrdir)
ofxFile1 = xfrdir + "quotes" + OfxDate() + str(random.randrange(1e5,1e6)) + ".ofx"
writer = OfxWriter(currency, account, 0, stockList, mfList)
writer.writeFile(ofxFile1)
if userdat.forceQuotes:
#generate a second file with non-zero shares. Getdata and Setup use this file
#to force quote reconciliation in Money, by sending ofxFile2, and then ofxFile1
ofxFile2 = xfrdir + "quotes" + OfxDate() + str(random.randrange(1e5,1e6)) + ".ofx"
writer = OfxWriter(currency, account, 0.001, stockList, mfList)
writer.writeFile(ofxFile2)
if glob.glob(ofxFile1) == []:
status = False
# write quotes.htm file
htmFileName = QuoteHTMwriter(qList)
#append results to QuoteHistory.csv if enabled
if status and userdat.savequotehistory:
csvFile = xfrdir+"QuoteHistory.csv"
print "Appending quote results to {0}...".format(csvFile)
newfile = (glob.glob(csvFile) == [])
f = open(csvFile,"a")
if newfile:
f.write('Symbol,Name,Price,Date/Time,LastClose,%Change\n')
for s in qList:
#Fieldnames: symbol, name, price, quoteTime, pclose, pchange
t = s.quoteTime
t2 = t[4:6]+'/'+t[6:8]+'/'+t[0:4]+' '+ t[8:10]+":"+t[10:12]+":"+t[12:14]
line = '"{0}","{1}",{2},{3},{4},{5}\n' \
.format(s.symbol, s.name, s.price, t2, s.pclose, s.pchange)
f.write(line)
f.close()
return status, ofxFile1, ofxFile2, htmFileName | OfxWriter | identifier_name |
quotes.py | # quotes.py
# http://sites.google.com/site/pocketsense/
#
# Original Version: TFB (http://thefinancebuff.com)
#
# This script retrieves price quotes for a list of stock and mutual fund ticker symbols from Yahoo! Finance.
# It creates a dummy OFX file and then imports the file to the default application associated with the .ofx extension.
# I wrote this script in order to use Microsoft Money after the quote downloading feature is disabled by Microsoft.
#
# For more information, see
# http://thefinancebuff.com/2009/09/security-quote-script-for-microsoft-money.html
# Revisions (pocketsense)
# -----------------------------------------------------
# 04-Mar-2010*rlc
# - Initial changes/edits for incorporation w/ the "pocketsense" pkg (formatting, method of call, etc.)
# - Examples:
# - Debug control
# - use .\xfr for data
# - moved stock/fund ticker symbols to sites.dat, separating user info from the code
# 18-mar-2010*rlc
# - Skip stock/fund symbols that aren't recognized by Yahoo! Finance (rather than throw an error)
# 07-May-2010*rlc
# - Try not to bomb if the server connection fails or times out and set return STATUS accordingly
# - Changed output file format to QUOTES+time$.ofx
# 09-Sep-2010*rlc
# - Add support for alternate Yahoo! quote site URL (defined in sites.dat as YahooURL: url)
# - Use CSV utility to parse csv data
# - Write out quote history file to quotes.csv
# 12-Oct-2010*rlc
# - Fixed bug in QuoteHistory date field
# 24-Nov-2010*rlc
# - Skip quotes with missing parameters. Otherwise, Money mail throw an error during import.
# - Add an "account balance" data field of zero (balance=0) for the overall statement.
# 10-Jan-2010*rlc
# - Write quote summary to xfrdir\quotes.htm
# - Moved _header, OfxField, OfxTag, _genuid, and OfxDate functios to Removed "\r" from linebreaks.
# Will reuse when combining statements
# 18-Feb-2011*rlc:
# - Use ticker symbol when stock name from Yahoo is null
# - Added Cal's yahoo screen scraper for symbols not available via the csv interface
# - Added YahooTimeZone option
# - Added support for quote multiplier option
# 22-Mar-2011*rlc:
# - Added support for alternate ticker symbol to send to Money (instead of Yahoo symbol)
# Default symbol = Yahoo ticker
# 03Sep2013*rlc
# - Modify to support European versions of MS Money 2005 (and probably 2003/2004)
# * Added INVTRANLIST tag set
# * Added support for forceQuotes option. Force additional quote reponse to adjust
# shares held to non-zero and back.
# - Updated YahooScrape code for updated Yahoo html screen-formatting
# 19Jul2013*rlc
# - Bug fix. Strip commas from YahooScrape price results
# - Added YahooScrape support for quote symbols with a '^' char (e.g., ^DJI)
# 21Oct2013*rlc
# - Added support for quoteAccount
# 09Jan2014*rlc
# - Fixed bug related to ForceQuotes and change of calendar year.
# 19Jan2014*rlc:
# -Added support for EnableGoogleFinance option
# -Reworked the way that quotes are retrieved, to improve reliability
# 14Feb2014*rlc:
# -Extended url timeout. Some ex-US users were having issues.
# -Fixed bug that popped up when EnableYahooFinace=No
# 25Feb2014*rlc:
# -Changed try/catch for URLopen to catch *any* exception
# 14Sep2015*rlc
# -Changed yahoo time parse to read hours in 24hr format
# 09Nov2017*rlc
# -Replace Yahoo quotes csv w/ json
# -Removed yahooScrape option
# 24Mar2018*rlc
# -Use longName when available for Yahoo quotes. Mutual fund *family* name is sometimes given as shortName (see vhcox as example)
import os, sys, time, urllib2, socket, shlex, re, csv, uuid, json
import site_cfg
from control2 import *
from rlib1 import *
from datetime import datetime
join = str.join
class Security:
"""
Encapsulate a stock or mutual fund. A Security has a ticker, a name, a price quote, and
the as-of date and time for the price quote. Name, price and as-of date and time are retrieved
from Yahoo! Finance.
fields:
status, source, ticker, name, price, quoteTime, pclose, pchange
"""
def __init__(self, item):
#item = {"ticker":TickerSym, 'm':multiplier, 's':symbol}
# TickerSym = symbol to grab from Yahoo
# m = multiplier for quote
# s = symbol to pass to Money
self.ticker = item['ticker']
self.multiplier = item['m']
self.symbol = item['s']
self.status = True
socket.setdefaulttimeout(10) #default socket timeout for server read, secs
def _removeIllegalChars(self, inputString):
pattern = re.compile("[^a-zA-Z0-9 ,.-]+")
return pattern.sub("", inputString)
def getQuote(self):
#Yahoo! Finance:
# name (n), lastprice (l1), date (d1), time(t1), previous close (p), %change (p2)
if Debug: |
self.status=False
self.source='Y'
#note: each try for a quote sets self.status=true if successful
if eYahoo:
csvtxt = self.getYahooQuote()
quote = self.csvparse(csvtxt)
if self.status: self.source='Y'
if not self.status and eGoogle:
# try screen scrape
csvtxt = self.getGoogleQuote()
quote = self.csvparse(csvtxt)
if self.status: self.source='G'
if not self.status:
print "** ", self.ticker, ': invalid quote response. Skipping...'
self.name = '*InvalidSymbol*'
else:
#show/save what we got rlc*2010
# example: "Amazon.com, Inc.",78.46,"9/3/2009","4:00pm", 80.00, "-1.96%"
# Security names may have embedded commas, so use CSV utility to parse (rlc*2010)
if Debug: print "Quote result string:", csvtxt
self.name = quote[0]
self.price = quote[1]
self.date = quote[2]
self.time = quote[3]
self.pclose = quote[4]
self.pchange = quote[5]
#clean things up, format datetime str, and apply multiplier
# if security name is null, replace name with symbol
if self.name.strip()=='': self.name = self.ticker
self.price = str(float2(self.price)*self.multiplier) #adjust price by multiplier
self.date = self.date.lstrip('0 ')
self.datetime = datetime.strptime(self.date + " " + self.time, "%m/%d/%Y %H:%M%p")
self.quoteTime = self.datetime.strftime("%Y%m%d%H%M%S") + '[' + YahooTimeZone + ']'
if '?' not in self.pclose and 'N/A' not in self.pclose:
#adjust last close price by multiplier
self.pclose = str(float2(self.pclose)*self.multiplier) #previous close
name = self.ticker
if self.symbol <> self.ticker:
name = self.ticker + '(' + self.symbol + ')'
print self.source+':' , name, self.price, self.date, self.time, self.pchange
def csvparse(self, csvtxt):
quote=[]
self.status=True
csvlst = [csvtxt] # csv.reader reads lists the same as files
reader = csv.reader(csvlst)
for row in reader: # we only have one row... so read it into a quote list
quote = row # quote[]= [name, price, quoteTime, pclose, pchange], all as strings
if len(quote) < 6:
self.status=False
elif quote[1] == '0.00' or quote[2] == 'N/A':
self.status=False
return quote
def getYahooQuote(self):
#read Yahoo json data api, and return csv
url = YahooURL + "?symbols=%s" % self.ticker
csvtxt=""
self.status=True
try:
ht=urllib2.urlopen(url).read()
self.quoteURL = 'https://finance.yahoo.com/quote/%s' % self.ticker #html link
except:
if Debug: print "** Error reading " + url + "\n"
self.status = False
if self.status:
try:
j = json.loads(ht) #parse json to dict
jd = j['quoteResponse']['result'][0] #inside response pkg
#use longName if available, otherwise use shortName field
try:
name = jd['longName']
except:
name = jd['shortName']
price = jd['regularMarketPrice']
mtime = jd['regularMarketTime']
lastPrice = jd['regularMarketPreviousClose']
changePer = jd['regularMarketChangePercent']
qtime = time.localtime(mtime)
qdateS = time.strftime("%m/%d/%Y", qtime)
qtimeS = time.strftime("%I:%M%p", qtime)
changeS = '{0:.2}%'.format(changePer)
name = '"' + self._removeIllegalChars(name) + '"' #cleanup foreign chars and quote
csvtxt = ','.join([name, str(price), qdateS, qtimeS, str(lastPrice), changeS])
if Debug: print "Yahoo csvtxt=",csvtxt
except:
#not formatted as expected?
if Debug: print "An error occured by parsing the Yahoo Finance reponse for: ", self.ticker
self.status=False
return csvtxt
def getGoogleQuote(self):
#New screen scrape function: 19-Jan-2014*rlc
# This function creates a csvtxt string with the same format as the Yahoo csv interface
# Example return: "Amazon.com, Inc.","78.46","9/3/2009","4:00pm", 80.00, "-1.96%"
# Gets data from Google Finance
self.status = True # fresh start
csvtxt = ""
if Debug: print "Trying Google Finance for: ", self.ticker
#Example url: https://www.google.com/finance?q=msft
url = GoogleURL + "?q=" + self.ticker
try:
ht=urllib2.urlopen(url).read()
self.quoteURL = url
except:
print "** error reading " + url + "\n"
self.status = False
ticker = self.ticker.replace("^","\^") #use literal regex character
if self.status:
try:
#Name
t1 = '(<meta itemprop="name".*?content=")(.*?)(")'
p = re.compile(t1, re.IGNORECASE | re.DOTALL)
rslt = p.findall(ht)
name= rslt[0][1]
#price
t1 = '(<meta itemprop="price".*?content=")(.*?)(")'
p = re.compile(t1, re.IGNORECASE | re.DOTALL)
rslt = p.findall(ht)
price= rslt[0][1]
#Price change%
t1 = '(<meta itemprop="priceChangePercent".*?content=")(.*?)(")'
p = re.compile(t1, re.IGNORECASE | re.DOTALL)
rslt = p.findall(ht)
pchange= rslt[0][1] + '%'
#Google date/time format= "yyyy-mm-ddThh:mm:ssZ"
# Example = "2014-01-10T21:30:00Z"
t1 = '(<meta itemprop="quoteTime".*?content=")(.*?)(")'
p = re.compile(t1, re.IGNORECASE | re.DOTALL | re.MULTILINE)
rslt = p.findall(ht)
date1= rslt[0][1]
qdate = datetime.strptime(date1, "%Y-%m-%dT%H:%M:%SZ")
date2 = qdate.strftime("%m/%d/%Y").lstrip('0 ') #mm/dd/yyyy, but no leading zero or spaces
#name may contain commas and illegal chars, so clenaup & enclose in quotes
name = '"' + self._removeIllegalChars(name) + '"'
#price may contain commas, but we don't want them
price = ''.join([c for c in price if c in '1234567890.'])
csvtxt = ','.join([name, price, date2, '04:00PM', '?', pchange])
if Debug: print "Google csvtxt=",csvtxt
except:
self.status=False
if Debug: print "An error occured by parsing the Google Finance reponse for: ", self.ticker
return csvtxt
class OfxWriter:
"""
Create an OFX file based on a list of stocks and mutual funds.
"""
def __init__(self, currency, account, shares, stockList, mfList):
self.currency = currency
self.account = account
self.shares = shares
self.stockList = stockList
self.mfList = mfList
self.dtasof = self.get_dtasof()
def get_dtasof(self):
#15-Feb-2011: Use the latest quote date/time for the statement
today = datetime.today()
dtasof = today.strftime("%Y%m%d")+'120000' #default to today @ noon
lastdate = datetime(1,1,1) #but compare actual dates to long, long ago...
for ticker in self.stockList + self.mfList:
if ticker.datetime > lastdate and not ticker.datetime > today:
lastdate = ticker.datetime
dtasof = ticker.quoteTime
return dtasof
def _signOn(self):
"""Generate server signon response message"""
return OfxTag("SIGNONMSGSRSV1",
OfxTag("SONRS",
OfxTag("STATUS",
OfxField("CODE", "0"),
OfxField("SEVERITY", "INFO"),
OfxField("MESSAGE","Successful Sign On")
),
OfxField("DTSERVER", OfxDate()),
OfxField("LANGUAGE", "ENG"),
OfxField("DTPROFUP", "20010918083000"),
OfxTag("FI", OfxField("ORG", "PocketSense"))
)
)
def invPosList(self):
# create INVPOSLIST section, including all stock and MF symbols
posstock = []
for stock in self.stockList:
posstock.append(self._pos("stock", stock.symbol, stock.price, stock.quoteTime))
posmf = []
for mf in self.mfList:
posmf.append(self._pos("mf", mf.symbol, mf.price, mf.quoteTime))
return OfxTag("INVPOSLIST",
join("", posstock), #str.join("",StrList) = "str(0)+str(1)+str(2)..."
join("", posmf))
def _pos(self, type, symbol, price, quoteTime):
return OfxTag("POS" + type.upper(),
OfxTag("INVPOS",
OfxTag("SECID",
OfxField("UNIQUEID", symbol),
OfxField("UNIQUEIDTYPE", "TICKER")
),
OfxField("HELDINACCT", "CASH"),
OfxField("POSTYPE", "LONG"),
OfxField("UNITS", str(self.shares)),
OfxField("UNITPRICE", price),
OfxField("MKTVAL", str(float2(price)*self.shares)),
#OfxField("MKTVAL", "0"), #rlc:08-2013
OfxField("DTPRICEASOF", quoteTime)
)
)
def invStmt(self, acctid):
#write the INVSTMTRS section
stmt = OfxTag("INVSTMTRS",
OfxField("DTASOF", self.dtasof),
OfxField("CURDEF", self.currency),
OfxTag("INVACCTFROM",
OfxField("BROKERID", "PocketSense"),
OfxField("ACCTID",acctid)
),
OfxTag("INVTRANLIST",
OfxField("DTSTART", self.dtasof),
OfxField("DTEND", self.dtasof),
),
self.invPosList()
)
return stmt
def invServerMsg(self,stmt):
#wrap stmt in INVSTMTMSGSRSV1 tag set
s = OfxTag("INVSTMTTRNRS",
OfxField("TRNUID",ofxUUID()),
OfxTag("STATUS",
OfxField("CODE", "0"),
OfxField("SEVERITY", "INFO")),
OfxField("CLTCOOKIE","4"),
stmt)
return OfxTag("INVSTMTMSGSRSV1", s)
def _secList(self):
stockinfo = []
for stock in self.stockList:
stockinfo.append(self._info("stock", stock.symbol, stock.name, stock.price))
mfinfo = []
for mf in self.mfList:
mfinfo.append(self._info("mf", mf.symbol, mf.name, mf.price))
return OfxTag("SECLISTMSGSRSV1",
OfxTag("SECLIST",
join("", stockinfo),
join("", mfinfo)
)
)
def _info(self, type, symbol, name, price):
secInfo = OfxTag("SECINFO",
OfxTag("SECID",
OfxField("UNIQUEID", symbol),
OfxField("UNIQUEIDTYPE", "TICKER")
),
OfxField("SECNAME", name),
OfxField("TICKER", symbol),
OfxField("UNITPRICE", price),
OfxField("DTASOF", self.dtasof)
)
if type.upper() == "MF":
info = OfxTag(type.upper() + "INFO",
secInfo,
OfxField("MFTYPE", "OPENEND")
)
else:
info = OfxTag(type.upper() + "INFO", secInfo)
return info
def getOfxMsg(self):
#create main OFX message block
return join('', [OfxTag('OFX',
'<!--Created by PocketSense scripts for Money-->',
'<!--https://sites.google.com/site/pocketsense/home-->',
self._signOn(),
self.invServerMsg(self.invStmt(self.account)),
self._secList()
)])
def writeFile(self, name):
f = open(name,"w")
f.write(OfxSGMLHeader())
f.write(self.getOfxMsg())
f.close()
#----------------------------------------------------------------------------
def getQuotes():
global YahooURL, eYahoo, GoogleURL, eGoogle, YahooTimeZone
status = True #overall status flag across all operations (true == no errors getting data)
#get site and other user-defined data
userdat = site_cfg.site_cfg()
stocks = userdat.stocks
funds = userdat.funds
eYahoo = userdat.enableYahooFinance
YahooURL = userdat.YahooURL
GoogleURL = userdat.GoogleURL
eGoogle = userdat.enableGoogleFinance
YahooTimeZone = userdat.YahooTimeZone
currency = userdat.quotecurrency
account = userdat.quoteAccount
ofxFile1, ofxFile2, htmFileName = '','',''
stockList = []
print "Getting security and fund quotes..."
for item in stocks:
sec = Security(item)
sec.getQuote()
status = status and sec.status
if sec.status: stockList.append(sec)
mfList = []
for item in funds:
sec = Security(item)
sec.getQuote()
status = status and sec.status
if sec.status: mfList.append(sec)
qList = stockList + mfList
if len(qList) > 0: #write results only if we have some data
#create quotes ofx file
if not os.path.exists(xfrdir):
os.mkdir(xfrdir)
ofxFile1 = xfrdir + "quotes" + OfxDate() + str(random.randrange(1e5,1e6)) + ".ofx"
writer = OfxWriter(currency, account, 0, stockList, mfList)
writer.writeFile(ofxFile1)
if userdat.forceQuotes:
#generate a second file with non-zero shares. Getdata and Setup use this file
#to force quote reconciliation in Money, by sending ofxFile2, and then ofxFile1
ofxFile2 = xfrdir + "quotes" + OfxDate() + str(random.randrange(1e5,1e6)) + ".ofx"
writer = OfxWriter(currency, account, 0.001, stockList, mfList)
writer.writeFile(ofxFile2)
if glob.glob(ofxFile1) == []:
status = False
# write quotes.htm file
htmFileName = QuoteHTMwriter(qList)
#append results to QuoteHistory.csv if enabled
if status and userdat.savequotehistory:
csvFile = xfrdir+"QuoteHistory.csv"
print "Appending quote results to {0}...".format(csvFile)
newfile = (glob.glob(csvFile) == [])
f = open(csvFile,"a")
if newfile:
f.write('Symbol,Name,Price,Date/Time,LastClose,%Change\n')
for s in qList:
#Fieldnames: symbol, name, price, quoteTime, pclose, pchange
t = s.quoteTime
t2 = t[4:6]+'/'+t[6:8]+'/'+t[0:4]+' '+ t[8:10]+":"+t[10:12]+":"+t[12:14]
line = '"{0}","{1}",{2},{3},{4},{5}\n' \
.format(s.symbol, s.name, s.price, t2, s.pclose, s.pchange)
f.write(line)
f.close()
return status, ofxFile1, ofxFile2, htmFileName | print "Getting quote for:", self.ticker | conditional_block |
quotes.py | # quotes.py
# http://sites.google.com/site/pocketsense/
#
# Original Version: TFB (http://thefinancebuff.com)
#
# This script retrieves price quotes for a list of stock and mutual fund ticker symbols from Yahoo! Finance.
# It creates a dummy OFX file and then imports the file to the default application associated with the .ofx extension.
# I wrote this script in order to use Microsoft Money after the quote downloading feature is disabled by Microsoft.
#
# For more information, see
# http://thefinancebuff.com/2009/09/security-quote-script-for-microsoft-money.html
# Revisions (pocketsense)
# -----------------------------------------------------
# 04-Mar-2010*rlc
# - Initial changes/edits for incorporation w/ the "pocketsense" pkg (formatting, method of call, etc.)
# - Examples:
# - Debug control
# - use .\xfr for data
# - moved stock/fund ticker symbols to sites.dat, separating user info from the code
# 18-mar-2010*rlc
# - Skip stock/fund symbols that aren't recognized by Yahoo! Finance (rather than throw an error)
# 07-May-2010*rlc
# - Try not to bomb if the server connection fails or times out and set return STATUS accordingly
# - Changed output file format to QUOTES+time$.ofx
# 09-Sep-2010*rlc
# - Add support for alternate Yahoo! quote site URL (defined in sites.dat as YahooURL: url)
# - Use CSV utility to parse csv data
# - Write out quote history file to quotes.csv
# 12-Oct-2010*rlc
# - Fixed bug in QuoteHistory date field
# 24-Nov-2010*rlc
# - Skip quotes with missing parameters. Otherwise, Money mail throw an error during import.
# - Add an "account balance" data field of zero (balance=0) for the overall statement.
# 10-Jan-2010*rlc
# - Write quote summary to xfrdir\quotes.htm
# - Moved _header, OfxField, OfxTag, _genuid, and OfxDate functios to Removed "\r" from linebreaks.
# Will reuse when combining statements
# 18-Feb-2011*rlc:
# - Use ticker symbol when stock name from Yahoo is null
# - Added Cal's yahoo screen scraper for symbols not available via the csv interface
# - Added YahooTimeZone option
# - Added support for quote multiplier option
# 22-Mar-2011*rlc:
# - Added support for alternate ticker symbol to send to Money (instead of Yahoo symbol)
# Default symbol = Yahoo ticker
# 03Sep2013*rlc
# - Modify to support European versions of MS Money 2005 (and probably 2003/2004)
# * Added INVTRANLIST tag set
# * Added support for forceQuotes option. Force additional quote reponse to adjust
# shares held to non-zero and back.
# - Updated YahooScrape code for updated Yahoo html screen-formatting
# 19Jul2013*rlc
# - Bug fix. Strip commas from YahooScrape price results
# - Added YahooScrape support for quote symbols with a '^' char (e.g., ^DJI)
# 21Oct2013*rlc
# - Added support for quoteAccount
# 09Jan2014*rlc
# - Fixed bug related to ForceQuotes and change of calendar year.
# 19Jan2014*rlc:
# -Added support for EnableGoogleFinance option
# -Reworked the way that quotes are retrieved, to improve reliability
# 14Feb2014*rlc:
# -Extended url timeout. Some ex-US users were having issues.
# -Fixed bug that popped up when EnableYahooFinace=No
# 25Feb2014*rlc:
# -Changed try/catch for URLopen to catch *any* exception
# 14Sep2015*rlc
# -Changed yahoo time parse to read hours in 24hr format
# 09Nov2017*rlc
# -Replace Yahoo quotes csv w/ json
# -Removed yahooScrape option
# 24Mar2018*rlc
# -Use longName when available for Yahoo quotes. Mutual fund *family* name is sometimes given as shortName (see vhcox as example)
import os, sys, time, urllib2, socket, shlex, re, csv, uuid, json
import site_cfg
from control2 import *
from rlib1 import *
from datetime import datetime
join = str.join
class Security:
"""
Encapsulate a stock or mutual fund. A Security has a ticker, a name, a price quote, and
the as-of date and time for the price quote. Name, price and as-of date and time are retrieved
from Yahoo! Finance.
fields:
status, source, ticker, name, price, quoteTime, pclose, pchange
"""
def __init__(self, item):
#item = {"ticker":TickerSym, 'm':multiplier, 's':symbol}
# TickerSym = symbol to grab from Yahoo
# m = multiplier for quote
# s = symbol to pass to Money
self.ticker = item['ticker']
self.multiplier = item['m']
self.symbol = item['s']
self.status = True
socket.setdefaulttimeout(10) #default socket timeout for server read, secs
def _removeIllegalChars(self, inputString):
pattern = re.compile("[^a-zA-Z0-9 ,.-]+")
return pattern.sub("", inputString)
def getQuote(self):
#Yahoo! Finance:
# name (n), lastprice (l1), date (d1), time(t1), previous close (p), %change (p2)
if Debug: print "Getting quote for:", self.ticker
self.status=False
self.source='Y'
#note: each try for a quote sets self.status=true if successful
if eYahoo:
csvtxt = self.getYahooQuote()
quote = self.csvparse(csvtxt)
if self.status: self.source='Y'
if not self.status and eGoogle:
# try screen scrape
csvtxt = self.getGoogleQuote()
quote = self.csvparse(csvtxt)
if self.status: self.source='G'
if not self.status:
print "** ", self.ticker, ': invalid quote response. Skipping...'
self.name = '*InvalidSymbol*'
else:
#show/save what we got rlc*2010
# example: "Amazon.com, Inc.",78.46,"9/3/2009","4:00pm", 80.00, "-1.96%"
# Security names may have embedded commas, so use CSV utility to parse (rlc*2010)
if Debug: print "Quote result string:", csvtxt
self.name = quote[0]
self.price = quote[1]
self.date = quote[2]
self.time = quote[3]
self.pclose = quote[4]
self.pchange = quote[5]
#clean things up, format datetime str, and apply multiplier
# if security name is null, replace name with symbol
if self.name.strip()=='': self.name = self.ticker
self.price = str(float2(self.price)*self.multiplier) #adjust price by multiplier
self.date = self.date.lstrip('0 ')
self.datetime = datetime.strptime(self.date + " " + self.time, "%m/%d/%Y %H:%M%p")
self.quoteTime = self.datetime.strftime("%Y%m%d%H%M%S") + '[' + YahooTimeZone + ']'
if '?' not in self.pclose and 'N/A' not in self.pclose:
#adjust last close price by multiplier
self.pclose = str(float2(self.pclose)*self.multiplier) #previous close
name = self.ticker
if self.symbol <> self.ticker:
name = self.ticker + '(' + self.symbol + ')'
print self.source+':' , name, self.price, self.date, self.time, self.pchange
def csvparse(self, csvtxt):
quote=[]
self.status=True
csvlst = [csvtxt] # csv.reader reads lists the same as files
reader = csv.reader(csvlst)
for row in reader: # we only have one row... so read it into a quote list
quote = row # quote[]= [name, price, quoteTime, pclose, pchange], all as strings
if len(quote) < 6:
self.status=False
elif quote[1] == '0.00' or quote[2] == 'N/A':
self.status=False
return quote
def getYahooQuote(self):
#read Yahoo json data api, and return csv
url = YahooURL + "?symbols=%s" % self.ticker
csvtxt=""
self.status=True
try:
ht=urllib2.urlopen(url).read()
self.quoteURL = 'https://finance.yahoo.com/quote/%s' % self.ticker #html link
except:
if Debug: print "** Error reading " + url + "\n"
self.status = False
if self.status:
try:
j = json.loads(ht) #parse json to dict
jd = j['quoteResponse']['result'][0] #inside response pkg
#use longName if available, otherwise use shortName field
try:
name = jd['longName']
except:
name = jd['shortName']
price = jd['regularMarketPrice']
mtime = jd['regularMarketTime']
lastPrice = jd['regularMarketPreviousClose']
changePer = jd['regularMarketChangePercent']
qtime = time.localtime(mtime)
qdateS = time.strftime("%m/%d/%Y", qtime)
qtimeS = time.strftime("%I:%M%p", qtime)
changeS = '{0:.2}%'.format(changePer)
name = '"' + self._removeIllegalChars(name) + '"' #cleanup foreign chars and quote
csvtxt = ','.join([name, str(price), qdateS, qtimeS, str(lastPrice), changeS])
if Debug: print "Yahoo csvtxt=",csvtxt
except:
#not formatted as expected?
if Debug: print "An error occured by parsing the Yahoo Finance reponse for: ", self.ticker
self.status=False
return csvtxt
def getGoogleQuote(self):
#New screen scrape function: 19-Jan-2014*rlc
# This function creates a csvtxt string with the same format as the Yahoo csv interface
# Example return: "Amazon.com, Inc.","78.46","9/3/2009","4:00pm", 80.00, "-1.96%"
# Gets data from Google Finance
self.status = True # fresh start
csvtxt = ""
if Debug: print "Trying Google Finance for: ", self.ticker
#Example url: https://www.google.com/finance?q=msft
url = GoogleURL + "?q=" + self.ticker
try:
ht=urllib2.urlopen(url).read()
self.quoteURL = url
except:
print "** error reading " + url + "\n"
self.status = False
ticker = self.ticker.replace("^","\^") #use literal regex character
if self.status:
try:
#Name
t1 = '(<meta itemprop="name".*?content=")(.*?)(")'
p = re.compile(t1, re.IGNORECASE | re.DOTALL)
rslt = p.findall(ht)
name= rslt[0][1]
#price
t1 = '(<meta itemprop="price".*?content=")(.*?)(")'
p = re.compile(t1, re.IGNORECASE | re.DOTALL)
rslt = p.findall(ht)
price= rslt[0][1]
#Price change%
t1 = '(<meta itemprop="priceChangePercent".*?content=")(.*?)(")'
p = re.compile(t1, re.IGNORECASE | re.DOTALL)
rslt = p.findall(ht)
pchange= rslt[0][1] + '%'
#Google date/time format= "yyyy-mm-ddThh:mm:ssZ"
# Example = "2014-01-10T21:30:00Z"
t1 = '(<meta itemprop="quoteTime".*?content=")(.*?)(")'
p = re.compile(t1, re.IGNORECASE | re.DOTALL | re.MULTILINE)
rslt = p.findall(ht)
date1= rslt[0][1]
qdate = datetime.strptime(date1, "%Y-%m-%dT%H:%M:%SZ")
date2 = qdate.strftime("%m/%d/%Y").lstrip('0 ') #mm/dd/yyyy, but no leading zero or spaces
#name may contain commas and illegal chars, so clenaup & enclose in quotes
name = '"' + self._removeIllegalChars(name) + '"'
#price may contain commas, but we don't want them
price = ''.join([c for c in price if c in '1234567890.'])
csvtxt = ','.join([name, price, date2, '04:00PM', '?', pchange])
if Debug: print "Google csvtxt=",csvtxt
except:
self.status=False
if Debug: print "An error occured by parsing the Google Finance reponse for: ", self.ticker
return csvtxt
class OfxWriter:
|
#----------------------------------------------------------------------------
def getQuotes():
global YahooURL, eYahoo, GoogleURL, eGoogle, YahooTimeZone
status = True #overall status flag across all operations (true == no errors getting data)
#get site and other user-defined data
userdat = site_cfg.site_cfg()
stocks = userdat.stocks
funds = userdat.funds
eYahoo = userdat.enableYahooFinance
YahooURL = userdat.YahooURL
GoogleURL = userdat.GoogleURL
eGoogle = userdat.enableGoogleFinance
YahooTimeZone = userdat.YahooTimeZone
currency = userdat.quotecurrency
account = userdat.quoteAccount
ofxFile1, ofxFile2, htmFileName = '','',''
stockList = []
print "Getting security and fund quotes..."
for item in stocks:
sec = Security(item)
sec.getQuote()
status = status and sec.status
if sec.status: stockList.append(sec)
mfList = []
for item in funds:
sec = Security(item)
sec.getQuote()
status = status and sec.status
if sec.status: mfList.append(sec)
qList = stockList + mfList
if len(qList) > 0: #write results only if we have some data
#create quotes ofx file
if not os.path.exists(xfrdir):
os.mkdir(xfrdir)
ofxFile1 = xfrdir + "quotes" + OfxDate() + str(random.randrange(1e5,1e6)) + ".ofx"
writer = OfxWriter(currency, account, 0, stockList, mfList)
writer.writeFile(ofxFile1)
if userdat.forceQuotes:
#generate a second file with non-zero shares. Getdata and Setup use this file
#to force quote reconciliation in Money, by sending ofxFile2, and then ofxFile1
ofxFile2 = xfrdir + "quotes" + OfxDate() + str(random.randrange(1e5,1e6)) + ".ofx"
writer = OfxWriter(currency, account, 0.001, stockList, mfList)
writer.writeFile(ofxFile2)
if glob.glob(ofxFile1) == []:
status = False
# write quotes.htm file
htmFileName = QuoteHTMwriter(qList)
#append results to QuoteHistory.csv if enabled
if status and userdat.savequotehistory:
csvFile = xfrdir+"QuoteHistory.csv"
print "Appending quote results to {0}...".format(csvFile)
newfile = (glob.glob(csvFile) == [])
f = open(csvFile,"a")
if newfile:
f.write('Symbol,Name,Price,Date/Time,LastClose,%Change\n')
for s in qList:
#Fieldnames: symbol, name, price, quoteTime, pclose, pchange
t = s.quoteTime
t2 = t[4:6]+'/'+t[6:8]+'/'+t[0:4]+' '+ t[8:10]+":"+t[10:12]+":"+t[12:14]
line = '"{0}","{1}",{2},{3},{4},{5}\n' \
.format(s.symbol, s.name, s.price, t2, s.pclose, s.pchange)
f.write(line)
f.close()
return status, ofxFile1, ofxFile2, htmFileName | """
Create an OFX file based on a list of stocks and mutual funds.
"""
def __init__(self, currency, account, shares, stockList, mfList):
self.currency = currency
self.account = account
self.shares = shares
self.stockList = stockList
self.mfList = mfList
self.dtasof = self.get_dtasof()
def get_dtasof(self):
#15-Feb-2011: Use the latest quote date/time for the statement
today = datetime.today()
dtasof = today.strftime("%Y%m%d")+'120000' #default to today @ noon
lastdate = datetime(1,1,1) #but compare actual dates to long, long ago...
for ticker in self.stockList + self.mfList:
if ticker.datetime > lastdate and not ticker.datetime > today:
lastdate = ticker.datetime
dtasof = ticker.quoteTime
return dtasof
def _signOn(self):
"""Generate server signon response message"""
return OfxTag("SIGNONMSGSRSV1",
OfxTag("SONRS",
OfxTag("STATUS",
OfxField("CODE", "0"),
OfxField("SEVERITY", "INFO"),
OfxField("MESSAGE","Successful Sign On")
),
OfxField("DTSERVER", OfxDate()),
OfxField("LANGUAGE", "ENG"),
OfxField("DTPROFUP", "20010918083000"),
OfxTag("FI", OfxField("ORG", "PocketSense"))
)
)
def invPosList(self):
# create INVPOSLIST section, including all stock and MF symbols
posstock = []
for stock in self.stockList:
posstock.append(self._pos("stock", stock.symbol, stock.price, stock.quoteTime))
posmf = []
for mf in self.mfList:
posmf.append(self._pos("mf", mf.symbol, mf.price, mf.quoteTime))
return OfxTag("INVPOSLIST",
join("", posstock), #str.join("",StrList) = "str(0)+str(1)+str(2)..."
join("", posmf))
def _pos(self, type, symbol, price, quoteTime):
return OfxTag("POS" + type.upper(),
OfxTag("INVPOS",
OfxTag("SECID",
OfxField("UNIQUEID", symbol),
OfxField("UNIQUEIDTYPE", "TICKER")
),
OfxField("HELDINACCT", "CASH"),
OfxField("POSTYPE", "LONG"),
OfxField("UNITS", str(self.shares)),
OfxField("UNITPRICE", price),
OfxField("MKTVAL", str(float2(price)*self.shares)),
#OfxField("MKTVAL", "0"), #rlc:08-2013
OfxField("DTPRICEASOF", quoteTime)
)
)
def invStmt(self, acctid):
#write the INVSTMTRS section
stmt = OfxTag("INVSTMTRS",
OfxField("DTASOF", self.dtasof),
OfxField("CURDEF", self.currency),
OfxTag("INVACCTFROM",
OfxField("BROKERID", "PocketSense"),
OfxField("ACCTID",acctid)
),
OfxTag("INVTRANLIST",
OfxField("DTSTART", self.dtasof),
OfxField("DTEND", self.dtasof),
),
self.invPosList()
)
return stmt
def invServerMsg(self,stmt):
#wrap stmt in INVSTMTMSGSRSV1 tag set
s = OfxTag("INVSTMTTRNRS",
OfxField("TRNUID",ofxUUID()),
OfxTag("STATUS",
OfxField("CODE", "0"),
OfxField("SEVERITY", "INFO")),
OfxField("CLTCOOKIE","4"),
stmt)
return OfxTag("INVSTMTMSGSRSV1", s)
def _secList(self):
stockinfo = []
for stock in self.stockList:
stockinfo.append(self._info("stock", stock.symbol, stock.name, stock.price))
mfinfo = []
for mf in self.mfList:
mfinfo.append(self._info("mf", mf.symbol, mf.name, mf.price))
return OfxTag("SECLISTMSGSRSV1",
OfxTag("SECLIST",
join("", stockinfo),
join("", mfinfo)
)
)
def _info(self, type, symbol, name, price):
secInfo = OfxTag("SECINFO",
OfxTag("SECID",
OfxField("UNIQUEID", symbol),
OfxField("UNIQUEIDTYPE", "TICKER")
),
OfxField("SECNAME", name),
OfxField("TICKER", symbol),
OfxField("UNITPRICE", price),
OfxField("DTASOF", self.dtasof)
)
if type.upper() == "MF":
info = OfxTag(type.upper() + "INFO",
secInfo,
OfxField("MFTYPE", "OPENEND")
)
else:
info = OfxTag(type.upper() + "INFO", secInfo)
return info
def getOfxMsg(self):
#create main OFX message block
return join('', [OfxTag('OFX',
'<!--Created by PocketSense scripts for Money-->',
'<!--https://sites.google.com/site/pocketsense/home-->',
self._signOn(),
self.invServerMsg(self.invStmt(self.account)),
self._secList()
)])
def writeFile(self, name):
f = open(name,"w")
f.write(OfxSGMLHeader())
f.write(self.getOfxMsg())
f.close() | identifier_body |
quotes.py | # quotes.py
# http://sites.google.com/site/pocketsense/
#
# Original Version: TFB (http://thefinancebuff.com)
#
# This script retrieves price quotes for a list of stock and mutual fund ticker symbols from Yahoo! Finance.
# It creates a dummy OFX file and then imports the file to the default application associated with the .ofx extension.
# I wrote this script in order to use Microsoft Money after the quote downloading feature is disabled by Microsoft.
#
# For more information, see
# http://thefinancebuff.com/2009/09/security-quote-script-for-microsoft-money.html
# Revisions (pocketsense)
# -----------------------------------------------------
# 04-Mar-2010*rlc
# - Initial changes/edits for incorporation w/ the "pocketsense" pkg (formatting, method of call, etc.)
# - Examples:
# - Debug control
# - use .\xfr for data
# - moved stock/fund ticker symbols to sites.dat, separating user info from the code
# 18-mar-2010*rlc
# - Skip stock/fund symbols that aren't recognized by Yahoo! Finance (rather than throw an error)
# 07-May-2010*rlc
# - Try not to bomb if the server connection fails or times out and set return STATUS accordingly
# - Changed output file format to QUOTES+time$.ofx
# 09-Sep-2010*rlc
# - Add support for alternate Yahoo! quote site URL (defined in sites.dat as YahooURL: url)
# - Use CSV utility to parse csv data
# - Write out quote history file to quotes.csv
# 12-Oct-2010*rlc
# - Fixed bug in QuoteHistory date field
# 24-Nov-2010*rlc
# - Skip quotes with missing parameters. Otherwise, Money mail throw an error during import.
# - Add an "account balance" data field of zero (balance=0) for the overall statement.
# 10-Jan-2010*rlc
# - Write quote summary to xfrdir\quotes.htm
# - Moved _header, OfxField, OfxTag, _genuid, and OfxDate functios to Removed "\r" from linebreaks.
# Will reuse when combining statements
# 18-Feb-2011*rlc:
# - Use ticker symbol when stock name from Yahoo is null
# - Added Cal's yahoo screen scraper for symbols not available via the csv interface
# - Added YahooTimeZone option
# - Added support for quote multiplier option
# 22-Mar-2011*rlc:
# - Added support for alternate ticker symbol to send to Money (instead of Yahoo symbol)
# Default symbol = Yahoo ticker
# 03Sep2013*rlc
# - Modify to support European versions of MS Money 2005 (and probably 2003/2004)
# * Added INVTRANLIST tag set
# * Added support for forceQuotes option. Force additional quote reponse to adjust
# shares held to non-zero and back.
# - Updated YahooScrape code for updated Yahoo html screen-formatting
# 19Jul2013*rlc
# - Bug fix. Strip commas from YahooScrape price results
# - Added YahooScrape support for quote symbols with a '^' char (e.g., ^DJI)
# 21Oct2013*rlc
# - Added support for quoteAccount
# 09Jan2014*rlc
# - Fixed bug related to ForceQuotes and change of calendar year.
# 19Jan2014*rlc:
# -Added support for EnableGoogleFinance option
# -Reworked the way that quotes are retrieved, to improve reliability
# 14Feb2014*rlc:
# -Extended url timeout. Some ex-US users were having issues.
# -Fixed bug that popped up when EnableYahooFinace=No
# 25Feb2014*rlc:
# -Changed try/catch for URLopen to catch *any* exception
# 14Sep2015*rlc
# -Changed yahoo time parse to read hours in 24hr format
# 09Nov2017*rlc
# -Replace Yahoo quotes csv w/ json
# -Removed yahooScrape option
# 24Mar2018*rlc
# -Use longName when available for Yahoo quotes. Mutual fund *family* name is sometimes given as shortName (see vhcox as example)
import os, sys, time, urllib2, socket, shlex, re, csv, uuid, json
import site_cfg
from control2 import *
from rlib1 import *
from datetime import datetime
join = str.join
class Security:
"""
Encapsulate a stock or mutual fund. A Security has a ticker, a name, a price quote, and
the as-of date and time for the price quote. Name, price and as-of date and time are retrieved
from Yahoo! Finance.
fields:
status, source, ticker, name, price, quoteTime, pclose, pchange
"""
def __init__(self, item):
#item = {"ticker":TickerSym, 'm':multiplier, 's':symbol}
# TickerSym = symbol to grab from Yahoo
# m = multiplier for quote
# s = symbol to pass to Money
self.ticker = item['ticker']
self.multiplier = item['m']
self.symbol = item['s']
self.status = True
socket.setdefaulttimeout(10) #default socket timeout for server read, secs
def _removeIllegalChars(self, inputString):
pattern = re.compile("[^a-zA-Z0-9 ,.-]+")
return pattern.sub("", inputString)
def getQuote(self):
#Yahoo! Finance:
# name (n), lastprice (l1), date (d1), time(t1), previous close (p), %change (p2)
if Debug: print "Getting quote for:", self.ticker
self.status=False
self.source='Y'
#note: each try for a quote sets self.status=true if successful
if eYahoo:
csvtxt = self.getYahooQuote()
quote = self.csvparse(csvtxt)
if self.status: self.source='Y'
if not self.status and eGoogle:
# try screen scrape
csvtxt = self.getGoogleQuote()
quote = self.csvparse(csvtxt)
if self.status: self.source='G'
if not self.status:
print "** ", self.ticker, ': invalid quote response. Skipping...'
self.name = '*InvalidSymbol*'
else:
#show/save what we got rlc*2010
# example: "Amazon.com, Inc.",78.46,"9/3/2009","4:00pm", 80.00, "-1.96%"
# Security names may have embedded commas, so use CSV utility to parse (rlc*2010)
if Debug: print "Quote result string:", csvtxt
self.name = quote[0]
self.price = quote[1]
self.date = quote[2]
self.time = quote[3]
self.pclose = quote[4]
self.pchange = quote[5]
#clean things up, format datetime str, and apply multiplier
# if security name is null, replace name with symbol
if self.name.strip()=='': self.name = self.ticker
self.price = str(float2(self.price)*self.multiplier) #adjust price by multiplier
self.date = self.date.lstrip('0 ')
self.datetime = datetime.strptime(self.date + " " + self.time, "%m/%d/%Y %H:%M%p")
self.quoteTime = self.datetime.strftime("%Y%m%d%H%M%S") + '[' + YahooTimeZone + ']'
if '?' not in self.pclose and 'N/A' not in self.pclose:
#adjust last close price by multiplier
self.pclose = str(float2(self.pclose)*self.multiplier) #previous close
name = self.ticker
if self.symbol <> self.ticker:
name = self.ticker + '(' + self.symbol + ')'
print self.source+':' , name, self.price, self.date, self.time, self.pchange
def csvparse(self, csvtxt):
quote=[]
self.status=True
csvlst = [csvtxt] # csv.reader reads lists the same as files
reader = csv.reader(csvlst)
for row in reader: # we only have one row... so read it into a quote list
quote = row # quote[]= [name, price, quoteTime, pclose, pchange], all as strings
if len(quote) < 6:
self.status=False
elif quote[1] == '0.00' or quote[2] == 'N/A':
self.status=False
return quote
def getYahooQuote(self):
#read Yahoo json data api, and return csv
url = YahooURL + "?symbols=%s" % self.ticker
csvtxt=""
self.status=True
try:
ht=urllib2.urlopen(url).read()
self.quoteURL = 'https://finance.yahoo.com/quote/%s' % self.ticker #html link
except:
if Debug: print "** Error reading " + url + "\n"
self.status = False
if self.status:
try:
j = json.loads(ht) #parse json to dict
jd = j['quoteResponse']['result'][0] #inside response pkg
#use longName if available, otherwise use shortName field
try:
name = jd['longName']
except:
name = jd['shortName']
price = jd['regularMarketPrice']
mtime = jd['regularMarketTime']
lastPrice = jd['regularMarketPreviousClose']
changePer = jd['regularMarketChangePercent']
qtime = time.localtime(mtime)
qdateS = time.strftime("%m/%d/%Y", qtime)
qtimeS = time.strftime("%I:%M%p", qtime)
changeS = '{0:.2}%'.format(changePer)
name = '"' + self._removeIllegalChars(name) + '"' #cleanup foreign chars and quote
csvtxt = ','.join([name, str(price), qdateS, qtimeS, str(lastPrice), changeS])
if Debug: print "Yahoo csvtxt=",csvtxt
except:
#not formatted as expected?
if Debug: print "An error occured by parsing the Yahoo Finance reponse for: ", self.ticker
self.status=False
return csvtxt
def getGoogleQuote(self):
#New screen scrape function: 19-Jan-2014*rlc
# This function creates a csvtxt string with the same format as the Yahoo csv interface
# Example return: "Amazon.com, Inc.","78.46","9/3/2009","4:00pm", 80.00, "-1.96%"
# Gets data from Google Finance
self.status = True # fresh start
csvtxt = ""
if Debug: print "Trying Google Finance for: ", self.ticker
#Example url: https://www.google.com/finance?q=msft
url = GoogleURL + "?q=" + self.ticker
try:
ht=urllib2.urlopen(url).read()
self.quoteURL = url
except:
print "** error reading " + url + "\n"
self.status = False
ticker = self.ticker.replace("^","\^") #use literal regex character
if self.status:
try:
#Name
t1 = '(<meta itemprop="name".*?content=")(.*?)(")'
p = re.compile(t1, re.IGNORECASE | re.DOTALL)
rslt = p.findall(ht)
name= rslt[0][1]
#price
t1 = '(<meta itemprop="price".*?content=")(.*?)(")'
p = re.compile(t1, re.IGNORECASE | re.DOTALL)
rslt = p.findall(ht)
price= rslt[0][1]
#Price change%
t1 = '(<meta itemprop="priceChangePercent".*?content=")(.*?)(")'
p = re.compile(t1, re.IGNORECASE | re.DOTALL)
rslt = p.findall(ht)
pchange= rslt[0][1] + '%'
#Google date/time format= "yyyy-mm-ddThh:mm:ssZ"
# Example = "2014-01-10T21:30:00Z"
t1 = '(<meta itemprop="quoteTime".*?content=")(.*?)(")'
p = re.compile(t1, re.IGNORECASE | re.DOTALL | re.MULTILINE)
rslt = p.findall(ht)
date1= rslt[0][1]
qdate = datetime.strptime(date1, "%Y-%m-%dT%H:%M:%SZ")
date2 = qdate.strftime("%m/%d/%Y").lstrip('0 ') #mm/dd/yyyy, but no leading zero or spaces
#name may contain commas and illegal chars, so clenaup & enclose in quotes
name = '"' + self._removeIllegalChars(name) + '"'
#price may contain commas, but we don't want them
price = ''.join([c for c in price if c in '1234567890.'])
csvtxt = ','.join([name, price, date2, '04:00PM', '?', pchange])
if Debug: print "Google csvtxt=",csvtxt
except:
self.status=False
if Debug: print "An error occured by parsing the Google Finance reponse for: ", self.ticker
return csvtxt
class OfxWriter:
"""
Create an OFX file based on a list of stocks and mutual funds.
"""
def __init__(self, currency, account, shares, stockList, mfList):
self.currency = currency
self.account = account
self.shares = shares
self.stockList = stockList
self.mfList = mfList
self.dtasof = self.get_dtasof()
def get_dtasof(self):
#15-Feb-2011: Use the latest quote date/time for the statement
today = datetime.today()
dtasof = today.strftime("%Y%m%d")+'120000' #default to today @ noon
lastdate = datetime(1,1,1) #but compare actual dates to long, long ago...
for ticker in self.stockList + self.mfList:
if ticker.datetime > lastdate and not ticker.datetime > today:
lastdate = ticker.datetime
dtasof = ticker.quoteTime
return dtasof
def _signOn(self):
"""Generate server signon response message"""
return OfxTag("SIGNONMSGSRSV1",
OfxTag("SONRS",
OfxTag("STATUS",
OfxField("CODE", "0"),
OfxField("SEVERITY", "INFO"),
OfxField("MESSAGE","Successful Sign On")
),
OfxField("DTSERVER", OfxDate()),
OfxField("LANGUAGE", "ENG"),
OfxField("DTPROFUP", "20010918083000"),
OfxTag("FI", OfxField("ORG", "PocketSense"))
)
)
def invPosList(self):
# create INVPOSLIST section, including all stock and MF symbols
posstock = []
for stock in self.stockList:
posstock.append(self._pos("stock", stock.symbol, stock.price, stock.quoteTime))
posmf = [] | join("", posstock), #str.join("",StrList) = "str(0)+str(1)+str(2)..."
join("", posmf))
def _pos(self, type, symbol, price, quoteTime):
return OfxTag("POS" + type.upper(),
OfxTag("INVPOS",
OfxTag("SECID",
OfxField("UNIQUEID", symbol),
OfxField("UNIQUEIDTYPE", "TICKER")
),
OfxField("HELDINACCT", "CASH"),
OfxField("POSTYPE", "LONG"),
OfxField("UNITS", str(self.shares)),
OfxField("UNITPRICE", price),
OfxField("MKTVAL", str(float2(price)*self.shares)),
#OfxField("MKTVAL", "0"), #rlc:08-2013
OfxField("DTPRICEASOF", quoteTime)
)
)
def invStmt(self, acctid):
#write the INVSTMTRS section
stmt = OfxTag("INVSTMTRS",
OfxField("DTASOF", self.dtasof),
OfxField("CURDEF", self.currency),
OfxTag("INVACCTFROM",
OfxField("BROKERID", "PocketSense"),
OfxField("ACCTID",acctid)
),
OfxTag("INVTRANLIST",
OfxField("DTSTART", self.dtasof),
OfxField("DTEND", self.dtasof),
),
self.invPosList()
)
return stmt
def invServerMsg(self,stmt):
#wrap stmt in INVSTMTMSGSRSV1 tag set
s = OfxTag("INVSTMTTRNRS",
OfxField("TRNUID",ofxUUID()),
OfxTag("STATUS",
OfxField("CODE", "0"),
OfxField("SEVERITY", "INFO")),
OfxField("CLTCOOKIE","4"),
stmt)
return OfxTag("INVSTMTMSGSRSV1", s)
def _secList(self):
stockinfo = []
for stock in self.stockList:
stockinfo.append(self._info("stock", stock.symbol, stock.name, stock.price))
mfinfo = []
for mf in self.mfList:
mfinfo.append(self._info("mf", mf.symbol, mf.name, mf.price))
return OfxTag("SECLISTMSGSRSV1",
OfxTag("SECLIST",
join("", stockinfo),
join("", mfinfo)
)
)
def _info(self, type, symbol, name, price):
secInfo = OfxTag("SECINFO",
OfxTag("SECID",
OfxField("UNIQUEID", symbol),
OfxField("UNIQUEIDTYPE", "TICKER")
),
OfxField("SECNAME", name),
OfxField("TICKER", symbol),
OfxField("UNITPRICE", price),
OfxField("DTASOF", self.dtasof)
)
if type.upper() == "MF":
info = OfxTag(type.upper() + "INFO",
secInfo,
OfxField("MFTYPE", "OPENEND")
)
else:
info = OfxTag(type.upper() + "INFO", secInfo)
return info
def getOfxMsg(self):
#create main OFX message block
return join('', [OfxTag('OFX',
'<!--Created by PocketSense scripts for Money-->',
'<!--https://sites.google.com/site/pocketsense/home-->',
self._signOn(),
self.invServerMsg(self.invStmt(self.account)),
self._secList()
)])
def writeFile(self, name):
f = open(name,"w")
f.write(OfxSGMLHeader())
f.write(self.getOfxMsg())
f.close()
#----------------------------------------------------------------------------
def getQuotes():
global YahooURL, eYahoo, GoogleURL, eGoogle, YahooTimeZone
status = True #overall status flag across all operations (true == no errors getting data)
#get site and other user-defined data
userdat = site_cfg.site_cfg()
stocks = userdat.stocks
funds = userdat.funds
eYahoo = userdat.enableYahooFinance
YahooURL = userdat.YahooURL
GoogleURL = userdat.GoogleURL
eGoogle = userdat.enableGoogleFinance
YahooTimeZone = userdat.YahooTimeZone
currency = userdat.quotecurrency
account = userdat.quoteAccount
ofxFile1, ofxFile2, htmFileName = '','',''
stockList = []
print "Getting security and fund quotes..."
for item in stocks:
sec = Security(item)
sec.getQuote()
status = status and sec.status
if sec.status: stockList.append(sec)
mfList = []
for item in funds:
sec = Security(item)
sec.getQuote()
status = status and sec.status
if sec.status: mfList.append(sec)
qList = stockList + mfList
if len(qList) > 0: #write results only if we have some data
#create quotes ofx file
if not os.path.exists(xfrdir):
os.mkdir(xfrdir)
ofxFile1 = xfrdir + "quotes" + OfxDate() + str(random.randrange(1e5,1e6)) + ".ofx"
writer = OfxWriter(currency, account, 0, stockList, mfList)
writer.writeFile(ofxFile1)
if userdat.forceQuotes:
#generate a second file with non-zero shares. Getdata and Setup use this file
#to force quote reconciliation in Money, by sending ofxFile2, and then ofxFile1
ofxFile2 = xfrdir + "quotes" + OfxDate() + str(random.randrange(1e5,1e6)) + ".ofx"
writer = OfxWriter(currency, account, 0.001, stockList, mfList)
writer.writeFile(ofxFile2)
if glob.glob(ofxFile1) == []:
status = False
# write quotes.htm file
htmFileName = QuoteHTMwriter(qList)
#append results to QuoteHistory.csv if enabled
if status and userdat.savequotehistory:
csvFile = xfrdir+"QuoteHistory.csv"
print "Appending quote results to {0}...".format(csvFile)
newfile = (glob.glob(csvFile) == [])
f = open(csvFile,"a")
if newfile:
f.write('Symbol,Name,Price,Date/Time,LastClose,%Change\n')
for s in qList:
#Fieldnames: symbol, name, price, quoteTime, pclose, pchange
t = s.quoteTime
t2 = t[4:6]+'/'+t[6:8]+'/'+t[0:4]+' '+ t[8:10]+":"+t[10:12]+":"+t[12:14]
line = '"{0}","{1}",{2},{3},{4},{5}\n' \
.format(s.symbol, s.name, s.price, t2, s.pclose, s.pchange)
f.write(line)
f.close()
return status, ofxFile1, ofxFile2, htmFileName | for mf in self.mfList:
posmf.append(self._pos("mf", mf.symbol, mf.price, mf.quoteTime))
return OfxTag("INVPOSLIST", | random_line_split |
init.rs | use anyhow::{bail, Context, Result};
use nix::{
fcntl, sched, sys,
unistd::{Gid, Uid},
};
use oci_spec::Spec;
use std::{env, os::unix::io::AsRawFd};
use std::{fs, io::Write, path::Path, path::PathBuf};
use crate::{
capabilities,
namespaces::Namespaces,
notify_socket::NotifyListener,
process::child,
rootfs,
rootless::Rootless,
stdio::FileDescriptor,
syscall::{linux::LinuxSyscall, Syscall},
tty, utils,
};
// Make sure a given path is on procfs. This is to avoid the security risk that
// /proc path is mounted over. Ref: CVE-2019-16884
fn ensure_procfs(path: &Path) -> Result<()> {
let procfs_fd = fs::File::open(path)?;
let fstat_info = sys::statfs::fstatfs(&procfs_fd.as_raw_fd())?;
if fstat_info.filesystem_type() != sys::statfs::PROC_SUPER_MAGIC {
bail!(format!("{:?} is not on the procfs", path));
}
Ok(())
}
// Get a list of open fds for the calling process.
fn get_open_fds() -> Result<Vec<i32>> {
const PROCFS_FD_PATH: &str = "/proc/self/fd";
ensure_procfs(Path::new(PROCFS_FD_PATH))
.with_context(|| format!("{} is not the actual procfs", PROCFS_FD_PATH))?;
let fds: Vec<i32> = fs::read_dir(PROCFS_FD_PATH)?
.filter_map(|entry| match entry {
Ok(entry) => Some(entry.path()),
Err(_) => None,
})
.filter_map(|path| path.file_name().map(|file_name| file_name.to_owned()))
.filter_map(|file_name| file_name.to_str().map(String::from))
.filter_map(|file_name| -> Option<i32> {
// Convert the file name from string into i32. Since we are looking
// at /proc/<pid>/fd, anything that's not a number (i32) can be
// ignored. We are only interested in opened fds.
match file_name.parse() {
Ok(fd) => Some(fd),
Err(_) => None,
}
})
.collect();
Ok(fds)
}
// Cleanup any extra file descriptors, so the new container process will not
// leak a file descriptor from before execve gets executed. The first 3 fd will
// stay open: stdio, stdout, and stderr. We would further preserve the next
// "preserve_fds" number of fds. Set the rest of fd with CLOEXEC flag, so they
// will be closed after execve into the container payload. We can't close the
// fds immediatly since we at least still need it for the pipe used to wait on
// starting the container.
fn cleanup_file_descriptors(preserve_fds: i32) -> Result<()> {
let open_fds = get_open_fds().with_context(|| "Failed to obtain opened fds")?;
// Include stdin, stdout, and stderr for fd 0, 1, and 2 respectively.
let min_fd = preserve_fds + 3;
let to_be_cleaned_up_fds: Vec<i32> = open_fds
.iter()
.filter_map(|&fd| if fd >= min_fd { Some(fd) } else { None })
.collect();
to_be_cleaned_up_fds.iter().for_each(|&fd| {
// Intentionally ignore errors here -- the cases where this might fail
// are basically file descriptors that have already been closed.
let _ = fcntl::fcntl(fd, fcntl::F_SETFD(fcntl::FdFlag::FD_CLOEXEC));
});
Ok(())
}
pub struct ContainerInitArgs {
/// Flag indicating if an init or a tenant container should be created
pub init: bool,
/// Interface to operating system primitives
pub syscall: LinuxSyscall,
/// OCI complient runtime spec
pub spec: Spec,
/// Root filesystem of the container
pub rootfs: PathBuf,
/// Socket to communicate the file descriptor of the ptty
pub console_socket: Option<FileDescriptor>,
/// Options for rootless containers
pub rootless: Option<Rootless>,
/// Path to the Unix Domain Socket to communicate container start
pub notify_path: PathBuf,
/// File descriptos preserved/passed to the container init process.
pub preserve_fds: i32,
/// Pipe used to communicate with the child process
pub child: child::ChildProcess,
}
pub fn container_init(args: ContainerInitArgs) -> Result<()> {
let command = &args.syscall;
let spec = &args.spec;
let linux = &spec.linux.as_ref().context("no linux in spec")?;
let namespaces: Namespaces = linux.namespaces.clone().into();
// need to create the notify socket before we pivot root, since the unix
// domain socket used here is outside of the rootfs of container
let mut notify_socket: NotifyListener = NotifyListener::new(&args.notify_path)?;
let proc = &spec.process.as_ref().context("no process in spec")?;
let mut envs: Vec<String> = proc.env.clone();
let rootfs = &args.rootfs;
let mut child = args.child;
// if Out-of-memory score adjustment is set in specification. set the score
// value for the current process check
// https://dev.to/rrampage/surviving-the-linux-oom-killer-2ki9 for some more
// information
if let Some(ref resource) = linux.resources {
if let Some(oom_score_adj) = resource.oom_score_adj {
let mut f = fs::File::create("/proc/self/oom_score_adj")?;
f.write_all(oom_score_adj.to_string().as_bytes())?;
}
}
// if new user is specified in specification, this will be true and new
// namespace will be created, check
// https://man7.org/linux/man-pages/man7/user_namespaces.7.html for more
// information
if args.rootless.is_some() {
// child needs to be dumpable, otherwise the non root parent is not
// allowed to write the uid/gid maps
prctl::set_dumpable(true).unwrap();
child.request_identifier_mapping()?;
child.wait_for_mapping_ack()?;
prctl::set_dumpable(false).unwrap();
}
// set limits and namespaces to the process
for rlimit in proc.rlimits.iter() {
command.set_rlimit(rlimit).context("failed to set rlimit")?;
}
command
.set_id(Uid::from_raw(0), Gid::from_raw(0))
.context("failed to become root")?;
// set up tty if specified
if let Some(csocketfd) = args.console_socket {
tty::setup_console(&csocketfd)?;
}
// join existing namespaces
namespaces.apply_setns()?;
command.set_hostname(spec.hostname.as_ref().context("no hostname in spec")?)?;
if proc.no_new_privileges {
let _ = prctl::set_no_new_privileges(true);
}
if args.init |
command.set_id(Uid::from_raw(proc.user.uid), Gid::from_raw(proc.user.gid))?;
capabilities::reset_effective(command)?;
if let Some(caps) = &proc.capabilities {
capabilities::drop_privileges(caps, command)?;
}
// Take care of LISTEN_FDS used for systemd-active-socket. If the value is
// not 0, then we have to preserve those fds as well, and set up the correct
// environment variables.
let preserve_fds: i32 = match env::var("LISTEN_FDS") {
Ok(listen_fds_str) => {
let listen_fds = match listen_fds_str.parse::<i32>() {
Ok(v) => v,
Err(error) => {
log::warn!(
"LISTEN_FDS entered is not a fd. Ignore the value. {:?}",
error
);
0
}
};
// The LISTEN_FDS will have to be passed to container init process.
// The LISTEN_PID will be set to PID 1. Based on the spec, if
// LISTEN_FDS is 0, the variable should be unset, so we just ignore
// it here, if it is 0.
if listen_fds > 0 {
envs.append(&mut vec![
format!("LISTEN_FDS={}", listen_fds),
"LISTEN_PID=1".to_string(),
]);
}
args.preserve_fds + listen_fds
}
Err(env::VarError::NotPresent) => args.preserve_fds,
Err(env::VarError::NotUnicode(value)) => {
log::warn!(
"LISTEN_FDS entered is malformed: {:?}. Ignore the value.",
&value
);
args.preserve_fds
}
};
// clean up and handle perserved fds.
cleanup_file_descriptors(preserve_fds).with_context(|| "Failed to clean up extra fds")?;
// notify parents that the init process is ready to execute the payload.
child.notify_parent()?;
// listing on the notify socket for container start command
notify_socket.wait_for_container_start()?;
let args: &Vec<String> = &proc.args;
utils::do_exec(&args[0], args, &envs)?;
// After do_exec is called, the process is replaced with the container
// payload through execvp, so it should never reach here.
unreachable!();
}
#[cfg(test)]
mod tests {
use super::*;
use anyhow::{bail, Result};
use nix::{fcntl, sys, unistd};
use std::fs;
#[test]
fn test_get_open_fds() -> Result<()> {
let file = fs::File::open("/dev/null")?;
let fd = file.as_raw_fd();
let open_fds = super::get_open_fds()?;
if !open_fds.iter().any(|&v| v == fd) {
bail!("Failed to find the opened dev null fds: {:?}", open_fds);
}
// explicitly close the file before the test case returns.
drop(file);
// The stdio fds should also be contained in the list of opened fds.
if !vec![0, 1, 2]
.iter()
.all(|&stdio_fd| open_fds.iter().any(|&open_fd| open_fd == stdio_fd))
{
bail!("Failed to find the stdio fds: {:?}", open_fds);
}
Ok(())
}
#[test]
fn test_cleanup_file_descriptors() -> Result<()> {
// Open a fd without the CLOEXEC flag. Rust automatically adds the flag,
// so we use fcntl::open here for more control.
let fd = fcntl::open("/dev/null", fcntl::OFlag::O_RDWR, sys::stat::Mode::empty())?;
cleanup_file_descriptors(fd - 1).with_context(|| "Failed to clean up the fds")?;
let fd_flag = fcntl::fcntl(fd, fcntl::F_GETFD)?;
if (fd_flag & fcntl::FdFlag::FD_CLOEXEC.bits()) != 0 {
bail!("CLOEXEC flag is not set correctly");
}
unistd::close(fd)?;
Ok(())
}
}
| {
rootfs::prepare_rootfs(
spec,
rootfs,
namespaces
.clone_flags
.contains(sched::CloneFlags::CLONE_NEWUSER),
)
.with_context(|| "Failed to prepare rootfs")?;
// change the root of filesystem of the process to the rootfs
command
.pivot_rootfs(rootfs)
.with_context(|| format!("Failed to pivot root to {:?}", rootfs))?;
} | conditional_block |
init.rs | use anyhow::{bail, Context, Result};
use nix::{
fcntl, sched, sys,
unistd::{Gid, Uid},
};
use oci_spec::Spec;
use std::{env, os::unix::io::AsRawFd};
use std::{fs, io::Write, path::Path, path::PathBuf};
use crate::{
capabilities,
namespaces::Namespaces,
notify_socket::NotifyListener,
process::child,
rootfs,
rootless::Rootless,
stdio::FileDescriptor,
syscall::{linux::LinuxSyscall, Syscall},
tty, utils,
};
// Make sure a given path is on procfs. This is to avoid the security risk that
// /proc path is mounted over. Ref: CVE-2019-16884
fn ensure_procfs(path: &Path) -> Result<()> {
let procfs_fd = fs::File::open(path)?;
let fstat_info = sys::statfs::fstatfs(&procfs_fd.as_raw_fd())?;
if fstat_info.filesystem_type() != sys::statfs::PROC_SUPER_MAGIC {
bail!(format!("{:?} is not on the procfs", path));
}
Ok(())
}
// Get a list of open fds for the calling process.
fn get_open_fds() -> Result<Vec<i32>> {
const PROCFS_FD_PATH: &str = "/proc/self/fd";
ensure_procfs(Path::new(PROCFS_FD_PATH))
.with_context(|| format!("{} is not the actual procfs", PROCFS_FD_PATH))?;
let fds: Vec<i32> = fs::read_dir(PROCFS_FD_PATH)?
.filter_map(|entry| match entry {
Ok(entry) => Some(entry.path()),
Err(_) => None,
})
.filter_map(|path| path.file_name().map(|file_name| file_name.to_owned()))
.filter_map(|file_name| file_name.to_str().map(String::from))
.filter_map(|file_name| -> Option<i32> {
// Convert the file name from string into i32. Since we are looking
// at /proc/<pid>/fd, anything that's not a number (i32) can be
// ignored. We are only interested in opened fds.
match file_name.parse() {
Ok(fd) => Some(fd),
Err(_) => None,
}
})
.collect();
Ok(fds)
}
// Cleanup any extra file descriptors, so the new container process will not
// leak a file descriptor from before execve gets executed. The first 3 fd will
// stay open: stdio, stdout, and stderr. We would further preserve the next
// "preserve_fds" number of fds. Set the rest of fd with CLOEXEC flag, so they
// will be closed after execve into the container payload. We can't close the
// fds immediatly since we at least still need it for the pipe used to wait on
// starting the container.
fn cleanup_file_descriptors(preserve_fds: i32) -> Result<()> {
let open_fds = get_open_fds().with_context(|| "Failed to obtain opened fds")?;
// Include stdin, stdout, and stderr for fd 0, 1, and 2 respectively.
let min_fd = preserve_fds + 3;
let to_be_cleaned_up_fds: Vec<i32> = open_fds
.iter()
.filter_map(|&fd| if fd >= min_fd { Some(fd) } else { None })
.collect();
to_be_cleaned_up_fds.iter().for_each(|&fd| {
// Intentionally ignore errors here -- the cases where this might fail
// are basically file descriptors that have already been closed.
let _ = fcntl::fcntl(fd, fcntl::F_SETFD(fcntl::FdFlag::FD_CLOEXEC));
});
Ok(())
}
pub struct ContainerInitArgs {
/// Flag indicating if an init or a tenant container should be created
pub init: bool,
/// Interface to operating system primitives
pub syscall: LinuxSyscall,
/// OCI complient runtime spec
pub spec: Spec,
/// Root filesystem of the container
pub rootfs: PathBuf,
/// Socket to communicate the file descriptor of the ptty
pub console_socket: Option<FileDescriptor>,
/// Options for rootless containers
pub rootless: Option<Rootless>,
/// Path to the Unix Domain Socket to communicate container start
pub notify_path: PathBuf,
/// File descriptos preserved/passed to the container init process.
pub preserve_fds: i32,
/// Pipe used to communicate with the child process
pub child: child::ChildProcess,
}
pub fn container_init(args: ContainerInitArgs) -> Result<()> {
let command = &args.syscall;
let spec = &args.spec;
let linux = &spec.linux.as_ref().context("no linux in spec")?;
let namespaces: Namespaces = linux.namespaces.clone().into();
// need to create the notify socket before we pivot root, since the unix
// domain socket used here is outside of the rootfs of container
let mut notify_socket: NotifyListener = NotifyListener::new(&args.notify_path)?;
let proc = &spec.process.as_ref().context("no process in spec")?;
let mut envs: Vec<String> = proc.env.clone();
let rootfs = &args.rootfs;
let mut child = args.child;
// if Out-of-memory score adjustment is set in specification. set the score
// value for the current process check
// https://dev.to/rrampage/surviving-the-linux-oom-killer-2ki9 for some more
// information
if let Some(ref resource) = linux.resources {
if let Some(oom_score_adj) = resource.oom_score_adj {
let mut f = fs::File::create("/proc/self/oom_score_adj")?;
f.write_all(oom_score_adj.to_string().as_bytes())?;
}
}
// if new user is specified in specification, this will be true and new
// namespace will be created, check
// https://man7.org/linux/man-pages/man7/user_namespaces.7.html for more
// information
if args.rootless.is_some() {
// child needs to be dumpable, otherwise the non root parent is not
// allowed to write the uid/gid maps
prctl::set_dumpable(true).unwrap();
child.request_identifier_mapping()?;
child.wait_for_mapping_ack()?;
prctl::set_dumpable(false).unwrap();
}
// set limits and namespaces to the process
for rlimit in proc.rlimits.iter() {
command.set_rlimit(rlimit).context("failed to set rlimit")?;
}
command
.set_id(Uid::from_raw(0), Gid::from_raw(0))
.context("failed to become root")?;
// set up tty if specified
if let Some(csocketfd) = args.console_socket {
tty::setup_console(&csocketfd)?;
}
// join existing namespaces
namespaces.apply_setns()?;
command.set_hostname(spec.hostname.as_ref().context("no hostname in spec")?)?;
if proc.no_new_privileges {
let _ = prctl::set_no_new_privileges(true);
}
if args.init {
rootfs::prepare_rootfs(
spec,
rootfs,
namespaces
.clone_flags
.contains(sched::CloneFlags::CLONE_NEWUSER),
)
.with_context(|| "Failed to prepare rootfs")?;
// change the root of filesystem of the process to the rootfs
command
.pivot_rootfs(rootfs)
.with_context(|| format!("Failed to pivot root to {:?}", rootfs))?;
}
command.set_id(Uid::from_raw(proc.user.uid), Gid::from_raw(proc.user.gid))?;
capabilities::reset_effective(command)?;
if let Some(caps) = &proc.capabilities {
capabilities::drop_privileges(caps, command)?;
}
// Take care of LISTEN_FDS used for systemd-active-socket. If the value is
// not 0, then we have to preserve those fds as well, and set up the correct
// environment variables.
let preserve_fds: i32 = match env::var("LISTEN_FDS") {
Ok(listen_fds_str) => {
let listen_fds = match listen_fds_str.parse::<i32>() {
Ok(v) => v,
Err(error) => {
log::warn!(
"LISTEN_FDS entered is not a fd. Ignore the value. {:?}",
error
);
0
}
};
// The LISTEN_FDS will have to be passed to container init process.
// The LISTEN_PID will be set to PID 1. Based on the spec, if
// LISTEN_FDS is 0, the variable should be unset, so we just ignore
// it here, if it is 0.
if listen_fds > 0 {
envs.append(&mut vec![
format!("LISTEN_FDS={}", listen_fds),
"LISTEN_PID=1".to_string(),
]);
}
args.preserve_fds + listen_fds
}
Err(env::VarError::NotPresent) => args.preserve_fds,
Err(env::VarError::NotUnicode(value)) => { | "LISTEN_FDS entered is malformed: {:?}. Ignore the value.",
&value
);
args.preserve_fds
}
};
// clean up and handle perserved fds.
cleanup_file_descriptors(preserve_fds).with_context(|| "Failed to clean up extra fds")?;
// notify parents that the init process is ready to execute the payload.
child.notify_parent()?;
// listing on the notify socket for container start command
notify_socket.wait_for_container_start()?;
let args: &Vec<String> = &proc.args;
utils::do_exec(&args[0], args, &envs)?;
// After do_exec is called, the process is replaced with the container
// payload through execvp, so it should never reach here.
unreachable!();
}
#[cfg(test)]
mod tests {
use super::*;
use anyhow::{bail, Result};
use nix::{fcntl, sys, unistd};
use std::fs;
#[test]
fn test_get_open_fds() -> Result<()> {
let file = fs::File::open("/dev/null")?;
let fd = file.as_raw_fd();
let open_fds = super::get_open_fds()?;
if !open_fds.iter().any(|&v| v == fd) {
bail!("Failed to find the opened dev null fds: {:?}", open_fds);
}
// explicitly close the file before the test case returns.
drop(file);
// The stdio fds should also be contained in the list of opened fds.
if !vec![0, 1, 2]
.iter()
.all(|&stdio_fd| open_fds.iter().any(|&open_fd| open_fd == stdio_fd))
{
bail!("Failed to find the stdio fds: {:?}", open_fds);
}
Ok(())
}
#[test]
fn test_cleanup_file_descriptors() -> Result<()> {
// Open a fd without the CLOEXEC flag. Rust automatically adds the flag,
// so we use fcntl::open here for more control.
let fd = fcntl::open("/dev/null", fcntl::OFlag::O_RDWR, sys::stat::Mode::empty())?;
cleanup_file_descriptors(fd - 1).with_context(|| "Failed to clean up the fds")?;
let fd_flag = fcntl::fcntl(fd, fcntl::F_GETFD)?;
if (fd_flag & fcntl::FdFlag::FD_CLOEXEC.bits()) != 0 {
bail!("CLOEXEC flag is not set correctly");
}
unistd::close(fd)?;
Ok(())
}
} | log::warn!( | random_line_split |
init.rs | use anyhow::{bail, Context, Result};
use nix::{
fcntl, sched, sys,
unistd::{Gid, Uid},
};
use oci_spec::Spec;
use std::{env, os::unix::io::AsRawFd};
use std::{fs, io::Write, path::Path, path::PathBuf};
use crate::{
capabilities,
namespaces::Namespaces,
notify_socket::NotifyListener,
process::child,
rootfs,
rootless::Rootless,
stdio::FileDescriptor,
syscall::{linux::LinuxSyscall, Syscall},
tty, utils,
};
// Make sure a given path is on procfs. This is to avoid the security risk that
// /proc path is mounted over. Ref: CVE-2019-16884
fn ensure_procfs(path: &Path) -> Result<()> {
let procfs_fd = fs::File::open(path)?;
let fstat_info = sys::statfs::fstatfs(&procfs_fd.as_raw_fd())?;
if fstat_info.filesystem_type() != sys::statfs::PROC_SUPER_MAGIC {
bail!(format!("{:?} is not on the procfs", path));
}
Ok(())
}
// Get a list of open fds for the calling process.
fn get_open_fds() -> Result<Vec<i32>> {
const PROCFS_FD_PATH: &str = "/proc/self/fd";
ensure_procfs(Path::new(PROCFS_FD_PATH))
.with_context(|| format!("{} is not the actual procfs", PROCFS_FD_PATH))?;
let fds: Vec<i32> = fs::read_dir(PROCFS_FD_PATH)?
.filter_map(|entry| match entry {
Ok(entry) => Some(entry.path()),
Err(_) => None,
})
.filter_map(|path| path.file_name().map(|file_name| file_name.to_owned()))
.filter_map(|file_name| file_name.to_str().map(String::from))
.filter_map(|file_name| -> Option<i32> {
// Convert the file name from string into i32. Since we are looking
// at /proc/<pid>/fd, anything that's not a number (i32) can be
// ignored. We are only interested in opened fds.
match file_name.parse() {
Ok(fd) => Some(fd),
Err(_) => None,
}
})
.collect();
Ok(fds)
}
// Cleanup any extra file descriptors, so the new container process will not
// leak a file descriptor from before execve gets executed. The first 3 fd will
// stay open: stdio, stdout, and stderr. We would further preserve the next
// "preserve_fds" number of fds. Set the rest of fd with CLOEXEC flag, so they
// will be closed after execve into the container payload. We can't close the
// fds immediatly since we at least still need it for the pipe used to wait on
// starting the container.
fn cleanup_file_descriptors(preserve_fds: i32) -> Result<()> {
let open_fds = get_open_fds().with_context(|| "Failed to obtain opened fds")?;
// Include stdin, stdout, and stderr for fd 0, 1, and 2 respectively.
let min_fd = preserve_fds + 3;
let to_be_cleaned_up_fds: Vec<i32> = open_fds
.iter()
.filter_map(|&fd| if fd >= min_fd { Some(fd) } else { None })
.collect();
to_be_cleaned_up_fds.iter().for_each(|&fd| {
// Intentionally ignore errors here -- the cases where this might fail
// are basically file descriptors that have already been closed.
let _ = fcntl::fcntl(fd, fcntl::F_SETFD(fcntl::FdFlag::FD_CLOEXEC));
});
Ok(())
}
pub struct ContainerInitArgs {
/// Flag indicating if an init or a tenant container should be created
pub init: bool,
/// Interface to operating system primitives
pub syscall: LinuxSyscall,
/// OCI complient runtime spec
pub spec: Spec,
/// Root filesystem of the container
pub rootfs: PathBuf,
/// Socket to communicate the file descriptor of the ptty
pub console_socket: Option<FileDescriptor>,
/// Options for rootless containers
pub rootless: Option<Rootless>,
/// Path to the Unix Domain Socket to communicate container start
pub notify_path: PathBuf,
/// File descriptos preserved/passed to the container init process.
pub preserve_fds: i32,
/// Pipe used to communicate with the child process
pub child: child::ChildProcess,
}
pub fn container_init(args: ContainerInitArgs) -> Result<()> {
let command = &args.syscall;
let spec = &args.spec;
let linux = &spec.linux.as_ref().context("no linux in spec")?;
let namespaces: Namespaces = linux.namespaces.clone().into();
// need to create the notify socket before we pivot root, since the unix
// domain socket used here is outside of the rootfs of container
let mut notify_socket: NotifyListener = NotifyListener::new(&args.notify_path)?;
let proc = &spec.process.as_ref().context("no process in spec")?;
let mut envs: Vec<String> = proc.env.clone();
let rootfs = &args.rootfs;
let mut child = args.child;
// if Out-of-memory score adjustment is set in specification. set the score
// value for the current process check
// https://dev.to/rrampage/surviving-the-linux-oom-killer-2ki9 for some more
// information
if let Some(ref resource) = linux.resources {
if let Some(oom_score_adj) = resource.oom_score_adj {
let mut f = fs::File::create("/proc/self/oom_score_adj")?;
f.write_all(oom_score_adj.to_string().as_bytes())?;
}
}
// if new user is specified in specification, this will be true and new
// namespace will be created, check
// https://man7.org/linux/man-pages/man7/user_namespaces.7.html for more
// information
if args.rootless.is_some() {
// child needs to be dumpable, otherwise the non root parent is not
// allowed to write the uid/gid maps
prctl::set_dumpable(true).unwrap();
child.request_identifier_mapping()?;
child.wait_for_mapping_ack()?;
prctl::set_dumpable(false).unwrap();
}
// set limits and namespaces to the process
for rlimit in proc.rlimits.iter() {
command.set_rlimit(rlimit).context("failed to set rlimit")?;
}
command
.set_id(Uid::from_raw(0), Gid::from_raw(0))
.context("failed to become root")?;
// set up tty if specified
if let Some(csocketfd) = args.console_socket {
tty::setup_console(&csocketfd)?;
}
// join existing namespaces
namespaces.apply_setns()?;
command.set_hostname(spec.hostname.as_ref().context("no hostname in spec")?)?;
if proc.no_new_privileges {
let _ = prctl::set_no_new_privileges(true);
}
if args.init {
rootfs::prepare_rootfs(
spec,
rootfs,
namespaces
.clone_flags
.contains(sched::CloneFlags::CLONE_NEWUSER),
)
.with_context(|| "Failed to prepare rootfs")?;
// change the root of filesystem of the process to the rootfs
command
.pivot_rootfs(rootfs)
.with_context(|| format!("Failed to pivot root to {:?}", rootfs))?;
}
command.set_id(Uid::from_raw(proc.user.uid), Gid::from_raw(proc.user.gid))?;
capabilities::reset_effective(command)?;
if let Some(caps) = &proc.capabilities {
capabilities::drop_privileges(caps, command)?;
}
// Take care of LISTEN_FDS used for systemd-active-socket. If the value is
// not 0, then we have to preserve those fds as well, and set up the correct
// environment variables.
let preserve_fds: i32 = match env::var("LISTEN_FDS") {
Ok(listen_fds_str) => {
let listen_fds = match listen_fds_str.parse::<i32>() {
Ok(v) => v,
Err(error) => {
log::warn!(
"LISTEN_FDS entered is not a fd. Ignore the value. {:?}",
error
);
0
}
};
// The LISTEN_FDS will have to be passed to container init process.
// The LISTEN_PID will be set to PID 1. Based on the spec, if
// LISTEN_FDS is 0, the variable should be unset, so we just ignore
// it here, if it is 0.
if listen_fds > 0 {
envs.append(&mut vec![
format!("LISTEN_FDS={}", listen_fds),
"LISTEN_PID=1".to_string(),
]);
}
args.preserve_fds + listen_fds
}
Err(env::VarError::NotPresent) => args.preserve_fds,
Err(env::VarError::NotUnicode(value)) => {
log::warn!(
"LISTEN_FDS entered is malformed: {:?}. Ignore the value.",
&value
);
args.preserve_fds
}
};
// clean up and handle perserved fds.
cleanup_file_descriptors(preserve_fds).with_context(|| "Failed to clean up extra fds")?;
// notify parents that the init process is ready to execute the payload.
child.notify_parent()?;
// listing on the notify socket for container start command
notify_socket.wait_for_container_start()?;
let args: &Vec<String> = &proc.args;
utils::do_exec(&args[0], args, &envs)?;
// After do_exec is called, the process is replaced with the container
// payload through execvp, so it should never reach here.
unreachable!();
}
#[cfg(test)]
mod tests {
use super::*;
use anyhow::{bail, Result};
use nix::{fcntl, sys, unistd};
use std::fs;
#[test]
fn test_get_open_fds() -> Result<()> {
let file = fs::File::open("/dev/null")?;
let fd = file.as_raw_fd();
let open_fds = super::get_open_fds()?;
if !open_fds.iter().any(|&v| v == fd) {
bail!("Failed to find the opened dev null fds: {:?}", open_fds);
}
// explicitly close the file before the test case returns.
drop(file);
// The stdio fds should also be contained in the list of opened fds.
if !vec![0, 1, 2]
.iter()
.all(|&stdio_fd| open_fds.iter().any(|&open_fd| open_fd == stdio_fd))
{
bail!("Failed to find the stdio fds: {:?}", open_fds);
}
Ok(())
}
#[test]
fn | () -> Result<()> {
// Open a fd without the CLOEXEC flag. Rust automatically adds the flag,
// so we use fcntl::open here for more control.
let fd = fcntl::open("/dev/null", fcntl::OFlag::O_RDWR, sys::stat::Mode::empty())?;
cleanup_file_descriptors(fd - 1).with_context(|| "Failed to clean up the fds")?;
let fd_flag = fcntl::fcntl(fd, fcntl::F_GETFD)?;
if (fd_flag & fcntl::FdFlag::FD_CLOEXEC.bits()) != 0 {
bail!("CLOEXEC flag is not set correctly");
}
unistd::close(fd)?;
Ok(())
}
}
| test_cleanup_file_descriptors | identifier_name |
init.rs | use anyhow::{bail, Context, Result};
use nix::{
fcntl, sched, sys,
unistd::{Gid, Uid},
};
use oci_spec::Spec;
use std::{env, os::unix::io::AsRawFd};
use std::{fs, io::Write, path::Path, path::PathBuf};
use crate::{
capabilities,
namespaces::Namespaces,
notify_socket::NotifyListener,
process::child,
rootfs,
rootless::Rootless,
stdio::FileDescriptor,
syscall::{linux::LinuxSyscall, Syscall},
tty, utils,
};
// Make sure a given path is on procfs. This is to avoid the security risk that
// /proc path is mounted over. Ref: CVE-2019-16884
fn ensure_procfs(path: &Path) -> Result<()> {
let procfs_fd = fs::File::open(path)?;
let fstat_info = sys::statfs::fstatfs(&procfs_fd.as_raw_fd())?;
if fstat_info.filesystem_type() != sys::statfs::PROC_SUPER_MAGIC {
bail!(format!("{:?} is not on the procfs", path));
}
Ok(())
}
// Get a list of open fds for the calling process.
fn get_open_fds() -> Result<Vec<i32>> |
// Cleanup any extra file descriptors, so the new container process will not
// leak a file descriptor from before execve gets executed. The first 3 fd will
// stay open: stdio, stdout, and stderr. We would further preserve the next
// "preserve_fds" number of fds. Set the rest of fd with CLOEXEC flag, so they
// will be closed after execve into the container payload. We can't close the
// fds immediatly since we at least still need it for the pipe used to wait on
// starting the container.
fn cleanup_file_descriptors(preserve_fds: i32) -> Result<()> {
let open_fds = get_open_fds().with_context(|| "Failed to obtain opened fds")?;
// Include stdin, stdout, and stderr for fd 0, 1, and 2 respectively.
let min_fd = preserve_fds + 3;
let to_be_cleaned_up_fds: Vec<i32> = open_fds
.iter()
.filter_map(|&fd| if fd >= min_fd { Some(fd) } else { None })
.collect();
to_be_cleaned_up_fds.iter().for_each(|&fd| {
// Intentionally ignore errors here -- the cases where this might fail
// are basically file descriptors that have already been closed.
let _ = fcntl::fcntl(fd, fcntl::F_SETFD(fcntl::FdFlag::FD_CLOEXEC));
});
Ok(())
}
pub struct ContainerInitArgs {
/// Flag indicating if an init or a tenant container should be created
pub init: bool,
/// Interface to operating system primitives
pub syscall: LinuxSyscall,
/// OCI complient runtime spec
pub spec: Spec,
/// Root filesystem of the container
pub rootfs: PathBuf,
/// Socket to communicate the file descriptor of the ptty
pub console_socket: Option<FileDescriptor>,
/// Options for rootless containers
pub rootless: Option<Rootless>,
/// Path to the Unix Domain Socket to communicate container start
pub notify_path: PathBuf,
/// File descriptos preserved/passed to the container init process.
pub preserve_fds: i32,
/// Pipe used to communicate with the child process
pub child: child::ChildProcess,
}
pub fn container_init(args: ContainerInitArgs) -> Result<()> {
let command = &args.syscall;
let spec = &args.spec;
let linux = &spec.linux.as_ref().context("no linux in spec")?;
let namespaces: Namespaces = linux.namespaces.clone().into();
// need to create the notify socket before we pivot root, since the unix
// domain socket used here is outside of the rootfs of container
let mut notify_socket: NotifyListener = NotifyListener::new(&args.notify_path)?;
let proc = &spec.process.as_ref().context("no process in spec")?;
let mut envs: Vec<String> = proc.env.clone();
let rootfs = &args.rootfs;
let mut child = args.child;
// if Out-of-memory score adjustment is set in specification. set the score
// value for the current process check
// https://dev.to/rrampage/surviving-the-linux-oom-killer-2ki9 for some more
// information
if let Some(ref resource) = linux.resources {
if let Some(oom_score_adj) = resource.oom_score_adj {
let mut f = fs::File::create("/proc/self/oom_score_adj")?;
f.write_all(oom_score_adj.to_string().as_bytes())?;
}
}
// if new user is specified in specification, this will be true and new
// namespace will be created, check
// https://man7.org/linux/man-pages/man7/user_namespaces.7.html for more
// information
if args.rootless.is_some() {
// child needs to be dumpable, otherwise the non root parent is not
// allowed to write the uid/gid maps
prctl::set_dumpable(true).unwrap();
child.request_identifier_mapping()?;
child.wait_for_mapping_ack()?;
prctl::set_dumpable(false).unwrap();
}
// set limits and namespaces to the process
for rlimit in proc.rlimits.iter() {
command.set_rlimit(rlimit).context("failed to set rlimit")?;
}
command
.set_id(Uid::from_raw(0), Gid::from_raw(0))
.context("failed to become root")?;
// set up tty if specified
if let Some(csocketfd) = args.console_socket {
tty::setup_console(&csocketfd)?;
}
// join existing namespaces
namespaces.apply_setns()?;
command.set_hostname(spec.hostname.as_ref().context("no hostname in spec")?)?;
if proc.no_new_privileges {
let _ = prctl::set_no_new_privileges(true);
}
if args.init {
rootfs::prepare_rootfs(
spec,
rootfs,
namespaces
.clone_flags
.contains(sched::CloneFlags::CLONE_NEWUSER),
)
.with_context(|| "Failed to prepare rootfs")?;
// change the root of filesystem of the process to the rootfs
command
.pivot_rootfs(rootfs)
.with_context(|| format!("Failed to pivot root to {:?}", rootfs))?;
}
command.set_id(Uid::from_raw(proc.user.uid), Gid::from_raw(proc.user.gid))?;
capabilities::reset_effective(command)?;
if let Some(caps) = &proc.capabilities {
capabilities::drop_privileges(caps, command)?;
}
// Take care of LISTEN_FDS used for systemd-active-socket. If the value is
// not 0, then we have to preserve those fds as well, and set up the correct
// environment variables.
let preserve_fds: i32 = match env::var("LISTEN_FDS") {
Ok(listen_fds_str) => {
let listen_fds = match listen_fds_str.parse::<i32>() {
Ok(v) => v,
Err(error) => {
log::warn!(
"LISTEN_FDS entered is not a fd. Ignore the value. {:?}",
error
);
0
}
};
// The LISTEN_FDS will have to be passed to container init process.
// The LISTEN_PID will be set to PID 1. Based on the spec, if
// LISTEN_FDS is 0, the variable should be unset, so we just ignore
// it here, if it is 0.
if listen_fds > 0 {
envs.append(&mut vec![
format!("LISTEN_FDS={}", listen_fds),
"LISTEN_PID=1".to_string(),
]);
}
args.preserve_fds + listen_fds
}
Err(env::VarError::NotPresent) => args.preserve_fds,
Err(env::VarError::NotUnicode(value)) => {
log::warn!(
"LISTEN_FDS entered is malformed: {:?}. Ignore the value.",
&value
);
args.preserve_fds
}
};
// clean up and handle perserved fds.
cleanup_file_descriptors(preserve_fds).with_context(|| "Failed to clean up extra fds")?;
// notify parents that the init process is ready to execute the payload.
child.notify_parent()?;
// listing on the notify socket for container start command
notify_socket.wait_for_container_start()?;
let args: &Vec<String> = &proc.args;
utils::do_exec(&args[0], args, &envs)?;
// After do_exec is called, the process is replaced with the container
// payload through execvp, so it should never reach here.
unreachable!();
}
#[cfg(test)]
mod tests {
use super::*;
use anyhow::{bail, Result};
use nix::{fcntl, sys, unistd};
use std::fs;
#[test]
fn test_get_open_fds() -> Result<()> {
let file = fs::File::open("/dev/null")?;
let fd = file.as_raw_fd();
let open_fds = super::get_open_fds()?;
if !open_fds.iter().any(|&v| v == fd) {
bail!("Failed to find the opened dev null fds: {:?}", open_fds);
}
// explicitly close the file before the test case returns.
drop(file);
// The stdio fds should also be contained in the list of opened fds.
if !vec![0, 1, 2]
.iter()
.all(|&stdio_fd| open_fds.iter().any(|&open_fd| open_fd == stdio_fd))
{
bail!("Failed to find the stdio fds: {:?}", open_fds);
}
Ok(())
}
#[test]
fn test_cleanup_file_descriptors() -> Result<()> {
// Open a fd without the CLOEXEC flag. Rust automatically adds the flag,
// so we use fcntl::open here for more control.
let fd = fcntl::open("/dev/null", fcntl::OFlag::O_RDWR, sys::stat::Mode::empty())?;
cleanup_file_descriptors(fd - 1).with_context(|| "Failed to clean up the fds")?;
let fd_flag = fcntl::fcntl(fd, fcntl::F_GETFD)?;
if (fd_flag & fcntl::FdFlag::FD_CLOEXEC.bits()) != 0 {
bail!("CLOEXEC flag is not set correctly");
}
unistd::close(fd)?;
Ok(())
}
}
| {
const PROCFS_FD_PATH: &str = "/proc/self/fd";
ensure_procfs(Path::new(PROCFS_FD_PATH))
.with_context(|| format!("{} is not the actual procfs", PROCFS_FD_PATH))?;
let fds: Vec<i32> = fs::read_dir(PROCFS_FD_PATH)?
.filter_map(|entry| match entry {
Ok(entry) => Some(entry.path()),
Err(_) => None,
})
.filter_map(|path| path.file_name().map(|file_name| file_name.to_owned()))
.filter_map(|file_name| file_name.to_str().map(String::from))
.filter_map(|file_name| -> Option<i32> {
// Convert the file name from string into i32. Since we are looking
// at /proc/<pid>/fd, anything that's not a number (i32) can be
// ignored. We are only interested in opened fds.
match file_name.parse() {
Ok(fd) => Some(fd),
Err(_) => None,
}
})
.collect();
Ok(fds)
} | identifier_body |
batch-rotate.go | // Copyright (c) 2015-2023 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero 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 Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
package cmd
import (
"bytes"
"context"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"io"
"math/rand"
"net/http"
"runtime"
"strconv"
"strings"
"time"
jsoniter "github.com/json-iterator/go"
"github.com/minio/minio-go/v7/pkg/tags"
"github.com/minio/minio/internal/crypto"
xhttp "github.com/minio/minio/internal/http"
"github.com/minio/minio/internal/kms"
"github.com/minio/minio/internal/logger"
"github.com/minio/pkg/env"
"github.com/minio/pkg/wildcard"
"github.com/minio/pkg/workers"
)
// keyrotate:
// apiVersion: v1
// bucket: BUCKET
// prefix: PREFIX
// encryption:
// type: sse-s3 # valid values are sse-s3 and sse-kms
// key: <new-kms-key> # valid only for sse-kms
// context: <new-kms-key-context> # valid only for sse-kms
// # optional flags based filtering criteria
// # for all objects
// flags:
// filter:
// newerThan: "7d" # match objects newer than this value (e.g. 7d10h31s)
// olderThan: "7d" # match objects older than this value (e.g. 7d10h31s)
// createdAfter: "date" # match objects created after "date"
// createdBefore: "date" # match objects created before "date"
// tags:
// - key: "name"
// value: "pick*" # match objects with tag 'name', with all values starting with 'pick'
// metadata:
// - key: "content-type"
// value: "image/*" # match objects with 'content-type', with all values starting with 'image/'
// kmskey: "key-id" # match objects with KMS key-id (applicable only for sse-kms)
// notify:
// endpoint: "https://notify.endpoint" # notification endpoint to receive job status events
// token: "Bearer xxxxx" # optional authentication token for the notification endpoint
// retry:
// attempts: 10 # number of retries for the job before giving up
// delay: "500ms" # least amount of delay between each retry
//go:generate msgp -file $GOFILE -unexported
// BatchKeyRotateKV is a datatype that holds key and values for filtering of objects
// used by metadata filter as well as tags based filtering.
type BatchKeyRotateKV struct {
Key string `yaml:"key" json:"key"`
Value string `yaml:"value" json:"value"`
}
// Validate returns an error if key is empty
func (kv BatchKeyRotateKV) Validate() error |
// Empty indicates if kv is not set
func (kv BatchKeyRotateKV) Empty() bool {
return kv.Key == "" && kv.Value == ""
}
// Match matches input kv with kv, value will be wildcard matched depending on the user input
func (kv BatchKeyRotateKV) Match(ikv BatchKeyRotateKV) bool {
if kv.Empty() {
return true
}
if strings.EqualFold(kv.Key, ikv.Key) {
return wildcard.Match(kv.Value, ikv.Value)
}
return false
}
// BatchKeyRotateRetry datatype represents total retry attempts and delay between each retries.
type BatchKeyRotateRetry struct {
Attempts int `yaml:"attempts" json:"attempts"` // number of retry attempts
Delay time.Duration `yaml:"delay" json:"delay"` // delay between each retries
}
// Validate validates input replicate retries.
func (r BatchKeyRotateRetry) Validate() error {
if r.Attempts < 0 {
return errInvalidArgument
}
if r.Delay < 0 {
return errInvalidArgument
}
return nil
}
// BatchKeyRotationType defines key rotation type
type BatchKeyRotationType string
const (
sses3 BatchKeyRotationType = "sse-s3"
ssekms BatchKeyRotationType = "sse-kms"
)
// BatchJobKeyRotateEncryption defines key rotation encryption options passed
type BatchJobKeyRotateEncryption struct {
Type BatchKeyRotationType `yaml:"type" json:"type"`
Key string `yaml:"key" json:"key"`
Context string `yaml:"context" json:"context"`
kmsContext kms.Context `msg:"-"`
}
// Validate validates input key rotation encryption options.
func (e BatchJobKeyRotateEncryption) Validate() error {
if e.Type != sses3 && e.Type != ssekms {
return errInvalidArgument
}
spaces := strings.HasPrefix(e.Key, " ") || strings.HasSuffix(e.Key, " ")
if e.Type == ssekms && spaces {
return crypto.ErrInvalidEncryptionKeyID
}
if e.Type == ssekms && GlobalKMS != nil {
ctx := kms.Context{}
if e.Context != "" {
b, err := base64.StdEncoding.DecodeString(e.Context)
if err != nil {
return err
}
json := jsoniter.ConfigCompatibleWithStandardLibrary
if err := json.Unmarshal(b, &ctx); err != nil {
return err
}
}
e.kmsContext = kms.Context{}
for k, v := range ctx {
e.kmsContext[k] = v
}
ctx["MinIO batch API"] = "batchrotate" // Context for a test key operation
if _, err := GlobalKMS.GenerateKey(GlobalContext, e.Key, ctx); err != nil {
return err
}
}
return nil
}
// BatchKeyRotateFilter holds all the filters currently supported for batch replication
type BatchKeyRotateFilter struct {
NewerThan time.Duration `yaml:"newerThan,omitempty" json:"newerThan"`
OlderThan time.Duration `yaml:"olderThan,omitempty" json:"olderThan"`
CreatedAfter time.Time `yaml:"createdAfter,omitempty" json:"createdAfter"`
CreatedBefore time.Time `yaml:"createdBefore,omitempty" json:"createdBefore"`
Tags []BatchKeyRotateKV `yaml:"tags,omitempty" json:"tags"`
Metadata []BatchKeyRotateKV `yaml:"metadata,omitempty" json:"metadata"`
KMSKeyID string `yaml:"kmskeyid" json:"kmskey"`
}
// BatchKeyRotateNotification success or failure notification endpoint for each job attempts
type BatchKeyRotateNotification struct {
Endpoint string `yaml:"endpoint" json:"endpoint"`
Token string `yaml:"token" json:"token"`
}
// BatchJobKeyRotateFlags various configurations for replication job definition currently includes
// - filter
// - notify
// - retry
type BatchJobKeyRotateFlags struct {
Filter BatchKeyRotateFilter `yaml:"filter" json:"filter"`
Notify BatchKeyRotateNotification `yaml:"notify" json:"notify"`
Retry BatchKeyRotateRetry `yaml:"retry" json:"retry"`
}
// BatchJobKeyRotateV1 v1 of batch key rotation job
type BatchJobKeyRotateV1 struct {
APIVersion string `yaml:"apiVersion" json:"apiVersion"`
Flags BatchJobKeyRotateFlags `yaml:"flags" json:"flags"`
Bucket string `yaml:"bucket" json:"bucket"`
Prefix string `yaml:"prefix" json:"prefix"`
Endpoint string `yaml:"endpoint" json:"endpoint"`
Encryption BatchJobKeyRotateEncryption `yaml:"encryption" json:"encryption"`
}
// Notify notifies notification endpoint if configured regarding job failure or success.
func (r BatchJobKeyRotateV1) Notify(ctx context.Context, body io.Reader) error {
if r.Flags.Notify.Endpoint == "" {
return nil
}
ctx, cancel := context.WithTimeout(ctx, 10*time.Second)
defer cancel()
req, err := http.NewRequestWithContext(ctx, http.MethodPost, r.Flags.Notify.Endpoint, body)
if err != nil {
return err
}
if r.Flags.Notify.Token != "" {
req.Header.Set("Authorization", r.Flags.Notify.Token)
}
clnt := http.Client{Transport: getRemoteInstanceTransport}
resp, err := clnt.Do(req)
if err != nil {
return err
}
xhttp.DrainBody(resp.Body)
if resp.StatusCode != http.StatusOK {
return errors.New(resp.Status)
}
return nil
}
// KeyRotate rotates encryption key of an object
func (r *BatchJobKeyRotateV1) KeyRotate(ctx context.Context, api ObjectLayer, objInfo ObjectInfo) error {
srcBucket := r.Bucket
srcObject := objInfo.Name
if objInfo.DeleteMarker || !objInfo.VersionPurgeStatus.Empty() {
return nil
}
sseKMS := crypto.S3KMS.IsEncrypted(objInfo.UserDefined)
sseS3 := crypto.S3.IsEncrypted(objInfo.UserDefined)
if !sseKMS && !sseS3 { // neither sse-s3 nor sse-kms disallowed
return errInvalidEncryptionParameters
}
if sseKMS && r.Encryption.Type == sses3 { // previously encrypted with sse-kms, now sse-s3 disallowed
return errInvalidEncryptionParameters
}
versioned := globalBucketVersioningSys.PrefixEnabled(srcBucket, srcObject)
versionSuspended := globalBucketVersioningSys.PrefixSuspended(srcBucket, srcObject)
lock := api.NewNSLock(r.Bucket, objInfo.Name)
lkctx, err := lock.GetLock(ctx, globalOperationTimeout)
if err != nil {
return err
}
ctx = lkctx.Context()
defer lock.Unlock(lkctx)
opts := ObjectOptions{
VersionID: objInfo.VersionID,
Versioned: versioned,
VersionSuspended: versionSuspended,
NoLock: true,
}
obj, err := api.GetObjectInfo(ctx, r.Bucket, objInfo.Name, opts)
if err != nil {
return err
}
oi := obj.Clone()
var (
newKeyID string
newKeyContext kms.Context
)
encMetadata := make(map[string]string)
for k, v := range oi.UserDefined {
if strings.HasPrefix(strings.ToLower(k), ReservedMetadataPrefixLower) {
encMetadata[k] = v
}
}
if (sseKMS || sseS3) && r.Encryption.Type == ssekms {
if err = r.Encryption.Validate(); err != nil {
return err
}
newKeyID = strings.TrimPrefix(r.Encryption.Key, crypto.ARNPrefix)
newKeyContext = r.Encryption.kmsContext
}
if err = rotateKey(ctx, []byte{}, newKeyID, []byte{}, r.Bucket, oi.Name, encMetadata, newKeyContext); err != nil {
return err
}
// Since we are rotating the keys, make sure to update the metadata.
oi.metadataOnly = true
oi.keyRotation = true
for k, v := range encMetadata {
oi.UserDefined[k] = v
}
if _, err := api.CopyObject(ctx, r.Bucket, oi.Name, r.Bucket, oi.Name, oi, ObjectOptions{
VersionID: oi.VersionID,
}, ObjectOptions{
VersionID: oi.VersionID,
NoLock: true,
}); err != nil {
return err
}
return nil
}
const (
batchKeyRotationName = "batch-rotate.bin"
batchKeyRotationFormat = 1
batchKeyRotateVersionV1 = 1
batchKeyRotateVersion = batchKeyRotateVersionV1
batchKeyRotateAPIVersion = "v1"
batchKeyRotateJobDefaultRetries = 3
batchKeyRotateJobDefaultRetryDelay = 250 * time.Millisecond
)
// Start the batch key rottion job, resumes if there was a pending job via "job.ID"
func (r *BatchJobKeyRotateV1) Start(ctx context.Context, api ObjectLayer, job BatchJobRequest) error {
ri := &batchJobInfo{
JobID: job.ID,
JobType: string(job.Type()),
StartTime: job.Started,
}
if err := ri.load(ctx, api, job); err != nil {
return err
}
globalBatchJobsMetrics.save(job.ID, ri)
lastObject := ri.Object
delay := job.KeyRotate.Flags.Retry.Delay
if delay == 0 {
delay = batchKeyRotateJobDefaultRetryDelay
}
rnd := rand.New(rand.NewSource(time.Now().UnixNano()))
skip := func(info FileInfo) (ok bool) {
if r.Flags.Filter.OlderThan > 0 && time.Since(info.ModTime) < r.Flags.Filter.OlderThan {
// skip all objects that are newer than specified older duration
return false
}
if r.Flags.Filter.NewerThan > 0 && time.Since(info.ModTime) >= r.Flags.Filter.NewerThan {
// skip all objects that are older than specified newer duration
return false
}
if !r.Flags.Filter.CreatedAfter.IsZero() && r.Flags.Filter.CreatedAfter.Before(info.ModTime) {
// skip all objects that are created before the specified time.
return false
}
if !r.Flags.Filter.CreatedBefore.IsZero() && r.Flags.Filter.CreatedBefore.After(info.ModTime) {
// skip all objects that are created after the specified time.
return false
}
if len(r.Flags.Filter.Tags) > 0 {
// Only parse object tags if tags filter is specified.
tagMap := map[string]string{}
tagStr := info.Metadata[xhttp.AmzObjectTagging]
if len(tagStr) != 0 {
t, err := tags.ParseObjectTags(tagStr)
if err != nil {
return false
}
tagMap = t.ToMap()
}
for _, kv := range r.Flags.Filter.Tags {
for t, v := range tagMap {
if kv.Match(BatchKeyRotateKV{Key: t, Value: v}) {
return true
}
}
}
// None of the provided tags filter match skip the object
return false
}
if len(r.Flags.Filter.Metadata) > 0 {
for _, kv := range r.Flags.Filter.Metadata {
for k, v := range info.Metadata {
if !strings.HasPrefix(strings.ToLower(k), "x-amz-meta-") && !isStandardHeader(k) {
continue
}
// We only need to match x-amz-meta or standardHeaders
if kv.Match(BatchKeyRotateKV{Key: k, Value: v}) {
return true
}
}
}
// None of the provided metadata filters match skip the object.
return false
}
if r.Flags.Filter.KMSKeyID != "" {
if v, ok := info.Metadata[xhttp.AmzServerSideEncryptionKmsID]; ok && strings.TrimPrefix(v, crypto.ARNPrefix) != r.Flags.Filter.KMSKeyID {
return false
}
}
return true
}
workerSize, err := strconv.Atoi(env.Get("_MINIO_BATCH_KEYROTATION_WORKERS", strconv.Itoa(runtime.GOMAXPROCS(0)/2)))
if err != nil {
return err
}
wk, err := workers.New(workerSize)
if err != nil {
// invalid worker size.
return err
}
retryAttempts := ri.RetryAttempts
ctx, cancel := context.WithCancel(ctx)
results := make(chan ObjectInfo, 100)
if err := api.Walk(ctx, r.Bucket, r.Prefix, results, ObjectOptions{
WalkMarker: lastObject,
WalkFilter: skip,
}); err != nil {
cancel()
// Do not need to retry if we can't list objects on source.
return err
}
for result := range results {
result := result
sseKMS := crypto.S3KMS.IsEncrypted(result.UserDefined)
sseS3 := crypto.S3.IsEncrypted(result.UserDefined)
if !sseKMS && !sseS3 { // neither sse-s3 nor sse-kms disallowed
continue
}
wk.Take()
go func() {
defer wk.Give()
for attempts := 1; attempts <= retryAttempts; attempts++ {
attempts := attempts
stopFn := globalBatchJobsMetrics.trace(batchKeyRotationMetricObject, job.ID, attempts, result)
success := true
if err := r.KeyRotate(ctx, api, result); err != nil {
stopFn(err)
logger.LogIf(ctx, err)
success = false
} else {
stopFn(nil)
}
ri.trackCurrentBucketObject(r.Bucket, result, success)
ri.RetryAttempts = attempts
globalBatchJobsMetrics.save(job.ID, ri)
// persist in-memory state to disk after every 10secs.
logger.LogIf(ctx, ri.updateAfter(ctx, api, 10*time.Second, job))
if success {
break
}
}
}()
}
wk.Wait()
ri.Complete = ri.ObjectsFailed == 0
ri.Failed = ri.ObjectsFailed > 0
globalBatchJobsMetrics.save(job.ID, ri)
// persist in-memory state to disk.
logger.LogIf(ctx, ri.updateAfter(ctx, api, 0, job))
buf, _ := json.Marshal(ri)
if err := r.Notify(ctx, bytes.NewReader(buf)); err != nil {
logger.LogIf(ctx, fmt.Errorf("unable to notify %v", err))
}
cancel()
if ri.Failed {
ri.ObjectsFailed = 0
ri.Bucket = ""
ri.Object = ""
ri.Objects = 0
time.Sleep(delay + time.Duration(rnd.Float64()*float64(delay)))
}
return nil
}
//msgp:ignore batchKeyRotationJobError
type batchKeyRotationJobError struct {
Code string
Description string
HTTPStatusCode int
}
func (e batchKeyRotationJobError) Error() string {
return e.Description
}
// Validate validates the job definition input
func (r *BatchJobKeyRotateV1) Validate(ctx context.Context, job BatchJobRequest, o ObjectLayer) error {
if r == nil {
return nil
}
if r.APIVersion != batchKeyRotateAPIVersion {
return errInvalidArgument
}
if r.Bucket == "" {
return errInvalidArgument
}
if _, err := o.GetBucketInfo(ctx, r.Bucket, BucketOptions{}); err != nil {
if isErrBucketNotFound(err) {
return batchKeyRotationJobError{
Code: "NoSuchSourceBucket",
Description: "The specified source bucket does not exist",
HTTPStatusCode: http.StatusNotFound,
}
}
return err
}
if GlobalKMS == nil {
return errKMSNotConfigured
}
if err := r.Encryption.Validate(); err != nil {
return err
}
for _, tag := range r.Flags.Filter.Tags {
if err := tag.Validate(); err != nil {
return err
}
}
for _, meta := range r.Flags.Filter.Metadata {
if err := meta.Validate(); err != nil {
return err
}
}
if err := r.Flags.Retry.Validate(); err != nil {
return err
}
return nil
}
| {
if kv.Key == "" {
return errInvalidArgument
}
return nil
} | identifier_body |
batch-rotate.go | // Copyright (c) 2015-2023 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero 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 Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
package cmd
import (
"bytes"
"context"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"io"
"math/rand"
"net/http"
"runtime"
"strconv"
"strings"
"time"
jsoniter "github.com/json-iterator/go"
"github.com/minio/minio-go/v7/pkg/tags"
"github.com/minio/minio/internal/crypto"
xhttp "github.com/minio/minio/internal/http"
"github.com/minio/minio/internal/kms"
"github.com/minio/minio/internal/logger"
"github.com/minio/pkg/env"
"github.com/minio/pkg/wildcard"
"github.com/minio/pkg/workers"
)
// keyrotate:
// apiVersion: v1
// bucket: BUCKET
// prefix: PREFIX
// encryption:
// type: sse-s3 # valid values are sse-s3 and sse-kms
// key: <new-kms-key> # valid only for sse-kms
// context: <new-kms-key-context> # valid only for sse-kms
// # optional flags based filtering criteria
// # for all objects
// flags:
// filter:
// newerThan: "7d" # match objects newer than this value (e.g. 7d10h31s)
// olderThan: "7d" # match objects older than this value (e.g. 7d10h31s)
// createdAfter: "date" # match objects created after "date"
// createdBefore: "date" # match objects created before "date"
// tags:
// - key: "name"
// value: "pick*" # match objects with tag 'name', with all values starting with 'pick'
// metadata:
// - key: "content-type"
// value: "image/*" # match objects with 'content-type', with all values starting with 'image/'
// kmskey: "key-id" # match objects with KMS key-id (applicable only for sse-kms)
// notify:
// endpoint: "https://notify.endpoint" # notification endpoint to receive job status events
// token: "Bearer xxxxx" # optional authentication token for the notification endpoint
// retry:
// attempts: 10 # number of retries for the job before giving up
// delay: "500ms" # least amount of delay between each retry
//go:generate msgp -file $GOFILE -unexported
// BatchKeyRotateKV is a datatype that holds key and values for filtering of objects
// used by metadata filter as well as tags based filtering.
type BatchKeyRotateKV struct {
Key string `yaml:"key" json:"key"`
Value string `yaml:"value" json:"value"`
}
// Validate returns an error if key is empty
func (kv BatchKeyRotateKV) Validate() error {
if kv.Key == "" {
return errInvalidArgument
}
return nil
}
// Empty indicates if kv is not set
func (kv BatchKeyRotateKV) Empty() bool {
return kv.Key == "" && kv.Value == ""
}
// Match matches input kv with kv, value will be wildcard matched depending on the user input
func (kv BatchKeyRotateKV) Match(ikv BatchKeyRotateKV) bool {
if kv.Empty() {
return true
}
if strings.EqualFold(kv.Key, ikv.Key) {
return wildcard.Match(kv.Value, ikv.Value)
}
return false
}
// BatchKeyRotateRetry datatype represents total retry attempts and delay between each retries.
type BatchKeyRotateRetry struct {
Attempts int `yaml:"attempts" json:"attempts"` // number of retry attempts
Delay time.Duration `yaml:"delay" json:"delay"` // delay between each retries
}
// Validate validates input replicate retries.
func (r BatchKeyRotateRetry) | () error {
if r.Attempts < 0 {
return errInvalidArgument
}
if r.Delay < 0 {
return errInvalidArgument
}
return nil
}
// BatchKeyRotationType defines key rotation type
type BatchKeyRotationType string
const (
sses3 BatchKeyRotationType = "sse-s3"
ssekms BatchKeyRotationType = "sse-kms"
)
// BatchJobKeyRotateEncryption defines key rotation encryption options passed
type BatchJobKeyRotateEncryption struct {
Type BatchKeyRotationType `yaml:"type" json:"type"`
Key string `yaml:"key" json:"key"`
Context string `yaml:"context" json:"context"`
kmsContext kms.Context `msg:"-"`
}
// Validate validates input key rotation encryption options.
func (e BatchJobKeyRotateEncryption) Validate() error {
if e.Type != sses3 && e.Type != ssekms {
return errInvalidArgument
}
spaces := strings.HasPrefix(e.Key, " ") || strings.HasSuffix(e.Key, " ")
if e.Type == ssekms && spaces {
return crypto.ErrInvalidEncryptionKeyID
}
if e.Type == ssekms && GlobalKMS != nil {
ctx := kms.Context{}
if e.Context != "" {
b, err := base64.StdEncoding.DecodeString(e.Context)
if err != nil {
return err
}
json := jsoniter.ConfigCompatibleWithStandardLibrary
if err := json.Unmarshal(b, &ctx); err != nil {
return err
}
}
e.kmsContext = kms.Context{}
for k, v := range ctx {
e.kmsContext[k] = v
}
ctx["MinIO batch API"] = "batchrotate" // Context for a test key operation
if _, err := GlobalKMS.GenerateKey(GlobalContext, e.Key, ctx); err != nil {
return err
}
}
return nil
}
// BatchKeyRotateFilter holds all the filters currently supported for batch replication
type BatchKeyRotateFilter struct {
NewerThan time.Duration `yaml:"newerThan,omitempty" json:"newerThan"`
OlderThan time.Duration `yaml:"olderThan,omitempty" json:"olderThan"`
CreatedAfter time.Time `yaml:"createdAfter,omitempty" json:"createdAfter"`
CreatedBefore time.Time `yaml:"createdBefore,omitempty" json:"createdBefore"`
Tags []BatchKeyRotateKV `yaml:"tags,omitempty" json:"tags"`
Metadata []BatchKeyRotateKV `yaml:"metadata,omitempty" json:"metadata"`
KMSKeyID string `yaml:"kmskeyid" json:"kmskey"`
}
// BatchKeyRotateNotification success or failure notification endpoint for each job attempts
type BatchKeyRotateNotification struct {
Endpoint string `yaml:"endpoint" json:"endpoint"`
Token string `yaml:"token" json:"token"`
}
// BatchJobKeyRotateFlags various configurations for replication job definition currently includes
// - filter
// - notify
// - retry
type BatchJobKeyRotateFlags struct {
Filter BatchKeyRotateFilter `yaml:"filter" json:"filter"`
Notify BatchKeyRotateNotification `yaml:"notify" json:"notify"`
Retry BatchKeyRotateRetry `yaml:"retry" json:"retry"`
}
// BatchJobKeyRotateV1 v1 of batch key rotation job
type BatchJobKeyRotateV1 struct {
APIVersion string `yaml:"apiVersion" json:"apiVersion"`
Flags BatchJobKeyRotateFlags `yaml:"flags" json:"flags"`
Bucket string `yaml:"bucket" json:"bucket"`
Prefix string `yaml:"prefix" json:"prefix"`
Endpoint string `yaml:"endpoint" json:"endpoint"`
Encryption BatchJobKeyRotateEncryption `yaml:"encryption" json:"encryption"`
}
// Notify notifies notification endpoint if configured regarding job failure or success.
func (r BatchJobKeyRotateV1) Notify(ctx context.Context, body io.Reader) error {
if r.Flags.Notify.Endpoint == "" {
return nil
}
ctx, cancel := context.WithTimeout(ctx, 10*time.Second)
defer cancel()
req, err := http.NewRequestWithContext(ctx, http.MethodPost, r.Flags.Notify.Endpoint, body)
if err != nil {
return err
}
if r.Flags.Notify.Token != "" {
req.Header.Set("Authorization", r.Flags.Notify.Token)
}
clnt := http.Client{Transport: getRemoteInstanceTransport}
resp, err := clnt.Do(req)
if err != nil {
return err
}
xhttp.DrainBody(resp.Body)
if resp.StatusCode != http.StatusOK {
return errors.New(resp.Status)
}
return nil
}
// KeyRotate rotates encryption key of an object
func (r *BatchJobKeyRotateV1) KeyRotate(ctx context.Context, api ObjectLayer, objInfo ObjectInfo) error {
srcBucket := r.Bucket
srcObject := objInfo.Name
if objInfo.DeleteMarker || !objInfo.VersionPurgeStatus.Empty() {
return nil
}
sseKMS := crypto.S3KMS.IsEncrypted(objInfo.UserDefined)
sseS3 := crypto.S3.IsEncrypted(objInfo.UserDefined)
if !sseKMS && !sseS3 { // neither sse-s3 nor sse-kms disallowed
return errInvalidEncryptionParameters
}
if sseKMS && r.Encryption.Type == sses3 { // previously encrypted with sse-kms, now sse-s3 disallowed
return errInvalidEncryptionParameters
}
versioned := globalBucketVersioningSys.PrefixEnabled(srcBucket, srcObject)
versionSuspended := globalBucketVersioningSys.PrefixSuspended(srcBucket, srcObject)
lock := api.NewNSLock(r.Bucket, objInfo.Name)
lkctx, err := lock.GetLock(ctx, globalOperationTimeout)
if err != nil {
return err
}
ctx = lkctx.Context()
defer lock.Unlock(lkctx)
opts := ObjectOptions{
VersionID: objInfo.VersionID,
Versioned: versioned,
VersionSuspended: versionSuspended,
NoLock: true,
}
obj, err := api.GetObjectInfo(ctx, r.Bucket, objInfo.Name, opts)
if err != nil {
return err
}
oi := obj.Clone()
var (
newKeyID string
newKeyContext kms.Context
)
encMetadata := make(map[string]string)
for k, v := range oi.UserDefined {
if strings.HasPrefix(strings.ToLower(k), ReservedMetadataPrefixLower) {
encMetadata[k] = v
}
}
if (sseKMS || sseS3) && r.Encryption.Type == ssekms {
if err = r.Encryption.Validate(); err != nil {
return err
}
newKeyID = strings.TrimPrefix(r.Encryption.Key, crypto.ARNPrefix)
newKeyContext = r.Encryption.kmsContext
}
if err = rotateKey(ctx, []byte{}, newKeyID, []byte{}, r.Bucket, oi.Name, encMetadata, newKeyContext); err != nil {
return err
}
// Since we are rotating the keys, make sure to update the metadata.
oi.metadataOnly = true
oi.keyRotation = true
for k, v := range encMetadata {
oi.UserDefined[k] = v
}
if _, err := api.CopyObject(ctx, r.Bucket, oi.Name, r.Bucket, oi.Name, oi, ObjectOptions{
VersionID: oi.VersionID,
}, ObjectOptions{
VersionID: oi.VersionID,
NoLock: true,
}); err != nil {
return err
}
return nil
}
const (
batchKeyRotationName = "batch-rotate.bin"
batchKeyRotationFormat = 1
batchKeyRotateVersionV1 = 1
batchKeyRotateVersion = batchKeyRotateVersionV1
batchKeyRotateAPIVersion = "v1"
batchKeyRotateJobDefaultRetries = 3
batchKeyRotateJobDefaultRetryDelay = 250 * time.Millisecond
)
// Start the batch key rottion job, resumes if there was a pending job via "job.ID"
func (r *BatchJobKeyRotateV1) Start(ctx context.Context, api ObjectLayer, job BatchJobRequest) error {
ri := &batchJobInfo{
JobID: job.ID,
JobType: string(job.Type()),
StartTime: job.Started,
}
if err := ri.load(ctx, api, job); err != nil {
return err
}
globalBatchJobsMetrics.save(job.ID, ri)
lastObject := ri.Object
delay := job.KeyRotate.Flags.Retry.Delay
if delay == 0 {
delay = batchKeyRotateJobDefaultRetryDelay
}
rnd := rand.New(rand.NewSource(time.Now().UnixNano()))
skip := func(info FileInfo) (ok bool) {
if r.Flags.Filter.OlderThan > 0 && time.Since(info.ModTime) < r.Flags.Filter.OlderThan {
// skip all objects that are newer than specified older duration
return false
}
if r.Flags.Filter.NewerThan > 0 && time.Since(info.ModTime) >= r.Flags.Filter.NewerThan {
// skip all objects that are older than specified newer duration
return false
}
if !r.Flags.Filter.CreatedAfter.IsZero() && r.Flags.Filter.CreatedAfter.Before(info.ModTime) {
// skip all objects that are created before the specified time.
return false
}
if !r.Flags.Filter.CreatedBefore.IsZero() && r.Flags.Filter.CreatedBefore.After(info.ModTime) {
// skip all objects that are created after the specified time.
return false
}
if len(r.Flags.Filter.Tags) > 0 {
// Only parse object tags if tags filter is specified.
tagMap := map[string]string{}
tagStr := info.Metadata[xhttp.AmzObjectTagging]
if len(tagStr) != 0 {
t, err := tags.ParseObjectTags(tagStr)
if err != nil {
return false
}
tagMap = t.ToMap()
}
for _, kv := range r.Flags.Filter.Tags {
for t, v := range tagMap {
if kv.Match(BatchKeyRotateKV{Key: t, Value: v}) {
return true
}
}
}
// None of the provided tags filter match skip the object
return false
}
if len(r.Flags.Filter.Metadata) > 0 {
for _, kv := range r.Flags.Filter.Metadata {
for k, v := range info.Metadata {
if !strings.HasPrefix(strings.ToLower(k), "x-amz-meta-") && !isStandardHeader(k) {
continue
}
// We only need to match x-amz-meta or standardHeaders
if kv.Match(BatchKeyRotateKV{Key: k, Value: v}) {
return true
}
}
}
// None of the provided metadata filters match skip the object.
return false
}
if r.Flags.Filter.KMSKeyID != "" {
if v, ok := info.Metadata[xhttp.AmzServerSideEncryptionKmsID]; ok && strings.TrimPrefix(v, crypto.ARNPrefix) != r.Flags.Filter.KMSKeyID {
return false
}
}
return true
}
workerSize, err := strconv.Atoi(env.Get("_MINIO_BATCH_KEYROTATION_WORKERS", strconv.Itoa(runtime.GOMAXPROCS(0)/2)))
if err != nil {
return err
}
wk, err := workers.New(workerSize)
if err != nil {
// invalid worker size.
return err
}
retryAttempts := ri.RetryAttempts
ctx, cancel := context.WithCancel(ctx)
results := make(chan ObjectInfo, 100)
if err := api.Walk(ctx, r.Bucket, r.Prefix, results, ObjectOptions{
WalkMarker: lastObject,
WalkFilter: skip,
}); err != nil {
cancel()
// Do not need to retry if we can't list objects on source.
return err
}
for result := range results {
result := result
sseKMS := crypto.S3KMS.IsEncrypted(result.UserDefined)
sseS3 := crypto.S3.IsEncrypted(result.UserDefined)
if !sseKMS && !sseS3 { // neither sse-s3 nor sse-kms disallowed
continue
}
wk.Take()
go func() {
defer wk.Give()
for attempts := 1; attempts <= retryAttempts; attempts++ {
attempts := attempts
stopFn := globalBatchJobsMetrics.trace(batchKeyRotationMetricObject, job.ID, attempts, result)
success := true
if err := r.KeyRotate(ctx, api, result); err != nil {
stopFn(err)
logger.LogIf(ctx, err)
success = false
} else {
stopFn(nil)
}
ri.trackCurrentBucketObject(r.Bucket, result, success)
ri.RetryAttempts = attempts
globalBatchJobsMetrics.save(job.ID, ri)
// persist in-memory state to disk after every 10secs.
logger.LogIf(ctx, ri.updateAfter(ctx, api, 10*time.Second, job))
if success {
break
}
}
}()
}
wk.Wait()
ri.Complete = ri.ObjectsFailed == 0
ri.Failed = ri.ObjectsFailed > 0
globalBatchJobsMetrics.save(job.ID, ri)
// persist in-memory state to disk.
logger.LogIf(ctx, ri.updateAfter(ctx, api, 0, job))
buf, _ := json.Marshal(ri)
if err := r.Notify(ctx, bytes.NewReader(buf)); err != nil {
logger.LogIf(ctx, fmt.Errorf("unable to notify %v", err))
}
cancel()
if ri.Failed {
ri.ObjectsFailed = 0
ri.Bucket = ""
ri.Object = ""
ri.Objects = 0
time.Sleep(delay + time.Duration(rnd.Float64()*float64(delay)))
}
return nil
}
//msgp:ignore batchKeyRotationJobError
type batchKeyRotationJobError struct {
Code string
Description string
HTTPStatusCode int
}
func (e batchKeyRotationJobError) Error() string {
return e.Description
}
// Validate validates the job definition input
func (r *BatchJobKeyRotateV1) Validate(ctx context.Context, job BatchJobRequest, o ObjectLayer) error {
if r == nil {
return nil
}
if r.APIVersion != batchKeyRotateAPIVersion {
return errInvalidArgument
}
if r.Bucket == "" {
return errInvalidArgument
}
if _, err := o.GetBucketInfo(ctx, r.Bucket, BucketOptions{}); err != nil {
if isErrBucketNotFound(err) {
return batchKeyRotationJobError{
Code: "NoSuchSourceBucket",
Description: "The specified source bucket does not exist",
HTTPStatusCode: http.StatusNotFound,
}
}
return err
}
if GlobalKMS == nil {
return errKMSNotConfigured
}
if err := r.Encryption.Validate(); err != nil {
return err
}
for _, tag := range r.Flags.Filter.Tags {
if err := tag.Validate(); err != nil {
return err
}
}
for _, meta := range r.Flags.Filter.Metadata {
if err := meta.Validate(); err != nil {
return err
}
}
if err := r.Flags.Retry.Validate(); err != nil {
return err
}
return nil
}
| Validate | identifier_name |
batch-rotate.go | // Copyright (c) 2015-2023 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero 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 Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
package cmd
import (
"bytes"
"context"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"io"
"math/rand"
"net/http"
"runtime"
"strconv"
"strings"
"time"
jsoniter "github.com/json-iterator/go"
"github.com/minio/minio-go/v7/pkg/tags"
"github.com/minio/minio/internal/crypto"
xhttp "github.com/minio/minio/internal/http"
"github.com/minio/minio/internal/kms"
"github.com/minio/minio/internal/logger"
"github.com/minio/pkg/env"
"github.com/minio/pkg/wildcard"
"github.com/minio/pkg/workers"
)
// keyrotate:
// apiVersion: v1
// bucket: BUCKET
// prefix: PREFIX
// encryption:
// type: sse-s3 # valid values are sse-s3 and sse-kms
// key: <new-kms-key> # valid only for sse-kms
// context: <new-kms-key-context> # valid only for sse-kms
// # optional flags based filtering criteria
// # for all objects
// flags:
// filter:
// newerThan: "7d" # match objects newer than this value (e.g. 7d10h31s)
// olderThan: "7d" # match objects older than this value (e.g. 7d10h31s)
// createdAfter: "date" # match objects created after "date"
// createdBefore: "date" # match objects created before "date"
// tags:
// - key: "name"
// value: "pick*" # match objects with tag 'name', with all values starting with 'pick'
// metadata:
// - key: "content-type"
// value: "image/*" # match objects with 'content-type', with all values starting with 'image/'
// kmskey: "key-id" # match objects with KMS key-id (applicable only for sse-kms)
// notify:
// endpoint: "https://notify.endpoint" # notification endpoint to receive job status events
// token: "Bearer xxxxx" # optional authentication token for the notification endpoint
// retry:
// attempts: 10 # number of retries for the job before giving up
// delay: "500ms" # least amount of delay between each retry
//go:generate msgp -file $GOFILE -unexported
// BatchKeyRotateKV is a datatype that holds key and values for filtering of objects
// used by metadata filter as well as tags based filtering.
type BatchKeyRotateKV struct {
Key string `yaml:"key" json:"key"`
Value string `yaml:"value" json:"value"`
}
// Validate returns an error if key is empty
func (kv BatchKeyRotateKV) Validate() error {
if kv.Key == "" {
return errInvalidArgument
}
return nil
}
// Empty indicates if kv is not set
func (kv BatchKeyRotateKV) Empty() bool {
return kv.Key == "" && kv.Value == ""
}
// Match matches input kv with kv, value will be wildcard matched depending on the user input
func (kv BatchKeyRotateKV) Match(ikv BatchKeyRotateKV) bool {
if kv.Empty() {
return true
}
if strings.EqualFold(kv.Key, ikv.Key) {
return wildcard.Match(kv.Value, ikv.Value)
}
return false
}
// BatchKeyRotateRetry datatype represents total retry attempts and delay between each retries.
type BatchKeyRotateRetry struct {
Attempts int `yaml:"attempts" json:"attempts"` // number of retry attempts
Delay time.Duration `yaml:"delay" json:"delay"` // delay between each retries
}
// Validate validates input replicate retries.
func (r BatchKeyRotateRetry) Validate() error {
if r.Attempts < 0 {
return errInvalidArgument
}
if r.Delay < 0 {
return errInvalidArgument
}
return nil
}
// BatchKeyRotationType defines key rotation type
type BatchKeyRotationType string
const (
sses3 BatchKeyRotationType = "sse-s3"
ssekms BatchKeyRotationType = "sse-kms"
)
// BatchJobKeyRotateEncryption defines key rotation encryption options passed
type BatchJobKeyRotateEncryption struct {
Type BatchKeyRotationType `yaml:"type" json:"type"`
Key string `yaml:"key" json:"key"`
Context string `yaml:"context" json:"context"`
kmsContext kms.Context `msg:"-"`
}
// Validate validates input key rotation encryption options.
func (e BatchJobKeyRotateEncryption) Validate() error {
if e.Type != sses3 && e.Type != ssekms {
return errInvalidArgument
}
spaces := strings.HasPrefix(e.Key, " ") || strings.HasSuffix(e.Key, " ")
if e.Type == ssekms && spaces {
return crypto.ErrInvalidEncryptionKeyID
}
if e.Type == ssekms && GlobalKMS != nil {
ctx := kms.Context{}
if e.Context != "" {
b, err := base64.StdEncoding.DecodeString(e.Context)
if err != nil {
return err
}
json := jsoniter.ConfigCompatibleWithStandardLibrary
if err := json.Unmarshal(b, &ctx); err != nil {
return err
}
}
e.kmsContext = kms.Context{}
for k, v := range ctx {
e.kmsContext[k] = v | }
}
return nil
}
// BatchKeyRotateFilter holds all the filters currently supported for batch replication
type BatchKeyRotateFilter struct {
NewerThan time.Duration `yaml:"newerThan,omitempty" json:"newerThan"`
OlderThan time.Duration `yaml:"olderThan,omitempty" json:"olderThan"`
CreatedAfter time.Time `yaml:"createdAfter,omitempty" json:"createdAfter"`
CreatedBefore time.Time `yaml:"createdBefore,omitempty" json:"createdBefore"`
Tags []BatchKeyRotateKV `yaml:"tags,omitempty" json:"tags"`
Metadata []BatchKeyRotateKV `yaml:"metadata,omitempty" json:"metadata"`
KMSKeyID string `yaml:"kmskeyid" json:"kmskey"`
}
// BatchKeyRotateNotification success or failure notification endpoint for each job attempts
type BatchKeyRotateNotification struct {
Endpoint string `yaml:"endpoint" json:"endpoint"`
Token string `yaml:"token" json:"token"`
}
// BatchJobKeyRotateFlags various configurations for replication job definition currently includes
// - filter
// - notify
// - retry
type BatchJobKeyRotateFlags struct {
Filter BatchKeyRotateFilter `yaml:"filter" json:"filter"`
Notify BatchKeyRotateNotification `yaml:"notify" json:"notify"`
Retry BatchKeyRotateRetry `yaml:"retry" json:"retry"`
}
// BatchJobKeyRotateV1 v1 of batch key rotation job
type BatchJobKeyRotateV1 struct {
APIVersion string `yaml:"apiVersion" json:"apiVersion"`
Flags BatchJobKeyRotateFlags `yaml:"flags" json:"flags"`
Bucket string `yaml:"bucket" json:"bucket"`
Prefix string `yaml:"prefix" json:"prefix"`
Endpoint string `yaml:"endpoint" json:"endpoint"`
Encryption BatchJobKeyRotateEncryption `yaml:"encryption" json:"encryption"`
}
// Notify notifies notification endpoint if configured regarding job failure or success.
func (r BatchJobKeyRotateV1) Notify(ctx context.Context, body io.Reader) error {
if r.Flags.Notify.Endpoint == "" {
return nil
}
ctx, cancel := context.WithTimeout(ctx, 10*time.Second)
defer cancel()
req, err := http.NewRequestWithContext(ctx, http.MethodPost, r.Flags.Notify.Endpoint, body)
if err != nil {
return err
}
if r.Flags.Notify.Token != "" {
req.Header.Set("Authorization", r.Flags.Notify.Token)
}
clnt := http.Client{Transport: getRemoteInstanceTransport}
resp, err := clnt.Do(req)
if err != nil {
return err
}
xhttp.DrainBody(resp.Body)
if resp.StatusCode != http.StatusOK {
return errors.New(resp.Status)
}
return nil
}
// KeyRotate rotates encryption key of an object
func (r *BatchJobKeyRotateV1) KeyRotate(ctx context.Context, api ObjectLayer, objInfo ObjectInfo) error {
srcBucket := r.Bucket
srcObject := objInfo.Name
if objInfo.DeleteMarker || !objInfo.VersionPurgeStatus.Empty() {
return nil
}
sseKMS := crypto.S3KMS.IsEncrypted(objInfo.UserDefined)
sseS3 := crypto.S3.IsEncrypted(objInfo.UserDefined)
if !sseKMS && !sseS3 { // neither sse-s3 nor sse-kms disallowed
return errInvalidEncryptionParameters
}
if sseKMS && r.Encryption.Type == sses3 { // previously encrypted with sse-kms, now sse-s3 disallowed
return errInvalidEncryptionParameters
}
versioned := globalBucketVersioningSys.PrefixEnabled(srcBucket, srcObject)
versionSuspended := globalBucketVersioningSys.PrefixSuspended(srcBucket, srcObject)
lock := api.NewNSLock(r.Bucket, objInfo.Name)
lkctx, err := lock.GetLock(ctx, globalOperationTimeout)
if err != nil {
return err
}
ctx = lkctx.Context()
defer lock.Unlock(lkctx)
opts := ObjectOptions{
VersionID: objInfo.VersionID,
Versioned: versioned,
VersionSuspended: versionSuspended,
NoLock: true,
}
obj, err := api.GetObjectInfo(ctx, r.Bucket, objInfo.Name, opts)
if err != nil {
return err
}
oi := obj.Clone()
var (
newKeyID string
newKeyContext kms.Context
)
encMetadata := make(map[string]string)
for k, v := range oi.UserDefined {
if strings.HasPrefix(strings.ToLower(k), ReservedMetadataPrefixLower) {
encMetadata[k] = v
}
}
if (sseKMS || sseS3) && r.Encryption.Type == ssekms {
if err = r.Encryption.Validate(); err != nil {
return err
}
newKeyID = strings.TrimPrefix(r.Encryption.Key, crypto.ARNPrefix)
newKeyContext = r.Encryption.kmsContext
}
if err = rotateKey(ctx, []byte{}, newKeyID, []byte{}, r.Bucket, oi.Name, encMetadata, newKeyContext); err != nil {
return err
}
// Since we are rotating the keys, make sure to update the metadata.
oi.metadataOnly = true
oi.keyRotation = true
for k, v := range encMetadata {
oi.UserDefined[k] = v
}
if _, err := api.CopyObject(ctx, r.Bucket, oi.Name, r.Bucket, oi.Name, oi, ObjectOptions{
VersionID: oi.VersionID,
}, ObjectOptions{
VersionID: oi.VersionID,
NoLock: true,
}); err != nil {
return err
}
return nil
}
const (
batchKeyRotationName = "batch-rotate.bin"
batchKeyRotationFormat = 1
batchKeyRotateVersionV1 = 1
batchKeyRotateVersion = batchKeyRotateVersionV1
batchKeyRotateAPIVersion = "v1"
batchKeyRotateJobDefaultRetries = 3
batchKeyRotateJobDefaultRetryDelay = 250 * time.Millisecond
)
// Start the batch key rottion job, resumes if there was a pending job via "job.ID"
func (r *BatchJobKeyRotateV1) Start(ctx context.Context, api ObjectLayer, job BatchJobRequest) error {
ri := &batchJobInfo{
JobID: job.ID,
JobType: string(job.Type()),
StartTime: job.Started,
}
if err := ri.load(ctx, api, job); err != nil {
return err
}
globalBatchJobsMetrics.save(job.ID, ri)
lastObject := ri.Object
delay := job.KeyRotate.Flags.Retry.Delay
if delay == 0 {
delay = batchKeyRotateJobDefaultRetryDelay
}
rnd := rand.New(rand.NewSource(time.Now().UnixNano()))
skip := func(info FileInfo) (ok bool) {
if r.Flags.Filter.OlderThan > 0 && time.Since(info.ModTime) < r.Flags.Filter.OlderThan {
// skip all objects that are newer than specified older duration
return false
}
if r.Flags.Filter.NewerThan > 0 && time.Since(info.ModTime) >= r.Flags.Filter.NewerThan {
// skip all objects that are older than specified newer duration
return false
}
if !r.Flags.Filter.CreatedAfter.IsZero() && r.Flags.Filter.CreatedAfter.Before(info.ModTime) {
// skip all objects that are created before the specified time.
return false
}
if !r.Flags.Filter.CreatedBefore.IsZero() && r.Flags.Filter.CreatedBefore.After(info.ModTime) {
// skip all objects that are created after the specified time.
return false
}
if len(r.Flags.Filter.Tags) > 0 {
// Only parse object tags if tags filter is specified.
tagMap := map[string]string{}
tagStr := info.Metadata[xhttp.AmzObjectTagging]
if len(tagStr) != 0 {
t, err := tags.ParseObjectTags(tagStr)
if err != nil {
return false
}
tagMap = t.ToMap()
}
for _, kv := range r.Flags.Filter.Tags {
for t, v := range tagMap {
if kv.Match(BatchKeyRotateKV{Key: t, Value: v}) {
return true
}
}
}
// None of the provided tags filter match skip the object
return false
}
if len(r.Flags.Filter.Metadata) > 0 {
for _, kv := range r.Flags.Filter.Metadata {
for k, v := range info.Metadata {
if !strings.HasPrefix(strings.ToLower(k), "x-amz-meta-") && !isStandardHeader(k) {
continue
}
// We only need to match x-amz-meta or standardHeaders
if kv.Match(BatchKeyRotateKV{Key: k, Value: v}) {
return true
}
}
}
// None of the provided metadata filters match skip the object.
return false
}
if r.Flags.Filter.KMSKeyID != "" {
if v, ok := info.Metadata[xhttp.AmzServerSideEncryptionKmsID]; ok && strings.TrimPrefix(v, crypto.ARNPrefix) != r.Flags.Filter.KMSKeyID {
return false
}
}
return true
}
workerSize, err := strconv.Atoi(env.Get("_MINIO_BATCH_KEYROTATION_WORKERS", strconv.Itoa(runtime.GOMAXPROCS(0)/2)))
if err != nil {
return err
}
wk, err := workers.New(workerSize)
if err != nil {
// invalid worker size.
return err
}
retryAttempts := ri.RetryAttempts
ctx, cancel := context.WithCancel(ctx)
results := make(chan ObjectInfo, 100)
if err := api.Walk(ctx, r.Bucket, r.Prefix, results, ObjectOptions{
WalkMarker: lastObject,
WalkFilter: skip,
}); err != nil {
cancel()
// Do not need to retry if we can't list objects on source.
return err
}
for result := range results {
result := result
sseKMS := crypto.S3KMS.IsEncrypted(result.UserDefined)
sseS3 := crypto.S3.IsEncrypted(result.UserDefined)
if !sseKMS && !sseS3 { // neither sse-s3 nor sse-kms disallowed
continue
}
wk.Take()
go func() {
defer wk.Give()
for attempts := 1; attempts <= retryAttempts; attempts++ {
attempts := attempts
stopFn := globalBatchJobsMetrics.trace(batchKeyRotationMetricObject, job.ID, attempts, result)
success := true
if err := r.KeyRotate(ctx, api, result); err != nil {
stopFn(err)
logger.LogIf(ctx, err)
success = false
} else {
stopFn(nil)
}
ri.trackCurrentBucketObject(r.Bucket, result, success)
ri.RetryAttempts = attempts
globalBatchJobsMetrics.save(job.ID, ri)
// persist in-memory state to disk after every 10secs.
logger.LogIf(ctx, ri.updateAfter(ctx, api, 10*time.Second, job))
if success {
break
}
}
}()
}
wk.Wait()
ri.Complete = ri.ObjectsFailed == 0
ri.Failed = ri.ObjectsFailed > 0
globalBatchJobsMetrics.save(job.ID, ri)
// persist in-memory state to disk.
logger.LogIf(ctx, ri.updateAfter(ctx, api, 0, job))
buf, _ := json.Marshal(ri)
if err := r.Notify(ctx, bytes.NewReader(buf)); err != nil {
logger.LogIf(ctx, fmt.Errorf("unable to notify %v", err))
}
cancel()
if ri.Failed {
ri.ObjectsFailed = 0
ri.Bucket = ""
ri.Object = ""
ri.Objects = 0
time.Sleep(delay + time.Duration(rnd.Float64()*float64(delay)))
}
return nil
}
//msgp:ignore batchKeyRotationJobError
type batchKeyRotationJobError struct {
Code string
Description string
HTTPStatusCode int
}
func (e batchKeyRotationJobError) Error() string {
return e.Description
}
// Validate validates the job definition input
func (r *BatchJobKeyRotateV1) Validate(ctx context.Context, job BatchJobRequest, o ObjectLayer) error {
if r == nil {
return nil
}
if r.APIVersion != batchKeyRotateAPIVersion {
return errInvalidArgument
}
if r.Bucket == "" {
return errInvalidArgument
}
if _, err := o.GetBucketInfo(ctx, r.Bucket, BucketOptions{}); err != nil {
if isErrBucketNotFound(err) {
return batchKeyRotationJobError{
Code: "NoSuchSourceBucket",
Description: "The specified source bucket does not exist",
HTTPStatusCode: http.StatusNotFound,
}
}
return err
}
if GlobalKMS == nil {
return errKMSNotConfigured
}
if err := r.Encryption.Validate(); err != nil {
return err
}
for _, tag := range r.Flags.Filter.Tags {
if err := tag.Validate(); err != nil {
return err
}
}
for _, meta := range r.Flags.Filter.Metadata {
if err := meta.Validate(); err != nil {
return err
}
}
if err := r.Flags.Retry.Validate(); err != nil {
return err
}
return nil
} | }
ctx["MinIO batch API"] = "batchrotate" // Context for a test key operation
if _, err := GlobalKMS.GenerateKey(GlobalContext, e.Key, ctx); err != nil {
return err | random_line_split |
batch-rotate.go | // Copyright (c) 2015-2023 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero 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 Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
package cmd
import (
"bytes"
"context"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"io"
"math/rand"
"net/http"
"runtime"
"strconv"
"strings"
"time"
jsoniter "github.com/json-iterator/go"
"github.com/minio/minio-go/v7/pkg/tags"
"github.com/minio/minio/internal/crypto"
xhttp "github.com/minio/minio/internal/http"
"github.com/minio/minio/internal/kms"
"github.com/minio/minio/internal/logger"
"github.com/minio/pkg/env"
"github.com/minio/pkg/wildcard"
"github.com/minio/pkg/workers"
)
// keyrotate:
// apiVersion: v1
// bucket: BUCKET
// prefix: PREFIX
// encryption:
// type: sse-s3 # valid values are sse-s3 and sse-kms
// key: <new-kms-key> # valid only for sse-kms
// context: <new-kms-key-context> # valid only for sse-kms
// # optional flags based filtering criteria
// # for all objects
// flags:
// filter:
// newerThan: "7d" # match objects newer than this value (e.g. 7d10h31s)
// olderThan: "7d" # match objects older than this value (e.g. 7d10h31s)
// createdAfter: "date" # match objects created after "date"
// createdBefore: "date" # match objects created before "date"
// tags:
// - key: "name"
// value: "pick*" # match objects with tag 'name', with all values starting with 'pick'
// metadata:
// - key: "content-type"
// value: "image/*" # match objects with 'content-type', with all values starting with 'image/'
// kmskey: "key-id" # match objects with KMS key-id (applicable only for sse-kms)
// notify:
// endpoint: "https://notify.endpoint" # notification endpoint to receive job status events
// token: "Bearer xxxxx" # optional authentication token for the notification endpoint
// retry:
// attempts: 10 # number of retries for the job before giving up
// delay: "500ms" # least amount of delay between each retry
//go:generate msgp -file $GOFILE -unexported
// BatchKeyRotateKV is a datatype that holds key and values for filtering of objects
// used by metadata filter as well as tags based filtering.
type BatchKeyRotateKV struct {
Key string `yaml:"key" json:"key"`
Value string `yaml:"value" json:"value"`
}
// Validate returns an error if key is empty
func (kv BatchKeyRotateKV) Validate() error {
if kv.Key == "" {
return errInvalidArgument
}
return nil
}
// Empty indicates if kv is not set
func (kv BatchKeyRotateKV) Empty() bool {
return kv.Key == "" && kv.Value == ""
}
// Match matches input kv with kv, value will be wildcard matched depending on the user input
func (kv BatchKeyRotateKV) Match(ikv BatchKeyRotateKV) bool {
if kv.Empty() {
return true
}
if strings.EqualFold(kv.Key, ikv.Key) {
return wildcard.Match(kv.Value, ikv.Value)
}
return false
}
// BatchKeyRotateRetry datatype represents total retry attempts and delay between each retries.
type BatchKeyRotateRetry struct {
Attempts int `yaml:"attempts" json:"attempts"` // number of retry attempts
Delay time.Duration `yaml:"delay" json:"delay"` // delay between each retries
}
// Validate validates input replicate retries.
func (r BatchKeyRotateRetry) Validate() error {
if r.Attempts < 0 {
return errInvalidArgument
}
if r.Delay < 0 {
return errInvalidArgument
}
return nil
}
// BatchKeyRotationType defines key rotation type
type BatchKeyRotationType string
const (
sses3 BatchKeyRotationType = "sse-s3"
ssekms BatchKeyRotationType = "sse-kms"
)
// BatchJobKeyRotateEncryption defines key rotation encryption options passed
type BatchJobKeyRotateEncryption struct {
Type BatchKeyRotationType `yaml:"type" json:"type"`
Key string `yaml:"key" json:"key"`
Context string `yaml:"context" json:"context"`
kmsContext kms.Context `msg:"-"`
}
// Validate validates input key rotation encryption options.
func (e BatchJobKeyRotateEncryption) Validate() error {
if e.Type != sses3 && e.Type != ssekms {
return errInvalidArgument
}
spaces := strings.HasPrefix(e.Key, " ") || strings.HasSuffix(e.Key, " ")
if e.Type == ssekms && spaces {
return crypto.ErrInvalidEncryptionKeyID
}
if e.Type == ssekms && GlobalKMS != nil {
ctx := kms.Context{}
if e.Context != "" {
b, err := base64.StdEncoding.DecodeString(e.Context)
if err != nil {
return err
}
json := jsoniter.ConfigCompatibleWithStandardLibrary
if err := json.Unmarshal(b, &ctx); err != nil {
return err
}
}
e.kmsContext = kms.Context{}
for k, v := range ctx {
e.kmsContext[k] = v
}
ctx["MinIO batch API"] = "batchrotate" // Context for a test key operation
if _, err := GlobalKMS.GenerateKey(GlobalContext, e.Key, ctx); err != nil {
return err
}
}
return nil
}
// BatchKeyRotateFilter holds all the filters currently supported for batch replication
type BatchKeyRotateFilter struct {
NewerThan time.Duration `yaml:"newerThan,omitempty" json:"newerThan"`
OlderThan time.Duration `yaml:"olderThan,omitempty" json:"olderThan"`
CreatedAfter time.Time `yaml:"createdAfter,omitempty" json:"createdAfter"`
CreatedBefore time.Time `yaml:"createdBefore,omitempty" json:"createdBefore"`
Tags []BatchKeyRotateKV `yaml:"tags,omitempty" json:"tags"`
Metadata []BatchKeyRotateKV `yaml:"metadata,omitempty" json:"metadata"`
KMSKeyID string `yaml:"kmskeyid" json:"kmskey"`
}
// BatchKeyRotateNotification success or failure notification endpoint for each job attempts
type BatchKeyRotateNotification struct {
Endpoint string `yaml:"endpoint" json:"endpoint"`
Token string `yaml:"token" json:"token"`
}
// BatchJobKeyRotateFlags various configurations for replication job definition currently includes
// - filter
// - notify
// - retry
type BatchJobKeyRotateFlags struct {
Filter BatchKeyRotateFilter `yaml:"filter" json:"filter"`
Notify BatchKeyRotateNotification `yaml:"notify" json:"notify"`
Retry BatchKeyRotateRetry `yaml:"retry" json:"retry"`
}
// BatchJobKeyRotateV1 v1 of batch key rotation job
type BatchJobKeyRotateV1 struct {
APIVersion string `yaml:"apiVersion" json:"apiVersion"`
Flags BatchJobKeyRotateFlags `yaml:"flags" json:"flags"`
Bucket string `yaml:"bucket" json:"bucket"`
Prefix string `yaml:"prefix" json:"prefix"`
Endpoint string `yaml:"endpoint" json:"endpoint"`
Encryption BatchJobKeyRotateEncryption `yaml:"encryption" json:"encryption"`
}
// Notify notifies notification endpoint if configured regarding job failure or success.
func (r BatchJobKeyRotateV1) Notify(ctx context.Context, body io.Reader) error {
if r.Flags.Notify.Endpoint == "" {
return nil
}
ctx, cancel := context.WithTimeout(ctx, 10*time.Second)
defer cancel()
req, err := http.NewRequestWithContext(ctx, http.MethodPost, r.Flags.Notify.Endpoint, body)
if err != nil {
return err
}
if r.Flags.Notify.Token != "" {
req.Header.Set("Authorization", r.Flags.Notify.Token)
}
clnt := http.Client{Transport: getRemoteInstanceTransport}
resp, err := clnt.Do(req)
if err != nil {
return err
}
xhttp.DrainBody(resp.Body)
if resp.StatusCode != http.StatusOK {
return errors.New(resp.Status)
}
return nil
}
// KeyRotate rotates encryption key of an object
func (r *BatchJobKeyRotateV1) KeyRotate(ctx context.Context, api ObjectLayer, objInfo ObjectInfo) error {
srcBucket := r.Bucket
srcObject := objInfo.Name
if objInfo.DeleteMarker || !objInfo.VersionPurgeStatus.Empty() {
return nil
}
sseKMS := crypto.S3KMS.IsEncrypted(objInfo.UserDefined)
sseS3 := crypto.S3.IsEncrypted(objInfo.UserDefined)
if !sseKMS && !sseS3 { // neither sse-s3 nor sse-kms disallowed
return errInvalidEncryptionParameters
}
if sseKMS && r.Encryption.Type == sses3 { // previously encrypted with sse-kms, now sse-s3 disallowed
return errInvalidEncryptionParameters
}
versioned := globalBucketVersioningSys.PrefixEnabled(srcBucket, srcObject)
versionSuspended := globalBucketVersioningSys.PrefixSuspended(srcBucket, srcObject)
lock := api.NewNSLock(r.Bucket, objInfo.Name)
lkctx, err := lock.GetLock(ctx, globalOperationTimeout)
if err != nil {
return err
}
ctx = lkctx.Context()
defer lock.Unlock(lkctx)
opts := ObjectOptions{
VersionID: objInfo.VersionID,
Versioned: versioned,
VersionSuspended: versionSuspended,
NoLock: true,
}
obj, err := api.GetObjectInfo(ctx, r.Bucket, objInfo.Name, opts)
if err != nil {
return err
}
oi := obj.Clone()
var (
newKeyID string
newKeyContext kms.Context
)
encMetadata := make(map[string]string)
for k, v := range oi.UserDefined {
if strings.HasPrefix(strings.ToLower(k), ReservedMetadataPrefixLower) {
encMetadata[k] = v
}
}
if (sseKMS || sseS3) && r.Encryption.Type == ssekms {
if err = r.Encryption.Validate(); err != nil {
return err
}
newKeyID = strings.TrimPrefix(r.Encryption.Key, crypto.ARNPrefix)
newKeyContext = r.Encryption.kmsContext
}
if err = rotateKey(ctx, []byte{}, newKeyID, []byte{}, r.Bucket, oi.Name, encMetadata, newKeyContext); err != nil {
return err
}
// Since we are rotating the keys, make sure to update the metadata.
oi.metadataOnly = true
oi.keyRotation = true
for k, v := range encMetadata {
oi.UserDefined[k] = v
}
if _, err := api.CopyObject(ctx, r.Bucket, oi.Name, r.Bucket, oi.Name, oi, ObjectOptions{
VersionID: oi.VersionID,
}, ObjectOptions{
VersionID: oi.VersionID,
NoLock: true,
}); err != nil {
return err
}
return nil
}
const (
batchKeyRotationName = "batch-rotate.bin"
batchKeyRotationFormat = 1
batchKeyRotateVersionV1 = 1
batchKeyRotateVersion = batchKeyRotateVersionV1
batchKeyRotateAPIVersion = "v1"
batchKeyRotateJobDefaultRetries = 3
batchKeyRotateJobDefaultRetryDelay = 250 * time.Millisecond
)
// Start the batch key rottion job, resumes if there was a pending job via "job.ID"
func (r *BatchJobKeyRotateV1) Start(ctx context.Context, api ObjectLayer, job BatchJobRequest) error {
ri := &batchJobInfo{
JobID: job.ID,
JobType: string(job.Type()),
StartTime: job.Started,
}
if err := ri.load(ctx, api, job); err != nil {
return err
}
globalBatchJobsMetrics.save(job.ID, ri)
lastObject := ri.Object
delay := job.KeyRotate.Flags.Retry.Delay
if delay == 0 {
delay = batchKeyRotateJobDefaultRetryDelay
}
rnd := rand.New(rand.NewSource(time.Now().UnixNano()))
skip := func(info FileInfo) (ok bool) {
if r.Flags.Filter.OlderThan > 0 && time.Since(info.ModTime) < r.Flags.Filter.OlderThan {
// skip all objects that are newer than specified older duration
return false
}
if r.Flags.Filter.NewerThan > 0 && time.Since(info.ModTime) >= r.Flags.Filter.NewerThan {
// skip all objects that are older than specified newer duration
return false
}
if !r.Flags.Filter.CreatedAfter.IsZero() && r.Flags.Filter.CreatedAfter.Before(info.ModTime) {
// skip all objects that are created before the specified time.
return false
}
if !r.Flags.Filter.CreatedBefore.IsZero() && r.Flags.Filter.CreatedBefore.After(info.ModTime) {
// skip all objects that are created after the specified time.
return false
}
if len(r.Flags.Filter.Tags) > 0 {
// Only parse object tags if tags filter is specified.
tagMap := map[string]string{}
tagStr := info.Metadata[xhttp.AmzObjectTagging]
if len(tagStr) != 0 {
t, err := tags.ParseObjectTags(tagStr)
if err != nil {
return false
}
tagMap = t.ToMap()
}
for _, kv := range r.Flags.Filter.Tags {
for t, v := range tagMap {
if kv.Match(BatchKeyRotateKV{Key: t, Value: v}) {
return true
}
}
}
// None of the provided tags filter match skip the object
return false
}
if len(r.Flags.Filter.Metadata) > 0 {
for _, kv := range r.Flags.Filter.Metadata {
for k, v := range info.Metadata {
if !strings.HasPrefix(strings.ToLower(k), "x-amz-meta-") && !isStandardHeader(k) {
continue
}
// We only need to match x-amz-meta or standardHeaders
if kv.Match(BatchKeyRotateKV{Key: k, Value: v}) {
return true
}
}
}
// None of the provided metadata filters match skip the object.
return false
}
if r.Flags.Filter.KMSKeyID != "" {
if v, ok := info.Metadata[xhttp.AmzServerSideEncryptionKmsID]; ok && strings.TrimPrefix(v, crypto.ARNPrefix) != r.Flags.Filter.KMSKeyID {
return false
}
}
return true
}
workerSize, err := strconv.Atoi(env.Get("_MINIO_BATCH_KEYROTATION_WORKERS", strconv.Itoa(runtime.GOMAXPROCS(0)/2)))
if err != nil {
return err
}
wk, err := workers.New(workerSize)
if err != nil {
// invalid worker size.
return err
}
retryAttempts := ri.RetryAttempts
ctx, cancel := context.WithCancel(ctx)
results := make(chan ObjectInfo, 100)
if err := api.Walk(ctx, r.Bucket, r.Prefix, results, ObjectOptions{
WalkMarker: lastObject,
WalkFilter: skip,
}); err != nil {
cancel()
// Do not need to retry if we can't list objects on source.
return err
}
for result := range results {
result := result
sseKMS := crypto.S3KMS.IsEncrypted(result.UserDefined)
sseS3 := crypto.S3.IsEncrypted(result.UserDefined)
if !sseKMS && !sseS3 { // neither sse-s3 nor sse-kms disallowed
continue
}
wk.Take()
go func() {
defer wk.Give()
for attempts := 1; attempts <= retryAttempts; attempts++ |
}()
}
wk.Wait()
ri.Complete = ri.ObjectsFailed == 0
ri.Failed = ri.ObjectsFailed > 0
globalBatchJobsMetrics.save(job.ID, ri)
// persist in-memory state to disk.
logger.LogIf(ctx, ri.updateAfter(ctx, api, 0, job))
buf, _ := json.Marshal(ri)
if err := r.Notify(ctx, bytes.NewReader(buf)); err != nil {
logger.LogIf(ctx, fmt.Errorf("unable to notify %v", err))
}
cancel()
if ri.Failed {
ri.ObjectsFailed = 0
ri.Bucket = ""
ri.Object = ""
ri.Objects = 0
time.Sleep(delay + time.Duration(rnd.Float64()*float64(delay)))
}
return nil
}
//msgp:ignore batchKeyRotationJobError
type batchKeyRotationJobError struct {
Code string
Description string
HTTPStatusCode int
}
func (e batchKeyRotationJobError) Error() string {
return e.Description
}
// Validate validates the job definition input
func (r *BatchJobKeyRotateV1) Validate(ctx context.Context, job BatchJobRequest, o ObjectLayer) error {
if r == nil {
return nil
}
if r.APIVersion != batchKeyRotateAPIVersion {
return errInvalidArgument
}
if r.Bucket == "" {
return errInvalidArgument
}
if _, err := o.GetBucketInfo(ctx, r.Bucket, BucketOptions{}); err != nil {
if isErrBucketNotFound(err) {
return batchKeyRotationJobError{
Code: "NoSuchSourceBucket",
Description: "The specified source bucket does not exist",
HTTPStatusCode: http.StatusNotFound,
}
}
return err
}
if GlobalKMS == nil {
return errKMSNotConfigured
}
if err := r.Encryption.Validate(); err != nil {
return err
}
for _, tag := range r.Flags.Filter.Tags {
if err := tag.Validate(); err != nil {
return err
}
}
for _, meta := range r.Flags.Filter.Metadata {
if err := meta.Validate(); err != nil {
return err
}
}
if err := r.Flags.Retry.Validate(); err != nil {
return err
}
return nil
}
| {
attempts := attempts
stopFn := globalBatchJobsMetrics.trace(batchKeyRotationMetricObject, job.ID, attempts, result)
success := true
if err := r.KeyRotate(ctx, api, result); err != nil {
stopFn(err)
logger.LogIf(ctx, err)
success = false
} else {
stopFn(nil)
}
ri.trackCurrentBucketObject(r.Bucket, result, success)
ri.RetryAttempts = attempts
globalBatchJobsMetrics.save(job.ID, ri)
// persist in-memory state to disk after every 10secs.
logger.LogIf(ctx, ri.updateAfter(ctx, api, 10*time.Second, job))
if success {
break
}
} | conditional_block |
lib.rs | // まとめ
// - あらゆるところでパターンは使用されている
// - ちゃんと,あり得る可能性をカバーしよう
//
// python 3.10あたりで,pythonにも導入されるかも?
// (rustのsubprocessはpythonから影響を受けていたりなど,インスパイアされあっているような雰囲気)
//
//
// この章は辞書的な感じで,いろんなパターンとそのマッチング方法を列挙している感じ
// まずは6章の軽い復習+α
enum Coin {
Penny,
Nickel,
Dime,
Quarter,
}
pub fn simple_matching() {
let coins = vec![Coin::Penny, Coin::Nickel, Coin::Dime, Coin::Quarter];
for coin in coins.iter() {
println!(
"matched coin is {}",
match coin {
Coin::Penny => {
println!("Lucky penny!");
1
}
Coin::Nickel => 5,
Coin::Dime => 10,
Coin::Quarter => 25,
}
);
}
// Lucky penny!
// matched coin is 1
// matched coin is 5
// matched coin is 10
// matched coin is 25
}
pub fn all_patterns_must_be_covered() {
let a = 3;
let b = match a {
1 => 1,
2 => 2,
3 => 3,
_ => 0, // _パターンでカバーしないとだめ
// そうしないと下のコンパイルエラー
// patterns `std::i32::MIN..=0i32` and `4i32..=std::i32::MAX` not covered
};
println!("matched value is: {}", b);
}
// この例では輝かないが,if-let記法も道具箱にあるんですよ
// matchを使って表現するには冗長な場合に使いましょう
pub fn if_let_notation() {
let a = 3;
if let 1 = a {
println!("matched value is: 1");
} else if let 2 = a {
println!("matched value is: 2");
} else if let 3 = a {
println!("matched value is: 3");
} else {
println!("matched value is: others");
}
}
pub fn all_expressions_must_return_the_same_typed_value() {
let a = 3;
println!(
"matched value is: {}",
match a {
1 => "one",
2 => "two",
// 3 => 3, // expected '&str', found integer
// 異なる型を返すように書くことはできない
// どの型を基準にするかは,最初のパターンで返す型に依る
_ => "others",
}
);
// matched value is: others
}
// ここから18章の内容を本格的に
// ifとif-letが入り乱れるパターン
// お気に入りの色と年齢に応じて,背景色を変えることを考えているプログラム
// ややこしいからあまり使いたくないと感じた
pub fn mixed_if_statements() {
let favorite_color: Option<&str> = None;
let is_tuesday = false;
let age: Result<u8, _> = "34".parse();
if let Some(color) = favorite_color {
println!("Using your favorite color, {}, as the background", color);
} else if is_tuesday {
println!("Tuesday is green day");
} else if let Ok(age) = age {
if age > 30 {
println!("Using purple as the background color");
} else {
println!("Using orange as the background color");
}
} else {
println!("Using blue as the background color");
}
// Using purple as the background color
}
// whileにもパターンを
// なにかある限りpopする例
pub fn pop_as_long_as_vector_has_values() {
let mut stack = Vec::new();
stack.push(1);
stack.push(2);
stack.push(3);
while let Some(top) = stack.pop() {
println!("vector has {} on the top", top);
}
// vector has 3 on the top
// vector has 2 on the top
// vector has 1 on the top
}
// forでもパターンの考え方は使われている
// for x in yでは,xがパターンとなる
// ここでは,タプルとして分解する方法を示す
pub fn for_statement_can_use_patterns() {
let v = vec!['a', 'b', 'c'];
for (i, v) in v.iter().enumerate() {
println!("{} is at index {}", v, i);
}
// a is at index 0
// a is at index 1
// a is at index 2
}
// 実はいつもつかうlet文もパターンの考え方を使っている
pub fn let_statement_uses_pattern() {
// let PATTERN = EXPRESSION;
// ここでマッチしたものを変数_xに束縛することを意味するパターン
// なんでもいいよと言っている
let _x = 5;
// mismatched type
// expected a tuple with 3 elements, found one with 2 elements
// let (_x, _y) = (1, 2, 3);
// こうすると_x, _yのみに束縛できる(マッチングできる)
let (_x, _y, _) = (1, 2, 3);
}
// 難所:論駁可能性について(ろんばくかのうせいについて)
// '論駁'を英辞郎で検索すると'反論'へ誘導される
// 論駁可能,不可能の2つの形態が,パターンにはある
#[allow(irrefutable_let_patterns)]
pub fn various_refutables() {
// 論駁が可能なもの
// なんらかの可能性がある値について,合致しないことがあるパターン
let some_option_value = Some(3);
// 合致しないパターンを考慮した制御フローを書かないとコンパイルエラーになる
// 下のようにNoneの可能性を考慮して処理する
if let Some(x) = some_option_value {
println!("some option value is: {}", x);
}
// 論駁が不可能なもの
// あらゆるものにマッチする
// ワーニングがでる
// irrefutable if-let pattern
if let _x = 5 {
println!("x matches 5");
}
// これは論駁可能
// ワーニングはでない
// 5はかならずしもxに束縛されている値と等しいわけではない
let x = 5;
if let 5 = x {
println!("5 matches x");
}
}
// あたらしいyを導入するアームのあるmatch式
#[allow(unreachable_patterns)]
pub fn match_arm_begins_new_scope() {
let x = Some(5);
let y = 10;
match x {
Some(5) => println!("Got 50"),
// 新しい変数yがあらわれた
// 前に宣言しているyとは別物
// このマッチアームはSome(x)の値がなんであれマッチするので,この処理が実行される
// 外側のyと比較したい場合はマッチガード条件式を使用する必要がある
Some(y) => println!("Matched, y = {:?}", y),
// マッチガード条件式
// これはパターンではないため,新しい変数を導入しない
Some(n) if n == y => println!("Matched, n = {:?}", n),
_ => println!("Default case, x = {:?}", x),
}
}
// 複数のパターンにマッチさせる
pub fn multiple_match() {
let x = 1;
match x {
1 | 2 => println!("one or two"),
3 => println!("three"),
_ => println!("anything"),
}
}
// ..=で値の範囲に合致させる
pub fn range_match() {
let x = 5;
match x {
1..=5 => println!("one through five"),
_ => println!("something else"),
}
// one through five
let x = 'k';
match x {
'a'..='j' => println!("early ASCII letter"),
'k'..='z' => println!("late ASCII letter"),
_ => println!("something else"),
}
// late ASCII letter
}
struct Point2D {
x: i32,
y: i32,
}
pub fn decomposition_and_matching_of_struct_may_be_tricky() {
let p = Point2D { x: 0, y: 7 };
// 変数x, yとしてpの要素を取り出す
let Point2D { x, y } = p;
println!("x of Point is: {}", x); // 0
println!("y of Point is: {}", y); // 7
// match式で要素に応じた場合分け
match p {
// x軸上にいるか
Point2D { x, y: 0 } => println!("On the x axis at: {}", x),
// y軸上にいるか
Point2D { x: 0, y } => println!("On the y axis at: {}", y), // 7
// それ以外か
Point2D { x, y } => println!("On neither axis: ({}, {})", x, y),
}
}
enum Color {
Rgb(i32, i32, i32),
Hsv(i32, i32, i32),
}
enum Message {
Quit,
Move { x: i32, y: i32 },
Write(String),
ChangeColor(Color),
}
pub fn destructure_enum() {
let msgs = vec![
Message::Quit,
Message::Move { x: 3, y: 4 },
Message::Write("Hello!".to_string()),
Message::ChangeColor(Color::Rgb(0, 255, 128)),
Message::ChangeColor(Color::Hsv(0, 0, 0)),
];
for msg in msgs.iter() {
match msg {
Message::Quit => {
println!("The Quit variant has no data to destructure.");
}
Message::Move { x, y } => {
println!("Move in the x direction {} and in the y direction {}", x, y);
}
Message::Write(text) => {
println!("Text message: {}", text);
}
Message::ChangeColor(Color::Rgb(r, g, b)) => {
println!("Change the color to red {}, green {}, blue {}", r, g, b);
}
Message::ChangeColor(Color::Hsv(h, s, v)) => {
println!("Change the color to h {}, s {}, v {}", h, s, v);
}
}
}
}
pub fn destructure_nested_structures() {
let ((feet, inches), Point2D { x, y }) = ((3, 10), Point2D { x: 3, y: -10 });
let vs = [("feet", feet), ("inches", inches), ("p.x", x), ("p.y", y)];
for v in vs.iter() {
println!("{:?}: {}", v.0, v.1);
}
}
pub fn wild_card_in_the_nest() {
// Someの中身がなんであれ無視(Someであれば無視)
let mut setting_value = Some(5);
let new_setting_value = Some(10);
match (setting_value, new_setting_value) {
(Some(_), Some(_)) => {
println!("Can't overwrite an existing costomized value");
}
_ => {
setting_value = new_setting_value;
}
}
println!("setting_value: {:?}", setting_value);
}
// _x記法は所有権を奪う
pub fn difference_between_unused_value_and_wild_card() {
let s = Some(String::from("Hello?"));
if let Some(_) = s {
println!("found a string");
}
println!("the string: {:?}", s);
// Someの中身はDropトレイトあり.Moveされる
if let Some(_s) = s {
println!("found a string");
}
// 使用不可
// println!("the string: {:?}", s);
}
#[allow(dead_code)]
struct Point3D<T: std::fmt::Display> {
x: T,
y: T,
z: T,
}
// ある範囲の部分を無視する
#[allow(unreachable_patterns)]
pub fn ignore_a_range_of_structure() {
let p = Point3D::<f64> {
x: 0.3,
y: 6.45,
z: -23.0,
};
match p {
// xのみ興味がある書き方
// それでも,なんでもよいと言っているようなもの
// カバー漏れはないためコンパイル可能
Point3D { x, .. } => {
println!("x is {}", x);
}
// ちなみに,同じような守備範囲に思えるものを書いてもよさげ
// こちらを先にかくと,こちらが実行される
Point3D { x, y, .. } => {
println!("x, y is {}, {}", x, y);
}
}
}
pub fn ignore_a_range_of_tuple_and_list() {
let numbers = (2, 4, 8, 16, 32);
match numbers {
// ..は残りを省略するための書き方
// 下のような,どこまでが残りなのかわからないような書き方はできない
// (.., second, ..) => {
// println!("second is ...: {}", second);
// }
// こうしよう
(_, second, ..) => {
println!("second is ...: {}", second);
}
}
}
enum Msg {
Hello { id: i32 },
}
// @バインディング
// 値を保持する変数の生成と同時にパターンに一致するか調べる
#[allow(unreachable_patterns)]
pub fn at_binding() {
let msg = Msg::Hello { id: 5 };
match msg {
// 値を制限し,その範囲の値が含まれていることが保証される変数を生成
Msg::Hello { id: id_val @ 3..=7 } => {
println!("Found an id in range: {}", id_val);
}
// 変数の導入なし
Msg::Hello { id: 5 } => {
println!("Found an id: 5");
}
Msg::Hello { id } => {
println!("Found some other id: {}", id);
}
}
}
| identifier_name | ||
lib.rs | // まとめ
// - あらゆるところでパターンは使用されている
// - ちゃんと,あり得る可能性をカバーしよう
//
// python 3.10あたりで,pythonにも導入されるかも?
// (rustのsubprocessはpythonから影響を受けていたりなど,インスパイアされあっているような雰囲気)
//
//
// この章は辞書的な感じで,いろんなパターンとそのマッチング方法を列挙している感じ
// まずは6章の軽い復習+α
enum Coin {
Penny,
Nickel,
Dime,
Quarter,
}
pub fn simple_matching() {
let coins = vec![Coin::Penny, Coin::Nickel, Coin::Dime, Coin::Quarter];
for coin in coins.iter() {
println!(
"matched coin is {}",
match coin {
Coin::Penny => {
println!("Lucky penny!");
1
}
Coin::Nickel => 5,
Coin::Dime => 10,
Coin::Quarter => 25,
}
);
}
// Lucky penny!
// matched coin is 1
// matched coin is 5
// matched coin is 10
// matched coin is 25
}
pub fn all_patterns_must_be_covered() {
let a = 3;
let b = match a {
1 => 1,
2 => 2,
3 => 3,
_ => 0, // _パターンでカバーしないとだめ
// そうしないと下のコンパイルエラー
// patterns `std::i32::MIN..=0i32` and `4i32..=std::i32::MAX` not covered
};
println!("matched value is: {}", b);
}
// この例では輝かないが,if-let記法も道具箱にあるんですよ
// matchを使って表現するには冗長な場合に使いましょう
pub fn if_let_notation() {
let a = 3;
if let 1 = a {
println!("matched value is: 1");
} else if let 2 = a {
println!("matched value is: 2");
} else if let 3 = a {
println!("matched value is: 3");
} else {
println!("matched value is: others");
}
}
pub fn all_expressions_must_return_the_same_typed_value() {
let a = 3;
println!(
"matched value is: {}",
match a {
1 => "one",
2 => "two",
// 3 => 3, // expected '&str', found integer
// 異なる型を返すように書くことはできない
// どの型を基準にするかは,最初のパターンで返す型に依る
_ => "others",
}
);
// matched value is: others
}
// ここから18章の内容を本格的に
// ifとif-letが入り乱れるパターン
// お気に入りの色と年齢に応じて,背景色を変えることを考えているプログラム
// ややこしいからあまり使いたくないと感じた
pub fn mixed_if_statements() {
let favorite_color: Option<&str> = None;
let is_tuesday = false;
let age: Result<u8, _> = "34".parse();
if let Some(color) = favorite_color {
println!("Using your favorite color, {}, as the background", color);
} else if is_tuesday {
println!("Tuesday is green day");
} else if let Ok(age) = age {
if age > 30 {
println!("Using purple as the background color");
} else {
println!("Using orange as the background color");
}
} else {
println!("Using blue as the background color");
}
// Using purple as the background color
}
// whileにもパターンを
// なにかある限りpopする例
pub fn pop | 実はいつもつかうlet文もパターンの考え方を使っている
pub fn let_statement_uses_pattern() {
// let PATTERN = EXPRESSION;
// ここでマッチしたものを変数_xに束縛することを意味するパターン
// なんでもいいよと言っている
let _x = 5;
// mismatched type
// expected a tuple with 3 elements, found one with 2 elements
// let (_x, _y) = (1, 2, 3);
// こうすると_x, _yのみに束縛できる(マッチングできる)
let (_x, _y, _) = (1, 2, 3);
}
// 難所:論駁可能性について(ろんばくかのうせいについて)
// '論駁'を英辞郎で検索すると'反論'へ誘導される
// 論駁可能,不可能の2つの形態が,パターンにはある
#[allow(irrefutable_let_patterns)]
pub fn various_refutables() {
// 論駁が可能なもの
// なんらかの可能性がある値について,合致しないことがあるパターン
let some_option_value = Some(3);
// 合致しないパターンを考慮した制御フローを書かないとコンパイルエラーになる
// 下のようにNoneの可能性を考慮して処理する
if let Some(x) = some_option_value {
println!("some option value is: {}", x);
}
// 論駁が不可能なもの
// あらゆるものにマッチする
// ワーニングがでる
// irrefutable if-let pattern
if let _x = 5 {
println!("x matches 5");
}
// これは論駁可能
// ワーニングはでない
// 5はかならずしもxに束縛されている値と等しいわけではない
let x = 5;
if let 5 = x {
println!("5 matches x");
}
}
// あたらしいyを導入するアームのあるmatch式
#[allow(unreachable_patterns)]
pub fn match_arm_begins_new_scope() {
let x = Some(5);
let y = 10;
match x {
Some(5) => println!("Got 50"),
// 新しい変数yがあらわれた
// 前に宣言しているyとは別物
// このマッチアームはSome(x)の値がなんであれマッチするので,この処理が実行される
// 外側のyと比較したい場合はマッチガード条件式を使用する必要がある
Some(y) => println!("Matched, y = {:?}", y),
// マッチガード条件式
// これはパターンではないため,新しい変数を導入しない
Some(n) if n == y => println!("Matched, n = {:?}", n),
_ => println!("Default case, x = {:?}", x),
}
}
// 複数のパターンにマッチさせる
pub fn multiple_match() {
let x = 1;
match x {
1 | 2 => println!("one or two"),
3 => println!("three"),
_ => println!("anything"),
}
}
// ..=で値の範囲に合致させる
pub fn range_match() {
let x = 5;
match x {
1..=5 => println!("one through five"),
_ => println!("something else"),
}
// one through five
let x = 'k';
match x {
'a'..='j' => println!("early ASCII letter"),
'k'..='z' => println!("late ASCII letter"),
_ => println!("something else"),
}
// late ASCII letter
}
struct Point2D {
x: i32,
y: i32,
}
pub fn decomposition_and_matching_of_struct_may_be_tricky() {
let p = Point2D { x: 0, y: 7 };
// 変数x, yとしてpの要素を取り出す
let Point2D { x, y } = p;
println!("x of Point is: {}", x); // 0
println!("y of Point is: {}", y); // 7
// match式で要素に応じた場合分け
match p {
// x軸上にいるか
Point2D { x, y: 0 } => println!("On the x axis at: {}", x),
// y軸上にいるか
Point2D { x: 0, y } => println!("On the y axis at: {}", y), // 7
// それ以外か
Point2D { x, y } => println!("On neither axis: ({}, {})", x, y),
}
}
enum Color {
Rgb(i32, i32, i32),
Hsv(i32, i32, i32),
}
enum Message {
Quit,
Move { x: i32, y: i32 },
Write(String),
ChangeColor(Color),
}
pub fn destructure_enum() {
let msgs = vec![
Message::Quit,
Message::Move { x: 3, y: 4 },
Message::Write("Hello!".to_string()),
Message::ChangeColor(Color::Rgb(0, 255, 128)),
Message::ChangeColor(Color::Hsv(0, 0, 0)),
];
for msg in msgs.iter() {
match msg {
Message::Quit => {
println!("The Quit variant has no data to destructure.");
}
Message::Move { x, y } => {
println!("Move in the x direction {} and in the y direction {}", x, y);
}
Message::Write(text) => {
println!("Text message: {}", text);
}
Message::ChangeColor(Color::Rgb(r, g, b)) => {
println!("Change the color to red {}, green {}, blue {}", r, g, b);
}
Message::ChangeColor(Color::Hsv(h, s, v)) => {
println!("Change the color to h {}, s {}, v {}", h, s, v);
}
}
}
}
pub fn destructure_nested_structures() {
let ((feet, inches), Point2D { x, y }) = ((3, 10), Point2D { x: 3, y: -10 });
let vs = [("feet", feet), ("inches", inches), ("p.x", x), ("p.y", y)];
for v in vs.iter() {
println!("{:?}: {}", v.0, v.1);
}
}
pub fn wild_card_in_the_nest() {
// Someの中身がなんであれ無視(Someであれば無視)
let mut setting_value = Some(5);
let new_setting_value = Some(10);
match (setting_value, new_setting_value) {
(Some(_), Some(_)) => {
println!("Can't overwrite an existing costomized value");
}
_ => {
setting_value = new_setting_value;
}
}
println!("setting_value: {:?}", setting_value);
}
// _x記法は所有権を奪う
pub fn difference_between_unused_value_and_wild_card() {
let s = Some(String::from("Hello?"));
if let Some(_) = s {
println!("found a string");
}
println!("the string: {:?}", s);
// Someの中身はDropトレイトあり.Moveされる
if let Some(_s) = s {
println!("found a string");
}
// 使用不可
// println!("the string: {:?}", s);
}
#[allow(dead_code)]
struct Point3D<T: std::fmt::Display> {
x: T,
y: T,
z: T,
}
// ある範囲の部分を無視する
#[allow(unreachable_patterns)]
pub fn ignore_a_range_of_structure() {
let p = Point3D::<f64> {
x: 0.3,
y: 6.45,
z: -23.0,
};
match p {
// xのみ興味がある書き方
// それでも,なんでもよいと言っているようなもの
// カバー漏れはないためコンパイル可能
Point3D { x, .. } => {
println!("x is {}", x);
}
// ちなみに,同じような守備範囲に思えるものを書いてもよさげ
// こちらを先にかくと,こちらが実行される
Point3D { x, y, .. } => {
println!("x, y is {}, {}", x, y);
}
}
}
pub fn ignore_a_range_of_tuple_and_list() {
let numbers = (2, 4, 8, 16, 32);
match numbers {
// ..は残りを省略するための書き方
// 下のような,どこまでが残りなのかわからないような書き方はできない
// (.., second, ..) => {
// println!("second is ...: {}", second);
// }
// こうしよう
(_, second, ..) => {
println!("second is ...: {}", second);
}
}
}
enum Msg {
Hello { id: i32 },
}
// @バインディング
// 値を保持する変数の生成と同時にパターンに一致するか調べる
#[allow(unreachable_patterns)]
pub fn at_binding() {
let msg = Msg::Hello { id: 5 };
match msg {
// 値を制限し,その範囲の値が含まれていることが保証される変数を生成
Msg::Hello { id: id_val @ 3..=7 } => {
println!("Found an id in range: {}", id_val);
}
// 変数の導入なし
Msg::Hello { id: 5 } => {
println!("Found an id: 5");
}
Msg::Hello { id } => {
println!("Found some other id: {}", id);
}
}
}
| _as_long_as_vector_has_values() {
let mut stack = Vec::new();
stack.push(1);
stack.push(2);
stack.push(3);
while let Some(top) = stack.pop() {
println!("vector has {} on the top", top);
}
// vector has 3 on the top
// vector has 2 on the top
// vector has 1 on the top
}
// forでもパターンの考え方は使われている
// for x in yでは,xがパターンとなる
// ここでは,タプルとして分解する方法を示す
pub fn for_statement_can_use_patterns() {
let v = vec!['a', 'b', 'c'];
for (i, v) in v.iter().enumerate() {
println!("{} is at index {}", v, i);
}
// a is at index 0
// a is at index 1
// a is at index 2
}
// | identifier_body |
lib.rs | // まとめ
// - あらゆるところでパターンは使用されている
// - ちゃんと,あり得る可能性をカバーしよう
//
// python 3.10あたりで,pythonにも導入されるかも?
// (rustのsubprocessはpythonから影響を受けていたりなど,インスパイアされあっているような雰囲気)
//
//
// この章は辞書的な感じで,いろんなパターンとそのマッチング方法を列挙している感じ
// まずは6章の軽い復習+α
enum Coin {
Penny,
Nickel,
Dime,
Quarter,
}
pub fn simple_matching() {
let coins = vec![Coin::Penny, Coin::Nickel, Coin::Dime, Coin::Quarter];
for coin in coins.iter() {
println!(
"matched coin is {}",
match coin {
Coin::Penny => {
println!("Lucky penny!");
1
}
Coin::Nickel => 5,
Coin::Dime => 10,
Coin::Quarter => 25,
}
);
}
// Lucky penny!
// matched coin is 1
// matched coin is 5
// matched coin is 10
// matched coin is 25
}
pub fn all_patterns_must_be_covered() {
let a = 3;
let b = match a {
1 => 1,
2 => 2,
3 => 3,
_ => 0, // _パターンでカバーしないとだめ
// そうしないと下のコンパイルエラー
// patterns `std::i32::MIN..=0i32` and `4i32..=std::i32::MAX` not covered
};
println!("matched value is: {}", b);
}
// この例では輝かないが,if-let記法も道具箱にあるんですよ
// matchを使って表現するには冗長な場合に使いましょう
pub fn if_let_notation() {
let a = 3;
if let 1 = a {
println!("matched value is: 1");
} else if let 2 = a {
println!("matched value is: 2");
} else if let 3 = a {
println!("matched value is: 3");
} else {
println!("matched value is: others");
}
}
pub fn all_expressions_must_return_the_same_typed_value() {
let a = 3;
println!(
"matched value is: {}",
match a {
1 => "one",
2 => "two",
// 3 => 3, // expected '&str', found integer
// 異なる型を返すように書くことはできない
// どの型を基準にするかは,最初のパターンで返す型に依る
_ => "others",
}
);
// matched value is: others
}
// ここから18章の内容を本格的に
// ifとif-letが入り乱れるパターン
// お気に入りの色と年齢に応じて,背景色を変えることを考えているプログラム
// ややこしいからあまり使いたくないと感じた
pub fn mixed_if_statements() {
let favorite_color: Option<&str> = None;
let is_tuesday = false;
let age: Result<u8, _> = "34".parse();
if let Some(color) = favorite_color {
println!("Using your favorite color, {}, as the background", color);
} else if is_tuesday {
println!("Tuesday is green day");
} else if let Ok(age) = age {
if age > 30 {
println!("Using purple as the background color");
} else {
println!("Using orange as the background color");
}
} else {
println!("Using blue as the background color");
}
// Using purple as the background color
}
// whileにもパターンを
// なにかある限りpopする例
pub fn pop_as_long_as_vector_has_values() {
let mut stack = Vec::new();
stack.push(1);
stack.push(2);
stack.push(3);
while let Some(top) = stack.pop() {
println!("vector has {} on the top", top);
}
// vector has 3 on the top
// vector has 2 on the top
// vector has 1 on the top
}
// forでもパターンの考え方は使われている
// for x in yでは,xがパターンとなる
// ここでは,タプルとして分解する方法を示す
pub fn for_statement_can_use_patterns() {
let v = vec!['a', 'b', 'c'];
for (i, v) in v.iter().enumerate() {
println!("{} is at index {}", v, i);
}
// a is at index 0
// a is at index 1
// a is at index 2
}
// 実はいつもつかうlet文もパターンの考え方を使っている
pub fn let_statement_uses_pattern() {
// let PATTERN = EXPRESSION;
// ここでマッチしたものを変数_xに束縛することを意味するパターン
// なんでもいいよと言っている
let _x = 5;
// mismatched type
// expected a tuple with 3 elements, found one with 2 elements
// let (_x, _y) = (1, 2, 3);
// こうすると_x, _yのみに束縛できる(マッチングできる)
let (_x, _y, _) = (1, 2, 3);
}
// 難所:論駁可能性について(ろんばくかのうせいについて)
// '論駁'を英辞郎で検索すると'反論'へ誘導される
// 論駁可能,不可能の2つの形態が,パターンにはある
#[allow(irrefutable_let_patterns)]
pub fn various_refutables() {
// 論駁が可能なもの
// なんらかの可能性がある値について,合致しないことがあるパターン
let some_option_value = Some(3);
// 合致しないパターンを考慮した制御フローを書かないとコンパイルエラーになる
// 下のようにNoneの可能性を考慮して処理する
if let Some(x) = some_option_value {
println!("some option value is: {}", x);
}
// 論駁が不可能なもの
// あらゆるものにマッチする
// ワーニングがでる
// irrefutable if-let pattern
if let _x = 5 {
println!("x matches 5");
}
// これは論駁可能
// ワーニングはでない
// 5はかならずしもxに束縛されている値と等しいわけではない
let x = 5;
if let 5 = x {
println!("5 matches x");
}
}
// あたらしいyを導入するアームのあるmatch式
#[allow(unreachable_patterns)]
pub fn match_arm_begins_new_scope() {
let x = Some(5);
let y = 10;
match x {
Some(5) => println!("Got 50"),
// 新しい変数yがあらわれた
// 前に宣言しているyとは別物
// このマッチアームはSome(x)の値がなんであれマッチするので,この処理が実行される
// 外側のyと比較したい場合はマッチガード条件式を使用する必要がある
Some(y) => println!("Matched, y = {:?}", y),
// マッチガード条件式
// これはパターンではないため,新しい変数を導入しない
Some(n) if n == y => println!("Matched, n = {:?}", n),
_ => println!("Default case, x = {:?}", x),
}
}
// 複数のパターンにマッチさせる
pub fn multiple_match() {
let x = 1;
match x {
1 | 2 => println!("one or two"),
3 => println!("three"),
_ => println!("anything"),
}
}
// ..=で値の範囲に合致させる
pub fn range_match() {
let x = 5;
match x {
1..=5 => println!("one through five"),
_ => println!("something else"),
}
// one through five
let x = 'k';
match x {
'a'..='j' => println!("early ASCII letter"),
'k'..='z' => println!("late ASCII letter"),
_ => println!("something else"),
}
// late ASCII letter
}
struct Point2D {
x: i32,
y: i32,
}
pub fn decomposition_and_matching_of_struct_may_be_tricky() {
let p = Point2D { x: 0, y: 7 };
// 変数x, yとしてpの要素を取り出す
let Point2D { x, y } = p;
println!("x of Point is: {}", x); // 0
println!("y of Point is: {}", y); // 7
// match式で要素に応じた場合分け
match p {
// x軸上にいるか
Point2D { x, y: 0 } => println!("On the x axis at: {}", x),
// y軸上にいるか
Point2D { x: 0, y } => println!("On the y axis at: {}", y), // 7
// それ以外か
Point2D { x, y } => println!("On neither axis: ({}, {})", x, y),
}
}
enum Color {
Rgb(i32, i32, i32),
Hsv(i32, i32, i32),
}
enum Message {
Quit,
Move { x: i32, y: i32 },
Write(String),
ChangeColor(Color),
}
pub fn destructure_enum() { | Message::Quit,
Message::Move { x: 3, y: 4 },
Message::Write("Hello!".to_string()),
Message::ChangeColor(Color::Rgb(0, 255, 128)),
Message::ChangeColor(Color::Hsv(0, 0, 0)),
];
for msg in msgs.iter() {
match msg {
Message::Quit => {
println!("The Quit variant has no data to destructure.");
}
Message::Move { x, y } => {
println!("Move in the x direction {} and in the y direction {}", x, y);
}
Message::Write(text) => {
println!("Text message: {}", text);
}
Message::ChangeColor(Color::Rgb(r, g, b)) => {
println!("Change the color to red {}, green {}, blue {}", r, g, b);
}
Message::ChangeColor(Color::Hsv(h, s, v)) => {
println!("Change the color to h {}, s {}, v {}", h, s, v);
}
}
}
}
pub fn destructure_nested_structures() {
let ((feet, inches), Point2D { x, y }) = ((3, 10), Point2D { x: 3, y: -10 });
let vs = [("feet", feet), ("inches", inches), ("p.x", x), ("p.y", y)];
for v in vs.iter() {
println!("{:?}: {}", v.0, v.1);
}
}
pub fn wild_card_in_the_nest() {
// Someの中身がなんであれ無視(Someであれば無視)
let mut setting_value = Some(5);
let new_setting_value = Some(10);
match (setting_value, new_setting_value) {
(Some(_), Some(_)) => {
println!("Can't overwrite an existing costomized value");
}
_ => {
setting_value = new_setting_value;
}
}
println!("setting_value: {:?}", setting_value);
}
// _x記法は所有権を奪う
pub fn difference_between_unused_value_and_wild_card() {
let s = Some(String::from("Hello?"));
if let Some(_) = s {
println!("found a string");
}
println!("the string: {:?}", s);
// Someの中身はDropトレイトあり.Moveされる
if let Some(_s) = s {
println!("found a string");
}
// 使用不可
// println!("the string: {:?}", s);
}
#[allow(dead_code)]
struct Point3D<T: std::fmt::Display> {
x: T,
y: T,
z: T,
}
// ある範囲の部分を無視する
#[allow(unreachable_patterns)]
pub fn ignore_a_range_of_structure() {
let p = Point3D::<f64> {
x: 0.3,
y: 6.45,
z: -23.0,
};
match p {
// xのみ興味がある書き方
// それでも,なんでもよいと言っているようなもの
// カバー漏れはないためコンパイル可能
Point3D { x, .. } => {
println!("x is {}", x);
}
// ちなみに,同じような守備範囲に思えるものを書いてもよさげ
// こちらを先にかくと,こちらが実行される
Point3D { x, y, .. } => {
println!("x, y is {}, {}", x, y);
}
}
}
pub fn ignore_a_range_of_tuple_and_list() {
let numbers = (2, 4, 8, 16, 32);
match numbers {
// ..は残りを省略するための書き方
// 下のような,どこまでが残りなのかわからないような書き方はできない
// (.., second, ..) => {
// println!("second is ...: {}", second);
// }
// こうしよう
(_, second, ..) => {
println!("second is ...: {}", second);
}
}
}
enum Msg {
Hello { id: i32 },
}
// @バインディング
// 値を保持する変数の生成と同時にパターンに一致するか調べる
#[allow(unreachable_patterns)]
pub fn at_binding() {
let msg = Msg::Hello { id: 5 };
match msg {
// 値を制限し,その範囲の値が含まれていることが保証される変数を生成
Msg::Hello { id: id_val @ 3..=7 } => {
println!("Found an id in range: {}", id_val);
}
// 変数の導入なし
Msg::Hello { id: 5 } => {
println!("Found an id: 5");
}
Msg::Hello { id } => {
println!("Found some other id: {}", id);
}
}
} | let msgs = vec![ | random_line_split |
vggish_input.py | # Copyright (c) 2017-2019 Carnegie Mellon University. All rights reserved.
# Use of this source code is governed by BSD 3-clause license and the following
# license from the original code.
# This code is modified from Ubicoustics codebase. LICENSE infomation:
# SOFTWARE LICENSE AGREEMENT
# ACADEMIC OR NON-PROFIT ORGANIZATION NONCOMMERCIAL RESEARCH USE ONLY
#
# BY USING OR DOWNLOADING THE SOFTWARE, YOU ARE AGREEING TO THE TERMS OF THIS
# LICENSE AGREEMENT. IF YOU DO NOT AGREE WITH THESE TERMS, YOU MAY NOT USE OR
# DOWNLOAD THE SOFTWARE.
#
# This is a license agreement ("Agreement") between your academic institution
# or non-profit organization or self (called "Licensee" or "You" in this
# Agreement) and Carnegie Mellon University (called "Licensor" in this
# Agreement). All rights not specifically granted to you in this Agreement are
# reserved for Licensor.
#
# RESERVATION OF OWNERSHIP AND GRANT OF LICENSE: Licensor retains exclusive
# ownership of any copy of the Software (as defined below) licensed under this
# Agreement and hereby grants to Licensee a personal, non-exclusive,
# non-transferable license to use the Software for noncommercial research
# purposes, without the right to sublicense, pursuant to the terms and
# conditions of this Agreement. As used in this Agreement, the term "Software"
# means (i) the actual copy of all or any portion of code for program routines
# made accessible to Licensee by Licensor pursuant to this Agreement, inclusive
# of backups, updates, and/or merged copies permitted hereunder or subsequently
# supplied by Licensor, including all or any file structures, programming
# instructions, user interfaces and screen formats and sequences as well as any
# and all documentation and instructions related to it, and (ii) all or any
# derivatives and/or modifications created or made by You to any of the items
# specified in (i).
#
# CONFIDENTIALITY: Licensee acknowledges that the Software is proprietary to
# Licensor, and as such, Licensee agrees to receive all such materials in
# confidence and use the Software only in accordance with the terms of this
# Agreement. Licensee agrees to use reasonable effort to protect the Software
# from unauthorized use, reproduction, distribution, or publication.
#
# COPYRIGHT: The Software is owned by Licensor and is protected by United
# States copyright laws and applicable international treaties and/or
# conventions.
#
# PERMITTED USES: The Software may be used for your own noncommercial internal
# research purposes. You understand and agree that Licensor is not obligated to
# implement any suggestions and/or feedback you might provide regarding the
# Software, but to the extent Licensor does so, you are not entitled to any
# compensation related thereto.
#
# DERIVATIVES: You may create derivatives of or make modifications to the
# Software, however, You agree that all and any such derivatives and
# modifications will be owned by Licensor and become a part of the Software
# licensed to You under this Agreement. You may only use such derivatives and
# modifications for your own noncommercial internal research purposes, and you
# may not otherwise use, distribute or copy such derivatives and modifications
# in violation of this Agreement.
#
# BACKUPS: If Licensee is an organization, it may make that number of copies
# of the Software necessary for internal noncommercial use at a single site
# within its organization provided that all information appearing in or on the
# original labels, including the copyright and trademark notices are copied
# onto the labels of the copies.
#
# USES NOT PERMITTED: You may not distribute, copy or use the Software except
# as explicitly permitted herein. Licensee has not been granted any trademark
# license as part of this Agreement and may not use the name or mark
# “Ubicoustics", "Carnegie Mellon" or any renditions thereof without the prior
# written permission of Licensor.
#
# You may not sell, rent, lease, sublicense, lend, time-share or transfer, in
# whole or in part, or provide third parties access to prior or present
# versions (or any parts thereof) of the Software.
#
# ASSIGNMENT: You may not assign this Agreement or your rights hereunder
# without the prior written consent of Licensor. Any attempted assignment
# without such consent shall be null and void.
#
# TERM: The term of the license granted by this Agreement is from Licensee's
# acceptance of this Agreement by downloading the Software or by using the
# Software until terminated as provided below.
#
# The Agreement automatically terminates without notice if you fail to comply
# with any provision of this Agreement. Licensee may terminate this Agreement
# by ceasing using the Software. Upon any termination of this Agreement,
# Licensee will delete any and all copies of the Software. You agree that all
# provisions which operate to protect the proprietary rights of Licensor shall
# remain in force should breach occur and that the obligation of
# confidentiality described in this Agreement is binding in perpetuity and, as
# such, survives the term of the Agreement.
#
# FEE: Provided Licensee abides completely by the terms and conditions of this
# Agreement, there is no fee due to Licensor for Licensee's use of the Software
# in accordance with this Agreement.
#
# DISCLAIMER OF WARRANTIES: THE SOFTWARE IS PROVIDED "AS-IS" WITHOUT WARRANTY
# OF ANY KIND INCLUDING ANY WARRANTIES OF PERFORMANCE OR MERCHANTABILITY OR
# FITNESS FOR A PARTICULAR USE OR PURPOSE OR OF NON-INFRINGEMENT. LICENSEE
# BEARS ALL RISK RELATING TO QUALITY AND PERFORMANCE OF THE SOFTWARE AND
# RELATED MATERIALS.
#
# SUPPORT AND MAINTENANCE: No Software support or training by the Licensor is
# provided as part of this Agreement.
#
# EXCLUSIVE REMEDY AND LIMITATION OF LIABILITY: To the maximum extent permitted
# under applicable law, Licensor shall not be liable for direct, indirect,
# special, incidental, or consequential damages or lost profits related to
# Licensee's use of and/or inability to use the Software, even if Licensor is
#advised of the possibility of such damage.
#
# EXPORT REGULATION: Licensee agrees to comply with any and all applicable U.S.
# export control laws, regulations, and/or other laws related to embargoes and
# sanction programs administered by the Office of Foreign Assets Control.
#
# SEVERABILITY: If any provision(s) of this Agreement shall be held to be
# invalid, illegal, or unenforceable by a court or other tribunal of competent
# jurisdiction, the validity, legality and enforceability of the remaining
# provisions shall not in any way be affected or impaired thereby.
#
# NO IMPLIED WAIVERS: No failure or delay by Licensor in enforcing any right or
# remedy under this Agreement shall be construed as a waiver of any future or
# other exercise of such right or remedy by Licensor.
#
# GOVERNING LAW: This Agreement shall be construed and enforced in accordance
# with the laws of the Commonwealth of Pennsylvania without reference to
# conflict of laws principles. You consent to the personal jurisdiction of the
# courts of this County and waive their rights to venue outside of Allegheny
# County, Pennsylvania.
#
# ENTIRE AGREEMENT AND AMENDMENTS: This Agreement constitutes the sole and
# entire agreement between Licensee and Licensor as to the matter set forth
# herein and supersedes any previous agreements, understandings, and
# arrangements between the parties relating hereto.
import numpy as np
import resampy
from scipy.io import wavfile
import mel_features
import vggish_params
def wa | ata, sample_rate):
# Convert to mono.
if len(data.shape) > 1:
data = np.mean(data, axis=1)
# Resample to the rate assumed by VGGish.
if sample_rate != vggish_params.SAMPLE_RATE:
data = resampy.resample(data, sample_rate, vggish_params.SAMPLE_RATE)
# Compute log mel spectrogram features.
log_mel = mel_features.log_mel_spectrogram(
data,
audio_sample_rate=vggish_params.SAMPLE_RATE,
log_offset=vggish_params.LOG_OFFSET,
window_length_secs=vggish_params.STFT_WINDOW_LENGTH_SECONDS,
hop_length_secs=vggish_params.STFT_HOP_LENGTH_SECONDS,
num_mel_bins=vggish_params.NUM_MEL_BINS,
lower_edge_hertz=vggish_params.MEL_MIN_HZ,
upper_edge_hertz=vggish_params.MEL_MAX_HZ)
# Frame features into examples.
features_sample_rate = 1.0 / vggish_params.STFT_HOP_LENGTH_SECONDS
example_window_length = int(round(
vggish_params.EXAMPLE_WINDOW_SECONDS * features_sample_rate))
example_hop_length = int(round(
vggish_params.EXAMPLE_HOP_SECONDS * features_sample_rate))
log_mel_examples = mel_features.frame(
log_mel,
window_length=example_window_length,
hop_length=example_hop_length)
return log_mel_examples
def waveform_to_examples_subtract_bg(data, sample_rate, bg):
# Convert to mono.
if len(data.shape) > 1:
data = np.mean(data, axis=1)
# Resample to the rate assumed by VGGish.
if sample_rate != vggish_params.SAMPLE_RATE:
data = resampy.resample(data, sample_rate, vggish_params.SAMPLE_RATE)
# Compute log mel spectrogram features.
log_mel = mel_features.log_mel_spectrogram_subtract_bg(
data,
bg,
audio_sample_rate=vggish_params.SAMPLE_RATE,
log_offset=vggish_params.LOG_OFFSET,
window_length_secs=vggish_params.STFT_WINDOW_LENGTH_SECONDS,
hop_length_secs=vggish_params.STFT_HOP_LENGTH_SECONDS,
num_mel_bins=vggish_params.NUM_MEL_BINS,
lower_edge_hertz=vggish_params.MEL_MIN_HZ,
upper_edge_hertz=vggish_params.MEL_MAX_HZ)
# Frame features into examples.
features_sample_rate = 1.0 / vggish_params.STFT_HOP_LENGTH_SECONDS
example_window_length = int(round(
vggish_params.EXAMPLE_WINDOW_SECONDS * features_sample_rate))
example_hop_length = int(round(
vggish_params.EXAMPLE_HOP_SECONDS * features_sample_rate))
log_mel_examples = mel_features.frame(
log_mel,
window_length=example_window_length,
hop_length=example_hop_length)
return log_mel_examples
def wavfile_to_examples(wav_file):
sr, wav_data = wavfile.read(wav_file)
assert wav_data.dtype == np.int16, 'Bad sample type: %r' % wav_data.dtype
samples = wav_data / 32768.0 # Convert to [-1.0, +1.0]
return waveform_to_examples(samples, sr)
| veform_to_examples(d | identifier_name |
vggish_input.py | # Copyright (c) 2017-2019 Carnegie Mellon University. All rights reserved.
# Use of this source code is governed by BSD 3-clause license and the following
# license from the original code.
# This code is modified from Ubicoustics codebase. LICENSE infomation:
# SOFTWARE LICENSE AGREEMENT
# ACADEMIC OR NON-PROFIT ORGANIZATION NONCOMMERCIAL RESEARCH USE ONLY
#
# BY USING OR DOWNLOADING THE SOFTWARE, YOU ARE AGREEING TO THE TERMS OF THIS
# LICENSE AGREEMENT. IF YOU DO NOT AGREE WITH THESE TERMS, YOU MAY NOT USE OR
# DOWNLOAD THE SOFTWARE.
#
# This is a license agreement ("Agreement") between your academic institution
# or non-profit organization or self (called "Licensee" or "You" in this
# Agreement) and Carnegie Mellon University (called "Licensor" in this
# Agreement). All rights not specifically granted to you in this Agreement are
# reserved for Licensor.
#
# RESERVATION OF OWNERSHIP AND GRANT OF LICENSE: Licensor retains exclusive
# ownership of any copy of the Software (as defined below) licensed under this
# Agreement and hereby grants to Licensee a personal, non-exclusive,
# non-transferable license to use the Software for noncommercial research
# purposes, without the right to sublicense, pursuant to the terms and
# conditions of this Agreement. As used in this Agreement, the term "Software"
# means (i) the actual copy of all or any portion of code for program routines
# made accessible to Licensee by Licensor pursuant to this Agreement, inclusive
# of backups, updates, and/or merged copies permitted hereunder or subsequently
# supplied by Licensor, including all or any file structures, programming
# instructions, user interfaces and screen formats and sequences as well as any
# and all documentation and instructions related to it, and (ii) all or any
# derivatives and/or modifications created or made by You to any of the items
# specified in (i).
#
# CONFIDENTIALITY: Licensee acknowledges that the Software is proprietary to
# Licensor, and as such, Licensee agrees to receive all such materials in
# confidence and use the Software only in accordance with the terms of this
# Agreement. Licensee agrees to use reasonable effort to protect the Software
# from unauthorized use, reproduction, distribution, or publication.
#
# COPYRIGHT: The Software is owned by Licensor and is protected by United
# States copyright laws and applicable international treaties and/or
# conventions.
#
# PERMITTED USES: The Software may be used for your own noncommercial internal
# research purposes. You understand and agree that Licensor is not obligated to
# implement any suggestions and/or feedback you might provide regarding the
# Software, but to the extent Licensor does so, you are not entitled to any
# compensation related thereto.
#
# DERIVATIVES: You may create derivatives of or make modifications to the
# Software, however, You agree that all and any such derivatives and
# modifications will be owned by Licensor and become a part of the Software
# licensed to You under this Agreement. You may only use such derivatives and
# modifications for your own noncommercial internal research purposes, and you
# may not otherwise use, distribute or copy such derivatives and modifications
# in violation of this Agreement.
#
# BACKUPS: If Licensee is an organization, it may make that number of copies
# of the Software necessary for internal noncommercial use at a single site
# within its organization provided that all information appearing in or on the
# original labels, including the copyright and trademark notices are copied
# onto the labels of the copies.
#
# USES NOT PERMITTED: You may not distribute, copy or use the Software except
# as explicitly permitted herein. Licensee has not been granted any trademark
# license as part of this Agreement and may not use the name or mark
# “Ubicoustics", "Carnegie Mellon" or any renditions thereof without the prior
# written permission of Licensor.
#
# You may not sell, rent, lease, sublicense, lend, time-share or transfer, in
# whole or in part, or provide third parties access to prior or present
# versions (or any parts thereof) of the Software.
#
# ASSIGNMENT: You may not assign this Agreement or your rights hereunder
# without the prior written consent of Licensor. Any attempted assignment
# without such consent shall be null and void.
#
# TERM: The term of the license granted by this Agreement is from Licensee's
# acceptance of this Agreement by downloading the Software or by using the
# Software until terminated as provided below.
#
# The Agreement automatically terminates without notice if you fail to comply
# with any provision of this Agreement. Licensee may terminate this Agreement
# by ceasing using the Software. Upon any termination of this Agreement,
# Licensee will delete any and all copies of the Software. You agree that all
# provisions which operate to protect the proprietary rights of Licensor shall
# remain in force should breach occur and that the obligation of
# confidentiality described in this Agreement is binding in perpetuity and, as
# such, survives the term of the Agreement.
#
# FEE: Provided Licensee abides completely by the terms and conditions of this
# Agreement, there is no fee due to Licensor for Licensee's use of the Software
# in accordance with this Agreement.
#
# DISCLAIMER OF WARRANTIES: THE SOFTWARE IS PROVIDED "AS-IS" WITHOUT WARRANTY
# OF ANY KIND INCLUDING ANY WARRANTIES OF PERFORMANCE OR MERCHANTABILITY OR
# FITNESS FOR A PARTICULAR USE OR PURPOSE OR OF NON-INFRINGEMENT. LICENSEE
# BEARS ALL RISK RELATING TO QUALITY AND PERFORMANCE OF THE SOFTWARE AND
# RELATED MATERIALS.
#
# SUPPORT AND MAINTENANCE: No Software support or training by the Licensor is
# provided as part of this Agreement.
#
# EXCLUSIVE REMEDY AND LIMITATION OF LIABILITY: To the maximum extent permitted
# under applicable law, Licensor shall not be liable for direct, indirect,
# special, incidental, or consequential damages or lost profits related to
# Licensee's use of and/or inability to use the Software, even if Licensor is
#advised of the possibility of such damage.
#
# EXPORT REGULATION: Licensee agrees to comply with any and all applicable U.S.
# export control laws, regulations, and/or other laws related to embargoes and
# sanction programs administered by the Office of Foreign Assets Control.
#
# SEVERABILITY: If any provision(s) of this Agreement shall be held to be
# invalid, illegal, or unenforceable by a court or other tribunal of competent
# jurisdiction, the validity, legality and enforceability of the remaining
# provisions shall not in any way be affected or impaired thereby.
#
# NO IMPLIED WAIVERS: No failure or delay by Licensor in enforcing any right or
# remedy under this Agreement shall be construed as a waiver of any future or
# other exercise of such right or remedy by Licensor.
#
# GOVERNING LAW: This Agreement shall be construed and enforced in accordance
# with the laws of the Commonwealth of Pennsylvania without reference to
# conflict of laws principles. You consent to the personal jurisdiction of the
# courts of this County and waive their rights to venue outside of Allegheny
# County, Pennsylvania.
#
# ENTIRE AGREEMENT AND AMENDMENTS: This Agreement constitutes the sole and
# entire agreement between Licensee and Licensor as to the matter set forth
# herein and supersedes any previous agreements, understandings, and
# arrangements between the parties relating hereto.
import numpy as np
import resampy
from scipy.io import wavfile
import mel_features
import vggish_params
|
def waveform_to_examples(data, sample_rate):
# Convert to mono.
if len(data.shape) > 1:
data = np.mean(data, axis=1)
# Resample to the rate assumed by VGGish.
if sample_rate != vggish_params.SAMPLE_RATE:
data = resampy.resample(data, sample_rate, vggish_params.SAMPLE_RATE)
# Compute log mel spectrogram features.
log_mel = mel_features.log_mel_spectrogram(
data,
audio_sample_rate=vggish_params.SAMPLE_RATE,
log_offset=vggish_params.LOG_OFFSET,
window_length_secs=vggish_params.STFT_WINDOW_LENGTH_SECONDS,
hop_length_secs=vggish_params.STFT_HOP_LENGTH_SECONDS,
num_mel_bins=vggish_params.NUM_MEL_BINS,
lower_edge_hertz=vggish_params.MEL_MIN_HZ,
upper_edge_hertz=vggish_params.MEL_MAX_HZ)
# Frame features into examples.
features_sample_rate = 1.0 / vggish_params.STFT_HOP_LENGTH_SECONDS
example_window_length = int(round(
vggish_params.EXAMPLE_WINDOW_SECONDS * features_sample_rate))
example_hop_length = int(round(
vggish_params.EXAMPLE_HOP_SECONDS * features_sample_rate))
log_mel_examples = mel_features.frame(
log_mel,
window_length=example_window_length,
hop_length=example_hop_length)
return log_mel_examples
def waveform_to_examples_subtract_bg(data, sample_rate, bg):
# Convert to mono.
if len(data.shape) > 1:
data = np.mean(data, axis=1)
# Resample to the rate assumed by VGGish.
if sample_rate != vggish_params.SAMPLE_RATE:
data = resampy.resample(data, sample_rate, vggish_params.SAMPLE_RATE)
# Compute log mel spectrogram features.
log_mel = mel_features.log_mel_spectrogram_subtract_bg(
data,
bg,
audio_sample_rate=vggish_params.SAMPLE_RATE,
log_offset=vggish_params.LOG_OFFSET,
window_length_secs=vggish_params.STFT_WINDOW_LENGTH_SECONDS,
hop_length_secs=vggish_params.STFT_HOP_LENGTH_SECONDS,
num_mel_bins=vggish_params.NUM_MEL_BINS,
lower_edge_hertz=vggish_params.MEL_MIN_HZ,
upper_edge_hertz=vggish_params.MEL_MAX_HZ)
# Frame features into examples.
features_sample_rate = 1.0 / vggish_params.STFT_HOP_LENGTH_SECONDS
example_window_length = int(round(
vggish_params.EXAMPLE_WINDOW_SECONDS * features_sample_rate))
example_hop_length = int(round(
vggish_params.EXAMPLE_HOP_SECONDS * features_sample_rate))
log_mel_examples = mel_features.frame(
log_mel,
window_length=example_window_length,
hop_length=example_hop_length)
return log_mel_examples
def wavfile_to_examples(wav_file):
sr, wav_data = wavfile.read(wav_file)
assert wav_data.dtype == np.int16, 'Bad sample type: %r' % wav_data.dtype
samples = wav_data / 32768.0 # Convert to [-1.0, +1.0]
return waveform_to_examples(samples, sr) | random_line_split | |
vggish_input.py | # Copyright (c) 2017-2019 Carnegie Mellon University. All rights reserved.
# Use of this source code is governed by BSD 3-clause license and the following
# license from the original code.
# This code is modified from Ubicoustics codebase. LICENSE infomation:
# SOFTWARE LICENSE AGREEMENT
# ACADEMIC OR NON-PROFIT ORGANIZATION NONCOMMERCIAL RESEARCH USE ONLY
#
# BY USING OR DOWNLOADING THE SOFTWARE, YOU ARE AGREEING TO THE TERMS OF THIS
# LICENSE AGREEMENT. IF YOU DO NOT AGREE WITH THESE TERMS, YOU MAY NOT USE OR
# DOWNLOAD THE SOFTWARE.
#
# This is a license agreement ("Agreement") between your academic institution
# or non-profit organization or self (called "Licensee" or "You" in this
# Agreement) and Carnegie Mellon University (called "Licensor" in this
# Agreement). All rights not specifically granted to you in this Agreement are
# reserved for Licensor.
#
# RESERVATION OF OWNERSHIP AND GRANT OF LICENSE: Licensor retains exclusive
# ownership of any copy of the Software (as defined below) licensed under this
# Agreement and hereby grants to Licensee a personal, non-exclusive,
# non-transferable license to use the Software for noncommercial research
# purposes, without the right to sublicense, pursuant to the terms and
# conditions of this Agreement. As used in this Agreement, the term "Software"
# means (i) the actual copy of all or any portion of code for program routines
# made accessible to Licensee by Licensor pursuant to this Agreement, inclusive
# of backups, updates, and/or merged copies permitted hereunder or subsequently
# supplied by Licensor, including all or any file structures, programming
# instructions, user interfaces and screen formats and sequences as well as any
# and all documentation and instructions related to it, and (ii) all or any
# derivatives and/or modifications created or made by You to any of the items
# specified in (i).
#
# CONFIDENTIALITY: Licensee acknowledges that the Software is proprietary to
# Licensor, and as such, Licensee agrees to receive all such materials in
# confidence and use the Software only in accordance with the terms of this
# Agreement. Licensee agrees to use reasonable effort to protect the Software
# from unauthorized use, reproduction, distribution, or publication.
#
# COPYRIGHT: The Software is owned by Licensor and is protected by United
# States copyright laws and applicable international treaties and/or
# conventions.
#
# PERMITTED USES: The Software may be used for your own noncommercial internal
# research purposes. You understand and agree that Licensor is not obligated to
# implement any suggestions and/or feedback you might provide regarding the
# Software, but to the extent Licensor does so, you are not entitled to any
# compensation related thereto.
#
# DERIVATIVES: You may create derivatives of or make modifications to the
# Software, however, You agree that all and any such derivatives and
# modifications will be owned by Licensor and become a part of the Software
# licensed to You under this Agreement. You may only use such derivatives and
# modifications for your own noncommercial internal research purposes, and you
# may not otherwise use, distribute or copy such derivatives and modifications
# in violation of this Agreement.
#
# BACKUPS: If Licensee is an organization, it may make that number of copies
# of the Software necessary for internal noncommercial use at a single site
# within its organization provided that all information appearing in or on the
# original labels, including the copyright and trademark notices are copied
# onto the labels of the copies.
#
# USES NOT PERMITTED: You may not distribute, copy or use the Software except
# as explicitly permitted herein. Licensee has not been granted any trademark
# license as part of this Agreement and may not use the name or mark
# “Ubicoustics", "Carnegie Mellon" or any renditions thereof without the prior
# written permission of Licensor.
#
# You may not sell, rent, lease, sublicense, lend, time-share or transfer, in
# whole or in part, or provide third parties access to prior or present
# versions (or any parts thereof) of the Software.
#
# ASSIGNMENT: You may not assign this Agreement or your rights hereunder
# without the prior written consent of Licensor. Any attempted assignment
# without such consent shall be null and void.
#
# TERM: The term of the license granted by this Agreement is from Licensee's
# acceptance of this Agreement by downloading the Software or by using the
# Software until terminated as provided below.
#
# The Agreement automatically terminates without notice if you fail to comply
# with any provision of this Agreement. Licensee may terminate this Agreement
# by ceasing using the Software. Upon any termination of this Agreement,
# Licensee will delete any and all copies of the Software. You agree that all
# provisions which operate to protect the proprietary rights of Licensor shall
# remain in force should breach occur and that the obligation of
# confidentiality described in this Agreement is binding in perpetuity and, as
# such, survives the term of the Agreement.
#
# FEE: Provided Licensee abides completely by the terms and conditions of this
# Agreement, there is no fee due to Licensor for Licensee's use of the Software
# in accordance with this Agreement.
#
# DISCLAIMER OF WARRANTIES: THE SOFTWARE IS PROVIDED "AS-IS" WITHOUT WARRANTY
# OF ANY KIND INCLUDING ANY WARRANTIES OF PERFORMANCE OR MERCHANTABILITY OR
# FITNESS FOR A PARTICULAR USE OR PURPOSE OR OF NON-INFRINGEMENT. LICENSEE
# BEARS ALL RISK RELATING TO QUALITY AND PERFORMANCE OF THE SOFTWARE AND
# RELATED MATERIALS.
#
# SUPPORT AND MAINTENANCE: No Software support or training by the Licensor is
# provided as part of this Agreement.
#
# EXCLUSIVE REMEDY AND LIMITATION OF LIABILITY: To the maximum extent permitted
# under applicable law, Licensor shall not be liable for direct, indirect,
# special, incidental, or consequential damages or lost profits related to
# Licensee's use of and/or inability to use the Software, even if Licensor is
#advised of the possibility of such damage.
#
# EXPORT REGULATION: Licensee agrees to comply with any and all applicable U.S.
# export control laws, regulations, and/or other laws related to embargoes and
# sanction programs administered by the Office of Foreign Assets Control.
#
# SEVERABILITY: If any provision(s) of this Agreement shall be held to be
# invalid, illegal, or unenforceable by a court or other tribunal of competent
# jurisdiction, the validity, legality and enforceability of the remaining
# provisions shall not in any way be affected or impaired thereby.
#
# NO IMPLIED WAIVERS: No failure or delay by Licensor in enforcing any right or
# remedy under this Agreement shall be construed as a waiver of any future or
# other exercise of such right or remedy by Licensor.
#
# GOVERNING LAW: This Agreement shall be construed and enforced in accordance
# with the laws of the Commonwealth of Pennsylvania without reference to
# conflict of laws principles. You consent to the personal jurisdiction of the
# courts of this County and waive their rights to venue outside of Allegheny
# County, Pennsylvania.
#
# ENTIRE AGREEMENT AND AMENDMENTS: This Agreement constitutes the sole and
# entire agreement between Licensee and Licensor as to the matter set forth
# herein and supersedes any previous agreements, understandings, and
# arrangements between the parties relating hereto.
import numpy as np
import resampy
from scipy.io import wavfile
import mel_features
import vggish_params
def waveform_to_examples(data, sample_rate):
# Convert to mono.
if |
def waveform_to_examples_subtract_bg(data, sample_rate, bg):
# Convert to mono.
if len(data.shape) > 1:
data = np.mean(data, axis=1)
# Resample to the rate assumed by VGGish.
if sample_rate != vggish_params.SAMPLE_RATE:
data = resampy.resample(data, sample_rate, vggish_params.SAMPLE_RATE)
# Compute log mel spectrogram features.
log_mel = mel_features.log_mel_spectrogram_subtract_bg(
data,
bg,
audio_sample_rate=vggish_params.SAMPLE_RATE,
log_offset=vggish_params.LOG_OFFSET,
window_length_secs=vggish_params.STFT_WINDOW_LENGTH_SECONDS,
hop_length_secs=vggish_params.STFT_HOP_LENGTH_SECONDS,
num_mel_bins=vggish_params.NUM_MEL_BINS,
lower_edge_hertz=vggish_params.MEL_MIN_HZ,
upper_edge_hertz=vggish_params.MEL_MAX_HZ)
# Frame features into examples.
features_sample_rate = 1.0 / vggish_params.STFT_HOP_LENGTH_SECONDS
example_window_length = int(round(
vggish_params.EXAMPLE_WINDOW_SECONDS * features_sample_rate))
example_hop_length = int(round(
vggish_params.EXAMPLE_HOP_SECONDS * features_sample_rate))
log_mel_examples = mel_features.frame(
log_mel,
window_length=example_window_length,
hop_length=example_hop_length)
return log_mel_examples
def wavfile_to_examples(wav_file):
sr, wav_data = wavfile.read(wav_file)
assert wav_data.dtype == np.int16, 'Bad sample type: %r' % wav_data.dtype
samples = wav_data / 32768.0 # Convert to [-1.0, +1.0]
return waveform_to_examples(samples, sr)
| len(data.shape) > 1:
data = np.mean(data, axis=1)
# Resample to the rate assumed by VGGish.
if sample_rate != vggish_params.SAMPLE_RATE:
data = resampy.resample(data, sample_rate, vggish_params.SAMPLE_RATE)
# Compute log mel spectrogram features.
log_mel = mel_features.log_mel_spectrogram(
data,
audio_sample_rate=vggish_params.SAMPLE_RATE,
log_offset=vggish_params.LOG_OFFSET,
window_length_secs=vggish_params.STFT_WINDOW_LENGTH_SECONDS,
hop_length_secs=vggish_params.STFT_HOP_LENGTH_SECONDS,
num_mel_bins=vggish_params.NUM_MEL_BINS,
lower_edge_hertz=vggish_params.MEL_MIN_HZ,
upper_edge_hertz=vggish_params.MEL_MAX_HZ)
# Frame features into examples.
features_sample_rate = 1.0 / vggish_params.STFT_HOP_LENGTH_SECONDS
example_window_length = int(round(
vggish_params.EXAMPLE_WINDOW_SECONDS * features_sample_rate))
example_hop_length = int(round(
vggish_params.EXAMPLE_HOP_SECONDS * features_sample_rate))
log_mel_examples = mel_features.frame(
log_mel,
window_length=example_window_length,
hop_length=example_hop_length)
return log_mel_examples
| identifier_body |
vggish_input.py | # Copyright (c) 2017-2019 Carnegie Mellon University. All rights reserved.
# Use of this source code is governed by BSD 3-clause license and the following
# license from the original code.
# This code is modified from Ubicoustics codebase. LICENSE infomation:
# SOFTWARE LICENSE AGREEMENT
# ACADEMIC OR NON-PROFIT ORGANIZATION NONCOMMERCIAL RESEARCH USE ONLY
#
# BY USING OR DOWNLOADING THE SOFTWARE, YOU ARE AGREEING TO THE TERMS OF THIS
# LICENSE AGREEMENT. IF YOU DO NOT AGREE WITH THESE TERMS, YOU MAY NOT USE OR
# DOWNLOAD THE SOFTWARE.
#
# This is a license agreement ("Agreement") between your academic institution
# or non-profit organization or self (called "Licensee" or "You" in this
# Agreement) and Carnegie Mellon University (called "Licensor" in this
# Agreement). All rights not specifically granted to you in this Agreement are
# reserved for Licensor.
#
# RESERVATION OF OWNERSHIP AND GRANT OF LICENSE: Licensor retains exclusive
# ownership of any copy of the Software (as defined below) licensed under this
# Agreement and hereby grants to Licensee a personal, non-exclusive,
# non-transferable license to use the Software for noncommercial research
# purposes, without the right to sublicense, pursuant to the terms and
# conditions of this Agreement. As used in this Agreement, the term "Software"
# means (i) the actual copy of all or any portion of code for program routines
# made accessible to Licensee by Licensor pursuant to this Agreement, inclusive
# of backups, updates, and/or merged copies permitted hereunder or subsequently
# supplied by Licensor, including all or any file structures, programming
# instructions, user interfaces and screen formats and sequences as well as any
# and all documentation and instructions related to it, and (ii) all or any
# derivatives and/or modifications created or made by You to any of the items
# specified in (i).
#
# CONFIDENTIALITY: Licensee acknowledges that the Software is proprietary to
# Licensor, and as such, Licensee agrees to receive all such materials in
# confidence and use the Software only in accordance with the terms of this
# Agreement. Licensee agrees to use reasonable effort to protect the Software
# from unauthorized use, reproduction, distribution, or publication.
#
# COPYRIGHT: The Software is owned by Licensor and is protected by United
# States copyright laws and applicable international treaties and/or
# conventions.
#
# PERMITTED USES: The Software may be used for your own noncommercial internal
# research purposes. You understand and agree that Licensor is not obligated to
# implement any suggestions and/or feedback you might provide regarding the
# Software, but to the extent Licensor does so, you are not entitled to any
# compensation related thereto.
#
# DERIVATIVES: You may create derivatives of or make modifications to the
# Software, however, You agree that all and any such derivatives and
# modifications will be owned by Licensor and become a part of the Software
# licensed to You under this Agreement. You may only use such derivatives and
# modifications for your own noncommercial internal research purposes, and you
# may not otherwise use, distribute or copy such derivatives and modifications
# in violation of this Agreement.
#
# BACKUPS: If Licensee is an organization, it may make that number of copies
# of the Software necessary for internal noncommercial use at a single site
# within its organization provided that all information appearing in or on the
# original labels, including the copyright and trademark notices are copied
# onto the labels of the copies.
#
# USES NOT PERMITTED: You may not distribute, copy or use the Software except
# as explicitly permitted herein. Licensee has not been granted any trademark
# license as part of this Agreement and may not use the name or mark
# “Ubicoustics", "Carnegie Mellon" or any renditions thereof without the prior
# written permission of Licensor.
#
# You may not sell, rent, lease, sublicense, lend, time-share or transfer, in
# whole or in part, or provide third parties access to prior or present
# versions (or any parts thereof) of the Software.
#
# ASSIGNMENT: You may not assign this Agreement or your rights hereunder
# without the prior written consent of Licensor. Any attempted assignment
# without such consent shall be null and void.
#
# TERM: The term of the license granted by this Agreement is from Licensee's
# acceptance of this Agreement by downloading the Software or by using the
# Software until terminated as provided below.
#
# The Agreement automatically terminates without notice if you fail to comply
# with any provision of this Agreement. Licensee may terminate this Agreement
# by ceasing using the Software. Upon any termination of this Agreement,
# Licensee will delete any and all copies of the Software. You agree that all
# provisions which operate to protect the proprietary rights of Licensor shall
# remain in force should breach occur and that the obligation of
# confidentiality described in this Agreement is binding in perpetuity and, as
# such, survives the term of the Agreement.
#
# FEE: Provided Licensee abides completely by the terms and conditions of this
# Agreement, there is no fee due to Licensor for Licensee's use of the Software
# in accordance with this Agreement.
#
# DISCLAIMER OF WARRANTIES: THE SOFTWARE IS PROVIDED "AS-IS" WITHOUT WARRANTY
# OF ANY KIND INCLUDING ANY WARRANTIES OF PERFORMANCE OR MERCHANTABILITY OR
# FITNESS FOR A PARTICULAR USE OR PURPOSE OR OF NON-INFRINGEMENT. LICENSEE
# BEARS ALL RISK RELATING TO QUALITY AND PERFORMANCE OF THE SOFTWARE AND
# RELATED MATERIALS.
#
# SUPPORT AND MAINTENANCE: No Software support or training by the Licensor is
# provided as part of this Agreement.
#
# EXCLUSIVE REMEDY AND LIMITATION OF LIABILITY: To the maximum extent permitted
# under applicable law, Licensor shall not be liable for direct, indirect,
# special, incidental, or consequential damages or lost profits related to
# Licensee's use of and/or inability to use the Software, even if Licensor is
#advised of the possibility of such damage.
#
# EXPORT REGULATION: Licensee agrees to comply with any and all applicable U.S.
# export control laws, regulations, and/or other laws related to embargoes and
# sanction programs administered by the Office of Foreign Assets Control.
#
# SEVERABILITY: If any provision(s) of this Agreement shall be held to be
# invalid, illegal, or unenforceable by a court or other tribunal of competent
# jurisdiction, the validity, legality and enforceability of the remaining
# provisions shall not in any way be affected or impaired thereby.
#
# NO IMPLIED WAIVERS: No failure or delay by Licensor in enforcing any right or
# remedy under this Agreement shall be construed as a waiver of any future or
# other exercise of such right or remedy by Licensor.
#
# GOVERNING LAW: This Agreement shall be construed and enforced in accordance
# with the laws of the Commonwealth of Pennsylvania without reference to
# conflict of laws principles. You consent to the personal jurisdiction of the
# courts of this County and waive their rights to venue outside of Allegheny
# County, Pennsylvania.
#
# ENTIRE AGREEMENT AND AMENDMENTS: This Agreement constitutes the sole and
# entire agreement between Licensee and Licensor as to the matter set forth
# herein and supersedes any previous agreements, understandings, and
# arrangements between the parties relating hereto.
import numpy as np
import resampy
from scipy.io import wavfile
import mel_features
import vggish_params
def waveform_to_examples(data, sample_rate):
# Convert to mono.
if len(data.shape) > 1:
data = np.mean(data, axis=1)
# Resample to the rate assumed by VGGish.
if sample_rate != vggish_params.SAMPLE_RATE:
da |
# Compute log mel spectrogram features.
log_mel = mel_features.log_mel_spectrogram(
data,
audio_sample_rate=vggish_params.SAMPLE_RATE,
log_offset=vggish_params.LOG_OFFSET,
window_length_secs=vggish_params.STFT_WINDOW_LENGTH_SECONDS,
hop_length_secs=vggish_params.STFT_HOP_LENGTH_SECONDS,
num_mel_bins=vggish_params.NUM_MEL_BINS,
lower_edge_hertz=vggish_params.MEL_MIN_HZ,
upper_edge_hertz=vggish_params.MEL_MAX_HZ)
# Frame features into examples.
features_sample_rate = 1.0 / vggish_params.STFT_HOP_LENGTH_SECONDS
example_window_length = int(round(
vggish_params.EXAMPLE_WINDOW_SECONDS * features_sample_rate))
example_hop_length = int(round(
vggish_params.EXAMPLE_HOP_SECONDS * features_sample_rate))
log_mel_examples = mel_features.frame(
log_mel,
window_length=example_window_length,
hop_length=example_hop_length)
return log_mel_examples
def waveform_to_examples_subtract_bg(data, sample_rate, bg):
# Convert to mono.
if len(data.shape) > 1:
data = np.mean(data, axis=1)
# Resample to the rate assumed by VGGish.
if sample_rate != vggish_params.SAMPLE_RATE:
data = resampy.resample(data, sample_rate, vggish_params.SAMPLE_RATE)
# Compute log mel spectrogram features.
log_mel = mel_features.log_mel_spectrogram_subtract_bg(
data,
bg,
audio_sample_rate=vggish_params.SAMPLE_RATE,
log_offset=vggish_params.LOG_OFFSET,
window_length_secs=vggish_params.STFT_WINDOW_LENGTH_SECONDS,
hop_length_secs=vggish_params.STFT_HOP_LENGTH_SECONDS,
num_mel_bins=vggish_params.NUM_MEL_BINS,
lower_edge_hertz=vggish_params.MEL_MIN_HZ,
upper_edge_hertz=vggish_params.MEL_MAX_HZ)
# Frame features into examples.
features_sample_rate = 1.0 / vggish_params.STFT_HOP_LENGTH_SECONDS
example_window_length = int(round(
vggish_params.EXAMPLE_WINDOW_SECONDS * features_sample_rate))
example_hop_length = int(round(
vggish_params.EXAMPLE_HOP_SECONDS * features_sample_rate))
log_mel_examples = mel_features.frame(
log_mel,
window_length=example_window_length,
hop_length=example_hop_length)
return log_mel_examples
def wavfile_to_examples(wav_file):
sr, wav_data = wavfile.read(wav_file)
assert wav_data.dtype == np.int16, 'Bad sample type: %r' % wav_data.dtype
samples = wav_data / 32768.0 # Convert to [-1.0, +1.0]
return waveform_to_examples(samples, sr)
| ta = resampy.resample(data, sample_rate, vggish_params.SAMPLE_RATE)
| conditional_block |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.