qudit-circuit 0.3.2

Accelerated and Extensible Quantum Library
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
//! Argument list types for quantum circuit parameters.
//!
//! This module provides the `ArgumentList` struct which represents a collection
//! of `Argument` instances that can be used to parameterize quantum circuits.
//! The list provides methods for extracting parameters, variable names, and
//! substitution expressions from all contained arguments.
//!
//! The module also provides conversions from various Rust collections and Python
//! iterables when the `python` feature is enabled.

use super::Argument;
use super::NameOrParameter;
use crate::Result;
use qudit_core::ParamIndices;
use qudit_expr::Expression;

/// Represents a list of arguments for quantum circuit parameters.
#[derive(Clone, Debug)]
pub struct ArgumentList {
    entries: Vec<Argument>,
}

impl ArgumentList {
    /// Creates a new `ArgumentList` from a vector of arguments.
    pub fn new(entries: Vec<Argument>) -> Self {
        Self { entries }
    }

    /// Returns a reference to the internal vector of arguments.
    pub fn arguments(&self) -> &[Argument] {
        &self.entries
    }

    /// Returns the number of arguments in this list.
    pub fn len(&self) -> usize {
        self.entries.len()
    }

    /// Returns whether this argument list is empty.
    pub fn is_empty(&self) -> bool {
        self.entries.is_empty()
    }

    /// Extracts the parameters from the list of arguments.
    ///
    /// This method aggregates parameters from all arguments in the list,
    /// removing duplicates for named parameters to ensure each unique
    /// parameter variable appears only once in the result.
    ///
    /// Note: one argument can correspond to multiple parameters. For example,
    /// if a user provides `"a*b"` as an argument, this will be managed as two
    /// separate named parameters, `a` and `b`. The expression containing
    /// the multiplication will get folded into the operation.
    ///
    /// # Returns
    /// A vector of `Parameter` instances representing all unique parameters
    /// required by the arguments in this list
    pub fn parameters(&self) -> Vec<NameOrParameter> {
        let mut params = vec![];
        for argument in self.entries.iter() {
            for param in argument.parameters() {
                if let NameOrParameter::Name(_) = param {
                    if params.contains(&param) {
                        continue;
                    }
                }
                params.push(param);
            }
        }
        params
    }

    /// Gathers the variable names associated with these arguments.
    ///
    /// Note: Non-parameterized arguments are assigned a name `unnamed_i`
    /// where `i` is generated from an internal counter to ensure uniqueness.
    /// Parameterized expression arguments return their actual variable names.
    /// The output of this can be one part of a `substitute_parameters` call on
    /// an expression informing the expression of the new variable names.
    pub fn variables(&self) -> Vec<String> {
        let mut new_variables = vec![];
        let mut unnamed_counter = 0;
        // TODO: "unnamed_" should result an error when used in an argument. (Should it?)

        for argument in self.entries.iter() {
            new_variables.extend(argument.variables(&mut unnamed_counter))
        }

        new_variables
    }

    /// Gathers the expressions associated with these arguments.
    ///
    /// Note: Non-expression arguments are converted to variable expressions
    /// with names `unnamed_i` where `i` is generated from an internal counter.
    /// Expression arguments are returned as-is. The output can be used as
    /// part of a `substitute_parameters` call on an expression informing
    /// the expression what to replace its current variables with.
    pub fn expressions(&self) -> Vec<Expression> {
        let mut new_variables = vec![];
        let mut unnamed_counter = 0;

        for argument in self.entries.iter() {
            new_variables.push(argument.as_substitution_expression(&mut unnamed_counter))
        }

        new_variables
    }

    /// Returns true if any non-simple arguments exist in the list
    ///
    /// A Non-simple argument is one that is not a single constant or single
    /// parameter (named or unnamed). For example, the expression `"a*b"`
    /// requires expression modification and is non-simple. This is because
    /// the multiplication of the two parameters gets folded into the
    /// expression being invoked with this argument list, and as a result,
    /// get's modified to accommodate a multiplication of two parameters in
    /// place of the one in that argument's slot.
    pub fn requires_expression_modification(&self) -> bool {
        self.entries
            .iter()
            .any(|arg| arg.requires_expression_modification())
    }

