1 // Copyright (c) 2017-2024, Lawrence Livermore National Security, LLC and other CEED contributors. 2 // All Rights Reserved. See the top-level LICENSE and NOTICE files for details. 3 // 4 // SPDX-License-Identifier: BSD-2-Clause 5 // 6 // This file is part of CEED: http://github.com/ceed 7 8 //! A Ceed QFunction represents the spatial terms of the point-wise functions 9 //! describing the physics at the quadrature points. 10 11 use std::pin::Pin; 12 13 use crate::prelude::*; 14 15 pub type QFunctionInputs<'a> = [&'a [crate::Scalar]; MAX_QFUNCTION_FIELDS]; 16 pub type QFunctionOutputs<'a> = [&'a mut [crate::Scalar]; MAX_QFUNCTION_FIELDS]; 17 18 // ----------------------------------------------------------------------------- 19 // QFunction Field context wrapper 20 // ----------------------------------------------------------------------------- 21 #[derive(Debug)] 22 pub struct QFunctionField<'a> { 23 ptr: bind_ceed::CeedQFunctionField, 24 _lifeline: PhantomData<&'a ()>, 25 } 26 27 // ----------------------------------------------------------------------------- 28 // Implementations 29 // ----------------------------------------------------------------------------- 30 impl<'a> QFunctionField<'a> { 31 /// Get the name of a QFunctionField 32 /// 33 /// ``` 34 /// # use libceed::prelude::*; 35 /// # fn main() -> libceed::Result<()> { 36 /// # let ceed = libceed::Ceed::default_init(); 37 /// const Q: usize = 8; 38 /// let qf = ceed.q_function_interior_by_name("Mass2DBuild")?; 39 /// 40 /// let inputs = qf.inputs()?; 41 /// 42 /// assert_eq!(inputs[0].name(), "dx", "Incorrect input name"); 43 /// assert_eq!(inputs[1].name(), "weights", "Incorrect input name"); 44 /// # Ok(()) 45 /// # } 46 /// ``` 47 pub fn name(&self) -> &str { 48 let mut name_ptr: *mut std::os::raw::c_char = std::ptr::null_mut(); 49 unsafe { 50 bind_ceed::CeedQFunctionFieldGetName( 51 self.ptr, 52 &mut name_ptr as *const _ as *mut *const _, 53 ); 54 } 55 unsafe { CStr::from_ptr(name_ptr) }.to_str().unwrap() 56 } 57 58 /// Get the size of a QFunctionField 59 /// 60 /// ``` 61 /// # use libceed::prelude::*; 62 /// # fn main() -> libceed::Result<()> { 63 /// # let ceed = libceed::Ceed::default_init(); 64 /// const Q: usize = 8; 65 /// let qf = ceed.q_function_interior_by_name("Mass2DBuild")?; 66 /// 67 /// let inputs = qf.inputs()?; 68 /// 69 /// assert_eq!(inputs[0].size(), 4, "Incorrect input size"); 70 /// assert_eq!(inputs[1].size(), 1, "Incorrect input size"); 71 /// # Ok(()) 72 /// # } 73 /// ``` 74 pub fn size(&self) -> usize { 75 let mut size = 0; 76 unsafe { 77 bind_ceed::CeedQFunctionFieldGetSize(self.ptr, &mut size); 78 } 79 usize::try_from(size).unwrap() 80 } 81 82 /// Get the evaluation mode of a QFunctionField 83 /// 84 /// ``` 85 /// # use libceed::prelude::*; 86 /// # fn main() -> libceed::Result<()> { 87 /// # let ceed = libceed::Ceed::default_init(); 88 /// const Q: usize = 8; 89 /// let qf = ceed.q_function_interior_by_name("Mass2DBuild")?; 90 /// 91 /// let inputs = qf.inputs()?; 92 /// 93 /// assert_eq!( 94 /// inputs[0].eval_mode(), 95 /// EvalMode::Grad, 96 /// "Incorrect input evaluation mode" 97 /// ); 98 /// assert_eq!( 99 /// inputs[1].eval_mode(), 100 /// EvalMode::Weight, 101 /// "Incorrect input evaluation mode" 102 /// ); 103 /// # Ok(()) 104 /// # } 105 /// ``` 106 pub fn eval_mode(&self) -> crate::EvalMode { 107 let mut mode = 0; 108 unsafe { 109 bind_ceed::CeedQFunctionFieldGetEvalMode(self.ptr, &mut mode); 110 } 111 crate::EvalMode::from_u32(mode as u32) 112 } 113 } 114 115 // ----------------------------------------------------------------------------- 116 // QFunction option 117 // ----------------------------------------------------------------------------- 118 pub enum QFunctionOpt<'a> { 119 SomeQFunction(&'a QFunction<'a>), 120 SomeQFunctionByName(&'a QFunctionByName<'a>), 121 None, 122 } 123 124 /// Construct a QFunctionOpt reference from a QFunction reference 125 impl<'a> From<&'a QFunction<'_>> for QFunctionOpt<'a> { 126 fn from(qfunc: &'a QFunction) -> Self { 127 debug_assert!(qfunc.qf_core.ptr != unsafe { bind_ceed::CEED_QFUNCTION_NONE }); 128 Self::SomeQFunction(qfunc) 129 } 130 } 131 132 /// Construct a QFunctionOpt reference from a QFunction by Name reference 133 impl<'a> From<&'a QFunctionByName<'_>> for QFunctionOpt<'a> { 134 fn from(qfunc: &'a QFunctionByName) -> Self { 135 debug_assert!(qfunc.qf_core.ptr != unsafe { bind_ceed::CEED_QFUNCTION_NONE }); 136 Self::SomeQFunctionByName(qfunc) 137 } 138 } 139 140 impl<'a> QFunctionOpt<'a> { 141 /// Transform a Rust libCEED QFunctionOpt into C libCEED CeedQFunction 142 pub(crate) fn to_raw(self) -> bind_ceed::CeedQFunction { 143 match self { 144 Self::SomeQFunction(qfunc) => qfunc.qf_core.ptr, 145 Self::SomeQFunctionByName(qfunc) => qfunc.qf_core.ptr, 146 Self::None => unsafe { bind_ceed::CEED_QFUNCTION_NONE }, 147 } 148 } 149 150 /// Check if a QFunctionOpt is Some 151 /// 152 /// ``` 153 /// # use libceed::prelude::*; 154 /// # fn main() -> libceed::Result<()> { 155 /// # let ceed = libceed::Ceed::default_init(); 156 /// let mut user_f = |[u, weights, ..]: QFunctionInputs, [v, ..]: QFunctionOutputs| { 157 /// // Iterate over quadrature points 158 /// v.iter_mut() 159 /// .zip(u.iter().zip(weights.iter())) 160 /// .for_each(|(v, (u, w))| *v = u * w); 161 /// 162 /// // Return clean error code 163 /// 0 164 /// }; 165 /// 166 /// let qf = ceed 167 /// .q_function_interior(1, Box::new(user_f))? 168 /// .input("u", 1, EvalMode::Interp)? 169 /// .input("weights", 1, EvalMode::Weight)? 170 /// .output("v", 1, EvalMode::Interp)?; 171 /// let qf_opt = QFunctionOpt::from(&qf); 172 /// assert!(qf_opt.is_some(), "Incorrect QFunctionOpt"); 173 /// 174 /// let qf = ceed.q_function_interior_by_name("Mass1DBuild")?; 175 /// let qf_opt = QFunctionOpt::from(&qf); 176 /// assert!(qf_opt.is_some(), "Incorrect QFunctionOpt"); 177 /// 178 /// let qf_opt = QFunctionOpt::None; 179 /// assert!(!qf_opt.is_some(), "Incorrect QFunctionOpt"); 180 /// # Ok(()) 181 /// # } 182 /// ``` 183 pub fn is_some(&self) -> bool { 184 match self { 185 Self::SomeQFunction(_) => true, 186 Self::SomeQFunctionByName(_) => true, 187 Self::None => false, 188 } 189 } 190 191 /// Check if a QFunctionOpt is SomeQFunction 192 /// 193 /// ``` 194 /// # use libceed::prelude::*; 195 /// # fn main() -> libceed::Result<()> { 196 /// # let ceed = libceed::Ceed::default_init(); 197 /// let mut user_f = |[u, weights, ..]: QFunctionInputs, [v, ..]: QFunctionOutputs| { 198 /// // Iterate over quadrature points 199 /// v.iter_mut() 200 /// .zip(u.iter().zip(weights.iter())) 201 /// .for_each(|(v, (u, w))| *v = u * w); 202 /// 203 /// // Return clean error code 204 /// 0 205 /// }; 206 /// 207 /// let qf = ceed 208 /// .q_function_interior(1, Box::new(user_f))? 209 /// .input("u", 1, EvalMode::Interp)? 210 /// .input("weights", 1, EvalMode::Weight)? 211 /// .output("v", 1, EvalMode::Interp)?; 212 /// let qf_opt = QFunctionOpt::from(&qf); 213 /// assert!(qf_opt.is_some_q_function(), "Incorrect QFunctionOpt"); 214 /// 215 /// let qf = ceed.q_function_interior_by_name("Mass1DBuild")?; 216 /// let qf_opt = QFunctionOpt::from(&qf); 217 /// assert!(!qf_opt.is_some_q_function(), "Incorrect QFunctionOpt"); 218 /// 219 /// let qf_opt = QFunctionOpt::None; 220 /// assert!(!qf_opt.is_some_q_function(), "Incorrect QFunctionOpt"); 221 /// # Ok(()) 222 /// # } 223 /// ``` 224 pub fn is_some_q_function(&self) -> bool { 225 match self { 226 Self::SomeQFunction(_) => true, 227 Self::SomeQFunctionByName(_) => false, 228 Self::None => false, 229 } 230 } 231 232 /// Check if a QFunctionOpt is SomeQFunctionByName 233 /// 234 /// ``` 235 /// # use libceed::prelude::*; 236 /// # fn main() -> libceed::Result<()> { 237 /// # let ceed = libceed::Ceed::default_init(); 238 /// let mut user_f = |[u, weights, ..]: QFunctionInputs, [v, ..]: QFunctionOutputs| { 239 /// // Iterate over quadrature points 240 /// v.iter_mut() 241 /// .zip(u.iter().zip(weights.iter())) 242 /// .for_each(|(v, (u, w))| *v = u * w); 243 /// 244 /// // Return clean error code 245 /// 0 246 /// }; 247 /// 248 /// let qf = ceed 249 /// .q_function_interior(1, Box::new(user_f))? 250 /// .input("u", 1, EvalMode::Interp)? 251 /// .input("weights", 1, EvalMode::Weight)? 252 /// .output("v", 1, EvalMode::Interp)?; 253 /// let qf_opt = QFunctionOpt::from(&qf); 254 /// assert!( 255 /// !qf_opt.is_some_q_function_by_name(), 256 /// "Incorrect QFunctionOpt" 257 /// ); 258 /// 259 /// let qf = ceed.q_function_interior_by_name("Mass1DBuild")?; 260 /// let qf_opt = QFunctionOpt::from(&qf); 261 /// assert!( 262 /// qf_opt.is_some_q_function_by_name(), 263 /// "Incorrect QFunctionOpt" 264 /// ); 265 /// 266 /// let qf_opt = QFunctionOpt::None; 267 /// assert!( 268 /// !qf_opt.is_some_q_function_by_name(), 269 /// "Incorrect QFunctionOpt" 270 /// ); 271 /// # Ok(()) 272 /// # } 273 /// ``` 274 pub fn is_some_q_function_by_name(&self) -> bool { 275 match self { 276 Self::SomeQFunction(_) => false, 277 Self::SomeQFunctionByName(_) => true, 278 Self::None => false, 279 } 280 } 281 282 /// Check if a QFunctionOpt is None 283 /// 284 /// ``` 285 /// # use libceed::prelude::*; 286 /// # fn main() -> libceed::Result<()> { 287 /// # let ceed = libceed::Ceed::default_init(); 288 /// let mut user_f = |[u, weights, ..]: QFunctionInputs, [v, ..]: QFunctionOutputs| { 289 /// // Iterate over quadrature points 290 /// v.iter_mut() 291 /// .zip(u.iter().zip(weights.iter())) 292 /// .for_each(|(v, (u, w))| *v = u * w); 293 /// 294 /// // Return clean error code 295 /// 0 296 /// }; 297 /// 298 /// let qf = ceed 299 /// .q_function_interior(1, Box::new(user_f))? 300 /// .input("u", 1, EvalMode::Interp)? 301 /// .input("weights", 1, EvalMode::Weight)? 302 /// .output("v", 1, EvalMode::Interp)?; 303 /// let qf_opt = QFunctionOpt::from(&qf); 304 /// assert!(!qf_opt.is_none(), "Incorrect QFunctionOpt"); 305 /// 306 /// let qf = ceed.q_function_interior_by_name("Mass1DBuild")?; 307 /// let qf_opt = QFunctionOpt::from(&qf); 308 /// assert!(!qf_opt.is_none(), "Incorrect QFunctionOpt"); 309 /// 310 /// let qf_opt = QFunctionOpt::None; 311 /// assert!(qf_opt.is_none(), "Incorrect QFunctionOpt"); 312 /// # Ok(()) 313 /// # } 314 /// ``` 315 pub fn is_none(&self) -> bool { 316 match self { 317 Self::SomeQFunction(_) => false, 318 Self::SomeQFunctionByName(_) => false, 319 Self::None => true, 320 } 321 } 322 } 323 324 // ----------------------------------------------------------------------------- 325 // QFunction context wrapper 326 // ----------------------------------------------------------------------------- 327 #[derive(Debug)] 328 pub(crate) struct QFunctionCore<'a> { 329 ptr: bind_ceed::CeedQFunction, 330 _lifeline: PhantomData<&'a ()>, 331 } 332 333 struct QFunctionTrampolineData { 334 number_inputs: usize, 335 number_outputs: usize, 336 input_sizes: [usize; MAX_QFUNCTION_FIELDS], 337 output_sizes: [usize; MAX_QFUNCTION_FIELDS], 338 user_f: Box<QFunctionUserClosure>, 339 } 340 341 pub struct QFunction<'a> { 342 qf_core: QFunctionCore<'a>, 343 qf_ctx_ptr: bind_ceed::CeedQFunctionContext, 344 trampoline_data: Pin<Box<QFunctionTrampolineData>>, 345 } 346 347 #[derive(Debug)] 348 pub struct QFunctionByName<'a> { 349 qf_core: QFunctionCore<'a>, 350 } 351 352 // ----------------------------------------------------------------------------- 353 // Destructor 354 // ----------------------------------------------------------------------------- 355 impl<'a> Drop for QFunctionCore<'a> { 356 fn drop(&mut self) { 357 unsafe { 358 if self.ptr != bind_ceed::CEED_QFUNCTION_NONE { 359 bind_ceed::CeedQFunctionDestroy(&mut self.ptr); 360 } 361 } 362 } 363 } 364 365 impl<'a> Drop for QFunction<'a> { 366 fn drop(&mut self) { 367 unsafe { 368 bind_ceed::CeedQFunctionContextDestroy(&mut self.qf_ctx_ptr); 369 } 370 } 371 } 372 373 // ----------------------------------------------------------------------------- 374 // Display 375 // ----------------------------------------------------------------------------- 376 impl<'a> fmt::Display for QFunctionCore<'a> { 377 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 378 let mut ptr = std::ptr::null_mut(); 379 let mut sizeloc = crate::MAX_BUFFER_LENGTH; 380 let cstring = unsafe { 381 let file = bind_ceed::open_memstream(&mut ptr, &mut sizeloc); 382 bind_ceed::CeedQFunctionView(self.ptr, file); 383 bind_ceed::fclose(file); 384 CString::from_raw(ptr) 385 }; 386 cstring.to_string_lossy().fmt(f) 387 } 388 } 389 /// View a QFunction 390 /// 391 /// ``` 392 /// # use libceed::prelude::*; 393 /// # fn main() -> libceed::Result<()> { 394 /// # let ceed = libceed::Ceed::default_init(); 395 /// let mut user_f = |[u, weights, ..]: QFunctionInputs, [v, ..]: QFunctionOutputs| { 396 /// // Iterate over quadrature points 397 /// v.iter_mut() 398 /// .zip(u.iter().zip(weights.iter())) 399 /// .for_each(|(v, (u, w))| *v = u * w); 400 /// 401 /// // Return clean error code 402 /// 0 403 /// }; 404 /// 405 /// let qf = ceed 406 /// .q_function_interior(1, Box::new(user_f))? 407 /// .input("u", 1, EvalMode::Interp)? 408 /// .input("weights", 1, EvalMode::Weight)? 409 /// .output("v", 1, EvalMode::Interp)?; 410 /// 411 /// println!("{}", qf); 412 /// # Ok(()) 413 /// # } 414 /// ``` 415 impl<'a> fmt::Display for QFunction<'a> { 416 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 417 self.qf_core.fmt(f) 418 } 419 } 420 421 /// View a QFunction by Name 422 /// 423 /// ``` 424 /// # use libceed::prelude::*; 425 /// # fn main() -> libceed::Result<()> { 426 /// # let ceed = libceed::Ceed::default_init(); 427 /// let qf = ceed.q_function_interior_by_name("Mass1DBuild")?; 428 /// println!("{}", qf); 429 /// # Ok(()) 430 /// # } 431 /// ``` 432 impl<'a> fmt::Display for QFunctionByName<'a> { 433 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 434 self.qf_core.fmt(f) 435 } 436 } 437 438 // ----------------------------------------------------------------------------- 439 // Core functionality 440 // ----------------------------------------------------------------------------- 441 impl<'a> QFunctionCore<'a> { 442 // Raw Ceed for error handling 443 #[doc(hidden)] 444 fn ceed(&self) -> bind_ceed::Ceed { 445 unsafe { bind_ceed::CeedQFunctionReturnCeed(self.ptr) } 446 } 447 448 // Error handling 449 #[doc(hidden)] 450 fn check_error(&self, ierr: i32) -> crate::Result<i32> { 451 crate::check_error(|| self.ceed(), ierr) 452 } 453 454 // Common implementation 455 pub fn apply(&self, Q: usize, u: &[Vector], v: &[Vector]) -> crate::Result<i32> { 456 let mut u_c = [std::ptr::null_mut(); MAX_QFUNCTION_FIELDS]; 457 for i in 0..std::cmp::min(MAX_QFUNCTION_FIELDS, u.len()) { 458 u_c[i] = u[i].ptr; 459 } 460 let mut v_c = [std::ptr::null_mut(); MAX_QFUNCTION_FIELDS]; 461 for i in 0..std::cmp::min(MAX_QFUNCTION_FIELDS, v.len()) { 462 v_c[i] = v[i].ptr; 463 } 464 let Q = i32::try_from(Q).unwrap(); 465 self.check_error(unsafe { 466 bind_ceed::CeedQFunctionApply(self.ptr, Q, u_c.as_mut_ptr(), v_c.as_mut_ptr()) 467 }) 468 } 469 470 pub fn inputs(&self) -> crate::Result<&[crate::QFunctionField]> { 471 // Get array of raw C pointers for inputs 472 let mut num_inputs = 0; 473 let mut inputs_ptr = std::ptr::null_mut(); 474 self.check_error(unsafe { 475 bind_ceed::CeedQFunctionGetFields( 476 self.ptr, 477 &mut num_inputs, 478 &mut inputs_ptr, 479 std::ptr::null_mut() as *mut bind_ceed::CeedInt, 480 std::ptr::null_mut() as *mut *mut bind_ceed::CeedQFunctionField, 481 ) 482 })?; 483 // Convert raw C pointers to fixed length slice 484 let inputs_slice = unsafe { 485 std::slice::from_raw_parts( 486 inputs_ptr as *const crate::QFunctionField, 487 num_inputs as usize, 488 ) 489 }; 490 Ok(inputs_slice) 491 } 492 493 pub fn outputs(&self) -> crate::Result<&[crate::QFunctionField]> { 494 // Get array of raw C pointers for outputs 495 let mut num_outputs = 0; 496 let mut outputs_ptr = std::ptr::null_mut(); 497 self.check_error(unsafe { 498 bind_ceed::CeedQFunctionGetFields( 499 self.ptr, 500 std::ptr::null_mut() as *mut bind_ceed::CeedInt, 501 std::ptr::null_mut() as *mut *mut bind_ceed::CeedQFunctionField, 502 &mut num_outputs, 503 &mut outputs_ptr, 504 ) 505 })?; 506 // Convert raw C pointers to fixed length slice 507 let outputs_slice = unsafe { 508 std::slice::from_raw_parts( 509 outputs_ptr as *const crate::QFunctionField, 510 num_outputs as usize, 511 ) 512 }; 513 Ok(outputs_slice) 514 } 515 } 516 517 // ----------------------------------------------------------------------------- 518 // User QFunction Closure 519 // ----------------------------------------------------------------------------- 520 pub type QFunctionUserClosure = dyn FnMut( 521 [&[crate::Scalar]; MAX_QFUNCTION_FIELDS], 522 [&mut [crate::Scalar]; MAX_QFUNCTION_FIELDS], 523 ) -> i32; 524 525 macro_rules! mut_max_fields { 526 ($e:expr) => { 527 [ 528 $e, $e, $e, $e, $e, $e, $e, $e, $e, $e, $e, $e, $e, $e, $e, $e, 529 ] 530 }; 531 } 532 unsafe extern "C" fn trampoline( 533 ctx: *mut ::std::os::raw::c_void, 534 q: bind_ceed::CeedInt, 535 inputs: *const *const bind_ceed::CeedScalar, 536 outputs: *const *mut bind_ceed::CeedScalar, 537 ) -> ::std::os::raw::c_int { 538 let trampoline_data: Pin<&mut QFunctionTrampolineData> = std::mem::transmute(ctx); 539 540 // Inputs 541 let inputs_slice: &[*const bind_ceed::CeedScalar] = 542 std::slice::from_raw_parts(inputs, MAX_QFUNCTION_FIELDS); 543 let mut inputs_array: [&[crate::Scalar]; MAX_QFUNCTION_FIELDS] = [&[0.0]; MAX_QFUNCTION_FIELDS]; 544 inputs_slice 545 .iter() 546 .take(trampoline_data.number_inputs) 547 .enumerate() 548 .map(|(i, &x)| { 549 std::slice::from_raw_parts(x, trampoline_data.input_sizes[i] * q as usize) 550 as &[crate::Scalar] 551 }) 552 .zip(inputs_array.iter_mut()) 553 .for_each(|(x, a)| *a = x); 554 555 // Outputs 556 let outputs_slice: &[*mut bind_ceed::CeedScalar] = 557 std::slice::from_raw_parts(outputs, MAX_QFUNCTION_FIELDS); 558 let mut outputs_array: [&mut [crate::Scalar]; MAX_QFUNCTION_FIELDS] = 559 mut_max_fields!(&mut [0.0]); 560 outputs_slice 561 .iter() 562 .take(trampoline_data.number_outputs) 563 .enumerate() 564 .map(|(i, &x)| { 565 std::slice::from_raw_parts_mut(x, trampoline_data.output_sizes[i] * q as usize) 566 as &mut [crate::Scalar] 567 }) 568 .zip(outputs_array.iter_mut()) 569 .for_each(|(x, a)| *a = x); 570 571 // User closure 572 (trampoline_data.get_unchecked_mut().user_f)(inputs_array, outputs_array) 573 } 574 575 unsafe extern "C" fn destroy_trampoline(ctx: *mut ::std::os::raw::c_void) -> ::std::os::raw::c_int { 576 let trampoline_data: Pin<&mut QFunctionTrampolineData> = std::mem::transmute(ctx); 577 drop(trampoline_data); 578 0 // Clean error code 579 } 580 581 // ----------------------------------------------------------------------------- 582 // QFunction 583 // ----------------------------------------------------------------------------- 584 impl<'a> QFunction<'a> { 585 // Constructor 586 pub fn create( 587 ceed: &crate::Ceed, 588 vlength: usize, 589 user_f: Box<QFunctionUserClosure>, 590 ) -> crate::Result<Self> { 591 let source_c = CString::new("").expect("CString::new failed"); 592 let mut ptr = std::ptr::null_mut(); 593 594 // Context for closure 595 let number_inputs = 0; 596 let number_outputs = 0; 597 let input_sizes = [0; MAX_QFUNCTION_FIELDS]; 598 let output_sizes = [0; MAX_QFUNCTION_FIELDS]; 599 let trampoline_data = unsafe { 600 Pin::new_unchecked(Box::new(QFunctionTrampolineData { 601 number_inputs, 602 number_outputs, 603 input_sizes, 604 output_sizes, 605 user_f, 606 })) 607 }; 608 609 // Create QFunction 610 let vlength = i32::try_from(vlength).unwrap(); 611 ceed.check_error(unsafe { 612 bind_ceed::CeedQFunctionCreateInterior( 613 ceed.ptr, 614 vlength, 615 Some(trampoline), 616 source_c.as_ptr(), 617 &mut ptr, 618 ) 619 })?; 620 621 // Set closure 622 let mut qf_ctx_ptr = std::ptr::null_mut(); 623 ceed.check_error(unsafe { 624 bind_ceed::CeedQFunctionContextCreate(ceed.ptr, &mut qf_ctx_ptr) 625 })?; 626 ceed.check_error(unsafe { 627 bind_ceed::CeedQFunctionContextSetData( 628 qf_ctx_ptr, 629 crate::MemType::Host as bind_ceed::CeedMemType, 630 crate::CopyMode::UsePointer as bind_ceed::CeedCopyMode, 631 std::mem::size_of::<QFunctionTrampolineData>(), 632 std::mem::transmute(trampoline_data.as_ref()), 633 ) 634 })?; 635 ceed.check_error(unsafe { 636 bind_ceed::CeedQFunctionContextSetDataDestroy( 637 qf_ctx_ptr, 638 crate::MemType::Host as bind_ceed::CeedMemType, 639 Some(destroy_trampoline), 640 ) 641 })?; 642 ceed.check_error(unsafe { bind_ceed::CeedQFunctionSetContext(ptr, qf_ctx_ptr) })?; 643 ceed.check_error(unsafe { bind_ceed::CeedQFunctionContextDestroy(&mut qf_ctx_ptr) })?; 644 Ok(Self { 645 qf_core: QFunctionCore { 646 ptr, 647 _lifeline: PhantomData, 648 }, 649 qf_ctx_ptr, 650 trampoline_data, 651 }) 652 } 653 654 /// Apply the action of a QFunction 655 /// 656 /// * `Q` - The number of quadrature points 657 /// * `input` - Array of input Vectors 658 /// * `output` - Array of output Vectors 659 /// 660 /// ``` 661 /// # use libceed::prelude::*; 662 /// # fn main() -> libceed::Result<()> { 663 /// # let ceed = libceed::Ceed::default_init(); 664 /// let mut user_f = |[u, weights, ..]: QFunctionInputs, [v, ..]: QFunctionOutputs| { 665 /// // Iterate over quadrature points 666 /// v.iter_mut() 667 /// .zip(u.iter().zip(weights.iter())) 668 /// .for_each(|(v, (u, w))| *v = u * w); 669 /// 670 /// // Return clean error code 671 /// 0 672 /// }; 673 /// 674 /// let qf = ceed 675 /// .q_function_interior(1, Box::new(user_f))? 676 /// .input("u", 1, EvalMode::Interp)? 677 /// .input("weights", 1, EvalMode::Weight)? 678 /// .output("v", 1, EvalMode::Interp)?; 679 /// 680 /// const Q: usize = 8; 681 /// let mut w = [0.; Q]; 682 /// let mut u = [0.; Q]; 683 /// let mut v = [0.; Q]; 684 /// 685 /// for i in 0..Q { 686 /// let x = 2. * (i as Scalar) / ((Q as Scalar) - 1.) - 1.; 687 /// u[i] = 2. + 3. * x + 5. * x * x; 688 /// w[i] = 1. - x * x; 689 /// v[i] = u[i] * w[i]; 690 /// } 691 /// 692 /// let uu = ceed.vector_from_slice(&u)?; 693 /// let ww = ceed.vector_from_slice(&w)?; 694 /// let mut vv = ceed.vector(Q)?; 695 /// vv.set_value(0.0); 696 /// { 697 /// let input = vec![uu, ww]; 698 /// let mut output = vec![vv]; 699 /// qf.apply(Q, &input, &output)?; 700 /// vv = output.remove(0); 701 /// } 702 /// 703 /// vv.view()? 704 /// .iter() 705 /// .zip(v.iter()) 706 /// .for_each(|(computed, actual)| { 707 /// assert_eq!( 708 /// *computed, *actual, 709 /// "Incorrect value in QFunction application" 710 /// ); 711 /// }); 712 /// # Ok(()) 713 /// # } 714 /// ``` 715 pub fn apply(&self, Q: usize, u: &[Vector], v: &[Vector]) -> crate::Result<i32> { 716 self.qf_core.apply(Q, u, v) 717 } 718 719 /// Add a QFunction input 720 /// 721 /// * `fieldname` - Name of QFunction field 722 /// * `size` - Size of QFunction field, `(ncomp * dim)` for `Grad` or 723 /// `(ncomp * 1)` for `None`, `Interp`, and `Weight` 724 /// * `emode` - `EvalMode::None` to use values directly, `EvalMode::Interp` 725 /// to use interpolated values, `EvalMode::Grad` to use 726 /// gradients, `EvalMode::Weight` to use quadrature weights 727 /// 728 /// ``` 729 /// # use libceed::prelude::*; 730 /// # fn main() -> libceed::Result<()> { 731 /// # let ceed = libceed::Ceed::default_init(); 732 /// let mut user_f = |[u, weights, ..]: QFunctionInputs, [v, ..]: QFunctionOutputs| { 733 /// // Iterate over quadrature points 734 /// v.iter_mut() 735 /// .zip(u.iter().zip(weights.iter())) 736 /// .for_each(|(v, (u, w))| *v = u * w); 737 /// 738 /// // Return clean error code 739 /// 0 740 /// }; 741 /// 742 /// let mut qf = ceed.q_function_interior(1, Box::new(user_f))?; 743 /// 744 /// qf = qf.input("u", 1, EvalMode::Interp)?; 745 /// qf = qf.input("weights", 1, EvalMode::Weight)?; 746 /// # Ok(()) 747 /// # } 748 /// ``` 749 pub fn input( 750 mut self, 751 fieldname: &str, 752 size: usize, 753 emode: crate::EvalMode, 754 ) -> crate::Result<Self> { 755 let name_c = CString::new(fieldname).expect("CString::new failed"); 756 let idx = self.trampoline_data.number_inputs; 757 self.trampoline_data.input_sizes[idx] = size; 758 self.trampoline_data.number_inputs += 1; 759 let (size, emode) = ( 760 i32::try_from(size).unwrap(), 761 emode as bind_ceed::CeedEvalMode, 762 ); 763 self.qf_core.check_error(unsafe { 764 bind_ceed::CeedQFunctionAddInput(self.qf_core.ptr, name_c.as_ptr(), size, emode) 765 })?; 766 Ok(self) 767 } 768 769 /// Add a QFunction output 770 /// 771 /// * `fieldname` - Name of QFunction field 772 /// * `size` - Size of QFunction field, `(ncomp * dim)` for `Grad` or 773 /// `(ncomp * 1)` for `None` and `Interp` 774 /// * `emode` - `EvalMode::None` to use values directly, `EvalMode::Interp` 775 /// to use interpolated values, `EvalMode::Grad` to use 776 /// gradients 777 /// 778 /// ``` 779 /// # use libceed::prelude::*; 780 /// # fn main() -> libceed::Result<()> { 781 /// # let ceed = libceed::Ceed::default_init(); 782 /// let mut user_f = |[u, weights, ..]: QFunctionInputs, [v, ..]: QFunctionOutputs| { 783 /// // Iterate over quadrature points 784 /// v.iter_mut() 785 /// .zip(u.iter().zip(weights.iter())) 786 /// .for_each(|(v, (u, w))| *v = u * w); 787 /// 788 /// // Return clean error code 789 /// 0 790 /// }; 791 /// 792 /// let mut qf = ceed.q_function_interior(1, Box::new(user_f))?; 793 /// 794 /// qf.output("v", 1, EvalMode::Interp)?; 795 /// # Ok(()) 796 /// # } 797 /// ``` 798 pub fn output( 799 mut self, 800 fieldname: &str, 801 size: usize, 802 emode: crate::EvalMode, 803 ) -> crate::Result<Self> { 804 let name_c = CString::new(fieldname).expect("CString::new failed"); 805 let idx = self.trampoline_data.number_outputs; 806 self.trampoline_data.output_sizes[idx] = size; 807 self.trampoline_data.number_outputs += 1; 808 let (size, emode) = ( 809 i32::try_from(size).unwrap(), 810 emode as bind_ceed::CeedEvalMode, 811 ); 812 self.qf_core.check_error(unsafe { 813 bind_ceed::CeedQFunctionAddOutput(self.qf_core.ptr, name_c.as_ptr(), size, emode) 814 })?; 815 Ok(self) 816 } 817 818 /// Get a slice of QFunction inputs 819 /// 820 /// ``` 821 /// # use libceed::prelude::*; 822 /// # fn main() -> libceed::Result<()> { 823 /// # let ceed = libceed::Ceed::default_init(); 824 /// let mut user_f = |[u, weights, ..]: QFunctionInputs, [v, ..]: QFunctionOutputs| { 825 /// // Iterate over quadrature points 826 /// v.iter_mut() 827 /// .zip(u.iter().zip(weights.iter())) 828 /// .for_each(|(v, (u, w))| *v = u * w); 829 /// 830 /// // Return clean error code 831 /// 0 832 /// }; 833 /// 834 /// let mut qf = ceed 835 /// .q_function_interior(1, Box::new(user_f))? 836 /// .input("u", 1, EvalMode::Interp)? 837 /// .input("weights", 1, EvalMode::Weight)?; 838 /// 839 /// let inputs = qf.inputs()?; 840 /// 841 /// assert_eq!(inputs.len(), 2, "Incorrect inputs array"); 842 /// # Ok(()) 843 /// # } 844 /// ``` 845 pub fn inputs(&self) -> crate::Result<&[crate::QFunctionField]> { 846 self.qf_core.inputs() 847 } 848 849 /// Get a slice of QFunction outputs 850 /// 851 /// ``` 852 /// # use libceed::prelude::*; 853 /// # fn main() -> libceed::Result<()> { 854 /// # let ceed = libceed::Ceed::default_init(); 855 /// let mut user_f = |[u, weights, ..]: QFunctionInputs, [v, ..]: QFunctionOutputs| { 856 /// // Iterate over quadrature points 857 /// v.iter_mut() 858 /// .zip(u.iter().zip(weights.iter())) 859 /// .for_each(|(v, (u, w))| *v = u * w); 860 /// 861 /// // Return clean error code 862 /// 0 863 /// }; 864 /// 865 /// let mut qf = ceed 866 /// .q_function_interior(1, Box::new(user_f))? 867 /// .output("v", 1, EvalMode::Interp)?; 868 /// 869 /// let outputs = qf.outputs()?; 870 /// 871 /// assert_eq!(outputs.len(), 1, "Incorrect outputs array"); 872 /// # Ok(()) 873 /// # } 874 /// ``` 875 pub fn outputs(&self) -> crate::Result<&[crate::QFunctionField]> { 876 self.qf_core.outputs() 877 } 878 } 879 880 // ----------------------------------------------------------------------------- 881 // QFunction 882 // ----------------------------------------------------------------------------- 883 impl<'a> QFunctionByName<'a> { 884 // Constructor 885 pub fn create(ceed: &crate::Ceed, name: &str) -> crate::Result<Self> { 886 let name_c = CString::new(name).expect("CString::new failed"); 887 let mut ptr = std::ptr::null_mut(); 888 ceed.check_error(unsafe { 889 bind_ceed::CeedQFunctionCreateInteriorByName(ceed.ptr, name_c.as_ptr(), &mut ptr) 890 })?; 891 Ok(Self { 892 qf_core: QFunctionCore { 893 ptr, 894 _lifeline: PhantomData, 895 }, 896 }) 897 } 898 899 /// Apply the action of a QFunction 900 /// 901 /// * `Q` - The number of quadrature points 902 /// * `input` - Array of input Vectors 903 /// * `output` - Array of output Vectors 904 /// 905 /// ``` 906 /// # use libceed::prelude::*; 907 /// # fn main() -> libceed::Result<()> { 908 /// # let ceed = libceed::Ceed::default_init(); 909 /// const Q: usize = 8; 910 /// let qf_build = ceed.q_function_interior_by_name("Mass1DBuild")?; 911 /// let qf_mass = ceed.q_function_interior_by_name("MassApply")?; 912 /// 913 /// let mut j = [0.; Q]; 914 /// let mut w = [0.; Q]; 915 /// let mut u = [0.; Q]; 916 /// let mut v = [0.; Q]; 917 /// 918 /// for i in 0..Q { 919 /// let x = 2. * (i as Scalar) / ((Q as Scalar) - 1.) - 1.; 920 /// j[i] = 1.; 921 /// w[i] = 1. - x * x; 922 /// u[i] = 2. + 3. * x + 5. * x * x; 923 /// v[i] = w[i] * u[i]; 924 /// } 925 /// 926 /// let jj = ceed.vector_from_slice(&j)?; 927 /// let ww = ceed.vector_from_slice(&w)?; 928 /// let uu = ceed.vector_from_slice(&u)?; 929 /// let mut vv = ceed.vector(Q)?; 930 /// vv.set_value(0.0); 931 /// let mut qdata = ceed.vector(Q)?; 932 /// qdata.set_value(0.0); 933 /// 934 /// { 935 /// let mut input = vec![jj, ww]; 936 /// let mut output = vec![qdata]; 937 /// qf_build.apply(Q, &input, &output)?; 938 /// qdata = output.remove(0); 939 /// } 940 /// 941 /// { 942 /// let mut input = vec![qdata, uu]; 943 /// let mut output = vec![vv]; 944 /// qf_mass.apply(Q, &input, &output)?; 945 /// vv = output.remove(0); 946 /// } 947 /// 948 /// vv.view()? 949 /// .iter() 950 /// .zip(v.iter()) 951 /// .for_each(|(computed, actual)| { 952 /// assert_eq!( 953 /// *computed, *actual, 954 /// "Incorrect value in QFunction application" 955 /// ); 956 /// }); 957 /// # Ok(()) 958 /// # } 959 /// ``` 960 pub fn apply(&self, Q: usize, u: &[Vector], v: &[Vector]) -> crate::Result<i32> { 961 self.qf_core.apply(Q, u, v) 962 } 963 964 /// Get a slice of QFunction inputs 965 /// 966 /// ``` 967 /// # use libceed::prelude::*; 968 /// # fn main() -> libceed::Result<()> { 969 /// # let ceed = libceed::Ceed::default_init(); 970 /// const Q: usize = 8; 971 /// let qf = ceed.q_function_interior_by_name("Mass1DBuild")?; 972 /// 973 /// let inputs = qf.inputs()?; 974 /// 975 /// assert_eq!(inputs.len(), 2, "Incorrect inputs array"); 976 /// # Ok(()) 977 /// # } 978 /// ``` 979 pub fn inputs(&self) -> crate::Result<&[crate::QFunctionField]> { 980 self.qf_core.inputs() 981 } 982 983 /// Get a slice of QFunction outputs 984 /// 985 /// ``` 986 /// # use libceed::prelude::*; 987 /// # fn main() -> libceed::Result<()> { 988 /// # let ceed = libceed::Ceed::default_init(); 989 /// const Q: usize = 8; 990 /// let qf = ceed.q_function_interior_by_name("Mass1DBuild")?; 991 /// 992 /// let outputs = qf.outputs()?; 993 /// 994 /// assert_eq!(outputs.len(), 1, "Incorrect outputs array"); 995 /// # Ok(()) 996 /// # } 997 /// ``` 998 pub fn outputs(&self) -> crate::Result<&[crate::QFunctionField]> { 999 self.qf_core.outputs() 1000 } 1001 } 1002 1003 // ----------------------------------------------------------------------------- 1004