    /// Creates a new `ArgumentList` by slicing the current list based on provided indices.
    ///
    /// # Arguments
    ///
    /// * `indices` - A slice of `usize` values representing the indices of the
    ///   arguments to include in the new list.
    ///
    /// # Returns
    ///
    /// A new `ArgumentList` containing only the arguments at the specified indices.
    ///
    /// # Panics
    ///
    /// Panics if any index in `indices` is out of bounds for the current `ArgumentList`.
    pub fn slice_by_indices<I>(&self, indices: I) -> Self
    where
        I: IntoIterator<Item = usize>,
    {
        indices.into_iter().map(|i| self[i].clone()).collect()
    }

    /// Maps the indices of arguments used by a specific instruction to their corresponding
    /// positions in the flattened, deduplicated parameter list of this `ArgumentList`.
    ///
    /// When an instruction uses arguments that contain multiple parameters (such as an
    /// expression `"a*b"`), this method resolves where the underlying variables (`a` and `b`)
    /// sit in the unique vector returned by [`parameters()`](Self::parameters). It guarantees
    /// that no duplicate indices are added to the mapping for a single instruction.
    ///
    /// # Arguments
    ///
    /// * `inner_indices` - An iterator yielding `usize` values. These represent the indices
    ///   of the arguments in this `ArgumentList` that are required by the target instruction.
    ///
    /// # Returns
    ///
    /// A `ParamIndices` collection containing the mapped, deduplicated positions of the
    /// required parameters within the master parameter list.
    pub fn map_indices_for_instruction<I>(&self, inner_indices: I) -> ParamIndices
    where
        I: IntoIterator<Item = usize>,
    {
        let unique_params = self.parameters();

        let mut mapped_indices = Vec::new();

        for i in inner_indices {
            // 2. Identify which argument was passed for this internal slot (e.g., "a*b")
            let argument = &self.entries[i];

            // 3. Find where the variables of "a*b" sit in the unique_params vector.
            for param in argument.parameters() {
                if let Some(new_pos) = unique_params.iter().position(|p| p == &param) {
                    // Avoid duplicates within a single instruction's index list
                    if !mapped_indices.contains(&new_pos) {
                        mapped_indices.push(new_pos);
                    }
                }
            }
        }

        ParamIndices::from(mapped_indices)
    }
}

impl std::ops::Deref for ArgumentList {
    type Target = [Argument];

    fn deref(&self) -> &Self::Target {
        &self.entries
    }
}

impl<E: Into<Argument>> From<Vec<E>> for ArgumentList {
    /// Converts a vector of argument-like values into an `ArgumentList`.
    fn from(value: Vec<E>) -> Self {
        Self::new(value.into_iter().map(|e| e.into()).collect())
    }
}

impl<E: Into<Argument>, const N: usize> From<[E; N]> for ArgumentList {
    /// Converts an array of argument-like values into an `ArgumentList`.
    fn from(value: [E; N]) -> Self {
        Self::new(value.into_iter().map(|e| e.into()).collect())
    }
}

impl<E: Into<Argument> + Clone, const N: usize> From<&[E; N]> for ArgumentList {
    /// Converts a reference to an array of argument-like values into an `ArgumentList`.
    fn from(value: &[E; N]) -> Self {
        Self::new(value.iter().map(|e| e.clone().into()).collect())
    }
}

impl TryFrom<Vec<String>> for ArgumentList {
    type Error = crate::Error;

    /// Converts a vector of strings into an `ArgumentList`.
    ///
    /// Each string is parsed as an expression argument using `Argument::try_from()`.
    /// If any string fails to parse, the entire conversion fails.
    fn try_from(value: Vec<String>) -> std::result::Result<Self, Self::Error> {
        let mut arguments = Vec::with_capacity(value.len());
        for s in value {
            arguments.push(
                Argument::try_from(s).map_err(|e| crate::Error::InvalidArgument {
                    message: e.to_string(),
                })?,
            );
        }
        Ok(ArgumentList::new(arguments))
    }
}

impl TryFrom<Vec<&str>> for ArgumentList {
    type Error = crate::Error;

    /// Converts a vector of string slices into an `ArgumentList`.
    ///
    /// Each string is parsed as an expression argument using `Argument::try_from()`.
    /// If any string fails to parse, the entire conversion fails.
    fn try_from(value: Vec<&str>) -> std::result::Result<Self, Self::Error> {
        let mut arguments = Vec::with_capacity(value.len());
        for s in value {
            arguments.push(
                Argument::try_from(s).map_err(|e| crate::Error::InvalidArgument {
                    message: e.to_string(),
                })?,
            );
        }
        Ok(ArgumentList::new(arguments))
    }
}

impl<const N: usize> TryFrom<[String; N]> for ArgumentList {
    type Error = crate::Error;

    /// Converts an array of strings into an `ArgumentList`.
    fn try_from(value: [String; N]) -> std::result::Result<Self, Self::Error> {
        let mut arguments = Vec::with_capacity(N);
        for s in value {
            arguments.push(
                Argument::try_from(s).map_err(|e| crate::Error::InvalidArgument {
                    message: e.to_string(),
                })?,
            );
        }
        Ok(ArgumentList::new(arguments))
    }
}

impl<const N: usize> TryFrom<[&str; N]> for ArgumentList {
    type Error = crate::Error;

    /// Converts an array of string slices into an `ArgumentList`.
    fn try_from(value: [&str; N]) -> std::result::Result<Self, Self::Error> {
        let mut arguments = Vec::with_capacity(N);
        for s in value {
            arguments.push(
                Argument::try_from(s).map_err(|e| crate::Error::InvalidArgument {
                    message: e.to_string(),
                })?,
            );
        }
        Ok(ArgumentList::new(arguments))
    }
}

/// Trait for types that can be converted to argument lists
impl<E: Into<Argument>> FromIterator<E> for ArgumentList {
    /// Creates an `ArgumentList` by collecting items from an iterator.
    ///
    /// Each item in the iterator is converted to an `Argument` using `Into::into()`.
    fn from_iter<T: IntoIterator<Item = E>>(iter: T) -> Self {
        Self::new(iter.into_iter().map(|e| e.into()).collect())
    }
}

pub trait IntoArgumentList {
    fn into_args(self, num_args: usize) -> Result<ArgumentList>;
}

impl IntoArgumentList for ArgumentList {
    fn into_args(self, num_args: usize) -> Result<ArgumentList> {
        if num_args != self.len() {
            Err(crate::Error::ArgumentListSizeMismatch {
                actual: self.len() as u64,
                expected: num_args as u64,
            })
        } else {
            Ok(self)
        }
    }
}

impl IntoArgumentList for Option<ArgumentList> {
    fn into_args(self, num_args: usize) -> Result<ArgumentList> {
        match self {
            Some(args) => args.into_args(num_args),
            None => {
                let args = ArgumentList::new(vec![Argument::Unspecified; num_args]);
                Ok(args)
            }
        }
    }
}

impl IntoArgumentList for () {
    fn into_args(self, num_args: usize) -> Result<ArgumentList> {
        let args = ArgumentList::new(vec![Argument::Unspecified; num_args]);
        Ok(args)
    }
}

// impl<T> IntoArgumentList for Option<T>
// where
//     T: TryInto<ArgumentList>,
//     T::Error: Into<crate::Error>
// {
//     fn into_args(self, num_args: usize) -> Result<ArgumentList> {
//         match self {
//             Some(args) => Ok(args.try_into().map_err(Into::into)?),
//             None => {
//                 let args = ArgumentList::new(vec![Argument::Unspecified; num_args]);
//                 Ok(args)
//             }
//         }
//     }
// }

impl<T> IntoArgumentList for T
where
    T: TryInto<ArgumentList>,
    T::Error: Into<crate::Error>,
{
    fn into_args(self, num_args: usize) -> Result<ArgumentList> {
        let args = self.try_into().map_err(Into::into)?;
        args.into_args(num_args)
    }
}

#[cfg(feature = "python")]
mod python_stub {
    use super::ArgumentList;
    use pyo3_stub_gen::impl_stub_type;
    impl_stub_type!(ArgumentList = Vec<f64>);
}

#[cfg(feature = "python")]
mod python {
    use super::Argument;
    use super::ArgumentList;
    use pyo3::exceptions::{PyTypeError, PyValueError};
    use pyo3::prelude::*;

    impl<'a, 'py> FromPyObject<'a, 'py> for ArgumentList {
        type Error = PyErr;

        /// Converts a Python object to an `ArgumentList`.
        ///
        /// # Supported conversions
        /// - Python lists/tuples containing argument-like values → `ArgumentList`
        /// - Single argument-like values → `ArgumentList` with one element
        /// - Empty iterables → Empty `ArgumentList`
        ///
        /// Each element in the iterable is converted using `Argument::extract()`.
        ///
        /// # Errors
        /// Returns `PyValueError` if any element cannot be converted to an `Argument`,
        /// or `PyTypeError` if the Python object is not iterable and not convertible to an `Argument`.
        fn extract(obj: Borrowed<'a, 'py, PyAny>) -> PyResult<Self> {
            // First, try to convert as a single argument
            if let Ok(arg) = Argument::extract(obj) {
                return Ok(ArgumentList::new(vec![arg]));
            }

            // If it's not a single argument, try to treat as an iterable (list, tuple, etc.)
            if let Ok(iter) = pyo3::types::PyIterator::from_object(&obj) {
                let mut arguments = Vec::new();
                for item in iter {
                    let item = item?;
                    match Argument::extract(item.as_borrowed()) {
                        Ok(arg) => arguments.push(arg),
                        Err(e) => {
                            return Err(PyValueError::new_err(format!(
                                "Cannot convert item to Argument: {}",
                                e
                            )));
                        }
                    }
                }
                return Ok(ArgumentList::new(arguments));
            }

            // If neither worked, return an error
            Err(PyTypeError::new_err(format!(
                "Cannot convert {} to ArgumentList: must be iterable or convertible to Argument",
                obj.get_type().name()?,
            )))
        }
    }

    #[cfg(test)]
    mod tests {
        use super::*;
        use pyo3::Python;
        use pyo3::types::{PyDict, PyFloat, PyList, PyString, PyTuple};
        #[test]
        fn test_from_py_empty_list() {
            Python::initialize();
            Python::attach(|py| {
                let empty_list = PyList::empty(py);
                let result = ArgumentList::extract(empty_list.as_any().as_borrowed()).unwrap();
                assert_eq!(result.len(), 0);
                assert!(result.is_empty());
            });
        }
        #[test]
        fn test_from_py_list_of_numbers() {
            Python::initialize();
            Python::attach(|py| {
                let py_list = PyList::new(py, [1.0, 2.5, 3.14]).unwrap();
                let result = ArgumentList::extract(py_list.as_any().as_borrowed()).unwrap();
                assert_eq!(result.len(), 3);

                let args = result.arguments();
                assert!(matches!(args[0], Argument::Float64(1.0)));
                assert!(matches!(args[1], Argument::Float64(2.5)));
                assert!(matches!(args[2], Argument::Float64(3.14)));
            });
        }
        #[test]
        fn test_from_py_tuple_mixed_types() {
            Python::initialize();
            Python::attach(|py| {
                let one = PyFloat::new(py, 1.5);
                let two = PyString::new(py, "x + 1");
                let none = py.None().into_bound(py);
                let items: Vec<&Bound<'_, PyAny>> = vec![one.as_any(), two.as_any(), &none];
                let py_tuple = PyTuple::new(py, items).unwrap();
                let result = ArgumentList::extract(py_tuple.as_any().as_borrowed()).unwrap();
                assert_eq!(result.len(), 3);

                let args = result.arguments();
                assert!(matches!(args[0], Argument::Float64(1.5)));
                assert!(matches!(args[1], Argument::Expression(_)));
                assert!(matches!(args[2], Argument::Unspecified));
            });
        }
        #[test]
        fn test_from_py_single_argument() {
            Python::initialize();
            Python::attach(|py| {
                let float_val = PyFloat::new(py, 42.0);
                let result = ArgumentList::extract(float_val.as_any().as_borrowed()).unwrap();
                assert_eq!(result.len(), 1);

                let args = result.arguments();
                assert!(matches!(args[0], Argument::Float64(42.0)));
            });
        }
        #[test]
        fn test_from_py_list_with_expressions() {
            Python::initialize();
            Python::attach(|py| {
                let one = PyString::new(py, "sin(x)");
                let two = PyString::new(py, "a*b + c");
                let three = PyString::new(py, "pi/4");
                let expressions = vec![one.as_any(), two.as_any(), three.as_any()];
                let py_list = PyList::new(py, expressions).unwrap();
                let result = ArgumentList::extract(py_list.as_any().as_borrowed()).unwrap();
                assert_eq!(result.len(), 3);

                let args = result.arguments();
                for arg in args {
                    assert!(matches!(arg, Argument::Expression(_)));
                }
            });
        }
        #[test]
        fn test_from_py_list_with_invalid_item() {
            Python::initialize();
            Python::attach(|py| {
                let one = PyFloat::new(py, 1.0);
                let two = PyDict::new(py); // This should fail
                let items: Vec<&Bound<'_, PyAny>> = vec![one.as_any(), two.as_any()];
                let py_list = PyList::new(py, items).unwrap();
                let result = ArgumentList::extract(py_list.as_any().as_borrowed());
                assert!(result.is_err());
                let err = result.unwrap_err();
                assert!(err.is_instance_of::<pyo3::exceptions::PyValueError>(py));
                assert!(err.to_string().contains("Cannot convert item to Argument"));
            });
        }
        #[test]
        fn test_from_py_list_with_complex_expression_rejected() {
            Python::initialize();
            Python::attach(|py| {
                let complex_expr = PyString::new(py, "1 + i");
                let items: Vec<&Bound<'_, PyAny>> = vec![
                    complex_expr.as_any(), // Complex expression
                ];
                let py_list = PyList::new(py, items).unwrap();
                let result = ArgumentList::extract(py_list.as_any().as_borrowed());
                assert!(result.is_err());
                let err = result.unwrap_err();
                assert!(err.is_instance_of::<pyo3::exceptions::PyValueError>(py));
            });
        }
        #[test]
        fn test_from_py_list_with_unnamed_rejected() {
            Python::initialize();
            Python::attach(|py| {
                let unnamed_expr = PyString::new(py, "unnamed_var");
                let items: Vec<&Bound<'_, PyAny>> = vec![unnamed_expr.as_any()];
                let py_list = PyList::new(py, items).unwrap();
                let result = ArgumentList::extract(py_list.as_any().as_borrowed());
                assert!(result.is_err());
                let err = result.unwrap_err();
                assert!(err.is_instance_of::<pyo3::exceptions::PyValueError>(py));
                assert!(
                    err.to_string()
                        .contains("Expression arguments cannot contain 'unnamed_'")
                );
            });
        }

        #[test]
        fn test_from_py_single_string_expression() {
            Python::initialize();
            Python::attach(|py| {
                let string_val = PyString::new(py, "x*y + z");
                let result = ArgumentList::extract(string_val.as_any().as_borrowed()).unwrap();
                assert_eq!(result.len(), 1);

                let args = result.arguments();
                assert!(matches!(args[0], Argument::Expression(_)));
            });
        }

        #[test]
        fn test_parameters_extraction() {
            Python::initialize();
            Python::attach(|py| {
                let one = PyString::new(py, "x");
                let two = PyString::new(py, "x + y"); // x should be deduplicated
                let three = PyFloat::new(py, 1.0);
                let expressions = vec![one.as_any(), two.as_any(), three.as_any()];
                let py_list = PyList::new(py, expressions).unwrap();
                let result = ArgumentList::extract(py_list.as_any().as_borrowed()).unwrap();

                let params = result.parameters();
                // Should have named parameters for x, y and a constant parameter
                assert_eq!(params.len(), 3);
            });
        }
    }
}
#[cfg(test)]
mod tests {
    use super::super::Parameter;
    use super::*;
    use qudit_expr::Expression;
    #[test]
    fn test_argumentlist_new() {
        let args = vec![Argument::Float64(1.0), Argument::Float64(2.0)];
        let list = ArgumentList::new(args);
        assert_eq!(list.len(), 2);
        assert!(!list.is_empty());
    }
    #[test]
    fn test_argumentlist_empty() {
        let list = ArgumentList::new(vec![]);
        assert_eq!(list.len(), 0);
        assert!(list.is_empty());
    }
    #[test]
    fn test_argumentlist_arguments_access() {
        let args = vec![Argument::Float64(1.0), Argument::Unspecified];
        let list = ArgumentList::new(args);
        let accessed_args = list.arguments();
        assert_eq!(accessed_args.len(), 2);
        assert!(matches!(accessed_args[0], Argument::Float64(1.0)));
        assert!(matches!(accessed_args[1], Argument::Unspecified));
    }
    #[test]
    fn test_parameters_single_argument() {
        let args = vec![Argument::Float64(42.0)];
        let list = ArgumentList::new(args);
        let params = list.parameters();
        assert_eq!(params.len(), 1);
        assert!(matches!(
            params[0],
            NameOrParameter::Parameter(Parameter::Assigned64(42.0))
        ));
    }
    #[test]
    fn test_parameters_deduplication() {
        let x_expr = Argument::try_from("x").unwrap();
        let xy_expr = Argument::try_from("x + y").unwrap();
        let args = vec![x_expr, xy_expr];
        let list = ArgumentList::new(args);
        let params = list.parameters();

        // Should have 2 unique named parameters: x and y
        assert_eq!(params.len(), 2);
        let param_names: Vec<String> = params
            .into_iter()
            .map(|p| match p {
                NameOrParameter::Name(name) => name,
                _ => panic!("Expected Named parameter"),
            })
            .collect();
        assert!(param_names.contains(&"x".to_string()));
        assert!(param_names.contains(&"y".to_string()));
    }
    #[test]
    fn test_parameters_mixed_types() {
        let args = vec![
            Argument::Float32(1.0),
            Argument::Float64(2.0),
            Argument::Unspecified,
            Argument::try_from("theta").unwrap(),
        ];
        let list = ArgumentList::new(args);
        let params = list.parameters();

        assert_eq!(params.len(), 4);
        assert!(matches!(
            params[0],
            NameOrParameter::Parameter(Parameter::Assigned32(1.0))
        ));
        assert!(matches!(
            params[1],
            NameOrParameter::Parameter(Parameter::Assigned64(2.0))
        ));
        assert!(matches!(
            params[2],
            NameOrParameter::Parameter(Parameter::Unassigned)
        ));
        assert!(matches!(params[3], NameOrParameter::Name(ref name) if name == "theta"));
    }
    #[test]
    fn test_variables_generation() {
        let args = vec![
            Argument::Float64(1.0),           // Should get unnamed_0
            Argument::try_from("x").unwrap(), // Should keep "x"
            Argument::Unspecified,            // Should get unnamed_1
        ];
        let list = ArgumentList::new(args);
        let vars = list.variables();

        assert_eq!(vars.len(), 3);
        assert_eq!(vars[0], "unnamed_0");
        assert_eq!(vars[1], "x");
        assert_eq!(vars[2], "unnamed_1");
    }
    #[test]
    fn test_variables_constant_expression() {
        let constant_expr = Expression::from_float_64(3.14);
        let args = vec![Argument::Expression(constant_expr), Argument::Float64(2.0)];
        let list = ArgumentList::new(args);
        let vars = list.variables();

        assert_eq!(vars.len(), 2);
        assert_eq!(vars[0], "unnamed_0"); // Constant expression gets unnamed
        assert_eq!(vars[1], "unnamed_1"); // Float gets unnamed
    }
    #[test]
    fn test_expressions_generation() {
        let args = vec![Argument::Float64(1.0), Argument::try_from("x + 1").unwrap()];
        let list = ArgumentList::new(args.clone());
        let exprs = list.expressions();

        assert_eq!(exprs.len(), 2);
        // First should be a variable expression with generated name
        assert_eq!(exprs[0], Expression::Variable("unnamed_0".to_string()));
        // Second should be the original expression
        if let Argument::Expression(original_expr) = &args[1] {
            assert_eq!(exprs[1], *original_expr);
        } else {
            panic!("Expected Expression argument");
        }
    }
    #[test]
    fn test_from_vec() {
        let values = vec![1.0f64, 2.0f64, 3.0f64];
        let list = ArgumentList::from(values);
        assert_eq!(list.len(), 3);

        let args = list.arguments();
        assert!(matches!(args[0], Argument::Float64(1.0)));
        assert!(matches!(args[1], Argument::Float64(2.0)));
        assert!(matches!(args[2], Argument::Float64(3.0)));
    }
    #[test]
    fn test_from_array() {
        let values = [1.0f32, 2.0f32];
        let list = ArgumentList::from(values);
        assert_eq!(list.len(), 2);

        let args = list.arguments();
        assert!(matches!(args[0], Argument::Float32(1.0)));
        assert!(matches!(args[1], Argument::Float32(2.0)));
    }
    #[test]
    fn test_from_array_ref() {
        let values = [1.0f64, 2.0f64];
        let list = ArgumentList::from(&values);
        assert_eq!(list.len(), 2);

        let args = list.arguments();
        assert!(matches!(args[0], Argument::Float64(1.0)));
        assert!(matches!(args[1], Argument::Float64(2.0)));
    }
    #[test]
    fn test_argumentlist_clone() {
        let args = vec![Argument::Float64(42.0), Argument::Unspecified];
        let list1 = ArgumentList::new(args);
        let list2 = list1.clone();

        assert_eq!(list1.len(), list2.len());
        assert_eq!(list1.arguments().len(), list2.arguments().len());
    }
    #[test]
    fn test_argumentlist_debug() {
        let args = vec![Argument::Float64(1.0)];
        let list = ArgumentList::new(args);
        let debug_str = format!("{:?}", list);
        assert!(debug_str.contains("ArgumentList"));
        assert!(debug_str.contains("Float64"));
    }
    #[test]
    fn test_complex_multivariate_parameter_extraction() {
        let args = vec![
            Argument::try_from("a*b").unwrap(),   // Variables: a, b
            Argument::try_from("c + a").unwrap(), // Variables: c, a (a deduplicated)
            Argument::Float64(1.0),               // Constant parameter
        ];
        let list = ArgumentList::new(args);
        let params = list.parameters();

        // Should have 3 named parameters (a, b, c) + 1 constant = 4 total
        assert_eq!(params.len(), 4);

        let named_count = params
            .iter()
            .filter(|p| matches!(p, NameOrParameter::Name(_)))
            .count();
        let constant_count = params
            .iter()
            .filter(|p| matches!(p, NameOrParameter::Parameter(Parameter::Assigned64(_))))
            .count();

        assert_eq!(named_count, 3); // a, b, c
        assert_eq!(constant_count, 1); // 1.0
    }

    #[test]
    fn test_large_argument_list() {
        let mut args = Vec::new();
        for i in 0..100 {
            args.push(Argument::Float64(i as f64));
        }

        let list = ArgumentList::new(args);
        assert_eq!(list.len(), 100);
        assert!(!list.is_empty());

        let params = list.parameters();
        assert_eq!(params.len(), 100); // Each float becomes a constant parameter

        let vars = list.variables();
        assert_eq!(vars.len(), 100); // Each gets an unnamed variable
        for (i, var) in vars.iter().enumerate() {
            assert_eq!(*var, format!("unnamed_{}", i));
        }
    }
}
#[test]
fn test_from_iterator() {
    let values = vec![1.0f64, 2.0f64, 3.0f64];
    let list: ArgumentList = values.into_iter().collect();
    assert_eq!(list.len(), 3);

    let args = list.arguments();
    assert!(matches!(args[0], Argument::Float64(1.0)));
    assert!(matches!(args[1], Argument::Float64(2.0)));
    assert!(matches!(args[2], Argument::Float64(3.0)));
}

#[test]
fn test_collect_from_range() {
    let list: ArgumentList = (0..5).map(|i| i as f64).collect();
    assert_eq!(list.len(), 5);

    let args = list.arguments();
    for (i, arg) in args.iter().enumerate() {
        assert!(matches!(arg, Argument::Float64(val) if *val == i as f64));
    }
}

#[test]
fn test_collect_mixed_types() {
    let mixed_args: Vec<Argument> = vec![
        Argument::Float64(1.0),
        Argument::Float32(2.0),
        Argument::Unspecified,
    ];
    let list: ArgumentList = mixed_args.into_iter().collect();
    assert_eq!(list.len(), 3);

    let args = list.arguments();
    assert!(matches!(args[0], Argument::Float64(1.0)));
    assert!(matches!(args[1], Argument::Float32(2.0)));
    assert!(matches!(args[2], Argument::Unspecified));
}

#[test]
fn test_try_from_vec_string() {
    let strings = vec!["x".to_string(), "y + 1".to_string(), "pi/2".to_string()];
    let result = ArgumentList::try_from(strings);
    assert!(result.is_ok());

    let list = result.unwrap();
    assert_eq!(list.len(), 3);

    let args = list.arguments();
    for arg in args {
        assert!(matches!(arg, Argument::Expression(_)));
    }
}

#[test]
fn test_try_from_vec_str() {
    let strings = vec!["a", "b*c", "sin(theta)"];
    let result = ArgumentList::try_from(strings);
    assert!(result.is_ok());

    let list = result.unwrap();
    assert_eq!(list.len(), 3);

    let args = list.arguments();
    for arg in args {
        assert!(matches!(arg, Argument::Expression(_)));
    }
}

#[test]
fn test_try_from_array_str() {
    let strings = ["x", "y"];
    let result = ArgumentList::try_from(strings);
    assert!(result.is_ok());

    let list = result.unwrap();
    assert_eq!(list.len(), 2);
}

#[test]
fn test_into_argument_list_from_vec_strings() {
    let strings = vec!["x", "y"];
    let result = strings.into_args(2);
    assert!(result.is_ok());

    let list = result.unwrap();
    assert_eq!(list.len(), 2);

    let args = list.arguments();
    for arg in args {
        assert!(matches!(arg, Argument::Expression(_)));
    }
}

#[test]
fn test_into_argument_list_from_vec_owned_strings() {
    let strings = vec!["x + 1".to_string(), "y * 2".to_string()];
    let result = strings.into_args(2);
    assert!(result.is_ok());

    let list = result.unwrap();
    assert_eq!(list.len(), 2);
}

#[test]
fn test_into_argument_list_size_mismatch() {
    let strings = vec!["x", "y"];
    let result = strings.into_args(3); // Expected 3 but got 2
    assert!(result.is_err());
}